I have a parametrized JUnit Class with something similar to this to setup the parametrized data:
#Parameters(name = "{index}: {0}/{1} : {2}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{
"Samsung",
new Object[] { "size", "10" },
"http://my.test.service.com/svc/brand/samsung?size=10"
},
{
"Apple",
new Object[] { "color", "red" },
"http://my.test.service.com/svc/brand/apple?color=red"
},
// Code truncated
});
}
After running the code, I can see the result like this:
[0: Samsung/[Ljava.lang.Object;#713dff89 : http://my.test.service.com/svc/brand/samsung?size=10]
[1: Apple/[Ljava.lang.Object;#23ab8f3f : http://my.test.service.com/svc/brand/apple?color=red]
etc...
This is quite logical as the second element {1} is an array.
Is there any way to get the content of the array?
E.g with a notation like
#Parameters(name = "{index}: {0}/{1[0]}-{1[1]} : {2}")
to get
[0: Samsung/size-10 : http://my.test.service.com/svc/brand/samsung?size=10]
[1: Apple/color-red : http://my.test.service.com/svc/brand/apple?color=red]
I tried to use {1}{0}, {1[0]} and {1.0} but none are working
The name-argument of the Parameters annotation is used as first parameter of a MessageFormat.format(pattern, args...) call.
I couldn't find a hint for formatting arrays in the javadoc of MessageFormat. My solution would be to add a fourth parameter to your list of parameters which contains the desired string.
Collection<Object[]> data = ... // build your data
for (Object[] parameter : data) {
parameter[3] = Arrays.toString((Object[]) parameter[1]);
}
return data;
Related
On this earlier thread, some of my code worked perfectly for the scenario in question.
I want to adapt the same code for another similar scenario and I'm yet to understand what could be wrong. This time around I have a coursemodule collection, a many:many relationship collection between courses and modules which only stores coursesId and moduleId. Since the code worked perfectly, I simply copied, did a little modification and arrived at the code below:
courses(){
var theslug = FlowRouter.getParam('myslug');
var mySchoolDocs = SchoolDb.findOne({slug: theslug});
var arrayModuleSchools = ModuleSchool.find({schoolId: mySchoolDocs._id});
// Transform the array of document into an array with only the ids
var arrayModuleId = [];
arrayModuleSchools.forEach(function(moduleSchools){
arrayModuleId.push(moduleSchools.moduleId);
});
var coursetoMod = CourseModules.find({}, {moduleId: {$in: arrayModuleId}});
if (coursetoMod) {
coursesArrayIds = [];
console.log(coursetoSchool);
coursetoMod.forEach(function (courseToModules) {
coursesArrayIds.push(courseToModules.coursesId);
});
return Courses.find({_id: {$in: coursesArrayIds}}).fetch();
}
}
To be specific, only 2 modules exist in the Modules collection, with ids - xfLM9DEzhCMYQpQ32 and PTbZQ9cTG9pByFsY2. The CourseModule collection has this has docs:
{
"_id" : "iXX4unJZRNcCw9bAm",
"moduleId" : "PTbZQ9cTG9pByFsY2",
"coursesId" : "FbgcdZxADHKRBj98z",
"createdAt" : ISODate("2017-08-25T16:36:17.173Z"),
"userId" : "n5rqFSHbhm7zqADyB"
}
{
"_id" : "RAJJFjqAjGoDeNhko",
"moduleId" : "PTbZQ9cTG9pByFsY2",
"coursesId" : "ESAf6NGpZzXeioecp",
"createdAt" : ISODate("2017-08-25T16:36:17.182Z"),
"userId" : "n5rqFSHbhm7zqADyB"
}
{
"_id" : "8ceuFwZK8Qduo5J5P",
"moduleId" : "xfLM9DEzhCMYQpQ32",
"coursesId" : "KnNj4GLcyMtvF8JmB",
"createdAt" : ISODate("2017-08-25T16:38:15.368Z"),
"userId" : "n5rqFSHbhm7zqADyB"
}
At the point where I log into the console I got that the selectorId is undefined:
L…n.Cursor {collection: LocalCollection, sorter: null, matcher:
M…o.Matcher, _selectorId: undefined, skip: undefined…}_projectionFn:
(obj)_selectorId: undefined_transform: nullcollection:
LocalCollectionfields: undefinedlimit: undefinedmatcher:
Minimongo.Matcherreactive: trueskip: undefinedsorter: null__proto__:
Object_depend: (changers, _allow_unordered)_getCollectionName:
()_getRawObjects: (options)_publishCursor: (sub)constructor:
(collection, selector, options)count: ()fetch: ()forEach: (callback,
thisArg)getTransform: ()map: (callback, thisArg)observe:
(options)observeChanges: (options)rewind: ()proto: Object
view.js:30 L…n.Cursor {collection: LocalCollection, sorter: null, matcher: M…o.Matcher, _selectorId: undefined, skip: undefined…}
All I want to do is to fetch the courses attached to a specific school currently displayed via the modules.
You are using the find function the wrong way:
var coursetoMod = CourseModules.find({}, {moduleId: {$in: arrayModuleId}});
The find() function takes two parameters : myCollection.find(query, projection). When you are filtering documents by field, it must be inside the query parameter. And the projection parameter is used to chose which fields to return.
In your case, here's the parameters you are using: query: {} and projection: {moduleId: {$in: arrayModuleId}}. But it needs to be: query: {moduleId: {$in: arrayModuleId}}
So you just have to use the $in as first parameter:
var coursetoMod = CourseModules.find({moduleId: {$in: arrayModuleId}});
By the way, if you want to see directly the documents returned by the find function inside a console.log, use .fetch() :
var coursetoMod = CourseModules.find({moduleId: {$in: arrayModuleId}}).fetch();
MongoDB find function documentation: https://docs.mongodb.com/manual/reference/method/db.collection.find/
#gaetan is on the right track with the answer, you need to use the query parameter instead of the projection parameter. There are some other simplifications that can be made in your code as well using the underscore library that is packaged with Meteor.
courses() {
const slug = FlowRouter.getParam('myslug');
const schoolId = SchoolDb.findOne({ slug })._id;
const Modules = ModuleSchool.find({ schoolId });
const ModuleIds = _.pluck(Modules,'moduleId');
const coursetoMod = CourseModules.find({ moduleId: { $in: ModuleIds }});
if (coursetoMod.length) {
coursesIds = _.pluck(coursetoMod,'coursesId');
return Courses.find({ _id: { $in: coursesArrayIds }}).fetch();
}
}
Here I have this json file.
{
"BnUs5hQZkJWLU9jGlpx9Ifq5ocf2" : {
"bio" : "Your bio!\r",
"birthday" : "Date of Birth?",
"location" : "Location?",
"markerBorder" : 1.5542403222038021E7,
"markerColor" : 8222122.31461079,
"name" : "NamesName?",
"profilePrivacy" : 2,
"sex" : "Gender?",
"privacy" : 2,
"points" : {
"-Kc7lfJk3XbPlNyk-wIR" : {
"address" : "dsfsdfasfsfd",
"description" : "status/desription",
"latitude" : 35.2,
"longitude" : -80.7,
"mediaTargets" : "none",
"pub" : false,
"timestamp" : 1486205926658
},
"aaa" : "aaa"
}
}
}
Those random string of charactors are automatically made when I use firebase.
In this scenario, there might be more "points" I will have to take account for. So when I reference points, I should be talking to an array since it contains both "-Kc7lfJk3XbPlNyk-wIR" (an array) and "aaa" (a string).
So why do I get a type error when trying to convert parsedObject.points into an array?
var parsedObject:Object = JSON.parse(e.target.data);
var multiArray:Array = parsedObject.points;
TypeError: Error #1034: Type Coercion failed: cannot convert Object#5c16089 to Array.
I'm basically trying to do the opposite of what this guy is doing.
Edit: I see in the notes that it only handles string, numbers and Boolean values..
I managed to work around it by adding a "parent" node in the object that duplicates the same value as the name of the entire node so I can reference it in the script. Is there a better way to go about this? Seems pretty redundant.
var parsedObject:Object = JSON.parse(e.target.data);
var myPoints:Object = parsedObject["points"];
//Get all trek names
for each (var key:Object in myPoints)
{
trace("Key = " + key.parent);
trace(parsedObject.treks[key.parent].latitude) //Returns -80.7
}
Because Array is a subclass of Object.
var A:Array = new Array();
var B:Object = new Object();
trace(A is Array); // true
trace(A is Object); // true
trace(B is Array); // false
trace(B is Object); // true
B = new Array(); // nothing wrong here
A = new Object(); // throws exception
So, you might want to tell what kind of data you want to obtain in the Array form from the parsedObject.points Object to proceed.
Alternately, that is how you get actual Array from JSON string:
{
"list": [1,2,3,4,5,6]
}
Looks like it's correctly being parsed by JSON.parse to me.
Arrays in JSON use square brackets, braces are interpreted as objects.
You'd only expect an Array from JSON.parse if you had
"points": [
...
]
whereas this is an Object:
"points": {
...
}
I suggest you look into why you aren't getting [] from your source.
I have recently started coding for iOS and using Swift. I am trying to build a small quiz app for practice. However, I am having an issue running a function that is stored in an array.
My question library swift file is as follows:
func getQuestionLibrary() -> NSArray {
var questionLibrary = [
[
"categoryName": "General Knowledge",
"functionName": generalknowledgeLibrary()
]]
As you can see it states the category and stores a function.
My code that works fine, uses this array (there are more entries) to dynamically create a list of categories to choose from. When a category is run it performs a segue and moves onto a view to display the categories.
If I hard code in the categories that app works great:
if playQuestionLibraryText == "General Knowledge" {
questionPack = generalknowledgeLibrary()
} else if playQuestionLibraryText == "Music" {
questionPack = musicLibrary()
} else if playQuestionLibraryText == "Film" {
questionPack = filmLibrary()
}
However, as the list is dynamic I would prefer it not to be hard coded.
Please can you assist me to allow the my code to search the array and run the function stored as functionName in the array when the correct category has been selected.
Thank you in advance.
The code:
"functionName": generalknowledgeLibrary()
Sets "functionName" to the result of calling the function.
Use:
"functionName": generalknowledgeLibrary
You are looking up a 'library' based on its name; use a Dictionary. Your 'library' is going to hold some stuff (as libraries are wont to do) and allow some behaviors - so capture it as an abstraction.
class Library { // maybe this is a 'questionPack'
// stuff in a library // that is okay, change the name
}
var libraryMap : [String:Library] =
["Music": Library(/*...*/),
"Film" : Library(/*...*/),
"General Knowledge" : Library(/*...*/)
// ....
]
if let library = libraryMap[playQuestionLibraryText] {
// do something with the library
}
i did a code to this question, using subscript
I created a class collection to manage your question. I believe the friend solution just remove () is more easy and correctly, but i created this class to complement my studies, because this I like enter here to try new solutions.
class QuestionCollection
{
struct QuestionItem {
var categoryName:String;
var function:()->Void //Here can add return type you need
}
private var dicCallbacks:[String:QuestionItem] = [String:QuestionItem]();
func add(categoryName:String, closure:()->Void //Here can add return type you need )
{
dicCallbacks[categoryName] = QuestionItem(categoryName: categoryName, function: closure);
}
subscript(categoryName:String)->()->Void //Here can add return type you need
{
get
{
if let callback = self.dicCallbacks[categoryName]
{
return callback.function;
}
return error;
}
set
{
dicCallbacks[categoryName] = QuestionItem(categoryName: categoryName, function: newValue);
}
}
func error()->Void
{
println("error try catch closure function")
}
}
How use this class
func musicTest()
{
println("test Music");
}
func musicGK()
{
println("test Music");
}
func musicFilm()
{
println("test Music");
}
var questionCollection = QuestionCollection();
questionCollection["Music"] = musicTest
questionCollection["General Knowledge"] = musicGK
questionCollection["Film"] = musicFilm
questionCollection["Music"]();
questionCollection["General Knowledge"]();
questionCollection["Film"]();
Sorry for slow reply. I changed my code as this works instead and I am happy with how it works.
The questions in the future will be populated via the internet via a loop.
struct Question {
var categoryName : String
var questionTitle : String
var answerA : String
var answerB : String
var answerC : String
var answerD : String
var correct : String
}
public struct QuestionLibrary {
var questions: [Question]
}
let QuizQuestions =
QuestionLibrary(
questions: [
Question(
categoryName: "General Knowledge",
questionTitle: "Question 1",
answerA: "A", answerB: "B", answerC: "C", answerD: "D", correct: "D"),
Question(
categoryName: "Music",
questionTitle: "Question 2",
answerA: "A", answerB: "B", answerC: "C", answerD: "D", correct: "A"),
Question(
categoryName: "Film",
questionTitle: "Question 3",
answerA: "A", answerB: "B", answerC: "C", answerD: "D", correct: "B")
])
My code then to retrieve questions based on the category is:
let questionLibrary = QuizQuestions.questions
var questionPack: Array<Question>?
questionPack = questionLibrary.filter({c in c.categoryName == "Music" })
I then select a random question
let question = questionPack![randomNumber]
And to display the question text is
question.questionTitle
So, my earlier question was about running functions in an array which I learnt I didn't need to do. But least I've answered so it might have others who need similar code :)
We have created an array of complextype(Carrier field) objects. See below metadata
{ shortName : 'Person',
namespace : 'Demo',
autoGeneratedKeyType : breeze.AutoGeneratedKeyType.Identity,
"dataProperties": [
{
"name": "carriers",
"complexTypeName":"Carrier:#Test",
"isScalar":false
}]
}
The Carrier entity is defined as below:
{
"shortName": "Carrier",
"namespace": "Test",
"isComplexType": true,
"dataProperties": [
{
"name": "Testing",
"isScalar":true,
"dataType": "String"
}
]
}
We have the following matching data for the above entities:
{
carriers: [
{
Testing : 'InputBox1'
},
{
Testing : 'InputBox2'
}
]
}
We are trying to dynamically add the complextype object(Carrier) to the above carriers array by using the following approach:
var test = {
"Testing" : "Test"
};
var result = manager.createEntity('Carrier', test);
The above code throws an exception(undefined is not a function) inside breeze.debug.js at line number 12457(see below code)
entity = entityType.createEntity(initialValues);
The exception is thrown since the complextype entity does not have 'createEntity' function in it.
What are we missing here?
Excellent question - Sorry I didn't have a chance to address this earlier.
When adding a complexType object you need to use the createInstance() method instead of the createEntity.
var thisEntityType = manager.metadataStore.getEntityType('Carrier');
var thisEntity = thisEntityType.createInstance(initialValues);
Basically you get the complexType and then create an instance of it using the values you want assigned. Keep in mind the initial values should be a hash object of course. Often I will include a helper function to do this for me like this -
function createComplexType(entityType, constructorProperties) {
var thisEntityType = manager.metadataStore.getEntityType(entityType);
var thisEntity = thisEntityType.createInstance(constructorProperties);
return thisEntity;
}
I have a schema like following : -
var P = {
s : [{
data : [],
sec : mongoose.Schema.Types.ObjectId
}]
};
Now I want to find only the object of section not entire the row. Like If I pass sec value I want only the value of s.data of that sec object.
example : -
{ s : [
{
data : [],
sec : '52b9830cadaa9d273200000d'
},{
data : [],
sec : '52b9830cadaa9d2732000005'
}
]
}
Result should be look like -
{
data : [],
sec : '52b9830cadaa9d2732000005'
}
I do not want all entire row. Is it possible? If yes, then please help me.
You can use the $elemMatch projection operator to limit an array field like s to a single, matched element, but you can't remove the s level of your document using find.
db.test.find({}, {_id: 0, s: {$elemMatch: {sec: '52b9830cadaa9d2732000005'}}})
outputs:
{
"s": [
{
"data": [ ],
"sec": "52b9830cadaa9d2732000005"
}
]
}
You can always get the value of some field by using find(). For example in your case:
db.collectionName.find({},{s.data:1})
So the first bracket is to apply any condition or query, and in the second bracket you have to define the field as 1(to fetch only those fields value).
Please check http://docs.mongodb.org/manual/reference/method/db.collection.find for more information.
Let me know if it solves your problem.
Not into Mongo or db but working with Pure JavaSript skills here is the Solution as you mentioned Node.js which would do the execution task of the below.
Schema
var P = { s : [
{
data : [],
sec : '52b9830cadaa9d273200000d'
},{
data : [],
sec : '52b9830cadaa9d2732000005'
}
]
};
Search Method Code
var search = function (search_sec){
for (var i=0; i<(P.s.length);i++){
var pointer = P.s[i].sec;
var dataRow = P.s[i];
if((pointer) === search_sec ){
console.log(dataRow);
}
}
};
Here is How you can call - search('search_id');
For example input :
search('52b9830cadaa9d2732000005');
Output:
[object Object] {
data: [],
sec: "52b9830cadaa9d2732000005"
}
Working Demo here - http://jsbin.com/UcobuVOf/1/watch?js,console