I am looking over some code that another programmer made where he calls a stored procedure. Before calling it, he creates an Array with the parameters needed for the stored procedure to query the table. He creates the array like this:
param = Array("#Name", 3, 8, "Tom", _
"#Age", 3, 8, 28, _
"#City", 100, 200, "Toronto)
The stored procedure uses #Name, #Age and #City to query the table.
My question is, what are the numbers in between for?
It looks like:
#Name = parameter name
3 = adInteger
8 = length
"Tom" = value
#Age= parameter name
3 = adInteger
8 = length
28 = value
#City= parameter name
100 = length
200 = adVarChar
"Toronto = value
Here is a list for the other ADO Data Types -
http://www.w3schools.com/ado/ado_datatypes.asp
My guess is that he is using an array of params, just something like this: https://stackoverflow.com/a/10142254/2385, where I use an array of params to pass to a function who add the params to the ADO command.
Without comments it's impossible to know for sure or without stepping through the code.
Otherwise, if this is asp.net the best you can do is look at the SqlParameter class and see the properties it has available:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx
I think you have two strong candidates for ParameterName and Value, but the two numerical values could be a few different things. 3 just happens to be the numerical value for SqlDbType.Char and while 100 has no corresponding SqlDbType, the default for that type is NVarChar.
The next number could be precision. Take a look at the Database table and see if you can match those values to the fields. For example, is City VarChar(200)?
Related
I have two arrays in Julia, X = Array{Float64,2} and Y = Array{Float64,2}. I'd like to perform a vlookup as per Excel functionality. I can't seem to find something like this.
the following code returns first matched from s details matrix using related record from a master matrix.
function vlook(master, detail, val)
val = master[findfirst(x->x==val,master[:,2]),1]
return detail[findfirst(x->x==val,detail[:,1]),2]
end
julia> vlook(a,b,103)
1005
A more general approach is to use DataFrame.jl, for working with tabular data.
VLOOKUP is a popular function amongst Excel users, and has signature:
VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
I've never much liked that last argument range_lookup. First it's not clear to me what "range_lookup" is intended to mean and second it's an optional argument defaulting to the much-less-likely-to-be-what-you-want value of TRUE for approximate matching, rather than FALSE for exact matching.
So in my attempt to write VLOOKUP equivalents in Julia I've dropped the range_lookup argument and added another argument keycol_index_num to allow for searching of other than the first column of table_array.
WARNING
I'm very new new to Julia, so there may be some howlers in the code below. But it seems to work for me. Julia 0.6.4. Also, and as already commented, using DataFrames might be a better solution for looking up values in an array-like structure.
#=
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Procedures: vlookup and vlookup_withfailsafe
Purpose : Inspired by Excel VLOOKUP. Searches a column of table_array for
lookup_values and returns the corresponding elements from another column of
table_array.
Arguments:
lookup_values: a value or array of values to be searched for inside
column keycol_index_num of table_array.
table_array: An array with two dimensions.
failsafe: a single value. The return contains this value whenever an element
of lookup_values is not found.
col_index_num: the number of the column of table_array from which values
are returned.
keycol_index_num: the number of the column of table_array to be searched.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=#
vlookup = function(lookup_values, table_array::AbstractArray, col_index_num::Int = 2, keycol_index_num::Int = 1)
if ndims(table_array)!=2
error("table_array must have 2 dimensions")
end
if isa(lookup_values,AbstractArray)
indexes = indexin(lookup_values,table_array[:,keycol_index_num])
if(any(indexes==0))
error("at least one element of lookup_values not found in column $keycol_index_num of table_array")
end
return(table_array[indexes,col_index_num])
else
index = indexin([lookup_values],table_array[:,keycol_index_num])[1]
if(index==0)
error("lookup_values not found in column $keycol_index_num of table_array")
end
return(table_array[index,col_index_num])
end
end
vlookup_withfailsafe = function(lookup_values, table_array::AbstractArray, failsafe, col_index_num::Int = 2, keycol_index_num::Int = 1)
if ndims(table_array)!=2
error("table_array must have 2 dimensions")
end
if !isa(failsafe,eltype(tablearray))
error("failsafe must be of the same type as the elements of table_array")
end
if isa(lookup_values,AbstractArray)
indexes = indexin(lookup_values,table_array[:,keycol_index_num])
Result = Array{eltype(table_array)}(size(lookup_values))
for i in 1:length(lookup_values)
if(indexes[i]==0)
Result[i] = failsafe
else
Result[i] = table_array[indexes[i],col_index_num]
end
end
return(Result)
else
index = indexin([lookup_values],table_array[:,keycol_index_num])[1]
if index == 0
return(failsafe)
else
return(table_array[index,col_index_num])
end
end
end
I have a dictionary of names with a number (a score) assigned to them. The file is laid out as so:
Person A,7
Peron B,6
If a name is repeated in the file e.g. Person B occurred on 3 lines with 3 different scores I want to calculate the mean average of these scores then append this result to a dictionary in the form of a list. However, I keep encountering an error when i try to sort the dictionary. Code below.
else:
for key in results:
keyValue = results[key]
if len(keyValue) > 1:
# Line below this needs modification
keyValue = list(sum(keyValue)/len(keyValue))
newResults[key] = keyValue
# Error in above code...
else:
newResults[key] = keyValue
print(newResults)
print(sorted(zip(newResults.values(), newResults.keys()), reverse=True))
Results is a dictionary of the people (the keys) and their scores (the values) where the values are lists so that:
results = {'Bob':[7],'Jane':[8,9]}
If you're using Python 3.x you can use its statistics library which contains a function mean. Now assuming that your dict looks like: results = {'Bob': [7], 'Jane': [8, 9]} you can create a newResults dict like this:
from statistics import mean
newResults = {key: mean(results[key]) for key in results}
This is called dict comprehension and as you can see it's kinda intuitive. Starting with { you're telling that dict is going to be created. Then with key: value you're defining its structure. Lastly, with for loop you iterate over a collection that will be used for the dict creation. You can achieve the same with:
newResults = {}
for key in results:
newResults[key] = mean(results[key])
You want to sort the dict in the end. Unfortunately it's not possible. You can either create an OrderedDict, which remembers the items insertion order or a list which will contain sorted keys to your dict. The latter will look like:
sortedKeys = sorted(newResults, key=lambda x: newResults[x])
Can anyone advice how I could compare values of 2 dictionaries. For example:
A = {'John': [(300, 5000), (700, 750), (10, 300)], 'Mary': [(12, 300), (5678, 9000), (200, 657), (800, 7894)]}
B = {‘Jim’:[(500,1000),(600,1500),(900,2000)], ‘Mary’:[(13,250), (1000,6000), (222,600)]}
I would like to compare the 2 such that if the 'key' (in this case 'Mary') is present between A and B dictionaries and the first and second numbers in the 'values' of B dictionaries are within that of the 'values in A (i.e. (13,250) and (222,600) are between (12,300) and (200, 657) respectively. The return results will therefore be 'Mary': [(13,250), (222,600)]
Thanks
Okay I did what I think you wanted and retrieved the results (13,250)
(222,600). So it looks like it is working. I made three classes one was the main class, another a Point Class, and another class that did the filling of the dictionaries and comparing. I didn't know how you made up your dictionaries. But I made it like so:
private Dictionary<String,Map<String,List<Point>>> first
= new Hashtable<String,Map<String,List<Point>>>();
It is dictionary that takes in a String and a Map, which takes in a String and a List, which takes in a Point Object. When I look at your snippet there; it just screamed Points. So I made a small class with x and y properties.
Next, one should make a method that will compare the values of the points like using less than and greater than:
Then in another method after you fill the Dictionary, then check the dictionary and loop through the size of the second list of the dictionary
int size = second.get("B").get("Mary").size();
for(int i =0; i<size; i++){
//compare method that you just made
}
Then print out results
My Output: Mary:(13,250)(222,600)
If you need any help with code please reply.
This is a newbie R question. I am beginning to explore the use of R for website analytics. I have a set of page view events which have common properties along with an arbitrary set of properties that depend on the page. For instance, all events will have a userId, createdAt, and pageId, but the "signup" page might have a special property origin whose value could be "adwords" or "organic", etc.
In JSON, the data might look like this:
[
{
"userId":null,
"pageId":"home",
"sessionId":"abcd",
"createdAt":1381013741,
"parameters":{},
},
{
"userId":123,
"pageId":"signup",
"sessionId":"abcd",
"createdAt":1381013787,
"parameters":{
"origin":"adwords",
"campaignId":4
}
}
]
I have been struggling to represent this data in R data structures effectively. In particular I need to be able to subset the event list by conditions based on the arbitrary key/value pairs, for instance, select all events whose pageId=="signup" and origin=="adwords".
There is enough diversity in the keys used for the arbitrary parameters that it seems unreasonable to create sparsely-populated columns for every possible key.
What I'm currently doing is pre-processing the data into two CSV files, core_properties.csv and parameters.csv, in the form:
# core_properties.csv (one record per pageview)
userId,pageId,sessionId,createdAt
,home,abcd
123,signup,abcd,1381013741
...
# parameters.csv (one record per k/v pair)
row,key,value # <- "row" here denotes the record index in core_properties.csv
1,origin,adwords
1,campaignId,4
...
I then read.table each file into a data frame, and I am now attempting to store the k/v pairs a list (with names=keys) inside cells of the core events data frame. This has been a lot of awkward trial and error, and the best approach I've found so far is the following:
events <- read.csv('core_properties.csv', header=TRUE)
parameters <- read.csv('parameters.csv',
header=TRUE,colClasses=c("character","character","character"))
paramLists <- sapply(1:nrow(events), function(x) { list() })
apply(parameters,1,function(x) {
paramLists [[ as.numeric(x[["row"]]) ]][[ x[["key"]] ]] <<- x[["value"]] })
events$parameters <- paramLists
I can now access the origin property of the first event by the syntax: events[1,][["parameters"]][[1]][["origin"]] - note it requires for some reason an extra [[1]] subscript in there. Data frames do not seem to appreciate being given lists as individual values for cells:
> events[1,][["parameters"]] <- list()
Error in `[[<-.data.frame`(`*tmp*`, "parameters", value = list()) :
replacement has 0 rows, data has 1
Is there a best practice for handling this sort of data? I have not found it discussed in the manuals and tutorials.
Thank you!
You can use nested lists in R that map nicely to JSON. I have shown a simple example where you filter based on parameter origin.
dat <- list(
list(userId = NULL, pageId = "home", createdAt = 1381013741, parameters = list()),
list(userId = NULL, pageId = "new", createdAt = 1381013741, parameters = list(origin = 'adwords', campaignId = 4))
)
Filter(function(l){length(l) > 0 && l$parameters$origin == 'adwords'}, dat)
When I use the following command below:
select *
from storm
where (variable = "TMP" OR
variable = "VVEL" OR
variable = "UGRD" OR
variable = "VGRD" OR
variable = "RH" OR
variable = "HGT") AND level >=150 AND level <=200
The variable part parses out what I need from there, but the level command seems to be completely ignored. All levels are displayed with this command, but I only want those between 150 and 200.
Any suggestions?
Thanks in advance!
try this:
select * from storm where variable IN ('TMP', 'VVEL', 'UGRD', 'VGRD', 'RH', 'HGT') AND level BETWEEN 150 AND 200