Im having a game where after I finish a certain level I put that level`s name In an Array and save that array to an SharedObject(SO). But somehow/somewhere I mess up things, because after closing and opening the game again, I load the SO data (to unlock the levels that I have passed) and it is (the loaded data) always messed up and not loading what it should load(sometimes it even trows some errors at me.)
The code is not that difficult but I have been looking at it for far to long and I need new eyes to see the obvious mistakes in it.
***********EDIT**********
So the code for the SO is this
public class LevelsData extends SharedObject
{
public static var LEVELS_DATA:SharedObject = SharedObject.getLocal("save_poi71");
public static function get LoadNamesOfLevelPassed():Array
{
var myLevelsArr:Array = [];
if( LEVELS_DATA.data.PlayedLevels_arr == undefined)
{
myLevelsArr.length = 0;
}
else
{
myLevelsArr = LEVELS_DATA.data.PlayedLevels_arr;
}
return myLevelsArr;
}
public static function set SaveLevel_Names( nameOfLevelPassed:Array ):void
{
LEVELS_DATA.data.PlayedLevels_arr = nameOfLevelPassed;
LEVELS_DATA.flush();
}
}
and the code in the game is this
.
.
.
.
private function didWePlaySameLevel():void
{
var namesPlayed_arr:Array = LevelsData.LoadNamesOfLevelPassed;
var namesTotal:int = namesPlayed_arr.length;
if( namesTotal == 0 )
{
trace(" ScreenInGame_2 | didWePlaySameLevel | namesTotal == 0 so we push Level_1");
namesPlayed_arr.push( Moving_Picture_Name );
LevelsData.SaveLevel_Names = namesPlayed_arr;
sameLevel = false;
}
else if( namesTotal != 0 )
{
for( var i:int = 0; i < namesTotal; i++)
{
trace(" ScreenInGame_2 | didWePlaySameLevel | " + Moving_Picture_Name + " ?==? " + namesPlayed_arr[ i ] );
trace(" ScreenInGame_2 | didWePlaySameLevel | namesPlayed_arr.length = " + namesPlayed_arr.length);
if( Moving_Picture_Name != namesPlayed_arr[ i ] )
{
trace(" ScreenInGame_2 | didWePlaySameLevel | " + Moving_Picture_Name + " != " + namesPlayed_arr[ i ] );
namesPlayed_arr.push( Moving_Picture_Name );
LevelsData.SaveLevel_Names = namesPlayed_arr;
sameLevel = false;
trace(" ScreenInGame_2 | didWePlaySameLevel | namesPlayed_arr.length = " + namesPlayed_arr.length);
}
}
}
}
.
.
.
if( levelsToUnlock < totalLevels && sameLevel == false )
{
trace("ScreenInGame | unlockOneMoreLevel | we UNLOCK 1 more level" );
unlockNextLevel();
}
***EDIT PROBLEM:
SomeHow i figured a way of solving my 1st problem, but now there is a new one and that is :
When the Array from the SO is != 0 i go into the else if statement. There i compare if any of the variables in the Array have the same name of the Moving_Picture_Name and if they dont then I set the sameLevel = false. The problem is that, if lets say I have passed/played 5 levels before( Level_1,Level_2,Level_3,Level_4,Level_5 ) and lets say I start playing Level_2 again it would show me this:
Level_2 != Level_1 - > and it will push itself into the Array and update the data
Level_2 == Level_2 - > it will do nothing
Level_2 != Level_3 - > and it will push itself into the Array and update the data
Level_2 != Level_4 - > and it will push itself into the Array and update the data
Level_2 != Level_5 - > and it will push itself into the Array and update the data
so it will actually push 4 Elements in the Array that exist already in that Array.
***THE QUESTION :
So how do I push the newLevel only if its name isnt in that Array(the one where I save the names), And how do I do nothing if the name exist in the Array already.
You may have to convert your array to ByteArray, and save that. When you read it back, you will have to do the reverse operation. StackOverflow example link
Related
after couple of days i finally got some values from 1st and 2nd line but after that at 4th line i got stacked and nothing works.
in need to get data from db where:
obrat | memb | tab3. | history
| member1 | 0. | 10
200 | member2 | member1. | 3
100 | member3 | member1. | 4
so if i will select from tab3 users which have my memb i need to sum their obrat and history. And doo the same think with them - select from tab3 where names are member1 and member2 and sum that.
my code:
while ($row = $resulto->fetch_assoc()) {
$memb2 = $row['memb'];
// second line member sel.
$resulto2 = $mysqli->query("SELECT * FROM users WHERE tab3='$memb2' ") or die($mysqli->error());
//pokud druhá linie
if ($resulto2->num_rows > 0) {
while ($row2 = $resulto2->fetch_assoc()) {
$memb3 = $row2['memb'];
} // should be 3. line
// get numbers from 2. line
$resulto2 = $mysqli->query("SELECT * FROM users WHERE tab3='$memb2' ") or die($mysqli->error());
$d = 0;
$rows2 = array();
$rows3c = array();
while ($rowd = $resulto2->fetch_array()) {
array_push($rows2, $rowd['obrat']);
array_push($rows3c, $rowd['history']);
}
$array2 = array_sum($rows2);
$count3 = array_sum($rows3c);
}
}
//end / get values first line
$resulto = $mysqli->query("SELECT * FROM users WHERE tab3='$memb' ") or die($mysqli->error());
$d = 0;
$rows = array();
$rows2c = array();
while ($rowd = $resulto->fetch_array()) {
array_push($rows, $rowd['obrat']);
array_push($rows2c, $rowd['history']);
}
$array = array_sum($rows);
$count2 = array_sum($rows2c);
}
some idea where is the problem?
or next way iam trying to :
$resulto2 = $mysqli->query("SELECT * FROM users WHERE tab3='$memb' ") or die($mysqli->error());
if ($resulto2->num_rows > 0) {
while ($row2 = $resulto2->fetch_assoc()) {
$memb2 = $row2['memb'];
$resulto2a = $mysqli->query("SELECT * FROM users WHERE tab3='$memb2' ") or die($mysqli->error());
while ($row2a = $resulto2a->fetch_assoc()) {
$memb3 = " OR memb='".$row2a['memb']."'";
//here i need to get one value which is sum from all users selecting
}
}
I am working on an android app that get json content of a webservice called "WebUntis". The Json content i am getting looks like:
{"jsonrpc":"2.0","id":"req-002",
"result":[
{"id":125043,"date":20110117,"startTime":800,"endTime":850,
"kl":[{"id":71}],
"te":[{"id":23}],
"su":[{"id":13}],
"ro":[{"id":1}]},
{"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
"kl":[{"id":71}],
"te":[{"id":41}],
"su":[{"id":19}],
"ro":[{"id":31}]},
...]}
As you can see in the result-array there are also other arrays like "kl", "su" and "ro"
I am getting the content of these array and then i store them in an arraylist.
But when one of these array is empty, like;
{"jsonrpc":"2.0","id":"req-002",
"result":[
{"id":125043,"date":20110117,"startTime":800,"endTime":850,
"**kl":[]**,
"te":[{"id":23}],
"su":[{"id":13}],
"ro":[{"id":1}]},
{"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
"kl":[{"id":71}],
"te":[{"id":41}],
"su":[{"id":19}],
"ro":[{"id":31}]},
...]}
I am always getting the error IndexOutOfRangeException,
but I am always telling it that it should not take the empty arrays, this is what I have tried:
JSONObject jsonResult = new JSONObject(s);
// Get the result object
JSONArray arr = jsonResult.getJSONArray("result");
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
anfangStunde[i] = c.getString("startTime");
endeStunde[i] = c.getString("endTime");
// get the jsonarrays (kl, su, ro)
kl = c.getJSONArray("kl");
su = c.getJSONArray("su");
ro = c.getJSONArray("ro");
// check if kl is not null
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
if (klassenID[i] != null) {
klasse = webuntis.klassenMap.get(klassenID[i]);
Log.d("ID und Klasse=", "" + klassenID[i] + ";" + klasse);
}
// get th ids
fachID[i] = su.getJSONObject(0).getString("id");
if (fachID[i] != null) {
fach = webuntis.faecherMap.get(fachID[i]);
Log.d("ID und Fach=", "" + fachID[i] + ";" + fach);
}
// "Start;Ende;Klasse;Fach;Raum" store in arraylist
webuntis.stundenPlan.add(anfangStunde[i] + ";" + endeStunde[i] + ";" + klasse + ";" + fach);
// Write Data into a file for offline use:
}
Can anyone help me ?
If the array is defined in the file but is empty, like:
...
"kl":[]
...
Then getJSONArray("kl") will return an empty array, but the object is not null. Then, if you do this:
kl = c.getJSONArray("kl");
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
kl is not null and kl.getJSONObject(0) will throw an exception - there is no first element in the array.
Instead you can check the length(), e.g.:
kl = c.getJSONArray("kl");
if(kl != null && kl.length() > 0 ){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
You can also use isEmpty() method, this is the method we use to check whether the list is empty or not. This method returns a Boolean value. It returns true if the list is empty otherwise it gives false. For example:
if (!k1.isEmpty()) {
klassenID[i] = kl.getJSONObject(0).getString("id");
}
You can use the regular length() method. It returns the size of JSONArray. If the array is empty, it will return 0. So, You can check whether it has elements or not. This also keeps you in track of total elements in the Array, You wont go out of Index.
if(k1 != null && k1.length != 0){
//Do something.
}
This is another way to do it...
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call,
Response<JsonObject> response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(new Gson().toJson(response.body()));
JSONArray returnArray = jsonObject.getJSONArray("my_array");
// Do Work Only If Not Null
if (!returnArray.isNull(0)) {
for (int l = 0; l < returnArray.length(); l++) {
if (returnArray.length() > 0) {
// Get The Json Object
JSONObject returnJSONObject = returnArray.getJSONObject(l);
// Get Details
String imageUrl = returnJSONObject.optString("image");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonObject> call,
Throwable t) {
}
});
I'm fetching a large Amount of data from RIA Service. the return type have group of objects like RouteA, HistroyRouteA. HistroyLogRouteA all have records for different years with same Unique Key.
I have to Bind this data dynamically to a RadGridView. Always I have unknown columns in result.
For this I followed
http://blogs.telerik.com/vladimirenchev/posts/11-09-28/dynamic-binding-for-your-silverlight-applications.aspx
http://www.telerik.com/forums/rowdetailstemplate-binding-with-dynamic-data
And build My data Collection with Code :
private void OnShowPreviousYear(object parameter)
{
GridViewHeaderCell cell = parameter as GridViewHeaderCell;
var head = cell.Column.Header;
this.context.Load<Route>(this.context.GetRoutesQuery(), LoadBehavior.MergeIntoCurrent, OnRouteHistoryLoadComplete, null);
}
private void OnRouteHistoryLoadComplete(LoadOperation<Route> lo)
{
object ro = null;
if (lo.Entities != null)
{
this.context.Load<Routeshistory>(this.context.GetRouteshistoriesQuery(), LoadBehavior.MergeIntoCurrent, (lp) =>
{
Route recent = lo.Entities.FirstOrDefault();
int year =(int)recent.Hpmsyear-1;
var rows = this.context.Routes.Join(this.context.Routeshistories,
r => r.Routeid.ToString(),
h => h.Routeid.ToString(),
(r, h) => new { r, h });//.Where(t => t.r.Routeid == t.h.Routeid );
RoutesGridData = new ObservableCollection<DataRow>();
int count = 0;
foreach (var tmpR in rows)
{
//Debug.WriteLine(tmpR.r.Routeid + " -- " + tmpR.h.Routeid);
if (count < 50)
{
DataRow row = new DataRow();
if (tmpR.r is Route)
{
Type type = tmpR.r.GetType();
foreach (PropertyInfo info in type.GetProperties())
{
// Debug.WriteLine(info.Name + "--- NAME OF PRR");
var val = info.GetValue(tmpR.r, null);
if (!info.Name.Equals("EntityConflict")
&& !info.Name.Equals("ValidationErrors")
&& !info.Name.Equals("HasValidationErrors")
&& !info.Name.Equals("EntityState")
&& !info.Name.Equals("HasChanges")
&& !info.Name.Equals("IsReadOnly")
&& !info.Name.Equals("EntityActions"))
{
row[info.Name] = val;
}
}
}
// other tables...
RoutesGridData.Add(row);
}
count++;
}
}, null);
}
// var b = ro;
}
this code works fine for small record like 50 rows. but I when It try to convert all data it become slow. and screen crashes. I think this is because of Reflection. Is there any other way to convert my fetch data into Dictionary? Means I can map my table to dictionary in Entity Framework or Linq can do this for me without getting my code slow etc.
My Entities are mapped with EF 6 & I m using Deart oracle connector.
Due to reflection it was getting extremely slow so I did in during Linq query it's working for a while what data I have with me.
var rowss = this.context.Routes.Join(this.context.Routeshistories,
r => r.Routeid,
h => h.Routeid,
(r, h) => new DataRow(
(from x in r.GetType().GetProperties() select x).Where(x => x.Name != "EntityConflict"
&& x.Name != "ValidationErrors"
&& x.Name != "HasValidationErrors"
&& x.Name != "HasChanges"
&& x.Name != "EntityState"
&& x.Name != "IsReadOnly"
&& x.Name != "EntityActions")
.ToDictionary(x => x.Name, x => (x.GetGetMethod().Invoke(r, null) == null ? "" : x.GetGetMethod().Invoke(r, null))),
(from x in h.GetType().GetProperties() select x).Where(x => x.Name == head)
.ToDictionary(x => x.Name + "-" + year.ToString(), x => (x.GetGetMethod().Invoke(h, null) == null ? "" : x.GetGetMethod().Invoke(h, null))))
);// , new EqualityComparerString()
RoutesGridData = new ObservableCollection<DataRow>(rowss);
Here is what I'm trying to do :
I have 2 lists.
List 1 : 00F0001,00F0002,00F0003,00F0004,00F0005,00F0006,00F0007,00F0008,00F0009,00F0010
List 2 : 00F0006,00F0007,00F0008 (this list is generate by the 1st item($debut) and the last one($fin))
What i want to do is :
return me true if the "List 2" is in the "List 1", just that.
So I tried with 2 for but I get blocked :/
My code :
$id = substr($debut,0,4);
echo '</br>id : '.$id; /* = 00F0*/
$Start = substr($debut,4,25);
$End = substr($fin,4,25);
$range = $End - $Start +1;
echo '</br>Range : '.$range; /* = 3 with the example I gave*/
for ($i = 0;$i < $range;$i++){
$indice2 = $Start + $i;
$Num_Serie = str_pad($indice2, 4, '0', STR_PAD_LEFT);
$Num_Serie_Final[$i] = $id.''.$Num_Serie;
}
$ArrayNS = $Num_Serie_Final;
$i_W = 0;
while(($produit = $reponse->fetch())AND($check3 == "false")){
$ArrayProduit[$i_W] = $produit[1];
$i_W++;
}
for ($i2 = 0; $i2 < $i_W; $i2++){
for ($i3 = 0; $i3 < $range; $i3++){
if ($ArrayNS[$i2] == $ArrayProduit[$i3]){
.... ???? .....
}
}
}
The 1st "for" is to build my "List 2".
The "while" loop is to generate my "List 1"
Then i did a double "for" loop but its here where I lock :/
EDIT
I tried something for the one interested :
for ($i3 = 0; $i3 < $range; $i3++){
for ($i2 = 0; $i2 < $i_W; $i2++){
if ($ArrayNS[$i3] == $ArrayProduit[$i2]){
for ($indice=0; $indice < $range; $indice++){
if ($ArrayNS[$indice] == $ArrayProduit[$i2+$indice]){
$ok = true;
echo '$ArrayNS[$indice] : '.$ArrayNS[$indice].' == $ArrayProduit[$i2+$indice] : '.$ArrayProduit[$i2+$indice].'</br>';
}
else {
$ok = false;
$id_erreur = $ArrayNS[$indice];
echo 'Fail with : '.$ArrayNS[$indice].' !== '.$ArrayProduit[$i2+$indice].'</br>';
}
}
if ($ok) {
echo 'Success !!!';
return ($ok);
}
else {
echo 'Fail !!!';
return ($id_erreur);
}
}
}
}
Probably not the best way to do it but it works ^^
I chose js for console testability, but the algorithm is the same in php.
This one returns an index, but you just have to check if your index is different from -1 to tell if it has been found or not.
The idea is to loop through each element of the haystack (l1 here) and if the current element matches the first element of our needle (l2) then we start to loop from the current haystack index (i) to the end of our needle index (i + j), but if any of these elements doesn't match (at the first occurrence) we skip to the next value of the haystack (l1) and try again. If we did not fail (failedMatch flag) then return the index of the subsequence (l2 in l1 start position).
If the subsequence doesn't appear in the haystack we return -1 by convention.
This is a left to right approach so it will only match the first occurrence of the subsequence, and if it appears more than once, you won't know.
var l1 = [1,2,3,3,4,5,6],
l2 = [3,4,5];
function subsequenceIndex(l1 /* haystack */, l2 /* needle */) {
var startIndex = -1,
failedMatch;
for (var i = 0; i < l1.length; i++) {
failedMatch = false;
if (l1[i] === l2[0]) {
for (var j = 1; j < l2.length; j++) {
// check first that l1[i + j] is set
if (l1[i + j] !== undefined && l2[j] !== l1[i + j]) {
failedMatch = true;
break;
}
}
if (!failedMatch) {
startIndex = i;
}
}
if (startIndex !== -1) {
return startIndex;
}
}
return startIndex;
}
I have a database with the following structure
user_id | cat_name | cat_slug | parent_id
-------------------------------------------
Tools | tools | 0 |
2 |Chainsaws |chainsaws | 1
etc
My end goal is to essentially have an array that has a breadcrumb trail of sorts that shows the category path, it could have anywhere from no parents to 5 levels of category parenting.
I was able to kind of get what I want.. with a few errors along the way. I keep getting a Trying to get property of non-object error. Althrough all my other attempts at returning values have failed.
My solution outputs my (semi - desired) effect underneath the errors, and with additional category breaks ( symbolized by ">" ). I was just hoping someone could help me clean it up, because I'm at a breaking point, after going about this for a few hours with no solution.
Model
function get_parent_trail($parent_id){
if ( $parent_id != 0 && $parent_id){
$parent_trail = array();
for( $i = 1; $i <= 4; $i ++ ) {
$this -> db -> select ( '*' );
$this -> db -> from ( 'categories' );
$this -> db -> where ( 'cat_id' , $parent_id );
$query = $this -> db -> get() -> row();
array_unshift( $parent_trail, $query->cat_name ) ;
$parent_id = $query->parents;
}
foreach( $parent_trail as $ti ) {
if ( $ti ) {
echo "<strong>" . $ti . "</strong> > ";
}
}
} else {
echo "<span style='color:red;'>No Parent Category</span>";
}
}
View
<table class='admin_table'>
<thead>
<th>ID</th>
<th>Name</th>
<th>Parent</th>
</thead>
<tbody>
<?php
foreach($cats as $cat){
echo "<tr>";
echo "<td>" . $cat['cat_id'] . "</td>";
echo "<td>" . $cat['cat_name'] . "</td>";
echo "<td>";
$this -> categories -> get_parent_trail( $cat['parents'] );
echo "</td>";
echo "</tr>";
}
?>
</tbody>
</table>
NOTE:
The '4' in the for loop doesn't need to be dynamic as I've set a hard limit of up to 5 categories, though there has been no need to go that far into sub-categories.
I also have an additional ">" at the end of my list, which I need to get rid of, I know the reason my way doesn't work, it's just the closest solution I could find for the time being.
End Result
Basically, I want my end result to look like;
With 2 'levels' of parent categories
id | name | slug | Parent(s)
-----------------------------------------------------------------------
1 | Electric Chainsaws | electric-chainsaws | Tools > Chainsaws
What you are wanting to do is build a recursive function.
Example of this would be:
function factorial($number)
{
if ($number < 2)
{
return 1;
}
else
{
return ($number * factorial($number-1));
}
}
After much hair pulling and several bottles of very strong rum, I was able to finally figure this out. I'm still relatively novice at using codeigniter so my solution may have some unnecessary steps to it, but I feel obliged to share what I learned. Here is my entire function.
function get_parent_trail($parent_id){
if ( $parent_id != 0 && $parent_id){
$parent_trail = array();
$inc = 0;
for( $i = 1; $i <= 4; $i ++ ) {
if ( $parent_id != 0 && $parent_id){
$this -> db -> select ( '*' );
$this -> db -> from ( 'categories' );
$this -> db -> where ( 'cat_id' , $parent_id );
$query = $this -> db -> get();
$row = $query -> row_array();
array_unshift( $parent_trail, $row['cat_name'] ) ;
$parent_id = $row['parents'];
} else {
$inc++;
}
}
$popOff = array_pop($parent_trail);
if ($inc > 2 ){
echo "<span style='color:red;'>No Parent Category</span>";
}
$string = '';
foreach( $parent_trail as $ti ) {
if ( $ti ) {
$string .= $ti.' > ';
}
}
(string) $test = substr($string, 0, -2);
echo $test;
} else {
echo "<span style='color:red;'>No Parent Category</span>";
}
}