Affichage des articles dont le libellé est Active questions tagged arrays - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged arrays - Stack Overflow. Afficher tous les articles

mardi 4 août 2015

Extracting elements of a tuple from an array of tuples in swift

I have managed quite easily to extract tuple from an array of tuples however I am stumped as to how to extract the elements of the tuple.

//: Playground - noun: a place where people can play

import UIKit

import Foundation

class ActivityDetailsModel {


    var activityCategory: String! // The choice of major activity


    init(activityCategory: String){
        self.activityCategory = activityCategory
    }

    class func activityForm(activityCategory: String) -> [(Question: String, Answer: String)] {
        var activityProfile: [(Question: String, Answer: String)] = [] //An array of tuples containing the users activity details

        switch activityCategory {
        case "Sport":
            activityProfile = [(Question:  "Home Club", Answer: "a"),(Question: "Other venues", Answer: "b")]// [, ["Activity days – Mon – Sunday": "c"], ["Player strength": "d"], ["Age group to play with": "e"]]
            return activityProfile
        case "Recreation":
            activityProfile = [(Question:  "Home Club2", Answer: "ab"),(Question: "Other venues3", Answer: "bc")]
            return activityProfile

        default:
            var activityProfile = [(Question:  "nixs", Answer: "nie")]
            return activityProfile
        }

    }


}
var actProf:[(Question: String, Answer: String)]
actProf = ActivityDetailsModel.activityForm("Recreation")
println(actProf[1])

This returns the second tuple from the array - all I need now is to extract the elements of the tuple

How to avoid creating a copy of an array of objects in swift

I have a dictionary of arrays that contain one kind of objects : database records. Each array is like a table associated to a key (table name) in the dictionary.

My issue is: How do I update a table (delete a record, add a record, etc) without making any temporary copy of the table, like I would do with an NSDictionary of NSArrays ?

Currently, I do :

func addRecord(theRecord: DatabaseRecord, inTable tableName: String)
{
    if var table = self.database[tableName]
    {
        table.append(theRecord)
        self.database[tableName] = table
    }
    else
    {
        self.database[tableName] = [theRecord];
    }
}

The issue is: a temporary copy of the table is made twice. This is pretty inefficient.

loop through multidimensional array and order sub-array by scores

I am trying to calculate the winning order of golfers when they are tied in a competition.

The rules are to use a "countback". i.e., if scores are tied after 9 holes, the best placed of the ties is the best score from the last 8 holes. then 7 holes, etc.

The best I can come up with is 2 arrays.

  1. An array with all the players who tied in a given round. ($ties)
  2. One which has the full score data in (referencing the database playerid) for all 9 holes. ($tie_perhole)

I loop through array 1, pulling data from array 2 and using the following formula to create a temporary array with the highest score:

$max = array_keys($array,max($array));

If $max only has 1 item, this player is the highest scorer. the loop through the first array is "by reference", so on the next iteration of the loop, his playerid is now longer in the array, thus ignored. this continues until there is only 1 playerid left in the first array.

However, it only works if a single player wins in each iteration. The scenario that doesn't work is if a sub-set of players tie on any iterations / countbacks.

I think my problem is the current structure I have will need the original $ties array to become split, and then to continue to iterate through the split arrays in the same way...

As an example...

The $ties array is as follows:

Array 
( 
    [18] => Array 
        ( 
            [0] => 77 
            [1] => 79 
            [2] => 76 
            [3] => 78 
        ) 
)

The $tie_perhole (score data) array is as follows:

