<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

{% include 'erpnext/selling/sales_common.js' %}

frappe.ui.form.on('Quotation', {
	setup: function(frm) {
		frm.custom_make_buttons = {
			'Sales Order': 'Make Sales Order'
		}
	},
	refresh: function(frm) {
		frm.trigger("set_label");
	},
	quotation_to: function(frm) {
		frm.trigger("set_label");
	},
	set_label: function(frm) {
		frm.fields_dict.customer_address.set_label(__(frm.doc.quotation_to + " Address"));
	}
});

erpnext.selling.QuotationController = erpnext.selling.SellingController.extend({
	onload: function(doc, dt, dn) {
		var me = this;
		this._super(doc, dt, dn);
		if(doc.customer && !doc.quotation_to)
			doc.quotation_to = "Customer";
		else if(doc.lead && !doc.quotation_to)
			doc.quotation_to = "Lead";

	},
	refresh: function(doc, dt, dn) {
		this._super(doc, dt, dn);
		doctype = doc.quotation_to == 'Customer' ? 'Customer':'Lead';
		frappe.dynamic_link = {doc: this.frm.doc, fieldname: doctype.toLowerCase(), doctype: doctype}

		var me = this;

		if (doc.__islocal) {
			this.frm.set_value('valid_till', frappe.datetime.add_months(doc.transaction_date, 1))
		}

		if(doc.docstatus == 1 && doc.status!=='Lost') {
			if(!doc.valid_till || frappe.datetime.get_diff(doc.valid_till, frappe.datetime.get_today()) > 0) {
				cur_frm.add_custom_button(__('Make Sales Order'),
					cur_frm.cscript['Make Sales Order']);
			}

			if(doc.status!=="Ordered") {
				cur_frm.add_custom_button(__('Set as Lost'),
					cur_frm.cscript['Declare Order Lost']);
			}
		}

		if (this.frm.doc.docstatus===0) {
			this.frm.add_custom_button(__('Opportunity'),
				function() {
					var setters = {};
					if(me.frm.doc.customer) {
						setters.customer = me.frm.doc.customer || undefined;
					} else if (me.frm.doc.lead) {
						setters.lead = me.frm.doc.lead || undefined;
					}
					erpnext.utils.map_current_doc({
						method: "erpnext.crm.doctype.opportunity.opportunity.make_quotation",
						source_doctype: "Opportunity",
						target: me.frm,
						setters: setters,
						get_query_filters: {
							status: ["not in", ["Lost", "Closed"]],
							company: me.frm.doc.company,
							// cannot set enquiry_type as setter, as the fieldname is order_type
							enquiry_type: me.frm.doc.order_type,
						}
					})
				}, __("Get items from"), "btn-default");
		}

		this.toggle_reqd_lead_customer();

	},

	quotation_to: function() {
		var me = this;
		if (this.frm.doc.quotation_to == "Lead") {
			this.frm.set_value("customer", null);
			this.frm.set_value("contact_person", null);
		} else if (this.frm.doc.quotation_to == "Customer") {
			this.frm.set_value("lead", null);
		}

		this.toggle_reqd_lead_customer();
	},

	toggle_reqd_lead_customer: function() {
		var me = this;

		this.frm.toggle_reqd("lead", this.frm.doc.quotation_to == "Lead");
		this.frm.toggle_reqd("customer", this.frm.doc.quotation_to == "Customer");

		// to overwrite the customer_filter trigger from queries.js
		this.frm.set_query('customer_address', erpnext.queries.address_query);
		this.frm.set_query('shipping_address_name', erpnext.queries.address_query);
	},

	tc_name: function() {
		this.get_terms();
	},

	validate_company_and_party: function(party_field) {
		if(!this.frm.doc.quotation_to) {
			frappe.msgprint(__("Please select a value for {0} quotation_to {1}", [this.frm.doc.doctype, this.frm.doc.name]));
			return false;
		} else if (this.frm.doc.quotation_to == "Lead") {
			return true;
		} else {
			return this._super(party_field);
		}
	},

	lead: function() {
		var me = this;
		if(!this.frm.doc.lead) {
			return;
		}

		frappe.call({
			method: "erpnext.crm.doctype.lead.lead.get_lead_details",
			args: {
				'lead': this.frm.doc.lead,
				'posting_date': this.frm.doc.transaction_date,
				'company': this.frm.doc.company,
			},
			callback: function(r) {
				if(r.message) {
					me.frm.updating_party_details = true;
					me.frm.set_value(r.message);
					me.frm.refresh();
					me.frm.updating_party_details = false;

				}
			}
		})
	}
});

cur_frm.script_manager.make(erpnext.selling.QuotationController);

cur_frm.fields_dict.lead.get_query = function(doc,cdt,cdn) {
	return{	query: "erpnext.controllers.queries.lead_query" }
}

cur_frm.cscript['Make Sales Order'] = function() {
	frappe.model.open_mapped_doc({
		method: "erpnext.selling.doctype.quotation.quotation.make_sales_order",
		frm: cur_frm
	})
}

cur_frm.cscript['Declare Order Lost'] = function(){
	var dialog = new frappe.ui.Dialog({
		title: "Set as Lost",
		fields: [
			{"fieldtype": "Text", "label": __("Reason for losing"), "fieldname": "reason",
				"reqd": 1 },
			{"fieldtype": "Button", "label": __("Update"), "fieldname": "update"},
		]
	});

	dialog.fields_dict.update.$input.click(function() {
		var args = dialog.get_values();
		if(!args) return;
		return cur_frm.call({
			method: "declare_order_lost",
			doc: cur_frm.doc,
			args: args.reason,
			callback: function(r) {
				if(r.exc) {
					frappe.msgprint(__("There were errors."));
					return;
				}
				dialog.hide();
				cur_frm.refresh();
			},
			btn: this
		})
	});
	dialog.show();

}

cur_frm.cscript.on_submit = function(doc, cdt, cdn) {
	if(cint(frappe.boot.notification_settings.quotation))
		cur_frm.email_doc(frappe.boot.notification_settings.quotation_message);
}

frappe.ui.form.on("Quotation Item", "items_on_form_rendered", function(frm, cdt, cdn) {
	// enable tax_amount field if Actual
})

