I have played with:
https://github.com/experteer/autocompleteTrigger/
as following:
(function ($, window, document, undefined) {
$.widget("ui.autocompleteTrigger", {
//Options to be used as defaults
options: {
triggerStart: "%{",
triggerEnd: "}"
},
_create: function () {
this.triggered = false;
this.triggered2 = false;
this.element.autocomplete($.extend({
search: function () {
/**
* #description only make a request and suggest items if acTrigger.triggered is true
*/
var acTrigger = $(this).data("autocompleteTrigger");
if (acTrigger.triggered == true || acTrigger.triggered2 == true) {
return true;
} else {
return false;
}
},
select: function (event, ui) {
/**
* #description if a item is selected, insert the value between triggerStart and triggerEnd
*/
var acTrigger = $(this).data("autocompleteTrigger");
var text = this.value;
var trigger = acTrigger.options.triggerStart;
var trigger2 = acTrigger.options.triggerStart2;
var cursorPosition = acTrigger.getCursorPosition();
var lastTrigger1Position = text.substring(0, cursorPosition).lastIndexOf(trigger);
var lastTrigger2Position = text.substring(0, cursorPosition).lastIndexOf(trigger2);
var lastTriggerPosition;
if (lastTrigger1Position > lastTrigger2Position) {
lastTriggerPosition = lastTrigger1Position;
} else {
lastTriggerPosition = lastTrigger2Position;
}
var firstTextPart = text.substring(0, lastTriggerPosition + trigger.length) + ui.item.value +
acTrigger.options.triggerEnd;
this.value = firstTextPart + text.substring(cursorPosition, text.length);
acTrigger.triggered = false;
acTrigger.triggered2 = false;
// set cursor position after the autocompleted text
this.selectionStart = firstTextPart.length;
this.selectionEnd = firstTextPart.length;
return false;
},
focus: function () {
/**
* #description prevent to replace the hole text, if a item is hovered
*/
return false;
},
minLength: 0
}, this.options))
.bind("keyup", function (event) {
/**
* #description Bind to keyup-events to detect text changes.
* If the trigger is found before the cursor, autocomplete will be called
*/
var acTrigger = $(this).data("autocompleteTrigger");
if (event.keyCode != $.ui.keyCode.UP && event.keyCode != $.ui.keyCode.DOWN) {
var text = this.value;
var textLength = text.length;
var cursorPosition = acTrigger.getCursorPosition();
var lastString;
var query;
var lastTriggerPosition;
var lastTriggerPosition2;
var trigger = acTrigger.options.triggerStart;
var trigger2 = acTrigger.options.triggerStart2;
if (acTrigger.triggered && text != "") {
// call autocomplete with the string after the trigger
// Example: triggerStart = #, string is '#foo' -> query string is 'foo'
$(this).autocomplete("option", "source", '/UITests/LookupFirst');
lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
query = text.substring(lastTriggerPosition + trigger.length, cursorPosition);
$(this).autocomplete("search", query);
}
if (acTrigger.triggered2 && text != "") {
// call autocomplete with the string after the trigger
// Example: triggerStart = #, string is '#foo' -> query string is 'foo'
$(this).autocomplete("option", "source", '/UITests/LookupSec');
lastTriggerPosition2 = text.substring(0, cursorPosition).lastIndexOf(trigger2);
query = text.substring(lastTriggerPosition2 + trigger2.length, cursorPosition);
$(this).autocomplete("search", query);
}
else if (textLength >= trigger.length) {
// set trigged to true, if the string before the cursor is triggerStart
lastString = text.substring(cursorPosition - trigger.length, cursorPosition);
acTrigger.triggered = (lastString === trigger);
acTrigger.triggered2 = (lastString === trigger2);
}
}
});
},
/**
* #description Destroy an instantiated plugin and clean up modifications the widget has made to the DOM
*/
destroy: function () {
// this.element.removeStuff();
// For UI 1.8, destroy must be invoked from the
// base widget
$.Widget.prototype.destroy.call(this);
// For UI 1.9, define _destroy instead and don't
// worry about
// calling the base widget
},
/**
* #description calculates the the current cursor position in the bound textfield, area,...
* #returns {int} the position of the cursor.
*/
getCursorPosition: function () {
var elem = this.element[0];
var position = 0;
// dom 3
if (elem.selectionStart >= 0) {
position = elem.selectionStart;
// IE
} else if (elem.ownerDocument.selection) {
var r = elem.ownerDocument.selection.createRange();
if (!r) return data;
var tr = elem.createTextRange(), ctr = tr.duplicate();
tr.moveToBookmark(r.getBookmark());
ctr.setEndPoint('EndToStart', tr);
position = ctr.text.length;
}
return position;
}
});
})(jQuery, window, document);
and in the View:
$('input,textarea').autocompleteTrigger({
triggerStart: '#',
triggerEnd: '',
triggerStart2: '##',
sourceOption1: '/UITests/LookupFirst',
sourceOption2: '/UITests/LookupSec'
});
Controller Action Method(LookupSec is identical) is:
public ActionResult LookupFirst(string q)
{
var list = new List<string>()
{
"Asp",
"BASIC",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
};
IEnumerable<string> data;
if (q != null)
{
data = list.Where(x => x.StartsWith(q));
}
else
data = list;
return Json(data, JsonRequestBehavior.AllowGet);
}
Now it supports two triggers # and # and two datasources for each one...
Problem is the searching doesnt work anymore, everything works as expected "Almost" but when i type something like "#as" it should filter the result but it doesnt!
any idea why this is not working ?
You seem to be using the LookupSec action to filter with the # character but in your question you have only shown the LookupFirst action which is associated with the # filter character. I have tested your code and it worked for # and not for # because LookupSec doesn't exist.
Once I have defined the LookupSec controller action it worked for both. Just be careful as right now you have hardcoded those action names in the widget itself so the sourceOption1 and sourceOption2 parameters will be completely ignored.
The query string parameter used by jquery autocomplete is called term, not q so fix your controller action as right now it isn't filtering anything:
public ActionResult LookupFirst(string term)
{
...
}
Related
I am trying to JsTree Checkbox checked unchecked based on condition.
i have to checked and unchecked based dropdown change event.
string has value 0 and 1.
0 means unchecked and 1 means checked.
This is my menu design
Here is my controller code.
[HttpPost]
public ActionResult GetSingleUser(int id)
{
MachineShopDBEntities DB = new MachineShopDBEntities();
var SPresult = DB.GetSingleUser(id).FirstOrDefault();
return Json(SPresult);
}
Here is my Script.
$("#UserSelect").change(function () {
$.post("/MenuMaster/GetSingleUser?id=" + $(this).val(),
function (data, status) {
var databaseString = data.MenuEnable;
var count = $('.menux ul li').length;
for (i = 0; i < count; i++) {
if (databaseString[i] == '0') {
$('.menux .jstree-anchor').removeClass('jstree-clicked');
}
else {
$('.menux .jstree-anchor').addClass('jstree-clicked');
}
}
});
});
Use the eq function to select the element based on index i
$("#UserSelect").change(function () {
$.post("/MenuMaster/GetSingleUser?id=" + $(this).val(),
function (data, status) {
var databaseString = data.MenuEnable;
var count = $('.menux ul li').length;
for (i = 0; i < count; i++) {
if (databaseString[i] == '0') {
$('.menux .jstree-anchor').eq(i).removeClass('jstree-clicked');
}
else {
$('.menux .jstree-anchor').eq(i).addClass('jstree-clicked');
}
}
});
});
I want to validate each input with so below is the code in js
var inputs = document.querySelectorAll('input[data-filter]');
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
var state = {
value: input.value,
start: input.selectionStart,
end: input.selectionEnd,
pattern: RegExp('^' + input.dataset.filter + '$')
};
input.addEventListener('input', function (event) {
if (state.pattern.test(input.value)) {
state.value = input.value;
} else {
input.value = state.value;
input.setSelectionRange(state.start, state.end);
}
});
input.addEventListener('keydown', function (event) {
state.start = input.selectionStart;
state.end = input.selectionEnd;
});
}
It works perfectly with textbox
#Html.TextBoxFor(m=>m.Telephone, new { id="phone", data_filter="\\+?(?:\\d\\s?){0,13}"})
Original regex ^\+?(?:\d\s?){11,13}$ escaped backslash as it was giving error
$("#phone").on("focus", function (evt) {
if(this.value.length < 11)
alert("Invalid");
});
It is not working with razor.What is the issue??
I am trying to figure out how to read Newick files for many animal species and i haven't been able to find a "logical method / process" to sort the Newick string in a simple programming language. I can read C# and AS and JS and GLSL and HLSL.
I can't find any simple resources, and the wiki article doesn't even talk about recursion. A pseudocode of how to parse newick would be so great and i can't find one.
Does anyone know the fastest way to read a newick file in Unity3d? Can you help to set me on the right track for a logical process to sort through the newick code, i.e:
(A,B,(C,D));
the branch lengh number is not important for the moment.
target project file:
(
(
(
(
(
(
Falco_rusticolus:0.846772,
Falco_jugger:0.846772
):0.507212,
(
Falco_cherrug:0.802297,
Falco_subniger:0.802297
):0.551687
):0.407358,
Falco_biarmicus:1.761342
):1.917030,
(
Falco_peregrinus:0.411352,
Falco_pelegrinoides:0.411352
):3.267020
):2.244290,
Falco_mexicanus:5.922662
):1.768128,
Falco_columbarius:7.69079
)
Implementing a parser if you have no background in formal grammars might be tough. So the easiest approach seems to be to use a parser generator, such as ANTLR, and then you only need to familiarize yourself with the grammar notation. You can generate a parser written in C# from a grammar.
Luckily you can find a newick grammar online: here.
UPDATE:
And if you did the above, then you'll get something like the following:
public class Branch
{
public double Length { get; set; }
public List<Branch> SubBranches { get; set; } = new List<Branch>();
}
public class Leaf : Branch
{
public string Name { get; set; }
}
public class Parser
{
private int currentPosition;
private string input;
public Parser(string text)
{
input = new string(text.Where(c=>!char.IsWhiteSpace(c)).ToArray());
currentPosition = 0;
}
public Branch ParseTree()
{
return new Branch { SubBranches = ParseBranchSet() };
}
private List<Branch> ParseBranchSet()
{
var ret = new List<Branch>();
ret.Add(ParseBranch());
while (PeekCharacter() == ',')
{
currentPosition++; // ','
ret.Add(ParseBranch());
}
return ret;
}
private Branch ParseBranch()
{
var tree = ParseSubTree();
currentPosition++; // ':'
tree.Length = ParseDouble();
return tree;
}
private Branch ParseSubTree()
{
if (char.IsLetter(PeekCharacter()))
{
return new Leaf { Name = ParseIdentifier() };
}
currentPosition++; // '('
var branches = ParseBranchSet();
currentPosition++; // ')'
return new Branch { SubBranches = branches };
}
private string ParseIdentifier()
{
var identifer = "";
char c;
while ((c = PeekCharacter()) != 0 && (char.IsLetter(c) || c == '_'))
{
identifer += c;
currentPosition++;
}
return identifer;
}
private double ParseDouble()
{
var num = "";
char c;
while((c = PeekCharacter()) != 0 && (char.IsDigit(c) || c == '.'))
{
num += c;
currentPosition++;
}
return double.Parse(num, CultureInfo.InvariantCulture);
}
private char PeekCharacter()
{
if (currentPosition >= input.Length-1)
{
return (char)0;
}
return input[currentPosition + 1];
}
}
Which can be used like this:
var tree = new Parser("((A:1, B:2):3, C:4)").ParseTree();
BTW the above parser implements the following grammar without any kind of error handling:
Tree -> "(" BranchSet ")"
BranchSet -> Branch ("," Branch)*
Branch -> Subtree ":" NUM
Subtree -> IDENTIFIER | "(" BranchSet ")"
Hope you're interested in converting Newick into JSON/Regular object, I think I was able to find a solution.
A quick google gave me links to the implementation on JS:
https://www.npmjs.com/package/biojs-io-newick
https://github.com/daviddao/biojs-io-newick
And, it wasn't hard for me to port JS code into AS3:
// The very funciton of converting Newick
function convertNewickToJSON(source:String):Object
{
var ancestors:Array = [];
var tree:Object = {};
var tokens:Array = source.split(/\s*(;|\(|\)|,|:)\s*/);
var subtree:Object;
for (var i = 0; i < tokens.length; i++)
{
var token:String = tokens[i];
switch (token)
{
case '(': // new children
subtree = {};
tree.children = [subtree];
ancestors.push(tree);
tree = subtree;
break;
case ',': // another branch
subtree = {};
ancestors[ancestors.length-1].children.push(subtree);
tree = subtree;
break;
case ')': // optional name next
tree = ancestors.pop();
break;
case ':': // optional length next
break;
default:
var x = tokens[i-1];
if (x == ')' || x == '(' || x == ',')
{
tree.name = token;
} else if (x == ':')
{
tree.branch_length = parseFloat(token);
}
}
}
return tree;
};
// Util function for parsing an object into a string
function objectToStr(obj:Object, paramsSeparator:String = "", isNeedUseSeparatorForChild:Boolean = false):String
{
var str:String = "";
if (isSimpleType(obj))
{
str = String(obj);
}else
{
var childSeparator:String = "";
if (isNeedUseSeparatorForChild)
{
childSeparator = paramsSeparator;
}
for (var propName:String in obj)
{
if (str == "")
{
str += "{ ";
}else
{
str += ", ";
}
str += propName + ": " + objectToStr(obj[propName], childSeparator) + paramsSeparator;
}
str += " }";
}
return str;
}
// One more util function
function isSimpleType(obj:Object):Boolean
{
var isSimple:Boolean = false;
if (typeof(obj) == "string" || typeof(obj) == "number" || typeof(obj) == "boolean")
{
isSimple = true;
}
return isSimple;
}
var tempNewickSource:String = "((((((Falco_rusticolus:0.846772,Falco_jugger:0.846772):0.507212,(Falco_cherrug:0.802297,Falco_subniger:0.802297):0.551687):0.407358,Falco_biarmicus:1.761342):1.917030,(Falco_peregrinus:0.411352,Falco_pelegrinoides:0.411352):3.267020):2.244290,Falco_mexicanus:5.922662):1.768128,Falco_columbarius:7.69079)";
var tempNewickJSON:Object = this.convertNewickToJSON(tempNewickSource);
var tempNewickJSONText:String = objectToStr(tempNewickJSON);
trace(tempNewickJSONText);
The code above gives the next trace:
{ name: , children: { 0: { name: , children: { 0: { name: , children: { 0: { name: , children: { 0: { name: , children: { 0: { name: , children: { 0: { name: Falco_rusticolus, branch_length: 0.846772 }, 1: { name: Falco_jugger, branch_length: 0.846772 } }, branch_length: 0.507212 }, 1: { name: , children: { 0: { name: Falco_cherrug, branch_length: 0.802297 }, 1: { name: Falco_subniger, branch_length: 0.802297 } }, branch_length: 0.551687 } }, branch_length: 0.407358 }, 1: { name: Falco_biarmicus, branch_length: 1.761342 } }, branch_length: 1.91703 }, 1: { name: , children: { 0: { name: Falco_peregrinus, branch_length: 0.411352 }, 1: { name: Falco_pelegrinoides, branch_length: 0.411352 } }, branch_length: 3.26702 } }, branch_length: 2.24429 }, 1: { name: Falco_mexicanus, branch_length: 5.922662 } }, branch_length: 1.768128 }, 1: { name: Falco_columbarius, branch_length: 7.69079 } } }
So, this approach gives a way to work with a Newick format as with JSON.
According to the title, you're interested not only in C#, but in AS3 implementation too (I'm not sure that you'll be able to use it in C# right "out-of-the-box", but maybe you will be able to port it to C#).
My users have requested that I change one of the fields from being required to optional, but still show/hide the warning message. Trying to do this with as little refactoring as I can I added an allowsubmission property on my data annotation on the server and in the jquery method on the client (see below).
Is it possible to set an ignore class on an element while still hiding/showing the message? It seems the method fires the first time and then stops firing after the ignore class is added, so the message stays on the screen.
Or is there a better way? Thank you.
$(document).ready(function () {
$("form").validate().settings.ignore = ".ignore, :hidden";
});
$.validator.unobtrusive.adapters.add('dependentrange', ['minvalueproperty', 'maxvalueproperty', 'allowsubmission'],
function (options) {
options.rules.dependentrange = options.params;
if (options.message) {
$.validator.messages.dependentrange = options.message;
}
}
);
$.validator.addMethod('dependentrange', function (value, element, params) {
var minValue = parseFloat($('input[name="' + params.minvalueproperty + '"]').val());
var maxValue = parseFloat($('input[name="' + params.maxvalueproperty + '"]').val());
var currentValue = parseFloat(value);
// if there is a value check it. If for some reason the min and max can't be found return true because
// i do not know the values to validate. Usually that is a coding mistake
if (isNaN(currentValue) || minValue > currentValue || currentValue > maxValue) {
var message = $(element).attr('data-val-dependentrange');
$.validator.messages.dependentrange = $.validator.format(message, minValue, maxValue);
if (params.allowsubmission) {
// once this property is added, the method does not fire
$(element).addClass("ignore");
}
return false;
}
$(element).removeClass('ignore');
return true;
}, '');
I ended up using validators API to show and hide my own warning message while always return true.
$.validator.unobtrusive.adapters.add('dependentrange', ['minvalueproperty', 'maxvalueproperty'], function (options) {
options.rules['dependentrange'] = options.params;
if (options.message) {
options.messages['dependentrange'] = options.message;
}
});
$.validator.addMethod("dependentrange", function (value, element, params) {
var valKeyed = parseFloat(value),
$elem = $(element),
$warning = $elem.closest('div').nextAll('.alert-warning:first')
msg = $elem.data('val-dependentrange),
isValid = this.optional(element) || valKeyed >= parseFloat(params.minvalueproperty) && valKeyed <= parseFloat(params.maxvalueproperty);
// there are no from or two found, so just return true with no warning
if (!params.minvalueproperty || !params.maxvalueproperty) {
return true;
}
if (isValid) {
$warning.text('')
$warning.addClass('hidden');
}
else {
$warning.text(msg)
$warning.removeClass('hidden');
}
return true;
});
I am using JQPlot to plot a chart on a page. I am plotting Line chart with marker points.
I want to change the color of the marker points.
I need each marker point to be in different color. Is it possible?
Thank you all in advance for your response.
Here is my code :
//In order to use keyboard highlight of the coordinates please click somewhere inside the Result frame.
$(document).ready(function() {
// Some simple loops to build up data arrays.
var cosPoints = [];
for (var i = 0; i < 2 * Math.PI; i += 2) {
cosPoints.push([i, Math.cos(i)]);
}
var plot3 = $.jqplot('chart', [cosPoints], {
cursor: {
show: true,
showTooltip: true,
showTooltipGridPosition: true,
// showTooltipDataPosition: false,
showTooltipUnitPosition: false,
useAxesFormatters: false,
// showVerticalLine : true,
followMouse: true
},
title: 'Line Style Options',
// Series options are specified as an array of objects, one object
seriesDefaults: {
markerRenderer: $.jqplot.MarkerRenderer,
markerOptions: {
color: 'red'
}
}
});
$('#chart').bind('jqplotDataClick', function(ev, seriesIndex, pointIndex, data) {
alert(data);
});
var counter = -1; //to start from the very first on first next click, on prev click it will start from last -- and this is how we want it
$('#buttonPrev').bind("click", function() {
counter--;
DoSomeThing(plot3);
});
$('#buttonNext').bind("click", function() {
counter++;
DoSomeThing(plot3);
});
$(document).keydown(function(e) {
if (e.keyCode == 37) {
$('#buttonPrev').click();
}
else if (e.keyCode == 39) {
$('#buttonNext').click();
}
});
function GetColors() {
var colors = ["red","blue","red","blue"];
return colors;
}
function DoSomeThing(plot) {
// *** highlight point in plot ***
//console.log(" sth "+ plot.series[0].data[1][1]);
var seriesIndex = 0; //0 as we have just one series
var data = plot.series[seriesIndex].data;
if (counter >= data.length) counter = 0;
else if (counter < 0) counter = data.length - 1;
var pointIndex = counter;
var x = plot.axes.xaxis.series_u2p(data[pointIndex][0]);
var y = plot.axes.yaxis.series_u2p(data[pointIndex][1]);
console.log("x= " + x + " y= " + y);
var r = 5;
var drawingCanvas = $(".jqplot-highlight-canvas")[0]; //$(".jqplot-series-canvas")[0];
var context = drawingCanvas.getContext('2d');
context.clearRect(0, 0, drawingCanvas.width, drawingCanvas.height); //plot.replot();
context.strokeStyle = "#000000";
context.fillStyle = "#FFFF00";
context.beginPath();
context.arc(x, y, r, 0, Math.PI * 2, true);
context.closePath();
context.stroke();
context.fill();
}
});
I'm not sure you can specify multiple colors for a single serie.
Either you can divide your serie into several series (ex. 4 series if you have a serie of 4 elements), and use seriesColors : myColorTab to specify different color for each series (thus for each of your elements) :
var myColorTab = new Array("#FF0000", "#384763", "#AA4312");
var plot3 = $.jqplot('chart(, [cos1, cos2, cos3], {
seriesColors : myColorTab
}
Please see working example here
P.S. : You can change the surely not-optimal way to push datas into cos1, cos2 and cos3.
EDIT
In order to change markerpoints back color, you can specify a color for each series :
series: [
{markerRenderer: $.jqplot.MarkerRenderer,
markerOptions: { color: 'red' }
},
{markerRenderer: $.jqplot.MarkerRenderer,
markerOptions: { color: 'blue' }
},
{markerRenderer: $.jqplot.MarkerRenderer,
markerOptions: { color: 'green' }
}
]
Please see edited JsFiddle here
Just Add seriesColors: ['#FFC526', '#C0504D', '#4BACC6', '#8064A2', '#9BBB59', '#F79646', '#948A54', '#4000E3'], above seriesDefaults in your code
I also needed to have different colored markers, and making separate series for each color really the way to go for me, so i made this pointRenderer:
$.jqplot.PointRenderer = function(){
$.jqplot.LineRenderer.call(this);
};
$.jqplot.PointRenderer.prototype = Object.create($.jqplot.LineRenderer.prototype);
$.jqplot.PointRenderer.prototype.constructor = $.jqplot.PointRenderer;
// called with scope of a series
$.jqplot.PointRenderer.prototype.init = function(options, plot) {
options = options || {};
this.renderer.markerOptionsEditor = false;
$.jqplot.LineRenderer.prototype.init.apply(this, arguments);
this._type = 'point';
}
// called within scope of series.
$.jqplot.PointRenderer.prototype.draw = function(ctx, gd, options, plot) {
var i;
// get a copy of the options, so we don't modify the original object.
var opts = $.extend(true, {}, options);
var markerOptions = opts.markerOptions;
ctx.save();
if (gd.length) {
// draw the markers
for (i=0; i<gd.length; i++) {
if (gd[i][0] != null && gd[i][1] != null) {
if (this.renderer.markerOptionsEditor) {
markerOptions = $.extend(true, {}, opts.markerOptions);
markerOptions = this.renderer.markerOptionsEditor.call(plot, this.data[i], markerOptions);
}
this.markerRenderer.draw(gd[i][0], gd[i][1], ctx, markerOptions);
}
}
}
ctx.restore();
};
The draw function is a stripped down version of the LineRenderer draw function, add the missing pieces from that function.