Array 
( 
    [18] => Array 
        ( 
            [77] => Array 
                ( 
                    [9] => 18 
                    [8] => 16 
                    [7] => 14 
                    [6] => 12 
                    [5] => 10 
                    [4] => 8 
                    [3] => 6 
                    [2] => 4 
                    [1] => 2 
                ) 
            [79] => Array 
                ( 
                    [9] => 18 
                    [8] => 17 
                    [7] => 15 
                    [6] => 14 
                    [5] => 11 
                    [4] => 9 
                    [3] => 7 
                    [2] => 5 
                    [1] => 3 
                ) 
            [76] => Array 
                ( 
                    [9] => 18 
                    [8] => 16 
                    [7] => 14 
                    [6] => 12 
                    [5] => 10 
                    [4] => 8 
                    [3] => 6 
                    [2] => 4 
                    [1] => 2 
                ) 
            [78] => Array 
                ( 
                    [9] => 18 
                    [8] => 17 
                    [7] => 15 
                    [6] => 13 
                    [5] => 11 
                    [4] => 9 
                    [3] => 7 
                    [2] => 5 
                    [1] => 3 
                ) 
        ) 
) 

So in this competition, player's 78 and 79 score highest on the 8th hole countback (17pts), so 1st and 2nd should be between them. Player 79 should then be 1st on the 6th hole countback (14pts, compared to 13pts). The same should occur for 3rd and 4th place with the 2 remaining other players.

There are other scenarios that can occur here, in that within a competition, there will likely be many groups of players (of different amounts) on different tied points through the leaderboard.

Also note, there will be some players on the leaderboard who are NOT tied and stay in their current outright position.

The basics of the working code I have is:

foreach ($ties as $comparekey => &$compareval) {
$tie_loop = 0;
for ($m = 9; $m >= 1; $m--) {
    $compare = array();
    foreach ($compareval as $tie) {
        $compare[$tie] = $tie_perhole[$comparekey][$tie][$m];
    }
    $row = array_keys($compare,max($compare));

    if (count($row) == 1) {
        $indexties = array_search($row[0], $ties[$comparekey]);
        unset($ties[$comparekey][$indexties]);
        // Now update this "winners" finishing position in a sorted array
        // This is a multidimensional array too, with custom function...
        $indexresults = searchForId($row[0], $comp_results_arr);
        $comp_results_arr[$indexresults][position] = $tie_loop;
        $tie_loop++;
    }
    // I think I need conditions here to filter if a subset of players tie
    // Other than count($row) == 1
    // And possibly splitting out into multiple $ties arrays for each thread...

    if (empty($ties[$comparekey])) {
        break;
    }
}
}
usort($comp_results_arr, 'compare_posn_asc');
foreach($comp_results_arr as $row) {
    //echo an HTML table...
}

Thanks in advance for any helpful insights, tips, thoughts, etc...

PHP: Adding to array replaces previous value

What I'm trying to do:
Pull data from a database and insert it into an array

The code I'm using:

sql = "SELECT * FROM `products`, categories WHERE category = cat_ID AND pro_ID = " . $_GET['id'];
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $name = $row['pro_name'];
            $cartContents[$name] = array(
                "id" => $row['pro_ID'],
                "name" => $row['pro_name'],
                "price" => $row['price'],
                "quantity" => $_GET['q']
            );
        }

The problem:
This does indeed take the values from the database and insert them into the array, but it replaces everything dat was in the array before this.

What I've tried:
- Replacing array(...) with [...]
- Using the following code:

$cartContents[$name]["id"] = $row['pro_ID'];
$cartContents[$name]["name"] = $row['pro_name'];
$cartContents[$name]["price"] = $row['price'];
$cartContents[$name]["quantity"] = $_GET['q'];

Any help would be greatly appreciated, thank you!

Using Hashmap contains to check for a duplicate key

So i have an interface.

    public interface ARecord {
        public BigInteger getAutoID();
        public String getACompId();
}