frappe.ui.form.on("Quotation Item", "stock_balance", function(frm, cdt, cdn) {
	var d = frappe.model.get_doc(cdt, cdn);
	frappe.route_options = {"item_code": d.item_code};
	frappe.set_route("query-report", "Stock Balance");
})
<commit_msg>Set at lost translated in quotation (#10652)<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

{% include 'erpnext/selling/sales_common.js' %}

frappe.ui.form.on('Quotation', {
	setup: function(frm) {
		frm.custom_make_buttons = {
			'Sales Order': 'Make Sales Order'
		}
	},
	refresh: function(frm) {
		frm.trigger("set_label");
	},
	quotation_to: function(frm) {
		frm.trigger("set_label");
	},
	set_label: function(frm) {
		frm.fields_dict.customer_address.set_label(__(frm.doc.quotation_to + " Address"));
	}
});

erpnext.selling.QuotationController = erpnext.selling.SellingController.extend({
	onload: function(doc, dt, dn) {
		var me = this;
		this._super(doc, dt, dn);
		if(doc.customer && !doc.quotation_to)
			doc.quotation_to = "Customer";
		else if(doc.lead && !doc.quotation_to)
			doc.quotation_to = "Lead";

	},
	refresh: function(doc, dt, dn) {
		this._super(doc, dt, dn);
		doctype = doc.quotation_to == 'Customer' ? 'Customer':'Lead';
		frappe.dynamic_link = {doc: this.frm.doc, fieldname: doctype.toLowerCase(), doctype: doctype}

		var me = this;

		if (doc.__islocal) {
			this.frm.set_value('valid_till', frappe.datetime.add_months(doc.transaction_date, 1))
		}

		if(doc.docstatus == 1 && doc.status!=='Lost') {
			if(!doc.valid_till || frappe.datetime.get_diff(doc.valid_till, frappe.datetime.get_today()) > 0) {
				cur_frm.add_custom_button(__('Make Sales Order'),
					cur_frm.cscript['Make Sales Order']);
			}

			if(doc.status!=="Ordered") {
				cur_frm.add_custom_button(__('Set as Lost'),
					cur_frm.cscript['Declare Order Lost']);
			}
		}

		if (this.frm.doc.docstatus===0) {
			this.frm.add_custom_button(__('Opportunity'),
				function() {
					var setters = {};
					if(me.frm.doc.customer) {
						setters.customer = me.frm.doc.customer || undefined;
					} else if (me.frm.doc.lead) {
						setters.lead = me.frm.doc.lead || undefined;
					}
					erpnext.utils.map_current_doc({
						method: "erpnext.crm.doctype.opportunity.opportunity.make_quotation",
						source_doctype: "Opportunity",
						target: me.frm,
						setters: setters,
						get_query_filters: {
							status: ["not in", ["Lost", "Closed"]],
							company: me.frm.doc.company,
							// cannot set enquiry_type as setter, as the fieldname is order_type
							enquiry_type: me.frm.doc.order_type,
						}
					})
				}, __("Get items from"), "btn-default");
		}

		this.toggle_reqd_lead_customer();

	},

	quotation_to: function() {
		var me = this;
		if (this.frm.doc.quotation_to == "Lead") {
			this.frm.set_value("customer", null);
			this.frm.set_value("contact_person", null);
		} else if (this.frm.doc.quotation_to == "Customer") {
			this.frm.set_value("lead", null);
		}

		this.toggle_reqd_lead_customer();
	},

	toggle_reqd_lead_customer: function() {
		var me = this;

		this.frm.toggle_reqd("lead", this.frm.doc.quotation_to == "Lead");
		this.frm.toggle_reqd("customer", this.frm.doc.quotation_to == "Customer");

		// to overwrite the customer_filter trigger from queries.js
		this.frm.set_query('customer_address', erpnext.queries.address_query);
		this.frm.set_query('shipping_address_name', erpnext.queries.address_query);
	},

	tc_name: function() {
		this.get_terms();
	},

	validate_company_and_party: function(party_field) {
		if(!this.frm.doc.quotation_to) {
			frappe.msgprint(__("Please select a value for {0} quotation_to {1}", [this.frm.doc.doctype, this.frm.doc.name]));
			return false;
		} else if (this.frm.doc.quotation_to == "Lead") {
			return true;
		} else {
			return this._super(party_field);
		}
	},

	lead: function() {
		var me = this;
		if(!this.frm.doc.lead) {
			return;
		}

		frappe.call({
			method: "erpnext.crm.doctype.lead.lead.get_lead_details",
			args: {
				'lead': this.frm.doc.lead,
				'posting_date': this.frm.doc.transaction_date,
				'company': this.frm.doc.company,
			},
			callback: function(r) {
				if(r.message) {
					me.frm.updating_party_details = true;
					me.frm.set_value(r.message);
					me.frm.refresh();
					me.frm.updating_party_details = false;

				}
			}
		})
	}
});

cur_frm.script_manager.make(erpnext.selling.QuotationController);

cur_frm.fields_dict.lead.get_query = function(doc,cdt,cdn) {
	return{	query: "erpnext.controllers.queries.lead_query" }
}

cur_frm.cscript['Make Sales Order'] = function() {
	frappe.model.open_mapped_doc({
		method: "erpnext.selling.doctype.quotation.quotation.make_sales_order",
		frm: cur_frm
	})
}

cur_frm.cscript['Declare Order Lost'] = function(){
	var dialog = new frappe.ui.Dialog({
		title: __('Set as Lost'),
		fields: [
			{"fieldtype": "Text", "label": __("Reason for losing"), "fieldname": "reason",
				"reqd": 1 },
			{"fieldtype": "Button", "label": __("Update"), "fieldname": "update"},
		]
	});

	dialog.fields_dict.update.$input.click(function() {
		var args = dialog.get_values();
		if(!args) return;
		return cur_frm.call({
			method: "declare_order_lost",
			doc: cur_frm.doc,
			args: args.reason,
			callback: function(r) {
				if(r.exc) {
					frappe.msgprint(__("There were errors."));
					return;
				}
				dialog.hide();
				cur_frm.refresh();
			},
			btn: this
		})
	});
	dialog.show();

}

cur_frm.cscript.on_submit = function(doc, cdt, cdn) {
	if(cint(frappe.boot.notification_settings.quotation))
		cur_frm.email_doc(frappe.boot.notification_settings.quotation_message);
}

frappe.ui.form.on("Quotation Item", "items_on_form_rendered", function(frm, cdt, cdn) {
	// enable tax_amount field if Actual
})

frappe.ui.form.on("Quotation Item", "stock_balance", function(frm, cdt, cdn) {
	var d = frappe.model.get_doc(cdt, cdn);
	frappe.route_options = {"item_code": d.item_code};
	frappe.set_route("query-report", "Stock Balance");
})
<|endoftext|>


<commit_before>window.prepareFur = function() {
	var shells = 30;

	var materials = [];
	var meshes = [];

	var diffuseTexture = new BABYLON.Texture("textures/leopard_fur.jpg", scene);
	var heightTexture = new BABYLON.Texture("textures/speckles.jpg", scene);
	var furTexture = BABYLON.FurMaterial.GenerateTexture("furTexture", scene);

	var fur = new BABYLON.FurMaterial("fur0", scene);
	fur.furLength = 4;
	fur.furAngle = 0;
	fur.furColor = new BABYLON.Color3(0.2, 0.2, 0.2);
	fur.diffuseTexture = diffuseTexture;
	fur.furOffset = 0;
	fur.furTexture = furTexture;

	var setValue = function(property, value) {
		for (var i=0; i < materials.length; i++) {
			materials[i][property] = value;
		}
	}

	var resetFur = function() {
		for (var i=1; i < materials.length; i++) {
			materials[i].dispose();
		}
		for (var i=1; i < meshes.length; i++) {
			meshes[i].dispose();
		}

		materials = [];
		meshes = [];
	};

	var setMeshesVisible = function(visible) {
		for (var i=1; i < meshes.length; i++) {
			meshes[i].isVisible = visible;
		}
	}

	var configureFur = function(mesh, apply) {
		meshes = [mesh];
		materials = [fur];

		mesh.material = fur;

		for (var i = 1; i < shells; i++) {
			var offsetFur = new BABYLON.FurMaterial("fur" + i, scene);
			offsetFur.furLength = 4;
			offsetFur.furAngle = 0;
			offsetFur.furColor = new BABYLON.Color3(0.2, 0.2, 0.2);
			offsetFur.diffuseTexture = diffuseTexture;
			offsetFur.furOffset = i / shells;
			offsetFur.furTexture = furTexture;
			offsetFur.highLevelFur = fur.highLevelFur;
			materials.push(offsetFur);

			var offsetMesh = mesh.clone(mesh.name + i);
			offsetMesh.isVisible = fur.highLevelFur && apply;
			offsetMesh.material = offsetFur;
			offsetMesh.skeleton = mesh.skeleton;
			meshes.push(offsetMesh);
		}

		for (var i=0; i < scene.skeletons.length; i++) {
			scene.beginAnimation(scene.skeletons[i], 0, 100, true, 0.8);
		}
	}

	// fur length
    registerRangeUI("fur", "Fur length", 0, 45, function(value) {
		setValue("furLength", value);
    }, function() {
        return fur.furLength;
    });

	// fur angle
    registerRangeUI("fur", "Fur angle", 0, Math.PI/2, function(value) {
		setValue("furAngle", value);
    }, function() {
        return fur.furAngle;
    });

    // fur color
	registerColorPicker("fur", "Fur color", "#703605", function(value) {
		fur.furColor.r = value.r/255;
		fur.furColor.g = value.g/255;
		fur.furColor.b = value.b/255;
	}, function() {
		return fur.furColor;
	});

	var DTON = false;
	registerButtonUI("fur", "Tgl Diffuse Tex", function() {
		DTON = !DTON;
		setValue("diffuseTexture", DTON ? diffuseTexture : null);
	});

	var HTON = false;
	registerButtonUI("fur", "Tgl Height Tex", function() {
		HTON = !HTON;
		setValue("heightTexture", HTON ? heightTexture : null);
	});

	registerRangeUI("fur", "High Level fur", false, true, function(value) {
		setValue("highLevelFur", value);
		setMeshesVisible(value);
    }, function() {
        return fur.highLevelFur;
    });

	registerRangeUI("fur", "Fur Gravity", 0, 1, function(value) {
		setValue("furGravity", new BABYLON.Vector3(value, value,value));
    }, function() {
        return fur.furGravity.x;
    });

	// fur animation speed
    registerRangeUI("fur", "Fur speed", 1, 1000, function(value) {
		setValue("furSpeed", value);
    }, function() {
        return fur.furSpeed;
    });

	// fur animation speed
    registerRangeUI("fur", "Fur Spacing", 0, 20, function(value) {
		setValue("furSpacing", value);
    }, function() {
        return fur.furSpacing;
    });

    return {
		/*
		materials: furs,
		meshes: meshes
		*/
		material: fur,
		resetFur: function() {
			resetFur();
		},
		configureFur: function(mesh, apply) {
			configureFur(mesh, apply);
		}
	};
};<commit_msg>fixed addfur<commit_after>window.prepareFur = function() {
	var shells = 30;
	var meshes = [];

	var diffuseTexture = new BABYLON.Texture("textures/leopard_fur.jpg", scene);
	var heightTexture = new BABYLON.Texture("textures/speckles.jpg", scene);
	var furTexture = BABYLON.FurMaterial.GenerateTexture("furTexture", scene);

	var fur = new BABYLON.FurMaterial("fur", scene);
	fur.furLength = 4;
	fur.furAngle = 0;
	fur.furColor = new BABYLON.Color3(1.0, 1.0, 1.0);
	fur.diffuseTexture = diffuseTexture;
    fur.furTexture = furTexture;

    // Sets the same value to all shells
	var setValue = function(property, value) {
		for (var i=0; i < meshes.length; i++) {
			meshes[i].material[property] = value;
		}
	}

	var resetFur = function() {
		for (var i=1; i < meshes.length; i++) {
            meshes[i].material.dispose();
			meshes[i].dispose();
		}

		meshes = [];
	};

	var setMeshesVisible = function(visible) {
		for (var i=1; i < meshes.length; i++) {
			meshes[i].isVisible = visible;
		}
	}

	var configureFur = function(mesh) {
        mesh.material = fur;
        meshes = BABYLON.FurMaterial.FurifyMesh(mesh, shells);

        // For animated meshes
		for (var i=0; i < scene.skeletons.length; i++) {
			scene.beginAnimation(scene.skeletons[i], 0, 100, true, 0.8);
		}
	}

	// fur length
    registerRangeUI("fur", "Fur length", 0, 45, function(value) {
		setValue("furLength", value);
    }, function() {
        return fur.furLength;
    });

	// fur angle
    registerRangeUI("fur", "Fur angle", 0, Math.PI/2, function(value) {
		setValue("furAngle", value);
    }, function() {
        return fur.furAngle;
    });

    // fur color
	registerColorPicker("fur", "Fur color", "#703605", function(value) {
		fur.furColor.r = value.r/255;
		fur.furColor.g = value.g/255;
		fur.furColor.b = value.b/255;
	}, function() {
		return fur.furColor;
	});

	var DTON = false;
	registerButtonUI("fur", "Tgl Diffuse Tex", function() {
		DTON = !DTON;
		setValue("diffuseTexture", DTON ? diffuseTexture : null);
	});

	var HTON = false;
	registerButtonUI("fur", "Tgl Height Tex", function() {
		HTON = !HTON;
		setValue("heightTexture", HTON ? heightTexture : null);
	});

    // If High level fur
	registerRangeUI("fur", "Hight Level fur", false, true, function(value) {
		setValue("highLevelFur", value);
		setMeshesVisible(value);
    }, function() {
        return fur.highLevelFur;
    });

    // Fur density
    registerRangeUI("fur", "Fur Density", 1, 50, function(value) {
       setValue("furDensity", value);
    }, function() {
        return fur.furDensity;
    });

    // Fur Gravity
	registerRangeUI("fur", "Fur Gravity", 0, 1, function(value) {
		setValue("furGravity", new BABYLON.Vector3(value, value, value));
    }, function() {
        return fur.furGravity.x;
    });

	// Fur animation speed
    registerRangeUI("fur", "Fur speed", 1, 1000, function(value) {
		setValue("furSpeed", value);
    }, function() {
        return fur.furSpeed;
    });

	// Fur spacing
    registerRangeUI("fur", "Fur Spacing", 0, 20, function(value) {
		setValue("furSpacing", value);
    }, function() {
        return fur.furSpacing;
    });

    return {
		material: fur,
		resetFur: function() {
			resetFur();
		},
		configureFur: function(mesh) {
			configureFur(mesh);
		}
	};
};<|endoftext|>


<commit_before>"use strict";

/**
 * @constructor
 */
function SerialAdapter(element)
{
    var
        serial = this,
        send_char;

    this.enabled = true;

    this.init = function(code_fn)
    {
        this.destroy();

        send_char = code_fn;

        element.addEventListener("keypress", keypress_handler, false);
        element.addEventListener("keydown", keydown_handler, false);
        element.addEventListener("paste", paste_handler, false);
    };

    this.destroy = function()
    {
        element.removeEventListener("keypress", keypress_handler, false);
        element.removeEventListener("keydown", keydown_handler, false);
        element.removeEventListener("paste", paste_handler, false);
    };

    this.put_str = function(str)
    {
        if(str === "\x08")
        {
            var text = element.textContent;
            element.textContent = text.substr(0, text.length - 1);
        }
        else
        {
            element.textContent += str;

            if(str === "\n")
            {
                element.scrollTop = 1e9;
            }
        }
    }

    function may_handle(e)
    {
        if(!serial.enabled)
        {
            return false;
        }

        // Something here?

        return true;
    }

    function keypress_handler(e)
    {
        if(!may_handle(e))
        {
            return;
        }

        var chr = e.keyCode;

        send_char(chr);
        e.preventDefault();
    }

    function keydown_handler(e)
    {
        var chr = e.keyCode;

        if(chr === 8)
        {
            // supress backspace
            send_char(127);
            e.preventDefault();
        }
    }

    function paste_handler(e)
    {
        //console.log(e.clipboardData.getData('text/plain'));

        var data = e.clipboardData.getData('text/plain');

        for(var i = 0; i < data.length; i++)
        {
            send_char(data.charCodeAt(i));
        }

        e.preventDefault();
    }
}
<commit_msg>Use textarea.value over textContent<commit_after>"use strict";

/**
 * @constructor
 */
function SerialAdapter(element)
{
    var
        serial = this,
        send_char;

    this.enabled = true;

    this.init = function(code_fn)
    {
        this.destroy();

        send_char = code_fn;

        element.addEventListener("keypress", keypress_handler, false);
        element.addEventListener("keydown", keydown_handler, false);
        element.addEventListener("paste", paste_handler, false);
    };

    this.destroy = function()
    {
        element.removeEventListener("keypress", keypress_handler, false);
        element.removeEventListener("keydown", keydown_handler, false);
        element.removeEventListener("paste", paste_handler, false);
    };

    this.put_str = function(str)
    {
        if(str === "\x08")
        {
            var text = element.value;
            element.value = text.substr(0, text.length - 1);
        }
        else if(str === "\r")
        {
            // do nothing
        }
        else
        {
            element.value += str;

            if(str === "\n")
            {
                element.scrollTop = 1e9;
            }
        }
    }

    function may_handle(e)
    {
        if(!serial.enabled)
        {
            return false;
        }

        // Something here?

        return true;
    }

    function keypress_handler(e)
    {
        if(!may_handle(e))
        {
            return;
        }

        var chr = e.keyCode;

        send_char(chr);
        e.preventDefault();
    }

    function keydown_handler(e)
    {
        var chr = e.keyCode;

        if(chr === 8)
        {
            // supress backspace
            send_char(127);
            e.preventDefault();
        }
    }

    function paste_handler(e)
    {
        //console.log(e.clipboardData.getData('text/plain'));

        var data = e.clipboardData.getData('text/plain');

        for(var i = 0; i < data.length; i++)
        {
            send_char(data.charCodeAt(i));
        }

        e.preventDefault();
    }
}
<|endoftext|>


<commit_before>{
	"translatorID":"1b9ed730-69c7-40b0-8a06-517a89a3a278",
	"translatorType":4,
	"label":"Sudoc",
	"creator":"Sean Takats and Michael Berkowitz",
	"target":"^http://www\\.sudoc\\.abes\\.fr",
	"minVersion":"1.0.0b3.r1",
	"maxVersion":"",
	"priority":100,
	"inRepository":true,
	"lastUpdated":"2008-05-19 17:30:00"
}

function detectWeb(doc, url) {
		var namespace = doc.documentElement.namespaceURI;
		var nsResolver = namespace ? function(prefix) {
				if (prefix == 'x') return namespace; else return null;
		} : null;

		var xpath = '//table/tbody/tr/td[1][@class="preslabel"]/strong';
		var multxpath = '//a[@id="InitialFocusPoint"]';
		var elt;

		if (elt = doc.evaluate(multxpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext()) {
				return "multiple";
		}
		else if (elt = doc.evaluate(xpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext())
		{
				var contenu = elt.textContent;
				var numRegexp = /(Num.ro.de.notice|Record.number)/;
				var m = numRegexp.exec(contenu);
				if (m) {
						// On a bien une notice d"ouvrage, on doit chercher limage
						// pour choisir le type de document
						var imgXpath = '/html/body/table/tbody/tr/td[1]/p/img/@src';
						var imgsrc = doc.evaluate(imgXpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().nodeValue;
						if (imgsrc){
								if (imgsrc.indexOf("icon_per.gif") > 0){
										return "book";
								} else if (imgsrc.indexOf("icon_books.gif") > 0){
										return "book";
								} else if (imgsrc.indexOf("icon_thesis.gif") > 0){
										return "thesis";
								} else if (imgsrc.indexOf("icon_art.gif") > 0){
										return "journalArticle";
								} else {
										return "book";
								}
						}
				}
		}
}

function scrape(doc) {
		var namespace = doc.documentElement.namespaceURI;
		var nsResolver = namespace ? function(prefix) {
				if (prefix == 'x') return namespace; else return null;
		} : null;

		var rowXpath = '//tr[td[@class="preslabel"]]';
		var tableRows = doc.evaluate(rowXpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
		var tableRow;

		var newItem = new Zotero.Item();
		// TODO add other item types using detectWeb's icon checking code
		newItem.itemType = "book";
		var imgXpath = '/html/body/table/tbody/tr/td[1]/p/img/@src';
		var imgsrc = doc.evaluate(imgXpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().nodeValue;
		if (imgsrc){
				if (imgsrc.indexOf("icon_per.gif") > 0){
						newItem.itemType = "book";
				} else if (imgsrc.indexOf("icon_books.gif") > 0){
						newItem.itemType = "book";
				} else if (imgsrc.indexOf("icon_thesis.gif") > 0){
						newItem.itemType = "thesis";
				} else if (imgsrc.indexOf("icon_art.gif") > 0){
						newItem.itemType = "journalArticle";
				} else {
						newItem.itemType = "book";
				}
		} else {
				newItem.itemType = "book";
		}
		while (tableRow = tableRows.iterateNext())
		{
				var field = doc.evaluate('./td[1]', tableRow, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
				var value = doc.evaluate('./td[2]', tableRow, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
				field = Zotero.Utilities.superCleanString(field);
				field = field.replace(/(\(s\))?\s*:\s*$/, "");
				if (field == "Titre" || field == "Title"){
						Zotero.debug("title = " + value);
						value = value.replace(/(\[[^\]]+\])/g,"");
						newItem.title = value.split(" / ")[0];
				}
				if (field.substr(0,6) == "Auteur" || field.substr(0,6) == "Author"){
						var authors = doc.evaluate('./td[2]/a', tableRow, nsResolver, XPathResult.ANY_TYPE, null);
						var author;
						while (author = authors.iterateNext()){
								var authorText = author.textContent;
								var authorParts = authorText.split(" (");
								newItem.creators.push(Zotero.Utilities.cleanAuthor(authorParts[0], "author", true));
						}
				}
				if (field.substr(0,4) == "Date"){
						newItem.date = value;
				}
				if (field.substr(0,7)  == "Editeur" || field.substr(0,9)  == "Publisher"){
						var pubParts = value.split(" : ");
						newItem.place = pubParts[0];
						// needs error checking below to avoid error
						if (pubParts[1] ) {
								pubParts = pubParts[1].split(", ");
								newItem.publisher = pubParts[0];
						}
				}
				if (field.substr(0,4) == "ISBN" || field.substr(0,4) == "ISSN"){
						newItem.ISBN = value.split(" (")[0];
				}
				if (field == "Description") {
						var m = value.match(/([0-9]+) (?:[pP])/);
						if (m) {
								newItem.pages = m[1];
						}
				}
				if (field.substr(0,5) == "Serie" || field.substr(0,10) == "Collection"){
						newItem.series = value;
				}
				if (field.substr(0,6) == "Sujets" || field.substr(0,8) == "Subjects"){
						var subjectElmts = doc.evaluate('./td[2]/a', tableRow, nsResolver, XPathResult.ANY_TYPE, null);
						var subject;
						var subjects;
						while (subject = subjectElmts.iterateNext()){
								subjects = subject.textContent.split(" -- ");
								newItem.tags = newItem.tags.concat(subjects);
						}
				}
				if (field == "In" || field == "Dans"){
						var jtitle = value.replace(/(\[[^\]]+\])/g,"");
						jtitle = jtitle.split(" / ")[0];
						jtitle = jtitle.split(" - ")[0];
						newItem.publicationTitle = jtitle;
						//get page numbers
						var m = value.match(/(?:[Pp]\. )([0-9\-]+)/);
						if (m) {
								newItem.pages = m[1];
						}
						//get ISBN or ISSN
						m = value.match(/(?:ISSN|ISBN) ([0-9Xx\-]+)/);
						if (m) {
								newItem.ISBN = m[1];
								newItem.ISSN = m[1];
						}
						// publicationTitle, issue/volume
				}
				// TODO Pages, Notes, Description, Language, Annexes
		}
		newItem.complete();
}

function doWeb(doc, url) {
		var namespace = doc.documentElement.namespaceURI;
		var nsResolver = namespace ? function(prefix) {
				if (prefix == 'x') return namespace; else return null;
		} : null;

		var multxpath = '//a[@id="InitialFocusPoint"]';
		var elt;

		if (elt = doc.evaluate(multxpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext()) {
				var newUrl = doc.evaluate('//base/@href', doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().nodeValue;
				var xpath = '//tr/td[3]/a';
				var elmts = doc.evaluate(xpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
				var elmt = elmts.iterateNext();
				var links = new Array();
				var availableItems = new Array();
				var i = 0;
				do {
						var link = doc.evaluate('./@href', elmt, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().nodeValue;
						var searchTitle = elmt.textContent;
						availableItems[i] = searchTitle;
						links[i] = link;
						i++;
				} while (elmt = elmts.iterateNext());
				var items = Zotero.selectItems(availableItems);

				if(!items) {
						return true;
				}
				var uris = new Array();
				for(var i in items) {
						uris.push(newUrl + links[i]);
				}
				Zotero.Utilities.processDocuments(uris, function(doc) { scrape(doc) },
						function() { Zotero.done(); }, null);
				Zotero.wait();
		}
		else {
				scrape(doc);
		}
}<commit_msg>updating Sudoc.js with sylvain's changes<commit_after>{
	"translatorID":"1b9ed730-69c7-40b0-8a06-517a89a3a278",
	"translatorType":4,
	"label":"Sudoc",
	"creator":"Sean Takats and Michael Berkowitz, updated by Sylvain Machefert",
	"target":"^http://www\\.sudoc\\.abes\\.fr",
	"minVersion":"1.0.0b3.r1",
	"maxVersion":"",
	"priority":100,
	"inRepository":true,
	"lastUpdated":"2008-05-19 17:30:00"
}

function detectWeb(doc, url) {
		var namespace = doc.documentElement.namespaceURI;
		var nsResolver = namespace ? function(prefix) {
				if (prefix == 'x') return namespace; else return null;
		} : null;

		var multxpath = '/html/body/div[2]/div/span';
		if (elt = doc.evaluate(multxpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext()) {
				var content = elt.textContent;
				if ( (content == "Résultats") || (content == "Results") )
				{
					return "multiple";
				}
				else if ( (content == "Notice complète") || (content == "title data") )
				{
					var xpathimage = '/html/body/div[2]/div[4]/span/img';
					if (elt = doc.evaluate(xpathimage, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext())
					{
						var type = elt.getAttribute('src');
						if (type.indexOf('article.gif') > 0)
						{
							return "journalArticle";
						}
						else if (type.indexOf('book.gif') > 0)
						{
							return "book";
						}
						else if (type.indexOf('handwriting.gif') > 0)
						{
							return "manuscript";
						}
						else if (type.indexOf('sons.gif') > 0)
						{
							return "audioRecording";
						}
						else if (type.indexOf('sound.gif') > 0)
						{
							return "audioRecording";
						}
						else if (type.indexOf('thesis.gif') > 0)
						{
							return "thesis";
						}
						else if (type.indexOf('map.gif') > 0)
						{
							return "map";
						}
						else
						{
							return "book";
						}
					}
				}
		}
}

function scrape(doc) {
		var namespace = doc.documentElement.namespaceURI;
		var nsResolver = namespace ? function(prefix) {
				if (prefix == 'x') return namespace; else return null;
		} : null;

		var zXpath = '/html/body/span[@class="Z3988"]';
		var eltCoins = doc.evaluate(zXpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
		if (eltCoins = doc.evaluate(zXpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext())
		{
			var coins = eltCoins.getAttribute('title');

			var newItem = new Zotero.Item();
			newItem.repository = false;	// do not save repository
			if(Zotero.Utilities.parseContextObject(coins, newItem))
			{
				if (newItem.title)
				{
					// We use the same method as in detectWeb to find
					// the real type of document
					var xpathimage = '/html/body/div[2]/div[4]/span/img';
					if (elt = doc.evaluate(xpathimage, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext())
					{
						var type = elt.getAttribute('src');
						var ZoteroType = '';
						if (type.indexOf('article.gif') > 0)
						{
							zoteroType = 'journalArticle';
						}
						else if (type.indexOf('book.gif') > 0)
						{
							zoteroType = 'book';
						}
						else if (type.indexOf('handwriting.gif') > 0)
						{
							zoteroType = 'manuscript';
						}
						else if (type.indexOf('sons.gif') > 0)
						{
							zoteroType = "audioRecording";
						}
						else if (type.indexOf('sound.gif') > 0)
						{
							zoteroType = "audioRecording";
						}
						else if (type.indexOf('thesis.gif') > 0)
						{
							zoteroType = "thesis";
						}
						else if (type.indexOf('map.gif') > 0)
						{
							zoteroType = "map";
						}
						else
						{
							zoteroType = "book";
						}
						newItem.itemType = zoteroType;
					}

					// 	We need to correct some informations where COinS is wrong
					var rowXpath = '//tr[td[@class="rec_lable"]]';
					var tableRows = doc.evaluate(rowXpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
					var tableRow;

					while (tableRow = tableRows.iterateNext())
					{
						var field = doc.evaluate('./td[1]', tableRow, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
						var value = doc.evaluate('./td[2]', tableRow, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
						field = Zotero.Utilities.superCleanString(field);
						field = field.replace(/(\(s\))?\s*:\s*$/, "");

						// With COins, only one author is taken, changed.
						if (field.substr(0,6) == "Auteur" || field.substr(0,6) == "Author")
						{
							var authors = doc.evaluate('./td[2]/div', tableRow, nsResolver, XPathResult.ANY_TYPE, null);
							newItem.creators = new Array();
							while (author = authors.iterateNext())
							{
								var authorText = author.textContent;

								authorFunction = authorText.split(". ")[1];
								authorText = authorText.split(". ")[0];
								if (authorFunction)
								{
									authorFunction = Zotero.Utilities.superCleanString(authorFunction);
								}
								var zoteroFunction = '';
								// TODO : Add other authotiry types
								if (authorFunction == 'Traduction')
								{
									zoteroFunction = 'Translator';
								}
								else
								{
									zoteroFunction = 'Author';
								}
								newItem.creators.push(Zotero.Utilities.cleanAuthor(authorText, zoteroFunction, true));
							}
						}
						// The serie isn't in COinS
						else 	if (field.substr(0,5) == "Serie" || field.substr(0,10) == "Collection")
						{
							newItem.series = value;
						}
						// When there's a subtitle, only main title is used !
						else if (field == "Titre" || field == "Title")
						{
							var title = '';
							var titles = doc.evaluate('./td[2]/div/span', tableRow, nsResolver, XPathResult.ANY_TYPE, null);
							while (partTitle = titles.iterateNext())
							{
								partTitle = partTitle.textContent;
								partTitle = partTitle.replace(/(\[[^\]]+\] ?)/g,"");
								title = title + partTitle;
							}
							// Remove the author
							title = title.split(" / ")[0];
							newItem.title = title;
						}
						// Language not defined in COinS
						else if ( (field == "Langue") || (field == "Language") )
						{
							newItem.language = value;
						}
						else if ( (field == "Résumé") || (field == "Abstract") )
						{
							if (newItem.abstractNote)
							{
								newItem.abstractNote = newItem.abstractNote + " " + value;
							}
							else
							{
								newItem.abstractNote = value;
							}

						}
						else if (field == "Notes")
						{
							if (newItem.abstractNote)
							{
								newItem.abstractNote = newItem.abstractNote + " " + value;
							}
							else
							{
								newItem.abstractNote = value;
							}
						}
					}
					newItem.complete();
				}
			}
		}
}

function doWeb(doc, url) {
		var namespace = doc.documentElement.namespaceURI;
		var nsResolver = namespace ? function(prefix) {
				if (prefix == 'x') return namespace; else return null;
		} : null;

		var multxpath = '/html/body/div[2]/div/span';
		if (elt = doc.evaluate(multxpath, doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext()) {
				var content = elt.textContent;
				if ( (content == "Résultats") || (content == "Results") )
				{
					var newUrl = doc.evaluate('//base/@href', doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().nodeValue;
					var xpath = '/html/body/div[2]/table/tbody/tr/td[3]/div/a';
					var elmts = doc.evaluate(xpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
					var elmt = elmts.iterateNext();
					var links = new Array();
					var availableItems = new Array();
					var i = 0;
					do {
						var link = doc.evaluate('./@href', elmt, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().nodeValue;
						var searchTitle = elmt.textContent;
						availableItems[i] = searchTitle;
						links[i] = link;
						i++;
					} while (elmt = elmts.iterateNext());
					var items = Zotero.selectItems(availableItems);

					if(!items) {
						return true;
					}

					var uris = new Array();
					for(var i in items) {
							uris.push(newUrl + links[i]);
							Zotero.debug(newUrl + links[i]);
					}
					Zotero.Utilities.processDocuments(uris, function(doc) { scrape(doc) },
							function() { Zotero.done(); }, null);
					Zotero.wait();
				}
				else if ( (content == "Notice complète") || (content == 'title data') )
				{
					scrape(doc);
				}
		}
}
<|endoftext|>


<commit_before>define(['db', 'eventHub', 'request', 'lobro'], function (db, eventHub, request, lobro) {
    'use strict';

    return new Promise(function (resolve/*, reject*/) {
        // create a model (database) named Products
        var model = db.createDB('Products');
        // enable model events
        model = eventHub.connect(model);
        // enable localStorage
        model = lobro.connect(model);
        // check if we already have the data
        if (model.getLocal('Products')) {
            // load localStorage data into the model
            model.sync('Products');
            // resolve and pass the model to the handler
            resolve(model);
            // when using eventHub with lobro, we can enable events so lobro will auto-update localStorage when data changes
            model.enableEvents();
        } else {
            request('devices.json').then(function (deviceData) {
                // get the XHR response into the deviceData argument
                // parse response json and grab the devices array
                var allData = JSON.parse(deviceData['response'])['devices'];
                // create a table called devices
                model.createTable('Devices');
                // copy the data array from the server into the Table
                // converts a collection of objects to relational structure
                model.insertJsonInto('Devices')(allData);
                // resolve and pass the model to the handler
                resolve(model);
                if (model.enableEvents) {
                    model.persist(db);
                    model.enableEvents();
                }
            });
        }
    });
});
<commit_msg>demo bug fix<commit_after>define(['db', 'eventHub', 'request', 'lobro'], function (db, eventHub, request, lobro) {
    'use strict';

    return new Promise(function (resolve/*, reject*/) {
        // create a model (database) named Products
        var model = db.createDB('Products');
        // enable model events
        model = eventHub.connect(model);
        // enable localStorage
        model = lobro.connect(model);
        // check if we already have the data
        if (model.getLocal('Products')) {
            // load localStorage data into the model
            model.sync('Products');
            // when using eventHub with lobro, we can enable events so lobro will auto-update localStorage when data changes
            model.enableEvents();
            // resolve and pass the model to the handler
            resolve(model);
        } else {
            request('devices.json').then(function (deviceData) {
                // get the XHR response into the deviceData argument
                // parse response json and grab the devices array
                var allData = JSON.parse(deviceData['response'])['devices'];
                // create a table called devices
                model.createTable('Devices');
                // copy the data array from the server into the Table
                // converts a collection of objects to relational structure
                model.insertJsonInto('Devices')(allData);
                if (model.enableEvents) {
                    model.persist(model);
                    model.enableEvents();
                }
                // resolve and pass the model to the handler
                resolve(model);
            });
        }
    });
});
<|endoftext|>


<commit_before>/**
 * Given a string, find the first non-repeating character in it and return it's
 * index. If it doesn't exist, return -1.
 *
 * Examples:
 *
 *  s = "leetcode"
 *  return 0.
 *
 *  s = "loveleetcode",
 *  return 2.
 *
 * Note: You may assume the string contain only lowercase letters.
 *
 * Solution Reference:
 *  https://discuss.leetcode.com/topic/55148/java-7-lines-solution-29ms
 *
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function(s) {
    const occurances = [];
    const charCodeBase = 'a'.charCodeAt(0)

    // collect character occurances
    for (let i = 0; i < s.length; i++) {
	let position = s.charCodeAt(i) - charCodeBase;
        if (!occurances[position]) occurances[position] = 1
        else occurances[position]++;

    }
    // find the first unique character
    for (let i = 0; i < s.length; i++)
        if (occurances[s.charCodeAt(i) - charCodeBase] === 1) return i;

    return -1;
};
<commit_msg>correct typo<commit_after>/**
 * Given a string, find the first non-repeating character in it and return it's
 * index. If it doesn't exist, return -1.
 *
 * Examples:
 *
 *  s = "leetcode"
 *  return 0.
 *
 *  s = "loveleetcode",
 *  return 2.
 *
 * Note: You may assume the string contain only lowercase letters.
 *
 * Solution Reference:
 *  https://discuss.leetcode.com/topic/55148/java-7-lines-solution-29ms
 *
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function(s) {
    const occurrences = [];
    const charCodeBase = 'a'.charCodeAt(0)

    // collect character occurances
    for (let i = 0; i < s.length; i++) {
	let position = s.charCodeAt(i) - charCodeBase;
        if (!occurrences[position]) occurrences[position] = 1
        else occurrences[position]++;

    }
    // find the first unique character
    for (let i = 0; i < s.length; i++)
        if (occurrences[s.charCodeAt(i) - charCodeBase] === 1) return i;

    return -1;
};
<|endoftext|>


<commit_before>$.widget('boom.assetManager', {
	baseUrl : '/cms/assets/',
	listUrl : '/cms/assets/list',
	filters : {
		page : 1
	},

	selected : [],

	tag : 0,
	sortby : '',

	addFilter : function(type, value) {
		this.filters.page = 1;
		this.filters[type] = value;
	},

	assetsUploaded : function(assetIds) {
		var assetManager = this;

		assetManager.getAssets();
		assetManager.uploader.hide();
	},

	bind : function() {
		var assetManager = this;

		this.bindContentArea();
		this.bindMenuButtons();

		this.uploader
			.assetUploader({
				done : function(e, data) {
					assetManager.assetsUploaded(data.result);
				}
			});
	},

	bindContentArea : function() {
		var assetManager = this;

		this.element
			.on('change', '#b-assets-sortby', function(event) {
				assetManager.sortBy(this.value);
			})
			.on('change', '#b-assets-types', function(event) {
				if (this.selectedIndex) {
					assetManager.addFilter('type', this.options[this.selectedIndex].innerHTML);
				} else {
					assetManager.addFilter('type', '');
				}

				assetManager.getAssets();
			})
			.on('click', '#b-assets-all', function(event) {
				assetManager.removeFilters();
				assetManager.getAssets();
			})
			.on('click', '.thumb a', function(event) {
				event.preventDefault();

				var $this = $(this);

				assetManager.select($this.attr('href').replace('#asset/', ''));
				$this.parent().parent().toggleClass('selected');
			})
			.on('focus', '#b-assets-filter-title, #b-tags-search input', function() {
				var $this = $(this);

				if ($this.val() == $this.attr('placeholder')) {
					$this.val('');
				}
			})
			.on('blur', '#b-assets-filter-title, #b-tags-search input', function() {
				var $this = $(this);

				if ($this.val() == '') {
					$this.val($this.attr('placeholder'));
				}
			});

		this.titleFilter = this.element
			.find('#b-assets-filter-title')
			.assetTitleFilter({
				search : function(event, ui) {
					assetManager.addFilter('title', $(this).val());
					assetManager.getAssets();
				},
				select : function(event, ui) {
					assetManager.addFilter('title', ui.item.value);
					assetManager.getAssets();
				}
			});

		this.element.find('#b-tags-search')
			.tagger_search({
				update : function(tagIds) {
					assetManager.addFilter('tag', tagIds);
					assetManager.getAssets();
				}
			});
	},

	bindMenuButtons : function() {
		var assetManager = this;

		this.menu
			.on('click', '#b-button-multiaction-delete', function() {
				var asset = new boomAsset(assetManager.selected.join('-'));

				asset.delete()
					.done(function() {
						assetManager.getAssets();
						assetManager.clearSelection();
				});
			})
			.on('click', '#b-button-multiaction-edit', function() {
				assetManager.viewAsset(assetManager.selected.join('-'));
				assetManager.clearSelection();
			})
			.on('click', '#b-button-multiaction-download', function() {
				var asset = new boomAsset(assetManager.selected.join('-'));

				asset.download();
			})
			.on('click', '#b-button-multiaction-clear', function() {
				assetManager.clearSelection();
			})
			.on('click', '#b-button-multiaction-tag', function() {
				var asset = new boomAsset(assetManager.selected.join('-')),
					dialog;

				dialog = new boomDialog({
					url: '/cms/tags/asset/list/' + asset.id,
					title: 'Asset tags',
					width: 440,
					cancelButton : false,
					onLoad: function() {
						$('#b-tags').tagger({
							type: 'asset',
							id: asset.id
						});
					}
				});
			})
			.on('click', '#b-assets-upload', function() {
				assetManager.uploader.show();
			});
	},

	clearSelection : function() {
		this.selected = [];
		this.toggleButtons();

		this.element.find('#b-assets-view-thumbs div').removeClass('selected');
	},

	_create : function() {
		this.menu = this.element.find('#b-topbar');
		this.uploader = this.element.find('#b-assets-upload-form');
		this.bind();

		this.getAssets();
	},

	getAssets : function() {
		var assetManager = this;

		$.post(this.listUrl, this.filters)
			.done(function(response) {
				var $response = $(response);

				assetManager.element
					.find('#b-assets-view-thumbs')
					.replaceWith($response.find('#b-assets-view-thumbs'));

				assetManager.element
					.find('#b-assets-view-thumbs')
					.justifyAssets();

				assetManager.element
					.find('.pagination')
					.replaceWith($response[2]);

				assetManager.initPagination();
				assetManager.clearSelection();
			});
	},

	getPage : function(page) {
		if (this.filters.page !== page) {
			this.addFilter('page', page);
			this.getAssets();
		}
	},

	initPagination : function() {
		var assetManager = this;

		assetManager.element.find('.pagination')
			.jqPagination({
				paged: function(page) {
					assetManager.getPage(page);
				}
			});
	},

	removeFilters : function() {
		this.filters = {
			page : 1
		};

		this.element.find('#b-assets-types').val(0);

		var $title = this.element.find('#b-assets-filter-title');
		$title.val($title.attr('placeholder'));

		this.getAssets();
	},

	select : function(asset_id) {
		var index = this.selected.indexOf(asset_id);

		if (index == -1) {
			this.selected.push(asset_id);
		} else {
			this.selected.splice(index, 1);
		}

		this.toggleButtons();
	},

	sortBy : function(sort) {
		this.sortby = sort;
		this.getAssets();
	},

	toggleButtons : function() {
		var buttons = $('[id|=b-button-multiaction]').not('#b-button-multiaction-edit');
		$('#b-button-multiaction-edit').button(this.selected.length == 1 ? 'enable' : 'disable');
		buttons.button(this.selected.length > 0 ? 'enable' : 'disable');
	},

	viewAsset : function(assetId) {
		var asset = new boomAsset(assetId),
			assetManager = this,
			dialog;

		dialog = new boomDialog({
			title : 'Edit Asset',
			url : this.baseUrl + 'view/' + assetId,
			width: document.documentElement.clientWidth >= 1000? '1000px' : '100%',
		})
		.done(function() {
			asset
				.save(dialog.contents.find('form').serialize())
				.done(function() {
					new boomNotification("Asset details saved");
				});
		});

		dialog.contents
			.on('click', '.b-assets-delete', function() {
				asset
					.delete()
					.done(function() {
						dialog.close();
						assetManager.getAssets();
					});
			})
			.on('click', '.b-assets-download', function(e) {
				e.preventDefault();
				asset.download();
			})
			.on('focus', '#thumbnail', function() {
				var $this = $(this),
					picker;
				picker = new boomAssetPicker($this.val())
					.done(function(assetId) {
						$this.val(assetId);
					});
			})
			.find('#b-tags')
			.tagger({
				type: 'asset',
				id: asset.id
			});
	}
});<commit_msg>Fixed sorting assets in asset manager<commit_after>$.widget('boom.assetManager', {
	baseUrl : '/cms/assets/',
	listUrl : '/cms/assets/list',
	postData : {
		page : 1
	},

	selected : [],

	tag : 0,
	sortby : '',

	addFilter : function(type, value) {
		this.postData.page = 1;
		this.postData[type] = value;
	},

	assetsUploaded : function(assetIds) {
		var assetManager = this;

		assetManager.getAssets();
		assetManager.uploader.hide();
	},

	bind : function() {
		var assetManager = this;

		this.bindContentArea();
		this.bindMenuButtons();

		this.uploader
			.assetUploader({
				done : function(e, data) {
					assetManager.assetsUploaded(data.result);
				}
			});
	},

	bindContentArea : function() {
		var assetManager = this;

		this.element
			.on('change', '#b-assets-sortby', function(event) {
				assetManager.sortBy(this.value);
			})
			.on('change', '#b-assets-types', function(event) {
				if (this.selectedIndex) {
					assetManager.addFilter('type', this.options[this.selectedIndex].innerHTML);
				} else {
					assetManager.addFilter('type', '');
				}

				assetManager.getAssets();
			})
			.on('click', '#b-assets-all', function(event) {
				assetManager.removeFilters();
				assetManager.getAssets();
			})
			.on('click', '.thumb a', function(event) {
				event.preventDefault();

				var $this = $(this);

				assetManager.select($this.attr('href').replace('#asset/', ''));
				$this.parent().parent().toggleClass('selected');
			})
			.on('focus', '#b-assets-filter-title, #b-tags-search input', function() {
				var $this = $(this);

				if ($this.val() == $this.attr('placeholder')) {
					$this.val('');
				}
			})
			.on('blur', '#b-assets-filter-title, #b-tags-search input', function() {
				var $this = $(this);

				if ($this.val() == '') {
					$this.val($this.attr('placeholder'));
				}
			});

		this.titleFilter = this.element
			.find('#b-assets-filter-title')
			.assetTitleFilter({
				search : function(event, ui) {
					assetManager.addFilter('title', $(this).val());
					assetManager.getAssets();
				},
				select : function(event, ui) {
					assetManager.addFilter('title', ui.item.value);
					assetManager.getAssets();
				}
			});

		this.element.find('#b-tags-search')
			.tagger_search({
				update : function(tagIds) {
					assetManager.addFilter('tag', tagIds);
					assetManager.getAssets();
				}
			});
	},

	bindMenuButtons : function() {
		var assetManager = this;

		this.menu
			.on('click', '#b-button-multiaction-delete', function() {
				var asset = new boomAsset(assetManager.selected.join('-'));

				asset.delete()
					.done(function() {
						assetManager.getAssets();
						assetManager.clearSelection();
				});
			})
			.on('click', '#b-button-multiaction-edit', function() {
				assetManager.viewAsset(assetManager.selected.join('-'));
				assetManager.clearSelection();
			})
			.on('click', '#b-button-multiaction-download', function() {
				var asset = new boomAsset(assetManager.selected.join('-'));

				asset.download();
			})
			.on('click', '#b-button-multiaction-clear', function() {
				assetManager.clearSelection();
			})
			.on('click', '#b-button-multiaction-tag', function() {
				var asset = new boomAsset(assetManager.selected.join('-')),
					dialog;

				dialog = new boomDialog({
					url: '/cms/tags/asset/list/' + asset.id,
					title: 'Asset tags',
					width: 440,
					cancelButton : false,
					onLoad: function() {
						$('#b-tags').tagger({
							type: 'asset',
							id: asset.id
						});
					}
				});
			})
			.on('click', '#b-assets-upload', function() {
				assetManager.uploader.show();
			});
	},

	clearSelection : function() {
		this.selected = [];
		this.toggleButtons();

		this.element.find('#b-assets-view-thumbs div').removeClass('selected');
	},

	_create : function() {
		this.menu = this.element.find('#b-topbar');
		this.uploader = this.element.find('#b-assets-upload-form');
		this.bind();

		this.getAssets();
	},

	getAssets : function() {
		var assetManager = this;

		$.post(this.listUrl, this.postData)
			.done(function(response) {
				var $response = $(response);

				assetManager.element
					.find('#b-assets-view-thumbs')
					.replaceWith($response.find('#b-assets-view-thumbs'));

				assetManager.element
					.find('#b-assets-view-thumbs')
					.justifyAssets();

				assetManager.element
					.find('.pagination')
					.replaceWith($response[2]);

				assetManager.initPagination();
				assetManager.clearSelection();
			});
	},

	getPage : function(page) {
		if (this.postData.page !== page) {
			this.addFilter('page', page);
			this.getAssets();
		}
	},

	initPagination : function() {
		var assetManager = this;

		assetManager.element.find('.pagination')
			.jqPagination({
				paged: function(page) {
					assetManager.getPage(page);
				}
			});
	},

	removeFilters : function() {
		this.postData = {
			page : 1
		};

		this.element.find('#b-assets-types').val(0);

		var $title = this.element.find('#b-assets-filter-title');
		$title.val($title.attr('placeholder'));

		this.getAssets();
	},

	select : function(asset_id) {
		var index = this.selected.indexOf(asset_id);

		if (index == -1) {
			this.selected.push(asset_id);
		} else {
			this.selected.splice(index, 1);
		}

		this.toggleButtons();
	},

	sortBy : function(sort) {
		this.postData['sortby'] = sort;
		this.getAssets();
	},

	toggleButtons : function() {
		var buttons = $('[id|=b-button-multiaction]').not('#b-button-multiaction-edit');
		$('#b-button-multiaction-edit').button(this.selected.length == 1 ? 'enable' : 'disable');
		buttons.button(this.selected.length > 0 ? 'enable' : 'disable');
	},

	viewAsset : function(assetId) {
		var asset = new boomAsset(assetId),
			assetManager = this,
			dialog;

		dialog = new boomDialog({
			title : 'Edit Asset',
			url : this.baseUrl + 'view/' + assetId,
			width: document.documentElement.clientWidth >= 1000? '1000px' : '100%',
		})
		.done(function() {
			asset
				.save(dialog.contents.find('form').serialize())
				.done(function() {
					new boomNotification("Asset details saved");
				});
		});

		dialog.contents
			.on('click', '.b-assets-delete', function() {
				asset
					.delete()
					.done(function() {
						dialog.close();
						assetManager.getAssets();
					});
			})
			.on('click', '.b-assets-download', function(e) {
				e.preventDefault();
				asset.download();
			})
			.on('focus', '#thumbnail', function() {
				var $this = $(this),
					picker;
				picker = new boomAssetPicker($this.val())
					.done(function(assetId) {
						$this.val(assetId);
					});
			})
			.find('#b-tags')
			.tagger({
				type: 'asset',
				id: asset.id
			});
	}
});<|endoftext|>


<commit_before>// Quantimodo.com JavaScript API v1.1.8.
// Requires JQuery.
Quantimodo = function () {

    var hostUrl = apiHost + '/api/';

    var GET = function (baseURL, allowedParams, params, successHandler, disableLooping) {
        if (accessToken) {
            var urlParams = [];
            for (var key in params) {
                if (jQuery.inArray(key, allowedParams) == -1) {
                    throw 'invalid parameter; allowed parameters: ' + allowedParams.toString();
                }
                urlParams.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));
            }

            var results = [];

            fetchAPI(0);

        } else {
            console.warn('No access token. Now will try to authenticate and to get it');
            window.location.href = '?connect=quantimodo';
        }

        function fetchAPI(offset) {

            var url = hostUrl;

            if (urlParams.length == 0) {
                url += baseURL + '?offset=' + offset + '&limit=200';
            } else {
                url += baseURL + '?' + urlParams.join('&') + '&offset=' + offset + '&limit=200';
            }
            console.debug('Fecthing: ' + url);
            jQuery.ajax({
                type: 'GET',
                url: url,
                dataType: 'json',
                contentType: 'application/json',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
                    if (typeof mashapeKey !== 'undefined' && mashapeKey) {
                        xhr.setRequestHeader('X-Mashape-Key', mashapeKey);
                    }
                },
                success: function (data, status, xhr) {

                    if (data.constructor === Array && !disableLooping) {
                        console.debug('Fetched: ' + data.length + ' items');
                        if (data.length > 0) {
                            results = results.concat(data);
                            fetchAPI(results.length);
                        } else {
                            successHandler(results);
                        }
                    } else {
                        successHandler(data)
                    }
                }
            });
        }
    };

    var POST = function (baseURL, requiredFields, items, successHandler) {
        console.debug('POST API Call');
        if (accessToken) {
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                for (var j = 0; j < requiredFields.length; j++) {
                    if (!(requiredFields[j] in item)) {
                        throw 'missing required field in POST data; required fields: ' + requiredFields.toString();
                    }
                }
            }
            jQuery.ajax({
                type: 'POST',
                url: hostUrl + baseURL,
                contentType: 'application/json',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
                    if (typeof mashapeKey !== 'undefined' && mashapeKey) {
                        xhr.setRequestHeader('X-Mashape-Key', mashapeKey);
                    }
                },
                data: JSON.stringify(items),
                dataType: 'json',
                success: successHandler
            });
        } else {
            console.warn('No access token. Now will try to authenticate and to get it');
            window.location.href = '?connect=quantimodo';
        }
    };

    var localCache = {

        timeOut: 1000 * 420,    //cache valid for 7 minutes
        cacheKeysPrefix: 'qmwp_cache_',

        exist: function (key) {
            if (localStorage.getItem(localCache.cacheKeysPrefix + key)) {

                var cachedData = JSON.parse(localStorage.getItem(localCache.cacheKeysPrefix + key));

                return new Date().getTime() - cachedData.cachedAt < localCache.timeOut;

            }
        },

        get: function (key) {

            var cachedData = JSON.parse(localStorage.getItem(localCache.cacheKeysPrefix + key));

            return cachedData.payload;

        },

        set: function (key, data) {

            localCache.clearOldData();

            localStorage.removeItem(localCache.cacheKeysPrefix + key);

            var dataToCache = JSON.stringify({
                cachedAt: new Date().getTime(),
                payload: data
            });

            localStorage.setItem(localCache.cacheKeysPrefix + key, dataToCache)

        },

        clearOldData: function () {
            //get all storage entries of current page local storage
            var storageEntries = Object.keys(localStorage);
            //go with each
            for (var i = 0; i < storageEntries.length; i++) {
                //and check if its a cache object
                if (storageEntries[i].substr(0, 11) == localCache.cacheKeysPrefix) {
                    //parse it if it's  a cahce object
                    var cachedData = JSON.parse(localStorage[storageEntries[i]]);
                    //check if it is still valid
                    if (new Date().getTime() - cachedData.cachedAt > localCache.timeOut) {
                        //if it's outdated - remove
                        localStorage.removeItem(storageEntries[i]);
                    }
                }
            }

        }

    };

    return {
        getMeasurements: function (params, f) {
            GET('measurements', [
                'variableName',
                'startTime',
                'endTime',
                'groupingWidth',
                'groupingTimezone',
                'source'], params, f);
        },
        getDailyMeasurements: function (params, f) {
            GET('v1/measurements/daily', [
                'variableName',
                'startTime',
                'endTime',
                'groupingWidth',
                'groupingTimezone'], params, f);
        },
        postMeasurements: function (measurements, f) {
            POST('measurements', [
                'source',
                'variable',
                'combinationOperation',
                'timestamp',
                'value',
                'unit'], measurements, f);
        },
        postMeasurementsV2: function (measurementset, f) {
            POST('measurements/v2', [
                'measurements',
                'name',
                'source',
                'category',
                'combinationOperation',
                'unit'], measurementset, f);
        },
        deleteVariableMeasurements: function (variables, f) {
            POST('measurements/delete', [
                'variableId',
                'variableName'], variables, f);
        },

        getMeasurementsRange: function (params, f) {
            GET('measurementsRange', [], params, f);
        },

        getMeasurementSources: function (params, f) {
            GET('measurementSources', [], params, f);
        },
        postMeasurementSources: function (measurements, f) {
            POST('measurementSources', ['name'], measurements, f);
        },
        getUnits: function (params, f) {
            GET('units', [
                'unitName',
                'abbreviatedUnitName',
                'categoryName'], params, f);
        },
        getUnitsForVariable: function (params, f) {
            GET('unitsVariable', [
                'variable',
                'unitName',
                'abbreviatedUnitName',
                'categoryName'], params, f);
        },
        postUnits: function (measurements, f) {
            POST('units', [
                'name',
                'abbreviatedName',
                'category',
                'conversionSteps'], measurements, f);
        },

        getUnitCategories: function (params, f) {
            GET('unitCategories', [], params, f);
        },
        postUnitCategories: function (measurements, f) {
            POST('unitCategories', ['name'], measurements, f);
        },

        getVariables: function (params, f) {

            if (localCache.exist('variables')) {
                f(localCache.get('variables'));
            } else {
                GET('variables', ['categoryName'], params, function (variables) {
                    localCache.set('variables', variables);
                    f(variables);
                });
            }

        },

        getVariableByName: function (name, f) {
            GET('variables/' + encodeURIComponent(name),['categoryName'], null, f, true);
        },

        postVariables: function (measurements, f) {
            POST('variables', ['name', 'category', 'unit', 'combinationOperation'], measurements, f);
        },

        searchVariables: function (query, f) {
            if (localCache.exist('searchVariables_' + query)) {
                f(localCache.get('searchVariables_' + query));
            } else {
                GET('variables/search/' + query, ['categoryName'], null, function (variables) {
                    localCache.set('searchVariables_' + query, variables);
                    f(variables);
                });

            }
        },

        getVariableCategories: function (params, f) {

            if (localCache.exist('variableCategories')) {
                f(localCache.get('variableCategories'));
            } else {
                GET('variableCategories', [], params, function (variableCategories) {
                    localCache.set('variableCategories', variableCategories);
                    f(variableCategories);
                }, true);
            }

        },
        postVariableCategories: function (measurements, f) {
            POST('variableCategories', ['name'], measurements, f);
        },

        getPairs: function (params, f) {
            GET('pairs', [
                'cause',
                'effect',
                'duration',
                'delay',
                'startTime',
                'endTime',
                'causeSource',
                'effectSource',
                'causeUnit',
                'effectUnit'], params, f);
        },

        getUserVariables: function (params, f) {
            GET('userVariables', ['variableName'], params, f);
        },
        postUserVariables: function (measurements, f) {
            POST('userVariables', ['variable'], measurements, f);
        },

        getCorrelations: function (params, f) {
            GET('correlations', ['effect'], params, f);
        },

        getCorrelateShare: function (params, f) {
            GET('share', ['id'], params, f);
        },
        postCorrelateShare: function (measurements, f) {
            POST('share', ['type', 'inputVariable', 'outputVariable'], measurements, f);
        },

        connectorsInterface: function (baseURL, defaultConnector) {
            this.params = {
                baseURL: typeof baseURL == 'undefined' ? hostUrl : hostUrl + baseURL,
                connector: typeof defaultConnector == 'undefined' ? null : defaultConnector
            };
            this.connector = function (name) {
                this.params.connector = name;
                return this;
            };
            this.do = function () {
                var action = arguments[0],
                    params = {},
                    f = undefined;

                if (typeof arguments[1] == 'object') {
                    params = arguments[1];
                    f = arguments[2];
                } else if (typeof arguments[1] == 'function') {
                    f = arguments[1];
                }
                switch (action) {
                    case 'connect':
                        this.sendRequest('connectors/' + this.params.connector + '/connect', params, f);
                        break;
                    case 'disconnect':
                        this.sendRequest('connectors/' + this.params.connector + '/disconnect', params, f);
                        break;
                    case 'update':
                        this.sendRequest('connectors/' + this.params.connector + '/update', params, f);
                        break;
                    case 'info':
                        this.sendRequest('connectors/' + this.params.connector + '/info', params, f);
                        break;
                }
            };
            this.listConnectors = function (f) {
                this.sendRequest('connectors/list', {}, f);
            };
            this.sendRequest = function (url, params, f) {
                console.debug('API Call via QM JS SDK ');
                if (accessToken) {
                    var that = this;
                    jQuery.ajax(this.params.baseURL + url, {
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
                            if (typeof mashapeKey !== 'undefined' && mashapeKey) {
                                xhr.setRequestHeader('X-Mashape-Key', mashapeKey);
                            }
                        },
                        data: params,
                        dataType: 'json'
                    }).done(function (data) {
                        if (typeof f != 'undefined') {
                            f(data, that.params.connector);
                        }
                    });
                } else {
                    console.warn('No access token. Now will try to authenticate and to get it');
                    window.location.href = '?connect=quantimodo';
                }

            };
        },

        url: hostUrl
    };
}();
<commit_msg>Don't loop when we're doing searches<commit_after>// Quantimodo.com JavaScript API v1.1.8.
// Requires JQuery.
Quantimodo = function () {

    var hostUrl = apiHost + '/api/';

    var GET = function (baseURL, allowedParams, params, successHandler, disableLooping) {
        if (accessToken) {
            var urlParams = [];
            for (var key in params) {
                if (jQuery.inArray(key, allowedParams) == -1) {
                    throw 'invalid parameter; allowed parameters: ' + allowedParams.toString();
                }
                urlParams.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));
            }

            var results = [];

            fetchAPI(0);

        } else {
            console.warn('No access token. Now will try to authenticate and to get it');
            window.location.href = '?connect=quantimodo';
        }

        function fetchAPI(offset) {

            var url = hostUrl;

            if (urlParams.length == 0) {
                url += baseURL + '?offset=' + offset + '&limit=200';
            } else {
                url += baseURL + '?' + urlParams.join('&') + '&offset=' + offset + '&limit=200';
            }
            console.debug('Fecthing: ' + url);
            jQuery.ajax({
                type: 'GET',
                url: url,
                dataType: 'json',
                contentType: 'application/json',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
                    if (typeof mashapeKey !== 'undefined' && mashapeKey) {
                        xhr.setRequestHeader('X-Mashape-Key', mashapeKey);
                    }
                },
                success: function (data, status, xhr) {

                    if (data.constructor === Array && !disableLooping) {
                        console.debug('Fetched: ' + data.length + ' items');
                        if (data.length > 0) {
                            results = results.concat(data);
                            fetchAPI(results.length);
                        } else {
                            successHandler(results);
                        }
                    } else {
                        successHandler(data)
                    }
                }
            });
        }
    };

    var POST = function (baseURL, requiredFields, items, successHandler) {
        console.debug('POST API Call');
        if (accessToken) {
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                for (var j = 0; j < requiredFields.length; j++) {
                    if (!(requiredFields[j] in item)) {
                        throw 'missing required field in POST data; required fields: ' + requiredFields.toString();
                    }
                }
            }
            jQuery.ajax({
                type: 'POST',
                url: hostUrl + baseURL,
                contentType: 'application/json',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
                    if (typeof mashapeKey !== 'undefined' && mashapeKey) {
                        xhr.setRequestHeader('X-Mashape-Key', mashapeKey);
                    }
                },
                data: JSON.stringify(items),
                dataType: 'json',
                success: successHandler
            });
        } else {
            console.warn('No access token. Now will try to authenticate and to get it');
            window.location.href = '?connect=quantimodo';
        }
    };

    var localCache = {

        timeOut: 1000 * 420,    //cache valid for 7 minutes
        cacheKeysPrefix: 'qmwp_cache_',

        exist: function (key) {
            if (localStorage.getItem(localCache.cacheKeysPrefix + key)) {

                var cachedData = JSON.parse(localStorage.getItem(localCache.cacheKeysPrefix + key));

                return new Date().getTime() - cachedData.cachedAt < localCache.timeOut;

            }
        },

        get: function (key) {

            var cachedData = JSON.parse(localStorage.getItem(localCache.cacheKeysPrefix + key));

            return cachedData.payload;

        },

        set: function (key, data) {

            localCache.clearOldData();

            localStorage.removeItem(localCache.cacheKeysPrefix + key);

            var dataToCache = JSON.stringify({
                cachedAt: new Date().getTime(),
                payload: data
            });

            localStorage.setItem(localCache.cacheKeysPrefix + key, dataToCache)

        },

        clearOldData: function () {
            //get all storage entries of current page local storage
            var storageEntries = Object.keys(localStorage);
            //go with each
            for (var i = 0; i < storageEntries.length; i++) {
                //and check if its a cache object
                if (storageEntries[i].substr(0, 11) == localCache.cacheKeysPrefix) {
                    //parse it if it's  a cahce object
                    var cachedData = JSON.parse(localStorage[storageEntries[i]]);
                    //check if it is still valid
                    if (new Date().getTime() - cachedData.cachedAt > localCache.timeOut) {
                        //if it's outdated - remove
                        localStorage.removeItem(storageEntries[i]);
                    }
                }
            }

        }

    };

    return {
        getMeasurements: function (params, f) {
            GET('measurements', [
                'variableName',
                'startTime',
                'endTime',
                'groupingWidth',
                'groupingTimezone',
                'source'], params, f);
        },
        getDailyMeasurements: function (params, f) {
            GET('v1/measurements/daily', [
                'variableName',
                'startTime',
                'endTime',
                'groupingWidth',
                'groupingTimezone'], params, f);
        },
        postMeasurements: function (measurements, f) {
            POST('measurements', [
                'source',
                'variable',
                'combinationOperation',
                'timestamp',
                'value',
                'unit'], measurements, f);
        },
        postMeasurementsV2: function (measurementset, f) {
            POST('measurements/v2', [
                'measurements',
                'name',
                'source',
                'category',
                'combinationOperation',
                'unit'], measurementset, f);
        },
        deleteVariableMeasurements: function (variables, f) {
            POST('measurements/delete', [
                'variableId',
                'variableName'], variables, f);
        },

        getMeasurementsRange: function (params, f) {
            GET('measurementsRange', [], params, f);
        },

        getMeasurementSources: function (params, f) {
            GET('measurementSources', [], params, f);
        },
        postMeasurementSources: function (measurements, f) {
            POST('measurementSources', ['name'], measurements, f);
        },
        getUnits: function (params, f) {
            GET('units', [
                'unitName',
                'abbreviatedUnitName',
                'categoryName'], params, f);
        },
        getUnitsForVariable: function (params, f) {
            GET('unitsVariable', [
                'variable',
                'unitName',
                'abbreviatedUnitName',
                'categoryName'], params, f);
        },
        postUnits: function (measurements, f) {
            POST('units', [
                'name',
                'abbreviatedName',
                'category',
                'conversionSteps'], measurements, f);
        },

        getUnitCategories: function (params, f) {
            GET('unitCategories', [], params, f);
        },
        postUnitCategories: function (measurements, f) {
            POST('unitCategories', ['name'], measurements, f);
        },

        getVariables: function (params, f) {

            if (localCache.exist('variables')) {
                f(localCache.get('variables'));
            } else {
                GET('variables', ['categoryName'], params, function (variables) {
                    localCache.set('variables', variables);
                    f(variables);
                });
            }

        },

        getVariableByName: function (name, f) {
            GET('variables/' + encodeURIComponent(name), ['categoryName'], null, f, true);
        },

        postVariables: function (measurements, f) {
            POST('variables', ['name', 'category', 'unit', 'combinationOperation'], measurements, f);
        },

        searchVariables: function (query, f) {
            if (localCache.exist('searchVariables_' + query)) {
                f(localCache.get('searchVariables_' + query));
            } else {
                GET('variables/search/' + query, ['categoryName'], null, function (variables) {
                    localCache.set('searchVariables_' + query, variables);
                    f(variables);
                }, true);

            }
        },

        getVariableCategories: function (params, f) {

            if (localCache.exist('variableCategories')) {
                f(localCache.get('variableCategories'));
            } else {
                GET('variableCategories', [], params, function (variableCategories) {
                    localCache.set('variableCategories', variableCategories);
                    f(variableCategories);
                }, true);
            }

        },
        postVariableCategories: function (measurements, f) {
            POST('variableCategories', ['name'], measurements, f);
        },

        getPairs: function (params, f) {
            GET('pairs', [
                'cause',
                'effect',
                'duration',
                'delay',
                'startTime',
                'endTime',
                'causeSource',
                'effectSource',
                'causeUnit',
                'effectUnit'], params, f);
        },

        getUserVariables: function (params, f) {
            GET('userVariables', ['variableName'], params, f);
        },
        postUserVariables: function (measurements, f) {
            POST('userVariables', ['variable'], measurements, f);
        },

        getCorrelations: function (params, f) {
            GET('correlations', ['effect'], params, f);
        },

        getCorrelateShare: function (params, f) {
            GET('share', ['id'], params, f);
        },
        postCorrelateShare: function (measurements, f) {
            POST('share', ['type', 'inputVariable', 'outputVariable'], measurements, f);
        },

        connectorsInterface: function (baseURL, defaultConnector) {
            this.params = {
                baseURL: typeof baseURL == 'undefined' ? hostUrl : hostUrl + baseURL,
                connector: typeof defaultConnector == 'undefined' ? null : defaultConnector
            };
            this.connector = function (name) {
                this.params.connector = name;
                return this;
            };
            this.do = function () {
                var action = arguments[0],
                    params = {},
                    f = undefined;

                if (typeof arguments[1] == 'object') {
                    params = arguments[1];
                    f = arguments[2];
                } else if (typeof arguments[1] == 'function') {
                    f = arguments[1];
                }
                switch (action) {
                    case 'connect':
                        this.sendRequest('connectors/' + this.params.connector + '/connect', params, f);
                        break;
                    case 'disconnect':
                        this.sendRequest('connectors/' + this.params.connector + '/disconnect', params, f);
                        break;
                    case 'update':
                        this.sendRequest('connectors/' + this.params.connector + '/update', params, f);
                        break;
                    case 'info':
                        this.sendRequest('connectors/' + this.params.connector + '/info', params, f);
                        break;
                }
            };
            this.listConnectors = function (f) {
                this.sendRequest('connectors/list', {}, f);
            };
            this.sendRequest = function (url, params, f) {
                console.debug('API Call via QM JS SDK ');
                if (accessToken) {
                    var that = this;
                    jQuery.ajax(this.params.baseURL + url, {
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
                            if (typeof mashapeKey !== 'undefined' && mashapeKey) {
                                xhr.setRequestHeader('X-Mashape-Key', mashapeKey);
                            }
                        },
                        data: params,
                        dataType: 'json'
                    }).done(function (data) {
                        if (typeof f != 'undefined') {
                            f(data, that.params.connector);
                        }
                    });
                } else {
                    console.warn('No access token. Now will try to authenticate and to get it');
                    window.location.href = '?connect=quantimodo';
                }

            };
        },

        url: hostUrl
    };
}();
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const validateOptions = require("schema-utils");
const { ConcatSource } = require("webpack-sources");
const Compilation = require("./Compilation");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const Template = require("./Template");

const schema = require("../schemas/plugins/BannerPlugin.json");

/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */
/** @typedef {import("./Compiler")} Compiler */

const wrapComment = str => {
	if (!str.includes("\n")) {
		return Template.toComment(str);
	}
	return `/*!\n * ${str
		.replace(/\*\//g, "* /")
		.split("\n")
		.join("\n * ")
		.replace(/\s+\n/g, "\n")
		.trimRight()}\n */`;
};

class BannerPlugin {
	/**
	 * @param {BannerPluginArgument} options options object
	 */
	constructor(options) {
		if (typeof options === "string" || typeof options === "function") {
			options = {
				banner: options
			};
		}

		validateOptions(schema, options, {
			name: "Banner Plugin",
			baseDataPath: "options"
		});

		this.options = options;

		const bannerOption = options.banner;
		if (typeof bannerOption === "function") {
			const getBanner = bannerOption;
			this.banner = this.options.raw
				? getBanner
				: data => wrapComment(getBanner(data));
		} else {
			const banner = this.options.raw
				? bannerOption
				: wrapComment(bannerOption);
			this.banner = () => banner;
		}
	}

	/**
	 * Apply the plugin
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		const options = this.options;
		const banner = this.banner;
		const matchObject = ModuleFilenameHelpers.matchObject.bind(
			undefined,
			options
		);

		compiler.hooks.compilation.tap("BannerPlugin", compilation => {
			compilation.hooks.processAssets.tap(
				{
					name: "BannerPlugin",
					stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
				},
				() => {
					let files;
					if (options.entryOnly) {
						files = new Set();
						for (const chunk of compilation.chunks) {
							if (chunk.canBeInitial()) {
								for (const file of chunk.files) files.add(file);
							}
						}
					} else {
						files = Object.keys(compilation.assets);
					}
					for (const chunk of compilation.chunks) {
						if (options.entryOnly && !chunk.canBeInitial()) {
							continue;
						}

						for (const file of chunk.files) {
							if (!matchObject(file)) {
								continue;
							}

							let filename = file;

							const data = {
								chunk,
								filename
							};

							const comment = compilation.getPath(banner, data);

							compilation.updateAsset(
								file,
								old => new ConcatSource(comment, "\n", old)
							);
						}
					}
				}
			);
		});
	}
}

module.exports = BannerPlugin;
<commit_msg>BannerPlugin: remove unnecessary code<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const validateOptions = require("schema-utils");
const { ConcatSource } = require("webpack-sources");
const Compilation = require("./Compilation");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const Template = require("./Template");

const schema = require("../schemas/plugins/BannerPlugin.json");

/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */
/** @typedef {import("./Compiler")} Compiler */

const wrapComment = str => {
	if (!str.includes("\n")) {
		return Template.toComment(str);
	}
	return `/*!\n * ${str
		.replace(/\*\//g, "* /")
		.split("\n")
		.join("\n * ")
		.replace(/\s+\n/g, "\n")
		.trimRight()}\n */`;
};

class BannerPlugin {
	/**
	 * @param {BannerPluginArgument} options options object
	 */
	constructor(options) {
		if (typeof options === "string" || typeof options === "function") {
			options = {
				banner: options
			};
		}

		validateOptions(schema, options, {
			name: "Banner Plugin",
			baseDataPath: "options"
		});

		this.options = options;

		const bannerOption = options.banner;
		if (typeof bannerOption === "function") {
			const getBanner = bannerOption;
			this.banner = this.options.raw
				? getBanner
				: data => wrapComment(getBanner(data));
		} else {
			const banner = this.options.raw
				? bannerOption
				: wrapComment(bannerOption);
			this.banner = () => banner;
		}
	}

	/**
	 * Apply the plugin
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		const options = this.options;
		const banner = this.banner;
		const matchObject = ModuleFilenameHelpers.matchObject.bind(
			undefined,
			options
		);

		compiler.hooks.compilation.tap("BannerPlugin", compilation => {
			compilation.hooks.processAssets.tap(
				{
					name: "BannerPlugin",
					stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
				},
				() => {
					for (const chunk of compilation.chunks) {
						if (options.entryOnly && !chunk.canBeInitial()) {
							continue;
						}

						for (const file of chunk.files) {
							if (!matchObject(file)) {
								continue;
							}

							const data = {
								chunk,
								filename: file
							};

							const comment = compilation.getPath(banner, data);

							compilation.updateAsset(
								file,
								old => new ConcatSource(comment, "\n", old)
							);
						}
					}
				}
			);
		});
	}
}

module.exports = BannerPlugin;
<|endoftext|>


<commit_before>export function formatString() {
    let format = arguments[0];
    let methodsArgs = arguments;
    return format.replace(/[{\[](\d+)[\]}]/gi, function (value, index) {
        console.log(`${value} => ${index}`);
        let argsIndex = parseInt(index) + 1;
        return methodsArgs[argsIndex];
    });
}
export function sort(items, column, order) {
    order = order === undefined ? "asc" : order;
    items = items.sort(function (a, b) {
        if (a[column] > b[column]) //sort string descending
            return order === "asc" ? 1 : -1;
        if (a[column] < b[column])
            return order === "asc" ? -1 : 1;
        return 0;//default return value (no sorting)
    });
    return items;
}<commit_msg>DNN-10617 Code review<commit_after>export function formatString() {
    let format = arguments[0];
    let methodsArgs = arguments;
    return format.replace(/[{\[](\d+)[\]}]/gi, function (value, index) {
        let argsIndex = parseInt(index) + 1;
        return methodsArgs[argsIndex];
    });
}
export function sort(items, column, order) {
    order = order === undefined ? "asc" : order;
    items = items.sort(function (a, b) {
        if (a[column] > b[column]) //sort string descending
            return order === "asc" ? 1 : -1;
        if (a[column] < b[column])
            return order === "asc" ? -1 : 1;
        return 0;//default return value (no sorting)
    });
    return items;
}<|endoftext|>


<commit_before>/**
 * A caching availability checker for alias availability
 */
var aliasAvailability = {};
function aliasAvailable (alias, callbackFunction) {
    if (aliasAvailability[alias] === undefined) {
	jQuery.post("handle_json/", '{"requestType": "ALIAS_AVAILABLE", "payload": "' + alias + '"}',
                    function(){
			return function(data){
			    if (data == 'true') {
				aliasAvailability[alias] = true;
			    }
			    else if (data == 'false') {
				aliasAvailability[alias] = false;
			    }
			    callbackFunction(aliasAvailability[alias]);
			}
		    }());
    }
    else {
	callbackFunction(aliasAvailability[alias]);
    }
}

function cleanAccents (s) {
    var r=s.toLowerCase();
    r = r.replace(new RegExp("\\s", 'g'),"");
    r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
    r = r.replace(new RegExp("æ", 'g'),"ae");
    r = r.replace(new RegExp("ç", 'g'),"c");
    r = r.replace(new RegExp("[èéêë]", 'g'),"e");
    r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
    r = r.replace(new RegExp("ñ", 'g'),"n");
    r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
    r = r.replace(new RegExp("œ", 'g'),"oe");
    r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
    r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
    r = r.replace(new RegExp("\\W", 'g'),"");
    return r;
};

function generateEmailForwards (firstName, givenNames, lastName) {
    var firstName = cleanAccents(firstName);
    var givenNames = givenNames.split(" ");
    for (var i=0; i<givenNames.length; i++) {
	givenNames[i] = cleanAccents(givenNames[i]);
    }
    var lastName = cleanAccents(lastName);

    var permutations = [];
    permutations.push(firstName + "." + lastName);
    permutations.push(lastName + "." + firstName);

    var nonFirstNames = [];
    var initials = [];
    $.each(givenNames, function (idx, val) {
	if (val != firstName) {
	    nonFirstNames.push(val);
	    initials.push(val[0]);
	}
    });

    if (initials.length > 0) {
	permutations.push(firstName + "." + initials[0] + "." + lastName);
	permutations.push(initials[0] + "." + firstName + "." + lastName);
    }
    return permutations;
}

<commit_msg>Fixed undefined appearing as middle initial.<commit_after>/**
 * A caching availability checker for alias availability
 */
var aliasAvailability = {};
function aliasAvailable (alias, callbackFunction) {
    if (aliasAvailability[alias] === undefined) {
	jQuery.post("handle_json/", '{"requestType": "ALIAS_AVAILABLE", "payload": "' + alias + '"}',
                    function(){
			return function(data){
			    if (data == 'true') {
				aliasAvailability[alias] = true;
			    }
			    else if (data == 'false') {
				aliasAvailability[alias] = false;
			    }
			    callbackFunction(aliasAvailability[alias]);
			}
		    }());
    }
    else {
	callbackFunction(aliasAvailability[alias]);
    }
}

function cleanAccents (s) {
    var r=s.toLowerCase();
    r = r.replace(new RegExp("\\s", 'g'),"");
    r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
    r = r.replace(new RegExp("æ", 'g'),"ae");
    r = r.replace(new RegExp("ç", 'g'),"c");
    r = r.replace(new RegExp("[èéêë]", 'g'),"e");
    r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
    r = r.replace(new RegExp("ñ", 'g'),"n");
    r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
    r = r.replace(new RegExp("œ", 'g'),"oe");
    r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
    r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
    r = r.replace(new RegExp("\\W", 'g'),"");
    return r;
};

function generateEmailForwards (firstName, givenNames, lastName) {
    var firstName = cleanAccents(firstName);
    var givenNames = givenNames.split(" ");
    for (var i=0; i<givenNames.length; i++) {
	givenNames[i] = cleanAccents(givenNames[i]);
    }
    var lastName = cleanAccents(lastName);

    var permutations = [];
    permutations.push(firstName + "." + lastName);
    permutations.push(lastName + "." + firstName);

    var nonFirstNames = [];
    var initials = [];
    $.each(givenNames, function (idx, val) {
	if (val !== undefined && val != firstName) {
	    nonFirstNames.push(val);
	    initials.push(val[0]);
	}
    });

    if (initials.length > 0) {
	permutations.push(firstName + "." + initials[0] + "." + lastName);
	permutations.push(initials[0] + "." + firstName + "." + lastName);
    }
    return permutations;
}

<|endoftext|>