Nodejs Array keeps distributing array over multiple lines - mysql

To keep this short, i m working on a small discord bot. The bot is supposed to grab a servers banlist and then put it into its database. The problem is, to make a bulk insert, you appearently need an array that is stuctured like this
[
["blah 1", "bluh 1"],
["blah 2", "bluh 2"]
]
The problem that i m facing is, it distorts the formatting of the array for some reason
[
["blah 1", "bluh 1"],
[
"blah 1",
"bluh 1"
],
]
This is the code i use to create the array
list.forEach(element => {
if(element.reason === null){ var reason = "No reason Given"}else{ var reason = element.reason}
var userArray = [
element.user.id,
element.user.username,
element.user.discriminator,
reason,
element.user.bot
]
banArray.push(userArray)
})

Okay, to put this short again (its 4:11 am here right now, and i m lacking a lot of sleep). I found the problem i was having. I tried to use an array in my prepared statement while putting the unknown value into brackets.
queryStmt = "INSERT INTO tbl_bans (dtUserId, dtUserName, dtDiscriminator, dtReason, dtBot) VALUES (?)";
Notice the (?). The problem is, that i simply didnt look correctly at the code sample, and overlooked that there were no () around the ? in the sample.

Related

Google books api returns missing parameters

I am making a react app that searches for a book by title and returns the results.
It's mostly working fine, but for some titles searched (such as "hello") it can't get the results because the parameters are missing.
Specially, the "amount" value is missing, and it can get me e-books that are not for sale even if I add the filter=paid-ebooks param while fetching the api. Using projection=full doesn't help either.
For example, when I call the api with
https://www.googleapis.com/books/v1/volumes?printType=books&filter=paid-ebooks&key=${APIKEY}
and use the fetched data inside books array in reactjs:
this.props.books.map((book, index) => {
return (
<CardItem
key={index}
title={book.volumeInfo.title}
authors={book.volumeInfo.authors ?
book.volumeInfo.authors.join(', ') :
"Not provided"}
price={book.saleInfo.listPrice.amount}
publisher={book.volumeInfo.publisher}
addToCart={() =>
this.props.addItem(this.props.books[index])}
/>
)
})
One of the results it gets is like this:
"saleInfo": {
"country": "TR",
"saleability": "NOT_FOR_SALE",
"isEbook": false
}
While it should be like, what's expected is :
"saleInfo": {
"country": "TR",
"saleability": "FOR_SALE",
"isEbook": true,
"listPrice": {
"amount": 17.23,
"currencyCode": "TRY"
}
And trying to search with this api answer throws the error :
TypeError: Cannot read property 'amount' of undefined
price={book.saleInfo.listPrice.amount}
As you can see in react code's authors, this issue comes up with authors parameter too, which I've bypassed as seen in the code. But I cannot do the same with amount. Is this a known error in Google Books API or is there a way to prevent this? I don't understand why it still returns me e-books that are not for sale even with filter=paid-ebooks param.
I have not dug into the API documentation. An ideal solution would be a query param that only sends back books with a list price (like you tried with filter=paid-ebooks). Because that's not working, a simple fix would be to filter your results once you get them.
Assuming the response contains an array of book objects, it would look something like this:
const paidBooks = apiResponse.data.filter(book => book.listPrice)
This code will take the response from the API, and filter out all books that do not contain a truthy value for listPrice
That totally right, actually i never used react but the same logic try using try{ }catch(error){} for those missing data

PHP iterating through array - Can't reach top level values?

I try to search long and hard to find my answers and almost never ask questions if I can help it. but it's 5am and I've been working on this project for quite a few months now and I'm stuck.
THE PROBLEM
I have a JSON file saved on my local server which has the following layout:
*Note I've cut down the JSON file to remove the bloat and focus on exactly what I'm trying to extract here.
{
"count": 74,
"results": [
{
"listing_id": 151323205,
"Images": [
{
"url_75x75": "https:\/\/img1.etsystatic.com\/013\/0\/7566894\/il_75x75.459599049_hptl.jpg",
},
]
}
],
"params": {
"limit": "1",
"shop_id": "username",
},
}
THE CODE
Now I've managed to iterate through all the other stuff like 'listing_id' & 'Images' but it appears the 'shop_id' is outside of the scope of my foreach command and inside the 'params' portion?
foreach($results->results as $product){
$products[$i]['url_75x75'] = $product->Images[0]->url_75x75;
$i++;
}
I'm not super PHP savvy so If you can dumb it down just a bit? It's probably something very simple for you guys and I'd like to learn what I'm doing wrong and how to do it right.
This isn't the full code like I stated so if you need more insight please ask. I didn't want to bombard people with a bunch of my keyboard slapping coding skills :)
Thank you so much! I love SO!
You should be able to get the shop id with the following code:
$shop_id = $results->params->shop_id;
You can use this inside the foreach loop if you want to (though its value will not change of course).
$results is probably your whole object, which contains all the data that was in the JSON. $results->results reads only the "results" part inside the JSON, so the loop only iterates over what is in there.
To read the shop id, you can just read:
echo $results->params->shop_id;
Params is on the same level as results so in your for each where you are looking at $results->results, you are not including params, you can nest your for each like
Foreach ($results as $result) {
Foreach ($result->results){}
Foreach ($result->params){}
}