and

    public class APPPRecord extends AbstratAPRecord implements ARecord{
    private BigInteger autoID;
    private String ACompId = null;
   //setter and getter}

In service,

    List<APPPRecord> PFRecord = null;
    while(scroll.next()){
    APPPRecord item = (APPPRecord) scroll.get(0);
    List<ARecord> recs = new ArrayList<ARecord>();
    recs.addAll(PFRecord);

My PFRecord list has results that are being duplicated. I have to use hash maps that can check for ACompId contains key. If the key already exists don't pass it to recs.addAll. How can I go about doing this? Any help appreciated

Facebook Ads API message '(#17) User request limit reached'

Good Day All,

I'm working on retrieving facebook ad stats through the Facebook Ads php sdk. I'm able to retrieve the stats the way I want, but I keep running into a rate limit problem. I don't think I'm making an absurd amount of calls to the api and I don't intend to other than to retrieve daily stats for a list of clients. I'm wondering anyone here sees a way I can make the calls, without receiving {message '(#17) User request limit reached} to get the stats and insights every day for all of our ad sets. Ultimately, we have about 10-20 campaigns running at any time and I need to report on these stats daily for clients. The example below returns only 4 ads within this adset. Anything higher than this, I typically receive the error message.

<?php

include 'vendor/vendor/autoload.php';
$ACCESS_TOKEN = '****';
$APP_ID = '****';
$APP_SECRET = '****';
$appsecret_proof= hash_hmac('sha256', $ACCESS_TOKEN, $APP_SECRET);  

use FacebookAds\Api;
Api::init($APP_ID, $APP_SECRET, $ACCESS_TOKEN, $appsecret_proof);

use FacebookAds\Object\AdUser;

//$user = (new AdUser('me'))->read(array('id'));
//echo $user->id ."\n";

use FacebookAds\Object\AdAccount;
use FacebookAds\Object\AdAccountFields;
use FacebookAds\Object\AdCampaign;
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\Fields\AdCreativeFields;
use FacebookAds\Object\AdGroup;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Values\InsightsPresets;
use FacebookAds\Object\Values\AdObjectives;

$insightsFields = array(
    'actions',
    'cpm',
    'ctr',
    'frequency',
    'impressions',
    'reach',
    'social_clicks',
    'social_impressions',
    'social_reach',
    'spend',
    'website_clicks',
    'video_p25_watched_actions',
    'video_p50_watched_actions',
    'video_p75_watched_actions',
    'video_p95_watched_actions',
    'video_p100_watched_actions',
    'video_avg_sec_watched_actions'
);
$statsFields = array(
    'actions',
);
$impressionCheck = array(
    'impressions',
);
$imageFields = array(
    'creative',
);
$adSetFields = array(
    'id',
    'name',
    'campaign_status'
);
$adGroupFields = array(
    'creative',
    'id',
    'name',
    'adgroup_status'
);  
$campaignFields = array(
    'id',
    'name',
    'campaign_group_status'
);
$campaignParams = array(        
    'date_preset' => InsightsPresets::LAST_MONTH,
);
$params = array(
    'date_preset' => InsightsPresets::LAST_MONTH,
);
$statsParams = array(
    'date_preset' => 'last_month',
);


/* Global Insights Variables */
$responseArray = '';
$facebook_cpm = '';
$facebook_ctr = '';
$facebook_frequency = '';
$facebook_impressions = '';
$facebook_reach = '';
$facebook_spend = '';
$facebook_website_clicks = '';
$video25Watched = '';
$video50Watched = '';
$video75Watched = '';
$video100Watched = '';
$videoAverageWatched = '';

/* Global Stats Variables */    
$facebookComment = '';
$facebookLike = '';
$facebookLinkClick = '';
$facebookMention = '';
$facebookOffsiteConversion = '';
$facebookPhotoView = '';
$facebookPost = '';
$facebookPostLike = '';
$facebookUnlike = '';
$facebookVideoPlay = '';
$facebookVideoView = '';
$facebookPageEngagement = '';
$facebookPostEngagement = '';
$facebookCheckin = '';

$account = new AdAccount('****');
$campaigns = $account->getAdCampaigns($campaignFields, $campaignParams);    

    $campaign = new AdCampaign('****');
    $adSets = $campaign->getAdSets($adSetFields, $params);

    foreach($adSets as $adSetKey => $adSetValue){                   
        $adSetID = $adSetValue->id;
        $adSetName = $adSetValue->name;         

        $adSet = new AdSet($adSetID);

        $adSetImpressionCheck = $adSet->getInsights($impressionCheck, $params); 
        $impressionsTrue = '';
        foreach($adSetImpressionCheck as $i => $c){
            $impressionsTrue = $c->impressions;
        }

        if ($impressionsTrue > 0){
            $adGroups = $adSet->getAdGroups($adGroupFields, $params);           
            foreach($adGroups as $k => $v){
                $adGroupID = $v->id;
                $adGroupName = $v->name;
                $adGroupCreative = $v->creative;                    

                $adGroup = new AdGroup($adGroupID);

                $insights = $adGroup->getInsights($insightsFields, $params);    
                $stats = $adGroup->getStats($statsFields, $params);

                foreach($insights as $key => $response){                        
                    $facebook_cpm = $response->cpm;
                    $facebook_ctr = $response->ctr;
                    $facebook_frequency = $response->frequency;
                    $facebook_impressions = $response->impressions;
                    $facebook_reach = $response->reach;
                    $facebook_spend = $response->spend;
                    $facebook_website_clicks = $response->website_clicks;
                    $facebook_date = $response->date_start;
                    $responseArray = $response->actions;
                    $adSetNameLowerCase = strtolower($adSetName);
                    if (strpos($adSetNameLowerCase, 'video') !== false){
                        $video25Watched = $response->video_p25_watched_actions[0]['value'];     
                        $video50Watched = $response->video_p50_watched_actions[0]['value'];
                        $video75Watched = $response->video_p75_watched_actions[0]['value'];
                        $video95Watched = $response->video_p95_watched_actions[0]['value'];
                        $video100Watched = $response->video_p100_watched_actions[0]['value'];
                        $videoAverageWatched = $response->video_avg_sec_watched_actions[0]['value'];
                        $videoActions = '
                            <li>25% Watched: '. $video25Watched .'</li>
                            <li>50% Watched: '. $video50Watched .'</li>
                            <li>75% Watched: '. $video75Watched .'</li>
                            <li>95% Watched: '. $video95Watched .'</li>
                            <li>100% Watched: '. $video100Watched .'</li>
                            <li>Average Video Watched: '. $videoAverageWatched .'</li>
                        ';
                    }                       
                    $returnInsights .= '                        
                        <strong style="display:block">'. $adSetName .'</strong>
                        <ul style="margin-left:40px">               
                            <li><strong>'. $adGroupName .'</strong></li>
                            <li><a href="'. $adGroupCreative .'">Ad Preview</a></li>
                            <li>CPM: '. $facebook_cpm .'</li>
                            <li>CTR: '. $facebook_ctr .'</li>
                            <li>Frequency: '. $facebook_frequency .'</li>
                            <li>Impressions: '. $facebook_impressions .'</li>
                            <li>Reach: '. $facebook_reach .'</li>
                            <li>Total Spend: '. $facebook_spend .'</li>
                            <li>Website Clicks: '. $facebook_website_clicks .'</li>
                            '. $videoActions .'
                        </ul>
                    ';
                }                   
                foreach($stats as $keyStats => $responseStats){                             
                    $responseStatsArray = $responseStats->actions;      
                    $facebookComment = $responseStatsArray['comment'];
                    $facebookLike = $responseStatsArray['like'];
                    $facebookLinkClick = $responseStatsArray['link_click'];
                    $facebookMention = $responseStatsArray['mention'];
                    $facebookOffsiteConversion = $responseStatsArray['offsite_conversion'];
                    $facebookPhotoView = $responseStatsArray['photo_view'];
                    $facebookPost = $responseStatsArray['post'];
                    $facebookPostLike = $responseStatsArray['post_like'];
                    $facebookUnlike = $responseStatsArray['unlike'];
                    $facebookVideoPlay = $responseStatsArray['video_play'];
                    $facebookVideoView = $responseStatsArray['video_view'];
                    $facebookPageEngagement = $responseStatsArray['page_engagement'];
                    $facebookPostEngagement = $responseStatsArray['post_engagement'];
                    $facebookCheckin = $responseStatsArray['checkin'];
                    $returnStats .= '
                        <strong style="display:block">'. $adSetName .'</strong>
                        <ul style="margin-left:40px">   
                            <li>Comments: '. $facebookComment .'</li>
                            <li>Likes: '. $facebookLike .'</li>
                            <li>Link Click: '. $facebookLinkClick .'</li>
                            <li>Facebook Mention: '. $facebookMention .'</li>
                            <li>Facebook Offsite Conversion: '. $facebookOffsiteConversion .'</li>
                            <li>Facebook Photo View: '. $facebookPhotoView .'</li>
                            <li>Facebook Posts: '. $facebookPost .'</li>
                            <li>Facebook Post Like: '. $facebookPostLike .'</li>
                            <li>Facebook Post Unlike: '. $facebookUnlike .'</li>
                            <li>Facebook Video Play: '. $facebookVideoPlay .'</li>
                            <li>Facebook Video View: '. $facebookVideoView .'</li>
                            <li>Facebook Page Engagement: '. $facebookPageEngagement .'</li>
                            <li>Facebook Post Engagement: '. $facebookPostEngagement .'</li>
                            <li>Facebook Checkin: '. $facebookCheckin .'</li>
                        </ul>
                    ';
                }
            }
        }
    }

    echo $returnInsights;
    echo $returnStats;

?>

P.S. I'm only using LAST_MONTH date preset temporarily as all accounts are currently paused...

Any and all recommendations are helpful. Thank you Stack community.

VBA- How to search date in array of dates coming from excel

I am trying to write a simple function in VBA which takes as input a date and an array of dates both coming from Excel. It then returns true if the given date is part of the array or false otherwise.

My problem is that arrays coming from excel are 2 dimensional but I always pass in a 1 dimensional array. In other words, a column and a row value so I can check values in my array but I pass in a 1 dimensional array.

Here is my code:

Function IsInArray(ByVal MyDate As Date, ByRef Holiday_Calendar As Range) As Boolean
Dim length As Integer
length = WorksheetFunction.Count(Holiday_Calendar)
Dim counter As Integer
'counter = 0

For counter = 0 To length
If Holiday_Calendar(counter) = MyDate Then
IsInArray = True
End If
Next counter

IsInArray = False
End Function

List vs Linked List vs Array vs Array List

What are the differences between these data types? Whenever I try to find the answer, I just get Java-specific questions about the difference between LinkedLists and Array Lists, but what are the differences between all four.

Also I would prefer if the answer was not too language specific, but could maybe use some examples from different languages.

Everything I know about linked lists and arrays comes from Lisp, but is there a difference between all four or just naming conventions?

How to save nil into serialized attribute in Rails 4.2

I am upgrading an app to Rails 4.2 and am running into an issue where nil values in a field that is serialized as an Array are getting interpreted as an empty array. Is there a way to get Rails 4.2 to differentiate between nil and an empty array for a serialized-as-Array attribute?

Top level problem demonstration:

#[old_app]
 > Rails.version
 => "3.0.3"
 > a = AsrProperty.new; a.save; a.keeps
 => nil

#[new_app]
 > Rails.version
 => "4.2.3"
 > a = AsrProperty.new; a.save; a.keeps
 => []

But it is important for my code to distinguish between nil and [], so this is a problem.

The model:

class AsrProperty < ActiveRecord::Base
  serialize :keeps, Array
  #[...]
end

I think the issue lies with Rails deciding to take a shortcut for attribute that are serialized as a specific type (e.g. Array) by storing the empty instance of that type as nil in the database. This can be seen by looking at the SQL statement executed in each app:

[old_app]: INSERT INTO asr_properties (lock_version, keeps) VALUES (0, NULL)

Note that the above log line has been edited for clarity; there are other serialized attributes that were being written due to old Rails' behavior.

[new_app]: INSERT INTO asr_properties (lock_version) VALUES (0)

There is a workaround: by removing the "Array" declaration on the serialization, Rails is forced to save [] and {} differently:

class AsrProperty < ActiveRecord::Base
  serialize :keeps #NOT ARRAY
  #[...]
end

Allows:

 > a = AsrProperty.new; a.save; a.keeps
 => []

I'll use this workaround for now, but: (1) I feel like declaring a type might allow more efficiency, and also prevents bugs by explicitly prohibiting the wrong data type being stored (2) I'd really like to figure out the "right" way to do it, if Rails does allow it.

So: can Rails 4.2 be told to store [] as its own thing in a serialized-as-Array attribute?

SQL "Update" Query occurring happens once in PHP "Foreach" loop but loop still runs

I am trying to have a foreach loop run through an array and update my database for each entry.

My code looks like this:

$basketID = mysqli_insert_id($conn);
$basket = $_SESSION['basket'];
$x = array_count_values($basket);
foreach($x as $prodID => $Quant){
    $sql = "
    UPDATE products SET stock = (stock - '$Quant') 
    WHERE productID = '$prodID'; 

    INSERT INTO basketitems(basketID, productID, quantity)
    VALUES ('$basketID','$prodID','$Quant'); ";

    mysqli_multi_query($conn, $sql);
}

The result at the moment is that the loop occurs say 5 times (if I have 5 items in the array) but the query only happens once [I placed a counter in to find out if it was breaking the loop and it counted 5 times]. If I remove the "Update" query then 5 items are inserted into the basketitems table.

Error converting object array to hashtable

Quick Overview: Script has two functions, one gets a two lists of roles and puts them in a hash table, then returns that hash table. Process-Roles then accepts a hash table, and does some comparisons on it.

$RoleTable is supposed to be a hash table, but I think after my Get-Roles function, Powershell makes the $RoleTable an object array. I then get a conversion error:

Cannot convert the "System.Object[]" value of type "System.Object[]" to type 
"System.Collections.Hashtable".

Here's the "main" of my script

$creds = Get-Credential
$MasterServer = Read-Host "`n Master Server"
$SlaveServer  = Read-Host "`n Slave Server"

$RoleTable = Get-Roles -MasterServer $MasterServer -SlaveServer $SlaveServer -Credential $creds

Process-Roles -RoleTable $RoleTable

Here's the function I make a hashtable in, and pass that to $RoleTable

function Get-Roles {
    Param(
        [Parameter(Mandatory=$True,Position=0)]
        [string]$MasterServer,

        [Parameter(Mandatory=$True,Position=1)]
        [string]$SlaveServer,

        [Parameter(Mandatory=$True,Position=2)]
        [pscredential]$Credential
    )

    $DiscoveredRoles = @{}

    # Get Master Roles
    Connect-VIServer $MasterServer -Credential $Credential
    $DiscoveredRoles["MasterRoles"] = Get-VIRole
    Disconnect-VIServer $MasterServer -Confirm:$false

    #Get Slave Roles
    Connect-VIServer $SlaveServer -Credential $Credential
    $DiscoveredRoles["SlaveRoles"] = Get-VIrole
    Disconnect-VIServer $SlaveServer -Confirm:$false

    Write-Verbose "`n + Retrieved Roles Successfully"

    return $DiscoveredRoles

}    

Here's where the error occurs. Process-Roles requires a hashtable, but I believe powershell converted $RoleTable to an array? (that's at least what my google-fu told me)

function Process-Roles { 
    param(
        [Parameter(Mandatory=$true)]
        [ValidateScript({ $_.ContainsKey("MasterRoles") -and $_.ContainsKey("SlaveRoles") })]
        [hashtable]$RoleTable
    )

    $MasterRoleNames = $RoleTable["MasterRoles"] |Select-Object -ExpandProperty Name

    $SlaveRoleNames = $RoleTable["SlaveRoles"] |Select-Object -ExpandProperty Name

    $MasterRoleNames |Where-Object { $SlaveRoleNames -notcontains $_ } |ForEach-Object {
        Write-Verbose "$_ doesn't exist on slave"    
    }

    $SlaveRoleNames |Where-Object { $MasterRoleNames -notcontains $_ } |ForEach-Object {
        Write-Verbose "$_ doesn't exist on Master"    
    }

    Write-Verbose "`n + Processed Roles Successfully"
}

display highest value

I have written a function which is used to pick the highest value and display everything from sql based on the ID. If aa[0] is highest it will display everything in ID 0, if not, it will display either 1 or 2. But the problem now is it only displays value in ID 0 although ID 1 is the highest! Anyone can help me to figuring out what;s wrong with my coding ? Thanks

  private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
                 // TODO Auto-generated method stub
                 double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray(); 
                 double highest=aa[0]; 
                 if(highest==aa[0])
                 {
                     String sql ="Select * from placeseen where ID =0";
                     DatabaseConnection db = new DatabaseConnection();
                     Connection  conn =db.getConnection();
                     PreparedStatement  ps = conn.prepareStatement(sql);
                     ResultSet rs = ps.executeQuery();
                     if (rs.next()) 
                     {  
                      String aaa=rs.getString("place1");  
                      String bbb=rs.getString("place2");
                      String cc=rs.getString("place3");
                      Tourism to =new Tourism();
                      to.setPlace1(aaa);
                      to.setPlace2(bbb);
                      to.setPlace3(cc);
                      DispDay dc=new DispDay();
                      dc.setVisible(true);
                     }
                     ps.close();
                     rs.close();
                     conn.close();
             }   else
             {
                  for(int i=0;i<aa.length;i++)
                 {
                     if(aa[i]>highest)
                     {
                         highest=aa[i];
                         System.out.println(highest);
                         String sql ="Select * from placeseen where ID =?";
                         DatabaseConnection db = new DatabaseConnection();
                         Connection  conn =db.getConnection();
                         PreparedStatement  ps = conn.prepareStatement(sql);
                         ps.setDouble(1, i); 
                         ResultSet rs = ps.executeQuery();
                         if (rs.next()) 
                         {  
                          String aaa=rs.getString("place1");  
                          String bbb=rs.getString("place2");
                          String cc=rs.getString("place3");
                          Tourism to =new Tourism();
                          to.setPlace1(aaa);
                          to.setPlace2(bbb);
                          to.setPlace3(cc);
                          DispDay dc=new DispDay();
                          dc.setVisible(true);
                         }
                         ps.close();
                         rs.close();
                         conn.close();
                 }   

                 }

             }

How to store 3 different types of data in one array

I need to store 3 linked bits of data in c. My original thought was a 3 dimensional array but that won't work as all 3 data types are different. The top level needs to be a char array. The second level needs to be a date/time so a integer. The third level is a temperature reading so needs to be a float.

Is the correct way to do this an array of pointers pointing to an array of pointers pointing to a array of floats? If so how would that be written in C?

Javascript: Make new array out of nested json object

I am getting data back which includes nested json objects and would like to make a new array containing those json objects. So if I am getting

[
   {
        "number": 1,
        "products": [
            {
                "fruit": "apple",
                "meat": "chicken"
            },
            {
                "fruit": "orange",
                "meat": "pork"
            }
        ]
    }
]

I would like the new array to be

[
    {
        "fruit": "apple",
        "meat": "chicken"
    },
    {
        "fruit": "orange",
        "meat": "pork"
    }
]

efficient way to create JavaScript object from array of properties and array of matching property values

Is it possible to create the the data1 array without using nested for loops?

// My starting Normalized data
var fields = ["name","age"];
var data2 = [["John",20],["Tom",25]]; 


// What I want the result to look like Denormalized
var data1 = [{"name":"John", "age":20},{"name":"Tom", "age":25}];


// My solution
var data1 = [];
for(var i = 0; i < data2.length; i++){
   var temp = {};
   for(var y = 0; y < fields.length; y++){
      temp[fields[y]] = data2[i][y];
   }
   data1.push(temp);
}

Modify if-counter inside a loop

I'm trying to modify a counter in if loop because one array index number needs to be corresponded by the other in order for me to change the place of it's text, but the space between the strings add 1 to the counter.

for(int i = 0, n = strlen(p); i < n; i++){

    if(isspace(p[i])){
        c1 = x[i-1];
        printf("%c", p[i]);
    }
    if(isalpha(p[i])){
        c1 = x[i];
        c2 = c1-96;
        printf("%c --- %c ---%d\n",p[i],c1, c2);
    }

This is one of the attempts but it made an infinite loop, I've tried different approach like:

    if(isspace(p[i))){
        printf("%c", p[i]);
        i -= 1;
    }

Why does my program display the Array address instead of its contents?

My C program consists of an array called 'test_var'. It has another integer array 'arr_int' that consists of a set of integer numbers. My code looks something like this:

 #include <stdlib.h>
 #include <stddef.h>
 #include <stdio.h>

 int State(var);
 int main()
       {
         int arr_int[3] ={1000, 1001, 1002, 1003};
         int var;
         int *test_var[4]={0};

         State(var)
         {
            int i;
            for(i=0; i<4; i++){
               test_var[i] = arr_int[i];
               i++;
                }
          return test_var[var];
          }

          printf("Enter a number between 0 and 3\n");
          scanf("%d",&var);   
          State(var);
          printf ("The array structure is %d", test_var[var]);

          return 0;
          }

However now when I try to print the returned value array test_var for the user input var=0 instead of the whole array(1000) I just get 0. What am I doing wrong here ? COuld somebody please tell me? Am I dereferencing the array in a wrong way?

prev() next() array element on PHP

I have problem,

$text = "My little brother give me a snack";

I sign that if the word = give it sign as verb and then it'll be current position

how to show my all previous position and my all next position.

output :

verb = give

current = give

subject = My little brother

object = a snack

I know that it can be applicate with prev() and next()

but how to use it ?

Thank's

Error when saving 3D array

I'm trying to save a 3D array of data to a file using the following code:

print "Writing results to a file..."
format = "GTiff"
driver = gdal.GetDriverByName(format)

fileName = 'path_to_folder/FLENAME.tif'
NumberOfBands = 46

new_dataset = driver.Create( fileName, 2400, 2400, NumberOfBands,6)
new_dataset = None

for band in range( NumberOfBands ):
    new_dataset.GetRasterBand(band + 1).WriteArray(DATA[band,:,:])

With this I get the error: 'NoneType' object has no attribute 'GetRasterBand'

I tried it without GetRasterband and got 'NoneType' object is not attainable.

Originally tried np.save as an alternative but it was not implemented and was advised to try this method instead. Any help would be appreciated. Thanks.

Swig Templates: How to check if value exists in array?

I'm using Swig on a new project. One of my variables is an array of values (strings). Is there a built-in operator in Swig to check if a value exists in an array? Per the docs, it would seem "in" should do it but no further detail is provided. Also, what's the proper way to negate it? I'm trying the following, but no luck. Would I need to write a custom tag?

{% if 'isTime' in dtSettings %}checked{% endif %}

{% if 'isTime' not in dtSettings %}hide{% endif %}
{% if !'isTime' in dtSettings %}hide{% endif %}
{% if !('isTime' in dtSettings) %}hide{% endif %}