alasql - Data source number 0 in undefined ,simple Javascript object as source then query, gives this error - alasql

<script src="https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js"></script>
var ProductList = JSON.parse('[{"ProductID":1,"ProductName":"Shoes"},{"ProductID":2,"ProductName":"Chocolate"}]');
alasql("CREATE TABLE Products (ProductID INT, ProductName string)");
alasql.tables.Products = ProductList; // when inspect, the table is present
var x = alasql("SELECT * FROM Products order by ProductID"); //throws error

I was able to solve it.
db.tables.Products.data - I was missing the data.
Parsing was not required.
var db = new alasql.Database();
db.exec("CREATE TABLE Products (ProductID INT, ProductName string)");
var ProductList = [{"ProductID":1,"ProductName":"Shoes"},{"ProductID":2,"ProductName":"Chocolate"}];
db.tables.Products.data = ProductList;
var res = db.exec("SELECT * FROM Products");

According to the image you shared, I see that you haven't give json data source.
You can fix it by ...
var x=alasql("Select * FROM ? ORDER BY ProductID",[Products])

Related

Googlesheet importxml find value using xpath

I need to get the integer value "maximum drawdown" from this website link =https://www.mql5.com/en/signals/1414510,
from google chrome i tried copy the xpath
//*[#id="radarChart"]/svg/text[8]/tspan[2]
then in google sheet, i write:
=importxml(https://www.mql5.com/en/signals/1414510, "//*[#id='radarChart']/svg/text[8]/tspan[2]")
It cant retrieve the value,
How to write the correct xpath to the value?
thanks
by xpath
Try for https://www.mql5.com/en/signals/1409351
=regexextract(importxml(A1,"//div[#class='s-data-columns hoverable']"),"\((.*)\)")
i highly recommand to test first this formula to have an overview
=importxml(A1,"//div[#class='s-data-columns hoverable']")
by json
the second way could be to parse the json contained in the source (var radarChart)
function radarChart(url){
var source = UrlFetchApp.fetch(url, {muteHttpExceptions: true}).getContentText().replace(/(\r\n|\n|\r|\t| )/gm,"")
var data = source.split(`new svgRadarChart($('radarChart'),[`)[1].split(']')[0]
var values = (data.match(/value : ([^,]+)/g))
var names = (data.match(/name : ([^,]+)/g))
var val
for (var i=0;i<names.length;i++){if (names[i]==`name : 'Maximum drawdown'`){val=values[i]}}
return (val)
}
or
function radarChart(url){
var source = UrlFetchApp.fetch(url, {muteHttpExceptions: true}).getContentText().replace(/(\r\n|\n|\r|\t| )/gm,"")
var data = source.split(`new svgRadarChart($('radarChart'),[`)[1].split(']')[0]
var values = (data.match(/value : ([^,]+)/g))
var names = (data.match(/name : ([^,]+)/g))
var result = []
for (var i=0;i<names.length;i++){
result.push([names[i].replace('name : ','').replace(/'/g,''),values[i].replace('value : ','')])
}
return (result)
}

App crashes when I am trying to saved data in my model

I am developing an App using Realm. At some point in my app when I try to manipulate my model, my app crashed in an unexpected way. Here is what the stack trace said
Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first
What I am trying to do :
lets break down my problem in parts.following is my model of app
#objcMembers public class ClassGroup : Object , Codable {
dynamic var Id : Int? = ""
dynamic var ClassName : String? = ""
dynamic var TeacherId : Int = 0
dynamic var Teachers : [TeacherMdoel]? = []
}
#objcMembers public class TeacherModel : Object , Codable {
dynamic var Id : String? = ""
dynamic var Name : String? = ""
dynamic var ClassId : Int = 0
dynamic var Students : [StudentClass]? = []
}
#objcMembers public class StudentModel : Object , Codable {
dynamic var Id : String? = ""
dynamic var Name : String? = ""
dynamic var ClassId : Int = 0
dynamic var TeacherId : Int = 0
}
now I am trying to get the list of all classes like this from realm (after saving them to realm )
let mClassLists = mDbHelper.realmObj.objects(ClassGroup.self)
Now here I get exception/error. What I am doing is, I am trying to populate my UITableView with some data that consist of all of the above models. I am fetching data and saving them in my model and trying to supply that list to UITableView but my app crash with the error I mentioned above
let mClassLists = mDbHelper.realmObj.objects(ClassGroup.self)
let classLists = Array (mClassLists)
for classModel in classLists {
let resultPredicateTeachers = NSPredicate(format: "ClassId == %#", classModel.Id)
let mTeachersList = mDbHelper.realmObj.objects(TeacherModel.self).filter(resultPredicateTeachers)
if(mTeachersList.count > 0){
var listTeachers : [TeacherModel] = []
for teacherModel in mTeachersList {
let resultPredicateStudent = NSPredicate(format: "TeacherId == 29")
let mStudentList = mDbHelper.realmObj.objects(StudentModel.self).filter(resultPredicateStudent)
if(mStudentList.count > 0){
let studentsList = Array(mStudentList)
teacherModel.Students = studentsList[0]
}
listTeachers.append(savedDetailItem)
}
classModel.Teachers? = (listTeachers)
listClassModel.append(classModel)
}
}
**In the Above code you can see that I am gathering data on behalf of Ids and saving the resultant arrays in the model. So I am getting error in the following line
**
teacherModel.Students = studentsList[0]
now I really do not understand why it is happening? I am not saving data in realm, I am saving in my model, still I am getting error.
In Realm database, if you want to modify any model (save new data or update), the operation should be performed in a write transaction:
try! realm.write {
realm.add(<your_model_objects>)
}

How to populate a table view in a order based off an element from a class

I have the following structures and arrays for my data and for my table view cells:
struct CellData
{
var cell: Int! = 1
var SegueIdentiier: String!
var text: String!
var image: UIImage!
}
struct Course {
var isEmpty: Bool = true
var Title: String = String()
var FK: String = String()
var Subject: String = String()
var teacher_fk: String = String()
var teacher_name: String = String()
var grading_period: String = String()
var room: String = String()
var block_abbreviation: String = String()
var block: Int = 0
var parser: XMLParser!
}
var ArrayOfCellData = [CellData(), CellData(), CellData(), CellData(), CellData(), CellData(), CellData(), CellData()]
var Courses = [Course(), Course(), Course(), Course(), Course(), Course(), Course(), Course(), Course(), Course(), Course(), Course()]
And when I parse an XML file the "block" is filled with a given number. Id like to populate my table view in order of these block numbers.
Ie if Courses[0].block = 4 and Courses[3].block = 2 id like to populate my table view in the order of Courses[3] then Courses[0].
I cant figure out how to do this for the life of me. This is my first time posting on Stackoverflow so please be nice! :)
One way to achieve the desired behaviour would be to sort your list of courses according to your desired sorting criteria.
Courses.sort {
$0.block < $1.block
}
You could also have a sorted copy of your list if the initial order is important for some reasons.
Edit - The other answer appears way simpler than mine, I'd totally go with that one haha. Though here is an example of looking up the documentation and working with what it tells you!
You need to sort your arrays. The indexPath of your cells needs to be able to uniquely determine the index of your array for your data to generate the cell, so you want your array to be sorted before you load the table.
You'll need to write a custom sort function for this, but it should be very easy: https://developer.apple.com/reference/foundation/nsarray/1408213-sortedarray
Your sort should look something like this:
func intSort(course1:Course, course2:Course, void *context) -> NSInteger
{
int v1 = course1.block;
int v2 = course2.block;
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
You may ned to pass the courses as Any and cast them to Courses in the function, but this should get you started.

How to sort NSmutableArray from one of it indexes (lat lng coordinates) in Swift

I'm new in swift and I'd know how to do that in php, but I'm lost with all those dictionaries and I have no idea how to do that in swift 2. I've been googling for a while and didn't found what I need.
I'm parsing a jSon and storing it's values in an NSMutableDictionary in a loop and at the end of the loop I store the NSMutableDictionary in an NSMutableArray, so at the end I have an NSMutableArray with 43 elements, and each element have about 10 keys with their values. I need to sort those 43 elements from their "distance" key and sort them descending. I don't know if that is posible with this current approach. The value of the key "distance" is an int number (meters). I don't know if to use an NSMutableDictionary inside an NSMutable Array is the correct approach to do this but I'm using it because it is possible to have string keys, and not numbers indexes, so for me it's easier to access the key "distance" than the index 8...
First I load the jSon content:
private func parseJson(json : NSMutableArray, tableView : UITableView){
var c : Int = 0
for j in json {
var jsonValues = NSMutableDictionary()
//Create main value
guard let value = j.valueForKey("value")?.valueForKey("value")! else{
continue
}
//Get name
guard let Name : String = (value.valueForKey("Name")?.valueForKey("en") as? String) else {
continue
}
jsonValues["name"] = Name
//more code like this....
TableData.append(Name)
nsDict.insertObject(jsonValues, atIndex: c)
c += 1
}
this is my NSMutableArray content after being loaded:
And this is the code I have this far. Im trying to load the sorted content in a new array, but in this new array some keys are missing.
//Reorder Array by shop distance from user...
var sortDescriptor:NSSortDescriptor = NSSortDescriptor(key: "distance", ascending: true)
var sortedArray : NSArray = nsDict.sortedArrayUsingDescriptors([sortDescriptor])//Crashes
print(sortedArray)
I've managed to sort the array with this technique:
created a new class with for my array
import Foundation
class JsonArrayValues {
init(){
}
var name = String()
var distance = Float()
var lat = Float()
var lng = Float()
var openingTime = String()
var country = String()
var code = String()
var address = String()
var categories = String()
var city = String()
var type = String()
var brands = String()
}
I instantiated one before the loop:
var jsonArrData : [JsonArrayValues] = []
And another one inside the loop, in which I've added the values:
var c : Int = 0
for j in json {
var jsonValues : JsonArrayValues = JsonArrayValues()
//Get name
guard let Name : String = (value.valueForKey("Name")?.valueForKey("en") as? String) else {
continue
}
jsonValues.name = Name
//more code...
jsonArrData.append(jsonValues)
c += 1
}
And finally I've been able to call the function to reorder the array:
//Reorder Array by shop distance from user...
jsonArrData.sortInPlace({$0.distance < $1.distance})
One of your first steps in any non-trivial project really should be to spend some time looking around on github for tools that simplify your problem. In this case, you'd find there are so very many tools to simplify working with JSON in Swift. I'd suggest you look at EVReflection and Gloss particularly, although there are also many people who use SwiftyJSON.
You don't mention how you're accessing the network; you could look at AFNetworking or Alamofire. The latter also has AlamofireJsonToObjects to help.
I also found JSONExport to be incredibly useful.
You'd be spending a lot less time futzing with details as in this unfortunate question and more getting on with your larger goal.

Swift Fill sections & rows in UiTableview

I am trying to fill in a table view from a dictionary data source and tried a lot to achieve desired result but lot of error, need help on this:
this is my test code in playground which almost gives me desired result, but when i try to do same thing in project nothing works:
I have marked my questions next to problem command line:
var sections = Dictionary<String, Array<String>>()
var mySId = ["s1","s2"]
var m``Sdate = ["jun1", "jun2"]
var mEdate = ["jun2", "jun4"]
var mytotalArr = [String]()
var index = 0
for myId in myScId {
mytotalArr.append(mSdate[index]) // transfer data to total array to group
mytotalArr.append(mEdate[index]) // tarnsfer data to total array to group
sections["\(myScId[index])"] = mytotalArr
index++
}
println(sections["sch1"]!) // "[jun1, jun1]"
// in project i do it like this
in cellForRowAtIndexPath
var myarr = sections[indexpath.section]
when i do same as above in project error message // Unresolved Identified indexPath
var mystring = sections["sch1"]!
println(mystring[1]) // "jun1"
Or Please suggest a way to achieve the result as below
Section header = Sch1 ,
row1 = jun1 // mSdate ,
row2 = jun2 // mEdate
section header = Sch2 ,
row1 = jun2 ,
row2 = jun4
Solution for this was not simple to figure out, but i managed using other Stack's.
Basically first you get the value from your first key in Dict, and that search for data witihin it.
little overkill on system and coding, but it works.

Resources