Filters aren't applied when data comes from $http

This is kind of a next-step from filter data using dropdown?, and callmekatootie's answer-plunk (http://plnkr.co/edit/n7TebC). Taking that and a few other things, I've got two dropdowns that can act together/apart to filter the data set, and I've applied a limit so it'll only show 4 (and then four more on ng-click, etc). The current plunk is here: http://plnkr.co/edit/Sc283f.
If I set the data inside the scope (no $http), and turn off the quantity limit, the two filters work perfectly.
If I add the limit first, like this:
<li data-ng-repeat="item in data | limitTo:quantity | filter:customFilter">
then it's giving me the first 4 items in data and then applying the filter, which in some cases gets me nothing. But if I reverse that and get the data first:
<li data-ng-repeat="item in data | filter:customFilter | limitTo:quantity">
the limit only works the first time. Change either filter and the limit no longer seems to apply regularly/correctly/something.
And if I change the data to come in via $http, none of it works. I just get the entire set, no filter, no limit. I could probably live with and/or figure out a way around and/or eventually fix the first two issues (the filters and the limit) but I just can't see any reason why the filters/limit work (mostly) when the data is local, but fail when the data's coming in through $http.
I'm sure I'm missing something really obvious and simple, but hell if I know. Anyone?
The test data is an array of animals...
[
{ animal : 'dog', color : 'blue'},
{ animal : 'cat', color : 'red'}
]
But the JSON downloaded by $http is an object with an animal in each property...
{
"0": {"title": "...", "animal": "dog", "color": "purple"},
"1": {"title": "...", "animal": "cat", "color": "yellow"}
}
Angular's built in filter only accepts arrays, which is why it's being bypassed when you give it an object instead.
You can change the service to return an array, or you can transform the data to an array when returned from $http with a function like this...
function toArray(data) {
var items = [];
angular.forEach(data, function (value) {
items.push(value);
});
return items;
}
$http.get('demo.json').success(function(data) {
$scope.data = toArray(data);
});
Updated Plunker

Getting and displaying JSON data fields using HTML and AngularJS

