Search Results

Search found 15239 results on 610 pages for 'array population'.

Page 91/610 | < Previous Page | 87 88 89 90 91 92 93 94 95 96 97 98  | Next Page >

  • RTTI Dynamic array TValue Delphi 2010

    - by user558126
    Hello I have a question. I am a newbie with Run Time Type Information from Delphi 2010. I need to set length to a dynamic array into a TValue. You can see the code. Type TMyArray = array of integer; TMyClass = class publihed function Do:TMyArray; end; function TMyClass.Do:TMyArray; begin SetLength(Result,5); for i:=0 to 4 Result[i]=3; end; ....... ....... ...... y:TValue; Param:array of TValue; ......... y=Methods[i].Invoke(Obj,Param);//delphi give me a DynArray type kind, is working, Param works to any functions. if Method[i].ReturnType.TypeKind = tkDynArray then//is working... begin I want to set length for y to 10000//i don't know how to write. end; I don't like Generics Collections.

    Read the article

  • Send array of string using tcp

    - by user2798455
    I'm not sure if this is possible but here it goes. Usually I send strings like this... Connection.IOHandler.WriteLn('alpha'); Connection.IOHandler.WriteLn('bravo'); Connection.IOHandler.WriteLn('charley'); //and so on.. But what if I want to send it in just one go, just send it all at once. Maybe I could put it on an array of strings then send the array. someStr : array[1..3] of string = ('alpha','bravo','charley');//this could be more ... StrListMem := TMemoryStream.Create; try StrListMem.WriteBuffer(someStr[0], Length(someStr)); StrListMem.Position:=0; Connection.IOHandler.Write(StrListMem, 0, True); finally StrListMem.Free; end; I just have no idea how to this right, maybe somebody can give an example? and how the receiver(client) will read it.

    Read the article

  • Reading a C/C++ data structure in C# from a byte array

    - by Chris Miller
    What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty): typedef OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12];} And would fill something like this: [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]public struct NewStuff{ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking;} What is best way to copy OldStuff to NewStuff, if OldStuff was passed as byte[] array? I'm currently doing something like the following, but it feels kind of clunky. GCHandle handle;NewStuff MyStuff;int BufferSize = Marshal.SizeOf(typeof(NewStuff));byte[] buff = new byte[BufferSize];Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);handle = GCHandle.Alloc(buff, GCHandleType.Pinned);MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));handle.Free(); Is there better way to accomplish this?

    Read the article

  • Get 1 array from 2 arrays (using RestKit 0.20)

    - by Reez
    I'm using RestKit and was wondering how to combine two array's into one array. I already have the data being pulled in separately from API1 and API2, but I don't know how to combine them into 1 tableView. Each API is pulling in media, and I want the combined tableView to show the most recent media (like any standard timeline does these days). I will post any extra code or help as necessary, thanks so much! Below shows API1 + API2 being pulled in correctly, but not combined into the tableView. Only data from API1 shows in the tableView. ViewController.m @interface StackOverflowViewController () @property (strong, nonatomic) NSArray *hArray; @property (strong, nonatomic) NSArray *springs; @property (strong, nonatomic) RKObjectManager *eObjectManager; @property (strong, nonatomic) NSArray *iArray; @property (strong, nonatomic) NSArray *imagesArray; @property (strong, nonatomic) RKObjectManager *iObjectManager; // Wain @property (strong, nonatomic) NSMutableArray *tableDataList; // Laarme @property (nonatomic, strong) NSMutableArray *contentArray; @property (nonatomic, strong) NSDateFormatter *dateFormatter1; // Dan @property (nonatomic, strong) NSMutableArray *combinedModel; @end @implementation StackOverflowViewController @synthesize tableView = _tableView; @synthesize spring; @synthesize leaf; @synthesize theme; @synthesize hArray; @synthesize springs; @synthesize eObjectManager; @synthesize iArray; @synthesize imagesArray; @synthesize iObjectManager; // Wain @synthesize tableDataList; // Laarme @synthesize contentArray; @synthesize dateFormatter1; // Dan @synthesize combinedModel; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self configureRestKit]; [self loadMediaDan]; [self sortCombinedModel]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)configureRestKit { // API1 // initialize AFNetworking HTTPClient NSURL *baseURLE = [NSURL URLWithString:@"https://api.e.com"]; AFHTTPClient *clientE = [[AFHTTPClient alloc] initWithBaseURL:baseURLE]; // initialize RestKit RKObjectManager *eManager = [[RKObjectManager alloc] initWithHTTPClient:clientE]; self.eObjectManager = eManager; // setup object mappings RKObjectMapping *feedMapping = [RKObjectMapping mappingForClass:[Feed class]]; [feedMapping addAttributeMappingsFromArray:@[@"headline", @"premium", @"published", @"description"]]; RKObjectMapping *linksMapping = [RKObjectMapping mappingForClass:[Links class]]; RKObjectMapping *webMapping = [RKObjectMapping mappingForClass:[Web class]]; [webMapping addAttributeMappingsFromArray:@[@"href"]]; RKObjectMapping *mobileMapping = [RKObjectMapping mappingForClass:[Mobile class]]; [mobileMapping addAttributeMappingsFromArray:@[@"href"]]; RKObjectMapping *imagesMapping = [RKObjectMapping mappingForClass:[Images class]]; [imagesMapping addAttributeMappingsFromArray:@[@"height", @"width", @"url"]]; [feedMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"links" toKeyPath:@"links" withMapping:linksMapping]]; [feedMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"images" toKeyPath:@"images" withMapping:imagesMapping]]; [linksMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"web" toKeyPath:@"web" withMapping:webMapping]]; [linksMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"mobile" toKeyPath:@"mobile" withMapping:mobileMapping]]; // register mappings with the provider using a response descriptor RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:feedMapping method:RKRequestMethodGET pathPattern:nil keyPath:@"feed" statusCodes:[NSIndexSet indexSetWithIndex:200]]; [self.eObjectManager addResponseDescriptor:responseDescriptor]; // API2 // initialize AFNetworking HTTPClient NSURL *baseURLI = [NSURL URLWithString:@"https://api.i.com"]; AFHTTPClient *clientI = [[AFHTTPClient alloc] initWithBaseURL:baseURLI]; // initialize RestKit RKObjectManager *iManager = [[RKObjectManager alloc] initWithHTTPClient:clientI]; self.iObjectManager = iManager; // setup object mappings RKObjectMapping *dataMapping = [RKObjectMapping mappingForClass:[Data class]]; [dataMapping addAttributeMappingsFromArray:@[@"link", @"created_time"]]; RKObjectMapping *imagesMapping = [RKObjectMapping mappingForClass:[ImagesI class]]; [IMapping addAttributeMappingsFromArray:@[@""]]; RKObjectMapping *standardResolutionMapping = [RKObjectMapping mappingForClass:[StandardResolution class]]; [standardResolutionMapping addAttributeMappingsFromArray:@[@"url", @"width", @"height"]]; RKObjectMapping *captionMapping = [RKObjectMapping mappingForClass:[Caption class]]; [captionMapping addAttributeMappingsFromArray:@[@"text", @"created_time"]]; RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[User class]]; [userMapping addAttributeMappingsFromArray:@[@"username"]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"images" toKeyPath:@"images" withMapping:imagesMapping]]; [imagesMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"standard_resolution" toKeyPath:@"standard_resolution" withMapping:standardResolutionMapping]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"caption" toKeyPath:@"caption" withMapping:captionMapping]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"user" toKeyPath:@"user" withMapping:userMapping]]; // register mappings with the provider using a response descriptor RKResponseDescriptor *responseDescriptor2 = [RKResponseDescriptor responseDescriptorWithMapping:dataMapping method:RKRequestMethodGET pathPattern:nil keyPath:@"data" statusCodes:[NSIndexSet indexSetWithIndex:200]]; [self.iObjectManager addResponseDescriptor:responseDescriptor2]; } - (void)loadMedia { // Laarme contentArray = [[NSMutableArray alloc] init]; [self sortByDates]; // API1 NSString *apikey = @kCLIENTKEY; NSDictionary *queryParams = @{@"apikey" : apikey,}; [self.eObjectManager getObjectsAtPath:[NSString stringWithFormat:@"v1/n/?limit=4&leafs=%@&themes=%@", leafAbbreviation, themeID] // Changed limit to 4 for the time being parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { hArray = mappingResult.array; [self.tableView reloadData]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(@"No?: %@", error); }]; // API2 [self.iObjectManager getObjectsAtPath:[NSString stringWithFormat:@"v1/u/2/m/recent/?client_id=e999"] parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { iArray = mappingResult.array; [self.tableView reloadData]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(@"No: %@", error); }]; } // Laarme - (void)sortByDates { NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init]; //Do the dateFormatter settings, you may have to use 2 NSDateFormatters if the format is different for Data & Feed //The initialization of the dateFormatter is done before the block, because its alloc/init take some time, and you may have to declare it with "__block" //Since in your edit you do that and it seems it's the same format, just do @property (nonatomic, strong) NSDateFormatter dateFormatter; NSArray *sortedArray = [contentArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { // Added Curly Braces around if else statements and used feedObject NSDate *aDate, *bDate; Feed *feedObject = (Feed *)a; Data *dataObject = (Data *)b; if ([a isKindOfClass:[Feed class]]) { //Feed *feedObject = (Feed *)a; aDate = [dateFormatter1 dateFromString:feedObject.published];} else { //if ([a isKindOfClass:[Data class]]) aDate = [dateFormatter2 dateFromString:dataObject.created_time];} if ([b isKindOfClass:[Feed class]]) { bDate = [dateFormatter1 dateFromString:feedObject.published];} else {//if ([b isKindOfClass:[Data class]]) bDate = [dateFormatter2 dateFromString:dataObject.created_time];} return [aDate compare:bDate]; }]; } #pragma mark - Table View - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // API1 //return hArray.count; // API2 //return iArray.count; // API1 + API2 return hArray.count + iArray.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell; if(indexPath.row < hArray.count) { // Date Change NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MMMM d, yyyy h:mma"]; // API 1 TableViewCell *api1Cell = [tableView dequeueReusableCellWithIdentifier:@"YourAPI1Cell"]; // Do everything you need to do with the api1Cell // Use the index in 'indexPath.row' to get the object from you array // API1 Feed *feedLocal = [hArray objectAtIndex:indexPath.row]; // API1 NSString *dateString = [self timeSincePublished:feedLocal.published]; NSString *headlineText = [NSString stringWithFormat:@"%@", feedLocal.headline]; NSString *descriptionText = [NSString stringWithFormat:@"%@", feedLocal.description]; NSString *premiumText = [NSString stringWithFormat:@"%@", feedLocal.premium]; api1Cell.labelHeadline.text = [NSString stringWithFormat:@"%@", headlineText]; api1Cell.labelPublished.text = dateString; api1Cell.labelDescription.text = descriptionText; // SDWebImage API1 if ([feedLocal.images count] == 0) { // Not sure anything needed here } else { Images *imageLocal = [feedLocal.images objectAtIndex:0]; NSString *imageURL = [NSString stringWithFormat:@"%@", imageLocal.url]; NSString *imageWith = [NSString stringWithFormat:@"%@", imageLocal.width]; NSString *imageHeight = [NSString stringWithFormat:@"%@", imageLocal.height]; __weak UITableViewCell *wcell = cell; [cell.imageView setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"X"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // Something }]; } cell = api1Cell; } else { // Date Change NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MMMM d, yyyy h:mma"]; // API 2 MRWebListTableViewCellTwo *api2Cell = [tableView dequeueReusableCellWithIdentifier:@"YourAPI2Cell"]; // Do everything you need to do with the api2Cell // Remember to use 'indexPath.row - hArray.count' as the index for getting an object for your second array // API 2 Data *dataLocal = [iArray objectAtIndex:indexPath.row - hArray.count]; // API 2 NSString *dateStringI = [self timeSincePublished:dataLocal.created_time]; NSString *captionTextI = [NSString stringWithFormat:@"%@", dataLocal.caption.text]; NSString *usernameI = [NSString stringWithFormat:@"%@", dataLocal.user.username]; api2Cell.labelHeadline.text = usernameI; api2Cell.labelDescription.text = captionTextI; api2Cell.labelPublished.text = dateStringI; // SDWebImage API 2 if ([dataLocal.images count] == 0) { NSLog(@"Images Count: %lu", (unsigned long)dataLocal.images.count); // Not sure anything needed here } else { ImagesI *imageLocalI = [dataLocal.images objectAtIndex:0]; StandardResolutionI *standardResolutionLocal = [imageLocalI.standard_resolution objectAtIndex:0]; NSString *imageURLI = [NSString stringWithFormat:@"%@", standardResolutionLocal.url]; NSString *imageWithI = [NSString stringWithFormat:@"%@", standardResolutionLocal.width]; NSString *imageHeightI = [NSString stringWithFormat:@"%@", standardResolutionLocal.height]; // 11.2 __weak UITableViewCell *wcell = cell; [cell.imageView setImageWithURL:[NSURL URLWithString:imageURLI] placeholderImage:[UIImage imageNamed:@"X"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // Something }]; } cell = api2Cell; } return cell; } Feed.h @property (nonatomic, strong) Links *links; @property (nonatomic, strong) NSString *headline; @property (nonatomic, strong) NSString *source; @property (nonatomic, strong) NSDate *published; @property (nonatomic, strong) NSString *description; @property (nonatomic, strong) NSString *premium; @property (nonatomic, strong) NSArray *images; Data.h @property (nonatomic, strong) NSString *link; @property (nonatomic, strong) NSDate *created_time; @property (nonatomic, strong) UserI *user; @property (nonatomic, strong) NSArray *images; @property (nonatomic, strong) CaptionI *caption;

    Read the article

  • remove duplicated array values in a function PHP

    - by Deividas Juškevicius
    I read all topics related to this question in stackoverflow and whole internet and cant find working sollution... Each owner has his item and when someone buy his item, owner gets an confirmation email, but when in cart is few same owner items, he gets several same email letters, so I need to remove dublicated array entries. I have tried to use DISTINCT and array_uniques functions but no luck. Any advices? I have an array and function to send mail.. function email($mail_array) { foreach(array_unique($mail_array) as $field => $value) { $result = mysql_query("select email from users where $field='$value'"); $row = mysql_fetch_array($result); $maail = mysql_real_escape_string($row['email']); $email_to = "".$maail.""; // rest of mail formatting code // create email headers $headers = 'From: '.$email_from."\r\n" . 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); } for ($i = 0; $i < $max; $i++) { $pid = $_SESSION['cart'][$i]['productid']; $owner = get_owner($pid); $mail_array = array( 'name' => $owner ); email($mail_array) //call function to send mail }

    Read the article

  • Passing an array of structs in C

    - by lelouch
    I'm having trouble passing an array of structs to a function in C. I've created the struct like this in main: int main() { struct Items { char code[10]; char description[30]; int stock; }; struct Items MyItems[10]; } I then access it like: MyItems[0].stock = 10; etc. I want to pass it to a function like so: ReadFile(MyItems); The function should read the array, and be able to edit it. Then I should be able to access the same array from other functions. I've tried heaps of declarations but none of them work. e.g. void ReadFile(struct Items[10]) I've had a look around for other questions, but the thing is they're all done different, with typedefs and asterisks. My teacher hasn't taught us pointers yet, so I'd like to do it with what I know. Any ideas? :S EDIT: Salvatore's answer is working after I fixed my prototype to: void ReadFile(struct Items[9]);

    Read the article

  • Android Parcelable create array

    - by Ozik Abdullaev
    In background i parse JSON, and then in this background i send Json to parcelable And in Parcelable i writestring with JSONObject.optString how i can write ArrayList? List<Row> result = new ArrayList<Row>(array.length()); for (int i = 0; i < array.length(); i++) { result.add(new Row(array.optJSONObject(i))); } Parcelable.java public Row(JSONObject from) { thumb = from.optString(TAG_THUMBNAILS); bigImage = from.optString(TAG_BIG_IMAGE); author = from.optString(TAG_AUTHOR); description = from.optString(TAG_DESCRIPTION); date = from.optString(TAG_DATE); } public Row(Parcel parcel) { thumb = parcel.readString(); bigImage = parcel.readString(); author = parcel.readString(); description = parcel.readString(); date = parcel.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(thumb); parcel.writeString(bigImage); parcel.writeString(author); parcel.writeString(description); parcel.writeString(date); }

    Read the article

  • php array split

    - by Rahul Mehta
    I am passing the space separated value to in input and split this in operation and make an array. givecard 442 ashutosh2 Y But i want to pass the message in this string and want to split as complete message in operation or output. givecard 442 ashutosh2 Y hi how are you if i split this line than i get the result is Array ( [0] => givecard [1] => 442 [2] => ashutosh2 [3] => Y [4] => hi [5] => how [6] => are [7] => you ) But i want like this Array ( [0] => givecard [1] => 442 [2] => ashutosh2 [3] => Y [4] => hi how are you ) as here hi how are you i want to extract as complete one message in a variable . How can i achieve this

    Read the article

  • Php JSON Response Array

    - by Nick Kl
    I have this php code. As you can see i query a mysql database through a function showallevents. I return a the $result to the $event variable. I try to return all rows of the data that i take with the msql_fetch_assoc. I don't get response even when i encode the $response variable. It returns null to all fields. Can anyone help me on what i am doing wrong. I had a valid code but it was returning only 1 row of data so i tried to make an associative array but seems i am failing. if ($tag == 'showallevents') { // Request type is show all events // show all events $event = $db->showallevents(); if ($event != false) { $data = array(); while($row = mysql_fetch_assoc($event)) { $data[] = array( $response["success"] = 1, $response["uid"] = $event["uid"], $response["event"]["date"] = $event["date"], $response["event"]["hours"] = $event["hours"], $response["event"]["store_name"] = $event["store_name"], $response["event"]["event_information"] = $event["event_information"], $response["event"]["event_type"] = $event["event_type"], $response["event"]["Phone"] = $event["Phone"], $response["event"]["address"] = $event["address"], $response["event"]["created_at"] = $event["created_at"], $response["event"]["updated_at"] = $event["updated_at"]); } echo json_encode($data); } else { // event not found // echo json with error = 1 $response["error"] = 1; $response["error_msg"] = "Events not found"; echo json_encode($response); } } else { echo "Access Denied"; } } ?>

    Read the article

  • javascript split() array contains

    - by Mahesha999
    While learning JavaScript, I did not get why the output when we print the array returned of the Sting.split() method (with regular expression as an argument) is as explained below. var colorString = "red,blue,green,yellow"; var colors = colorString.split(/[^\,]+/); document.write(colors); //this print 7 times comma: ,,,,,,, However when I print individual element of the array colors, it prints an empty string, three commas and an empty string: document.write(colors[0]); //empty string document.write(colors[1]); //, document.write(colors[2]); //, document.write(colors[3]); //, document.write(colors[4]); //empty string document.write(colors[5]); //undefined document.write(colors[6]); //undefined Then, why printing the array directly gives seven commas. Though I think its correct to have three commas in the second output, I did not get why there is a starting (at index 0) and ending empty string (at index 4). Please explain I am screwed up here.

    Read the article

  • PHP array checkbox and radio default value

    - by Arg Geo
    I have the code below in my wordpress options page. I can't define the default values for checkbox and radio. array( "name" => "Post Thumbnails", "desc" => "Choose if you want to display <strong>post thumbnails</strong> or not.", "id" => $shortname."_post_thumbs", "type" => "checkbox", "std" => "checked" ), array( "name" => "Example", "desc" => " The Descriptions", "id" => $shortname."_case_thumb", "type" => "radio", "options" => array("nothumb" => " Display nothing", "defthumb" => " Display thumbnail"), "std" => "nothumb" ), For the checkbox tried also "std" => "true" and "std" => " "... but didn't work. Thanks!

    Read the article

  • Convert List to Double Array by LINQ (C#3.0)

    - by Newbie
    I have two lists x1 and x2 of type double List<double> x1 = new List<double> { 0.0330, -0.6463}; List<double> x2 = new List<double> { -0.2718, -0.2240}; I am using the below function to convert it to double array List<List<double>> xData = new List<List<double>> { x1, x2 }; double[,] xArray = new double[xData.Count, xData[0].Count]; for (int i = 0; i < xData.Count; i++) { for (int j = 0; j < xData[0].Count; j++) { xArray[i, j] = xData[i][j]; } } Is it possible to do the same stuff (i.e. the function that is converting List to array) by using Linq. Using : (C#3.0) & Framework - 3.5 I want to do this by using Linq because I am learning it but not have sufficient knowledge to write that. Thanks Convert List to Double Array by LINQ (C#3.0)

    Read the article

  • Array, change color, as3

    - by pixelGreaser
    Hi Thanks for the help Yesterday, but I have on more question. How can I change color of text on certain words? My animation plays the text animation of THIS SALE IS RED HOT!!! I want RED HOT it to be red. It seems the array can be indexed in such a way to switch the color from Blue to Red. MY BANNER ADD var myArray:Array = ["THIS","SALE","IS","RED HOT!!!",]; var tm:Timer = new Timer(500); tm.addEventListener(TimerEvent.TIMER, countdown); function countdown(event:TimerEvent) { tx.text = myArray[(tm.currentCount-1)%myArray.length]; } tm.start(); tx.textColor = 0x0000FF; Cont...PSEUDO CODE //var myArray:Array = ["This","Sale","is","RED HOT!!!",]; var spliceRedhot = myArray.splice(-1); //trace(myArray[2]); trace(spliceRedhot); function mySplice(e:Event):void{ if (spliceRedhot = 4){ //Make RED HOT!!! red tx.textColor = 0xFF0000; } else{ //Text is Blue again tx.textColor = 0x0000FF; } }

    Read the article

  • Creating object/array to method in request based on __gettypes in PHP

    - by LochNess
    I'm having trouble with the array or object that should be passed based on the response from __gettypes. The __gettypes response: [0] => struct CDataWrapper { schema;any; } [1] => struct NewMember { MemberDetail MemberDetails;ArrayOfHobby Hobbies; } [2] => struct MemberDetail { string Name; string Age; string Sex; } [3] => struct ArrayOfHobby { Hobby Hobby; } [4] => struct Hobby { string Name; string HoursUsedOnHobbyWeekly;boolean Favourite; } ... etc. The methods are: [0] => ReceiveMemberResponse ReceiveMember(ReceiveMember $parameters) [1] => ReturnMemberResponse ReturnMember(ReturnMember $parameters) So far I have this PHP: $client = new SoapClient('http://domain.com?wsdl'); class MemberDetail { public $Name = ''; public $Age = ''; public $Sex = ''; } $mc = new MemberDetail(); $mc->Name= 'Bob'; $mc->Age= '14'; $mc->Sex= 'Male'; $myParam = array('ReceiveMember'=>$mc); $wcf = $client->ReceiveMember($myParam); $wcfResult = $wcf->ReturnMember; print_r($wcfResult) when i call the page it returns: Error 324 (net::ERR_EMPTY_RESPONSE): Unknown error. I'm not really sure how to create the array or object to pass on as $myParam since im no expert with PHP either.

    Read the article

  • How to sort array with undefined elements in IE7 JavaScript

    - by Gene Goykhman
    I am having trouble sorting an array that includes undefined elements (a sparse array) in IE7. This works great in Safari and Firefox of course, and I haven't tried other versions of IE, but here is a simple example. <html> <head> <script type="text/javascript"> function runscript() { var myArray = [{id: 2}, undefined, {id: 0}, {id: 1}, {id: 3}, {id: 4}, {id: 5}]; myArray.sort(function compare(a, b) { return a.id - b.id; }); var output = ''; for (loop in myArray) { output += myArray[loop].id + ' '; } alert(output); } </script> </head> <body onLoad="runscript();"> </body> The alert() at the end inexplicably shows 0 2 3 4 5 1. Removing the undefined element from the array correctly sorts it and the alert shows 0 1 2 3 4 5. Is there a way to work around this in IE7 so that I can reliably sort arrays that include undefined elements? I don't care where the undefined elements end up as long as the defined elements are sorted correctly.

    Read the article

  • Array of Arrays - writing to File problem

    - by iFloh
    Hi, and again my array of arrays ... I try to improve my app performance by buffering arrays on file for later reuse. I have an NSMutableArray that contains about 30 NSMutableArrays with NSNumber, NSDate and NSString Objects. I try to write the file using this call: bool result = [myArray writeToFile:[fileMethods getFullPath:[NSString stringWithFormat:@"iEts%@.arr", [aDate shortDateString]]] atomically:NO]; = result = FALSE. The Path method is: + (NSString *) getFullPath:(NSString *)forFileName { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; return [documentsDirectory stringByAppendingPathComponent:forFileName]; } and the aDate call returns a shortDateString with ddMMyy. The NSLog NSLog(@"%@", [fileMethods getFullPath:[NSString stringWithFormat:@"iEts%@.arr", [aDate shortDateString]]]); on the path generation returns: /Users/me/Library/Application Support/iPhone Simulator/User/Applications/86729620-EC1D-4C10-A799-0C638BB27933/Documents/iEts010510.arr FURTHER: It must have something to do with the Array of Arrays, since I also write 3 further simple arrays (containing NSStrings) that all succeed. The Array of Arrays gets generated using the addObject method Any ideas what could cause the trouble?

    Read the article

  • JSON Array Created in PHP/MySQL incorrectly decoded using JQuery

    - by Zak
    I am attempting to make an AJAX call to a very small PHP script that should return me an array that could be echo'd and decoded using JQuery. Here is what I have: My PHP page called to by AJAX: $web_q=mysql_query("select * from sec_u_g where uid='$id' "); $rs = array(); while($rs[] = mysql_fetch_assoc($web_q)) { } print_r(json_encode($rs)); This outputs: [{"id":"3","uid":"39","gid":"16"},{"id":"4","uid":"39","gid":"4"},{"id":"5","uid":"39","gid":"5"},{"id":"6","uid":"39","gid":"6"},{"id":"7","uid":"39","gid":"7"},{"id":"8","uid":"39","gid":"8"},{"id":"9","uid":"39","gid":"9"},false] I don't understand the "false" at the end for one .. But then I send to to JQuery and use: $.each(json.result, function(i, object) { $.each(object, function(property, value) { alert(property + "=" + value); }); }); This just fails. I try to alert "result" by itself which is set by: $.post("get_ug.php",{id:txt},function(result){ }); My output alerts are as follows: 1) The key is '0' and the value is '[' 2) The key is '1' and the value is 'f' 3) The key is '2' and the value is 'a' 4) The key is '3' and the value is 'l' 5) The key is '4' and the value is 's' 6) The key is '5' and the value is 'e' 7) The key is '6' and the value is ']' 8) The key is '7' and the value is ' ' (<-- Yes the line break is there in the alert) I am exhausted from trying different ideas and scripts. Other than setting a delimiter myself and concatenating my own array and decoding it with a custom script, does anyone have any ideas?? Thank you!!

    Read the article

  • Access array of c-structs using Python ctypes

    - by sadris
    I have a C-function that allocates memory at the address passed to and is accessed via Python. The pointer contents does contain an array of structs in the C code, but I am unable to get ctypes to access the array properly beyond the 0th element. How can I get the proper memory offset to be able to access the non-zero elements? Python's ctypes.memset is complaining about TypeErrors if I try to use their ctypes.memset function. typedef struct td_Group { unsigned int group_id; char groupname[256]; char date_created[32]; char date_modified[32]; unsigned int user_modified; unsigned int user_created; } Group; int getGroups(LIBmanager * handler, Group ** unallocatedPointer); ############# python code below: class Group(Structure): _fields_ = [("group_id", c_uint), ("groupname", c_char*256), ("date_created", c_char*32), ("date_modified", c_char*32), ("user_modified", c_uint), ("user_created", c_uint)] myGroups = c_void_p() count = libnativetest.getGroups( nativePointer, byref(myGroups) ) casted = cast( myGroups, POINTER(Group*count) ) for x in range(0,count): theGroup = cast( casted[x], POINTER(Group) ) # this only works for the first entry in the array: print "~~~~~~~~~~" + theGroup.contents.groupname Related: Access c_char_p_Array_256 in Python using ctypes

    Read the article

  • Interview Q: sorting an almost sorted array (elements misplaced by no more than k)

    - by polygenelubricants
    I was asked this interview question recently: You're given an array that is almost sorted, in that each of the N elements may be misplaced by no more than k positions from the correct sorted order. Find a space-and-time efficient algorithm to sort the array. I have an O(N log k) solution as follows. Let's denote arr[0..n) to mean the elements of the array from index 0 (inclusive) to N (exclusive). Sort arr[0..2k) Now we know that arr[0..k) are in their final sorted positions... ...but arr[k..2k) may still be misplaced by k! Sort arr[k..3k) Now we know that arr[k..2k) are in their final sorted positions... ...but arr[2k..3k) may still be misplaced by k Sort arr[2k..4k) .... Until you sort arr[ik..N), then you're done! This final step may be cheaper than the other steps when you have less than 2k elements left In each step, you sort at most 2k elements in O(k log k), putting at least k elements in their final sorted positions at the end of each step. There are O(N/k) steps, so the overall complexity is O(N log k). My questions are: Is O(N log k) optimal? Can this be improved upon? Can you do this without (partially) re-sorting the same elements?

    Read the article

  • Action listener for JButton array

    - by user530809
    Let's say I have a program with 2D array of buttons, and when you click one of them it turns red. I didn't want to declare every single button seperately so I just created JButton[][] array for them. The problem is that I don't know how to use action listener on any of the buttons in the array so it would change the color of this particular button, and none of related questions is relevant to this. I tried to use "for" but it doesn't help: package appli; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MainW extends JFrame implements ActionListener { public MainW(){ setSize(640,480); setTitle("title"); setLayout(null); JButton[][] btnz = new JButton[5][5]; for(Integer i=0;i<5;i++) { for(Integer j=0;j<5;j++) { btnz[i][j]= new JButton(""); btnz[i][j].setBackground(Color.WHITE); btnz[i][j].setBounds(10+20*i,10+20*j,20,20); add(btnz[i][j]); btnz[i][j].addActionListener(this); } } setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public void actionPerformed(ActionEvent e){ for(Integer i=0;i<5;i++) { for(Integer j=0;j<5;j++) { if (e.getSource()==btnz[i][j]); { btnz[i][j].setBackground(Color.RED); } } } } }

    Read the article

  • loop is cut one element of the array

    - by Walaa
    The problem is : Write a program that reads a number n and then declares an array of n elements. The program then fills the array with the first n numbers, where each number is two to the power of the previous. Finally, display array’s contents. My code : import java.util.*; public class Q1 { static Scanner scan = new Scanner (System.in); public static void main(String args [] ) { int num; int i = 0; System.out.println("Enter a number :"); num = scan.nextInt(); double [] a=new double[num]; a[0]= num ; for ( ;i<=a.length-1 ; i++) { a[i+1] = Math.pow(2,a[i]); System.out.println((int)(a[i]) ); } } } The error is : ----jGRASP exec: java Q1 Enter a number : 4 4 16 65536 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Q1.main(Q1.java:16) ----jGRASP wedge2: exit code for process is 1. why it says that? And the number by user printed twice!

    Read the article

  • Shortest Distance From An Array

    - by notyou61
    I have an ajax function which returns the latitudes and longitudes of locations stored in a database. These are returned and placed in an array. A calculation is performed to return their distance from the users current location based on the latitude/longitude. I would like to return only the record with the shortest calculated distance. My code is as follows: Ajax Success // Success success: function (data) { // Obtain Log/Lat navigator.geolocation.getCurrentPosition(function(position) { // Obtain Current Position Lat/Lon glbVar.latitude = position.coords.latitude; glbVar.longitude = position.coords.longitude; // Console Log //console.log('Lat: ' + glbVar.latitude + ' Lon: ' + glbVar.longitude); // Obtain Location Distances for ( var i = 0; i < data.length; i++ ) { // Location Instances var varLocation = data[i]; // Location Distance varLocation.distance = calculateDistance(glbVar.longitude, glbVar.latitude, varLocation.locationLongitude, varLocation.locationLatitude); } // Sort Locations By Distance var sortedData = data.sort(function(a, b) { // Return Locations return a.distance - b.distance; }); // Output Results $.map(sortedData, function(item) { // Obtain Location Distance varLocationsDistance = calculateDistance(glbVar.longitude, glbVar.latitude, item.locationLongitude, item.locationLatitude); // Obtain Location Radius Assignment if (varLocationsDistance <= varLocationRadius) { // Function Return functionReturn = $({locationID : item.locationID + ', Distance : ' + varLocationsDistance + ' m'}); // Return // Function to get the Min value in Array Array.min = function( sortedData ){ functionReturn = Math.min.apply( Math, sortedData ); // console.log(functionReturn); }; } }); }); } The calculateDistance function returns the distance from the users current location and those from the database. The varLocationsDistance <= varLocationRadius "If" statement returns records within a certain distance radius (100 meters), within that statement I would like to return the shortest distance. I am a self taught amateur web developer and as a result may not have provide enough information for an answer, please let me know. Thanks,

    Read the article

  • Will array_unique work also with array of objects?

    - by Richard Knop
    Is there a better way than using array-walk in combination with unserialize? I have two arrays which contain objects. The objects can be same or can be different. I want to merge both arrays and keep only unique objects. This seems to me like a very long solution for something so trivial. Is there any other way? class Dummy { private $name; public function __construct($theName) {$this->name=$theName;} } $arr = array(); $arr[] = new Dummy('Dummy 1'); $arr[] = new Dummy('Dummy 2'); $arr[] = new Dummy('Dummy 3'); $arr2 = array(); $arr2[] = new Dummy('Dummy 1'); $arr2[] = new Dummy('Dummy 2'); $arr2[] = new Dummy('Dummy 3'); function serializeArrayWalk(&$item) { $item = serialize($item); } function unSerializeArrayWalk(&$item) { $item = unserialize($item); } $finalArr = array_merge($arr, $arr2); array_walk($finalArr, 'serializeArrayWalk'); $finalArr = array_unique($finalArr); array_walk($finalArr, 'unSerializeArrayWalk'); var_dump($finalArr);

    Read the article

  • Is it possible to send back a json array along with seperate variables

    - by Scarface
    Hey guys I have an ajax jquery function that receives data from a php script. I want to return an array with all the online users which is retrieved from a mysql statement, and I want to send other separate variables I need for other purposes along with it. If anyone has any ideas, I would greatly appreciate it. NOTE: the example below is to illustrate what I want to do, I understand that json-encoding the array with other variables is dysfunctional. JQUERY $.ajax({ type: "POST", data: "parameters", url: "retrieval.php", dataType: 'json', success: function(json) { $('#div1').html(json.array); $('#div2').html(json.variable1); $('#div3').html(json.variable2); } }) PHP $qryuserscount1="SELECT * FROM active_users"; $userscount1=mysql_query($qryuserscount1); while ($row = mysql_fetch_array($userscount1)) { $onlineuser= $row['username']; $id=$row['id']; $data[]=$onlineuser.$id; //for example there are 3 users, should send 3 entries back } $data['variable1']='something'; $data['variable2']='something else'; $out = json_encode($data); print $out;

    Read the article

< Previous Page | 87 88 89 90 91 92 93 94 95 96 97 98  | Next Page >