I have a little problem.
i should implement a logic for a treeList which consist from a single parent and more children grouped into more groups by ID's.
I have an action which treats all nodes:
long callerGroup = -1L;
if (callerNode != null)
{
var service = this.tlServices.GetDataRecordByNode(callerNode) as __ServiceInfo;
if (service != null)
{
callerGroup = service.Group;
}
}
Action<TreeListNodes> action = null;
action = (nodes) =>
{
if (nodes != null && nodes.Count > 0)
{
foreach (TreeListNode node in nodes)
{
if (node.Level == 0 && !node.Checked)
{
node.Checked = true;
break;
}
else
{
var service = this.tlServices.GetDataRecordByNode(node) as __ServiceInfo;
if (service != null)
{
var group = service.Group;
//for ' 1 <= group <= 100' -> Mandatory Service, only ONE from group
if (callerGroup >= 1 && callerGroup <= 100)
{
if (group >= 1 && group <= 100)
{
//node.Checked = true; - not done
}
}
//for ' 101 <= group <= 1000 ' -> Mandatory Service, minimum ONE from group, but allow and MORE
if (callerGroup >= 101 && callerGroup <= 1000)
{
}
//for ' group >= 1001 ' -> optional Service, ALL from group
if (callerGroup >= 1001 && group >= 1001)
{
node.Checked = !node.Checked; // --> DONE.
}
}
}
action(node.Nodes);
}
}
};
action(this.tlServices.Nodes);
I have 3 cases:
#1. if 1 <= group <= 100 -> Mandatory Service, allow only ONE from group
#2. if 101 <= group <= 1000 -> Mandatory Service, allow minimum ONE from group, but allow and MORE
#3. if group >= 1001 -> optional Service, Check/ Uncheck ALL from group.
Result:
The #3 I've done easy, but how can i implement #1.
for #1 i found an implementation:
//for ' 1 <= group <= 100' -> Mandatory Service, only ONE from group
if (callerGroup >= 1 && callerGroup <= 100)
{
if (group >= 1 && group <= 100)
{
foreach (TreeListNode nd in nodes)
{
var svc = this.tlServices.GetDataRecordByNode(nd) as __ServiceInfo;
long gr = svc.Group;
if (gr == callerGroup && nd.Checked == true)
{
nd.Checked = false;
}
}
}
}`
Related
I’ve got a really large file, circa 10m rows, in which I’m trying to populate a column based on conditions on another column via a jsee macro. While it is quite quick for small files, it does take some time for the large file.
//pseudocode
//No sorting on Col1, which can have empty cells too
For all lines in file
IF (cell in Col2 IS empty) AND (cell in Col1 IS NOT empty) AND (cell in Col1 = previous cell in Col1)
THEN cell in Col2 = previous cell in Col2
//jsee code
document.CellMode = true; // Must be cell selection mode
totalLines = document.GetLines();
for( i = 1; i < totalLines; i++ ) {
nref = document.GetCell( i, 1, eeCellIncludeNone );
gsize = document.GetCell( i, 2, eeCellIncludeNone );
if (gsize == "" && nref != "" && nref == document.GetCell( i-1, 1, eeCellIncludeNone ) ) {
document.SetCell( i, 2, document.GetCell( i-1, 2, eeCellIncludeNone ) , eeAutoQuote);
}
}
Input File:
Reference
Group Size
14/12/01819
1
14/12/01820
1
15/01/00191
4
15/01/00191
15/01/00191
15/01/00198
15/01/00292
3
15/01/00292
15/01/00292
15/01/00401
5
15/01/00401
15/01/00402
1
15/01/00403
2
15/01/00403
15/01/00403
15/01/00403
15/01/00404
20/01/01400
1
Output File:
Reference
Group Size
14/12/01819
1
14/12/01820
1
15/01/00191
4
15/01/00191
4
15/01/00191
4
15/01/00198
15/01/00292
3
15/01/00292
3
15/01/00292
3
15/01/00401
5
15/01/00401
5
15/01/00402
1
15/01/00403
2
15/01/00403
2
15/01/00403
2
15/01/00403
2
15/01/00404
20/01/01400
1
Any ideas on how to optimise this and make it run even faster?
I wrote a JavaScript for EmEditor macro for you. You might need to set the correct numbers in the first 2 lines for iColReference and iColGroupSize.
iColReference = 1; // the column index of "Reference"
iColGroupSize = 2; // the column index of "Group Size"
document.CellMode = true; // Must be cell selection mode
sDelimiter = document.Csv.Delimiter; // retrieve the delimiter
nOldHeadingLines = document.HeadingLines; // retrieve old headings
document.HeadingLines = 0; // set No Headings
yBottom = document.GetLines(); // retrieve the number of lines
if( document.GetLine( yBottom ).length == 0 ) { // -1 if the last line is empty
--yBottom;
}
str = document.GetColumn( iColReference, sDelimiter, eeCellIncludeQuotes, 1, yBottom ); // get whole 1st column from top to bottom, separated by TAB
sCol1 = str.split( sDelimiter );
str = document.GetColumn( iColGroupSize, sDelimiter, eeCellIncludeQuotes, 1, yBottom ); // get whole 2nd column from top to bottom, separated by TAB
sCol2 = str.split( sDelimiter );
s1 = "";
s2 = "";
for( i = 0; i < yBottom; ++i ) { // loop through all lines
if( sCol2[i].length != 0 ) {
s1 = sCol1[i];
s2 = sCol2[i];
}
else {
if( s1.length != 0 && sCol1[i] == s1 ) { // same value as previous line, copy s2
if( s2.length != 0 ) {
sCol2[i] = s2;
}
}
else { // different value, empty s1 and s2
s1 = "";
s2 = "";
}
}
}
str = sCol2.join( sDelimiter );
document.SetColumn( iColGroupSize, str, sDelimiter, eeDontQuote ); // set whole 2nd column from top to bottom with the new values
document.HeadingLines = nOldHeadingLines; // restore the original number of headings
To run this, save this code as, for instance, Macro.jsee, and then select this file from Select... in the Macros menu. Finally, select Run Macro.jsee in the Macros menu.
I had a problem with this search algorithm, when the target value being the last element in the list, the middle becomes ZERO, where it must be 8, I calculated that by myself and I got 8, but when I do debug, I found zero again, if you can help, please feel free
this is the code :
class InterpolationSearch {
companion object{
fun Interpolation(list : List<Int> , Target_value : Int ){
var Lo = 0
var Hi = list.lastIndex
while (Lo <= Hi || list[Lo] <= list[Hi]){
var mid = Lo + ((Hi - Lo) / (list[Hi] - list[Lo])) * (Target_value - list[Lo]) // this is the middle.
if (list[mid] == Target_value){
println("success, target found in $mid")
break
}else if(list[mid] < Target_value){
Lo = mid + 1
}else if (list[mid] > Target_value){
Hi = mid -1
}
}
if (Lo >= Hi || list[Lo] >= list[Hi]){
println("failure, target not found")
}
}
}
}
fun main() {
val matrix = listOf<Int>( 32 , 33 , 54 , 1102 , 1124 , 1144 , 1150 , 1203 ,1222 )
try {
InterpolationSearch.Interpolation(matrix , 1222)
}catch (e : ArithmeticException){
println("SOMETHING DIVIDED BY ZERO :/")
}
}
set mid = Lo in case when Lo == Hi
Having IPv4 address ranges for a given country, how would one generate random address? For example, a single current set of ranges (one of many) for Singapore is:
+----------+----------+--------------+
| ip_from | ip_to | country_code |
+----------+----------+--------------+
| 18925568 | 18926079 | SG |
+----------+----------+--------------+
source: lite.ip2location.com
FAQ(3) explains that
IP_Number = 16777216*w + 65536*x + 256*y + z
where
IP_Address = w.x.y.z
IP_Number standing either for ip_from or ip_to. For the Singapore range presented above, it gives me:
16777216*w + 65536*x + 256*y + z >= 18925568; // from
16777216*w + 65536*x + 256*y + z <= 18926079; // to
How can I generate random w, x, y and z?
Here is a testable implementation (in JavaScript since that can be run directly here) and a little bit of a description.
First you need to generate random number from the specified range. If you have a function (let's call it random) that generates random real numbers between 0 and 0.999... [0,1) then you can do this.
num = (random() * (end - start + 1)) + start
Then you need to use mod 256 4 times to split the number into 4 parts and also use div 256 3 times on the given number (the fourth div operation would be unnecessary but if we are doing it in loop then we can just keep it there for the sake of simplicity as it doesn't change a thing).
(% - modulo, // - div)
first = num % 256
num = num // 256
second = num % 256
num = num // 256
third = num % 256
num = num // 256
fourth = num % 256
You can then push them into an array [fourth, third, second, first] (note the order here) and do some validation - some addresses are reserved for private internets so if you happen to generate one of them, just throw it away and generate a new one (you can either loop or recurse here till you generate a valid one).
Ip addresses in these ranges are reserved according to RFC 1918:
10.0.0.0 - 10.255.255.255 (10/8 prefix)
172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
And here is the implementation.
const start = 18925568;
const end = 18926079;
function _generateRandomIp(start, end) {
let r = Math.floor(Math.random() * (end - start + 1)) + start;
const ip = [];
for (let i = 0; i < 4; i++) {
ip.push(r % 256);
r = Math.floor(r / 256);
}
return ip.reverse(); // put the results mod/div into correct order
}
function generateRandomIp(start, end) {
let ip = _generateRandomIp(start, end);
let valid = true;
// ip can't be of format 10.xxx.xxx.xxx
if (ip[0] === 10) { valid = false; }
// ip can't be of format 172.16.xxx.xxx
if (ip[0] === 172 && ip[1] === 16) { valid = false; }
// ip can't be of format 192.168.xxx.xxx
if (ip[0] === 192 && ip[1] === 168) { valid = false; }
if (valid === true) {
return ip.join('.'); // convert ip to string format
} else {
return generateRandomIp(start, end); // try again
}
}
const ip = generateRandomIp(start, end);
console.log(ip);
The above snippet will generate a random ip address in that range each time you run it.
And here is the test case from the page that you have mentioned which says that number 3401190660 should be converted into 202.186.13.4, so let's just switch that randomly generated number for this one and try it.
const start = 18925568;
const end = 18926079;
function _generateRandomIp(start, end) {
let r = 3401190660; // here is that specific number
const ip = [];
for (let i = 0; i < 4; i++) {
ip.push(r % 256);
r = Math.floor(r / 256);
}
return ip.reverse(); // put the results mod/div into correct order
}
function generateRandomIp(start, end) {
let ip = _generateRandomIp(start, end);
let valid = true;
// ip can't be of format 10.xxx.xxx.xxx
if (ip[0] === 10) { valid = false; }
// ip can't be of format 172.16.xxx.xxx
if (ip[0] === 172 && ip[1] === 16) { valid = false; }
// ip can't be of format 192.168.xxx.xxx
if (ip[0] === 192 && ip[1] === 168) { valid = false; }
if (valid === true) {
return ip.join('.'); // convert ip to string format
} else {
return generateRandomIp(start, end); // try again
}
}
const ip = generateRandomIp(start, end);
console.log(ip);
And as we can see, this algorithm produced the correct result.
Based on this question & answer "How to retrieve unique count of a field using Kibana + Elastic Search"
I have been able to collect the individual count of the unique IP addresses from our Apache logs, however, What I actually want to do is to be able to display the count of the individual IP addresses, i.e. how many unique visitors.
I think I need to use the terms_stats facet to do this but I don't know what to set as the "value_field"
This is not possible with the current version of the kibana.
but i have what i did to achieve this is created the custom histogram panel.
to create the custom histogram panel, just copy the existing histogram and modify config.js, module.js to change all the path references to the new panel.
override the doSearch function to use the query http://www.elasticsearch.org/blog/count-elasticsearch/
and update the results parsing logic.
look for function
b.get_data = function(a, j, k)
return b.populate_modal(n), p = n.doSearch(), p.then(function(c) {
if (b.panelMeta.loading = !1, 0 === j && (b.legend = [], b.hits = 0, a = [], b.annotations = [], k = b.query_id = (new Date).getTime()), d.isUndefined(c.error)) {
if (b.query_id === k) {
var i, n, p, q = 0;
o = JSON.parse("[{\"query\":\"*\",\"alias\":\"\",\"color\":\"#7EB26D\",\"id\":0,\"pin\":false,\"type\":\"lucene\",\"enable\":true,\"parent\" : 0}]");
d.each(o, function(e) {
//alert(JSON.stringify(c));
//var f = c.aggregations.monthly.buckets[e.id];
if (d.isUndefined(a[q]) || 0 === j) {
var h = {interval: m,start_date: l && l.from,end_date: l && l.to,fill_style: b.panel.derivative ? "null" : b.panel.zerofill ? "minimal" : "no"};
i = new g.ZeroFilled(h), n = 0, p = {}
} else
i = a[q].time_series, n = a[q].hits, p = a[q].counters;
d.each(c.aggregations.monthly.buckets, function(a) {
var c;
n += a.visitor_count.value, b.hits += a.visitor_count.value, p[a.key] = (p[a.key] || 0) + a.visitor_count.value, "count" === b.panel.mode ? c = (i._data[a.key] || 0) + a.visitor_count.value : "mean" === b.panel.mode ? c = ((i._data[a.key] || 0) * (p[a.key] - a.visitor_count.value) + a.mean * a.visitor_count.value) / p[a.key] : "min" === b.panel.mode ? c = d.isUndefined(i._data[a.key]) ? a.min : i._data[a.key] < a.min ? i._data[a.key] : a.min : "max" === b.panel.mode ? c = d.isUndefined(i._data[a.key]) ? a.max : i._data[a.key] > a.max ? i._data[a.key] : a.max : "total" === b.panel.mode && (c = (i._data[a.key] || 0) + a.total), i.addValue(a.key, c)
}), b.legend[q] = {query: e,hits: n}, a[q] = {info: e,time_series: i,hits: n,counters: p}, q++
}), b.panel.annotate.enable && (b.annotations = b.annotations.concat(d.map(c.hits.hits, function(a) {
var c = d.omit(a, "_source", "sort", "_score"), g = d.extend(e.flatten_json(a._source), c);
return {min: a.sort[1],max: a.sort[1],eventType: "annotation",title: null,description: "<small><i class='icon-tag icon-flip-vertical'></i> " + g[b.panel.annotate.field] + "</small><br>" + f(a.sort[1]).format("YYYY-MM-DD HH:mm:ss"),score: a.sort[0]}
})), b.annotations = d.sortBy(b.annotations, function(a) {
return a.score * ("desc" === b.panel.annotate.sort[1] ? -1 : 1)
}), b.annotations = b.annotations.slice(0, b.panel.annotate.size))
}
} else
b.panel.error = b.parse_error(c.error);
b.$emit("render", a), j < h.indices.length - 1 && b.get_data(a, j + 1, k)
})
I'm creating a TicTacToe game using command line in Xcode. I've got everything working properly except I can't figure out how to avoid a player from taking another players spot. So if player one chooses spot [1][1], if either player enters spot [1][1] throughout the game they will get "Invalid entry, please try again" and they will have to choose another spot. Any suggestions?
- (void) getChoice1
{
do
{
if (player == 1 && winner == 0 && turns < 9)
{
do {
//player 1's input
NSLog(#"Player 1, please choose a cell.");
NSLog(#"Enter row number(1, 2, or 3).");
scanf("%ld", &row);
} while ((row != 1 && row != 2 && row != 3));
do{
NSLog(#"Enter column number(1, 2, or 3).");
scanf("%ld", &column);
} while ((column != 1 && column != 2 && column != 3));
//decrement players input -1
row--;
column--;
//ensure spot is unselected
if (arr[row][column] == 1 || arr[row][column] == 2) {
NSLog(#"Invalid entry, try another spot");
[self getChoice1];
}
else
{
//add input to board
arr [row][column] = 1;
//display updated board
[self showBoard];
//switch players
player = 2;
//add a turn
turns++;
//check for winner
[self checkWinner];
}
}
} while (turns < 9 && winner == 0 );
}
You have to make userInteraction disabled for that block.
For example if block1 is touched, make :
block1.userInteractionEnabled = NO;
Once, game is complete, make userInteractionEnabled fro all blocks again to YES.
This will work as I have also made one similar game.
In case of command line , you can set some variables for example if for x set 1, for 0 set 2, for no play set 0.
Then, once someone new press there check for 1 and 2 and do the required
With the help of a friend I realized I have to restructure the method completely. Here's my working answer.
do
{
if (winner == 0 && turns < 9)
{
do {
//player 1's input
if (player == 1) {
NSLog(#"Player 1, please choose a cell.");
} else {
NSLog(#"Player 2, please choose a cell.");
}
NSLog(#"Enter row number(1, 2, or 3).");
scanf("%ld", &row);
} while ((row != 1 && row != 2 && row != 3));
do{
NSLog(#"Enter column number(1, 2, or 3).");
scanf("%ld", &column);
} while ((column != 1 && column != 2 && column != 3));
//decrement players input -1
row--;
column--;
//add input to board
if (arr [row][column] == 0) {
arr [row][column] = player;
if (player == 1) {
player = 2;
} else {
player = 1;
}
//display updated board
[self showBoard];
//add a turn
turns++;
} else {
NSLog (#"Cell already used pick a different cell.");
}
//check for winner
[self checkWinner];
}
} while (turns < 9 && winner == 0 );
}