Im new to angularJS and web designing as a whole. Im trying to get a data field(or element) from a JSON. For example, this is what the JSON looks like
{
"Name":"Raymond Eugene Monce",
"Dateofbirth":"1924-0308T00:00:00Z",
"Ethnicity":"Caucasian",
"Languages":["{English}"],
},
and I'm trying to get the "Name" data field. This is what my .js file looks like,
var profile = angular.module('profile', ['ui.bootstrap','ngResource']);
profile.controller("profileController", ["$scope","$resource", function($scope, $resource) {
// get the user id
$scope.userid = sessionStorage["cerestiuserid"];
// json we get from server
$scope.apicall = sessionStorage["cerestihome"]; // NEED TO CHANGE API
// grabs the user we want
$scope.userResource = $resource($scope.apicall + "/api/userprofile/",
{Userid:21},
{'get':{method: 'POST'}}
);
// fetch JSON
$scope.userResource.get(function(result) {
// get the name field
$scope.name = result;
sessionStorage["name"] = JSON.stringify(result);
});
and my .html file,
<div ng-controller = "profileController" style="float:left">
<!-- profile pic -->
<div class="pull-left">
<div class="container-fluid">
<div class="profile">
<div class="row">
<div class="center-block">
<div class="profilePic">
<img ng-src="{{profilePic()}}" class="img-responsive">
<!-- name field -->
<label class="caption">
<h4>{{name.name}}</h4>
</label>
</div>
Again, Im not having problems with the Database or API calls. I just want to know how I can get and display the name field of the JSON. Thanks.
strelok2010's comment above should work although that depends on if your result really looks like the one defined at the top of your question.
Your result seems to be a normal javascript object not JSON. (yeah they are different, and that confused me when I learned it.) I assume that because you stringify the result from a javascript object into JSON. Therefore if that is working right your result is either a javascript object or an array of javascript objects. I'm assuming an array. You might want to check though.
I noticed your earlier post had a related problem.
In that one you were asking to access a property of an object that was in an array. In that case it was result as well. Here was the answer from your previous question
var result = [{"name": "Jason"
"date of birth": "february 23, 2985"
....
}];
var firstResultsName = result[0].name;
There are two things I am unsure of due to the inconsistency between this and your last question.
First your name property in your results object is spelled with a capital N here as opposed to a lower case n in your last question.
Keep in mind that capitilization matters in javascript.
Second your result in your last question was an array of objects and in this it seems to be just an object.
So depending on which one it is will determine your solution. So instead of writing every possible solution I'll show you how to determine the solution.
Remember we are dealing with a normal array of javascript objects. I'll try to go into detail so it's extra clear (sorry I heard you were new to web developement, I'm assuming JavaScript too.), but sorry if it's a little too detailed. I will also be breaking it into parts to go deeper into the array of objects that I'll use in my example, but traversing into the data structure can all be done in a single line as I will show.
You can only do actions on the 'outermost-form' (by the way 'outermost-form' is just a term I'll use for clarification it's not really a technical term.) and work your way into the collection (object/array/string)
As an example we have an array of people, with the array being the 'outermost-form'
var people = [
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
},
{
"name": "Timothy",
"Occupation": "Accountant",
"date of birth": "02/23/78"
}
];
If we saw the value of people at this moment it not surprisingly be.
[
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
},
{
"name": "Timothy",
"Occupation": "Accountant",
"date of birth": "02/23/78"
}
]
Start with the Array
Since it's an array as the 'outermost-form' we can get one of its values using an index. Just like any other array. Just for a bit of contrast I'll show you how what we are doing is similar to any other array by showing an example of an array by itself
// simple array example
var array = ["foo", "bar", "baz"];
array[0] // returns "foo"
// more simple array example, but less practical (it's more just for showing how javascript can work.)
["foo", "bar", "baz"][2] // returns "baz"
Back to our main example. Let's make a variable person and store our first person in the people array in that value.
var person = people[0];
Now if saw our person variable it would equal the following
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
}
You can see just like the normal array it grabs the first item in the array. You can see how we are slowly traversing into our people data structure. (that being an array of objects.)
Enter the Object
Okay so now we have the person object, but we want the name of that person so since we are dealing with an object we have to access its properties we can do this with either 'dot notation', e.g. <object>.<property>, or 'bracket notation' which can be done with either a variable or a string for the property name. e.g. <object>.["<property>"] or <object>.[<variable>]
So just as a side example I will show you what it normally takes to get the value of a property of an object just so you can compare and see there's no 'magic' going on. Keep in mind javascript is case-sensitive. Also javascript objects properties can go with or without surrounding quotes unlike JSON. One last thing having a space in the property name forces us to use quotes, and also forces us to access that property via bracket notation.
var result;
var obj = { foo: 1, Bar: 2, "foo bar": 3 };
var randomVarName = "Bar"; // notice the capital B in Bar is important since it was declared that way.
result = obj.foo; // result equals 1
result = obj[randomVarName]; // result equals 2
result = obj["foo bar"]; // result equals 3
Back again to our main train of thought. So we have traversed into our people array to find the person object now let's get their name.
var name = person.name;
The value of name would be.
"Bob"
You can do with that what you wish. You could have also used any of the previous ways to get an objects property including bracket notation.
Do Everything we just did in a Single Line
So to write that all in one line you would just write
people[0].name
Apply to your Question
So to apply to your question if your result looks like this
var result = [
{
"name": "Jason"
"date of birth": "february 23, 2985"
....
}
];
Then you need this to get the name
result[0].name
If it's just this
var result = {
"name": "Jason"
"date of birth": "february 23, 2985"
....
}
Then you just need
result.name
As asked in the comment if you want to get the date of birth property out of the object you need to use bracket notation to get the element out of an object. Bracket notation is one of the two object property accessors the other being dot notation. I covered both at the enter the object section. It can be used at anytime, but is usable in some cases that dot notation does not work.
An example and quote from MDN:
get = object[property_name];
object[property_name] = set;
property_name is a string. The string does not have to be a valid identifier; > it can have any value, e.g. "1foo", "!bar!", or even " " (a space).
So since certain character like spaces can't be used in dot notation bracket notation must be used in those special cases when those characters are present.
Below is the bracket notation of the date of birth.
result["date of birth"]
Like I said before it can be used anywhere, but generally dot notation is preferred for its brevity. So just to show that, we will show the name field being accessed using bracket notation:
result["name"]
One additional reason you may want to use bracket notation is for its ability to use variables like so.
var prop_name = "date of birth";
result[prop_name];
which actually if you understand the principle of that example the MDN example might make more sense.
If you have a question feel free to leave me a comment.

Linq to SQL InsertOnSubmit for multiple objects

I have a problem with Linq to SQL InsertOnSubmit, which only seems to work for the first item in a table.
For example with the following:
var noteDetail1 = new NoteDetail() { Title = "Test Note Title 1", NoteText = "Test note" };
var waiverDetail1 = new WaiverDetail() { Title = "Test Waiver Title 1", NoteText = "Test waiver details text" };
var riskDetail1 = new RiskDetail() { Title = "Test Risk Title 1", NoteText = "Test risk details text" };
context.Notes.InsertOnSubmit(noteDetail1);
context.Notes.InsertOnSubmit(riskDetail1);
context.Notes.InsertOnSubmit(waiverDetail1);
context.SubmitChanges();
I only get the first entity ("Test Note Title 1") inserted into the database. If I place a SubmitChanges after each InsertOnSubmit, all the rows are successfully inserted.
The above Types are all inherited from a Note class, so are inserted into the same table.
I am, however, experiencing the same problem with non-derived classes.
I've spent a long time looking at this but can't find what I've done wrong. The whole idea of InsertOnSubmit/SubmitChanges is so that you can do multiple changes so there must be something simple I am missing.
The problem was that I had overriden Equals in my entity classes so that entities with the same Id were considered the same. Obviously, Linq to SQL is using this at some point and getting the result that all new entities are equal (because they all have the Id of 0).
Thanks Jonathan for being my "Rubber Duck".