Arrays Incrementing: x++ vs x += 1

I've read that many developers use x += 1 instead of x++ for clarity. I understand that x++ can be ambiguous for new developers and that x += 1 is always more clear, but is there any difference in efficiency between the two? Example using for loop: for(x = 0; x < 1000; x += 1) vs for(x = 0; x < 1000; x++) I understand that it's usually not that big of a deal, but if I'm repeatedly calling a function that does this sort of loop, it could add up in the long run. Another example: while(

Arrays Get record of mongo from list array mongo

I use mongo, and I have a little problem here. I want to get a record, but I just have the id of an array list inside record. This is what my data looks like. { "_id": ObjectId("1113000001"), "menu": "desertsunday", "fruit": { "0": ObjectId("102b000000"), "1": ObjectId("5200000000"), "2": ObjectId("2900000000"), "3": ObjectId("9870000002") } } I just have 102b000000 for get the record, I need to get the menu from there but I can't get it with sta

Arrays Indexing an hastable

I have an hashtable that I add to when I am creating jobs with the following code: $jobtimer = @{} 1..10 | foreach { Start-Job -name $_ -ScriptBlock { Start-Sleep -Seconds (Get-Random -Minimum 456 -Maximum 46546520) } $jobtimer[$_] = [System.Diagnostics.Stopwatch]::StartNew() } (thank you @mjolinor for help with this by the way!!) I then loop through my jobs and fetch time elapsed on each job. But I'm having problems reading the values of the array. If I directly re

Arrays filter an array on the basis of some property of the objects of array

I have an array with some objects stored in it. Say I have objects of type application. Each application object has some information associated with it like applicationType, appId etc. I need to create seperate arrays for each applicationType. like everytime I need to fetch out the objects of same applicationType. i.e at the end i need to have an array that will consist of objects ( that will be arrays of same applicationType) eg : object at 0th index will be an array of application of applicati

Arrays VB.NET Checking for existing files and assigning new Version Numbers to the name?

Alright, this one has been driving me up a wall for the past few hours, and I feel like I can almost taste victory, but I am stuck. I am writing files into a directory based on user supplied requirements, and this particular section deals with assigning a new Version Number to the new file. So basically, this creates the new file using a naming convention of: Path\FileName_ver1 Path\FileName_ver2 And so on. The issue is, I cannot figure out how to determine if a file with similiar naming (m

VBA, Arrays, Ranges, Sorting

I have to write a function to sort a given range in VBA in Excel. (Bubble Sort) I have done the following : Function MySort(M2 As Range) Dim r As Integer r = M2.Rows.Count Dim M1 as range M1 = M2 Dim buffer For i = 0 To r For j = i To r If (M1.Item(i, 0) > M1.Item(j, 0)) Then buffer = M1.Item(i, 0) M1.Item(i, 0) = M1.Item(j, 0) M1.Item(j, 0) = buffer End If Next j Next

Interesting findings when combining Arrays in Scala

I'm having some trouble understanding Array combination in Scala. The following works fine: scala> Array('0', '1', '2') ++ Array('A', 'B', 'C') res0: Array[Char] = Array(0, 1, 2, A, B, C) But this one does not: scala> ('0' to '9').toArray ++ ('A' to 'Z').toArray <console>:8: error: polymorphic expression cannot be instantiated to expected type; found : [B >: Char]Array[B] required: scala.collection.GenTraversableOnce[?] ('0' to '9').toArray ++ ('A' to 'Z').t

Arrays Attach images to knnsearch o/p array

I am working on my project on pattern recognition and i am using knn search for finding nearest neighbors, the problem i am facing is that when i get the o/p in ascending order(Rank's) its some sort of array. x = [v_2;v_3;v_4;v_5]; Training samples y = v_1; sample image IDX = knnsearch(x,y,'K',4); o/p IDX=[2 3 1 4] final o/p this shows that my 'sample image' matches to 2nd image first, then to third and so on... So the question is how can i access these array elemnts. I want to att

Arrays subscript out of range while adding items to array

I'm trying to fill an array with members from an AD group. I keep getting the following error while trying to set newArray(count) to the user name. Microsoft VBScript runtime error: Subscript out of range Here is the relevant code: 'set up of domain variables and stuff, verified working Dim newArray() Dim x x = 0 Do While x < 1 Set objGroup = GetObject("WinNT://" & strDomain & "/" & strGroup & ",group") count = 0 For Each objUser In objGroup.Members n

Arrays Unexpected sort in Python deletes every second folder

I'm writing a script to cleanup old backup folders and every second folder seems to be deleted in a sorted directory listing. I've figured out how to work around it (by sorting again prior to delete), but don't understand why the workaround is necessary. This is the first method, which correctly sorts the array (confirmed via print), but which then deletes every second folder: # Build an array of the relevant backup directories, excluding files. BDL = [f for f in os.listdir(DST) if os.path.isd

Arrays Indexed float array in NASM x86 16-bit

I'm trying to fill an array of double-precision (64-bit) real numbers using the loop instructions in NASM x86 16-bit, but I get the invalid effective address error. The OS is Windows XP 32 bits, but the program actually runs as a MS-DOS 16-bit one. For example: mov cx, 10 fill_array: fld qword[yArray + cx*8] fstp qword[xArray + cx*8] loop fill_array Returns the previous error at the fld and fstp lines. The arrays are declared this way: yArray resq 10 xArray resq 10 I've a

Extracting information form multiple arrays

I am trying to use multiple arrays to extract information from a file and then echo that information out. The question from my homework is: • Use the /var/log/messages file, ask the user to enter a service name (eg. “syslogd”) and display the number of times the service restarted for a specific date. So for instance if the service restarted 5 times on November 11 2014, and 3 times on November 12 2014 your output should resemble the following: The syslogd service restarted 5 times on Nov 10, t

Arrays Iterate through an array - returned error "Attempted to access A(:,3); index out of bounds because size(A)=[4,2]"

I am new to MATLAB and I am trying to write some code to iterate through an imported Excel array and do a calculation on each column of the array separately. I am receiving the error "Attempted to access A(:,3); index out of bounds because size(A)=[4,2]" and I am not sure why, as I have tried to give the output variable matrix dimensions. Here is the code: filename = 'allsets.xlsx'; x1Range = 'B1:C5'; sheet = 1; A = xlsread(filename,sheet,x1Range); Mu1 = zeros(size(A)); Mu2 = zeros(size(B));

Arrays How to remove an array element in json-c?

Assuming the following JSON object, an array of [epoch, value] arrays: [ [0,1], [1912312314,2], [1912312857,5] ] What's the correct way to remove an element of the array ? The idea is to remove the one with an epoch alder than a given value. I use json-c 0.11. I tried : json_object *jsonHeatmapObj; jsonHeatmapObj = json_tokener_parse ( "[ [0,1], [1912312314,2], [1912312857,5] ]" ); for ( int idx=0 ; idx < json_object_array_length(jsonHeatmapObj) ; idx++ ) { json_object

Arrays Matlab exp produces unexpected result

As a Matlab-noob i've been experimenting a bit with the exp-function. What I found was that putting: a = 1.1 b = 5 test = exp (a+b) produced the desired (correct) answer. (test = 445.8578) However: replacing a with a matrix gave completely the wrong result. so a = [1.1 1.3 2.5 4.3] b = 5 test = exp(a+b) produced a wrong result (test = 1.0e+04 * 0.0446 0.0545 0.1808 1.0938) I'm probably overlooking something, but I don't know where I'm going wrong. Can anyone enlighten me?

Arrays Powershell loop files into program, if exit code is not equal to 0 move the file

I have a program that returns an exit code of 1 if a text file is empty or if it has a header record and no other contents. I'm trying to have powershell loop the contents of a folder (text files) into the program, and if the program returns an exit code not equal to 0, move the file to another location. Here's what I have so far: $files = Get-ChildItem -name C:\SourceFolder $files | ForEach-Object {C:\TestProgram.cmd $_ } | ForEach-Object { if ($LASTEXITCODE -ne 0) {Move-Item $_.FullName C:\D

Arrays Select objects based on an array

I have a list of Movies and a movie has an array of genres. Most movies have only one genre, but some of them have two, like "Drama" and "Comedy". I need to select all movies that match one or more category. For example, I want a query to select movies that are "Drama" or "Comedy". I did this { |mov| mov.genres.include? ['Drama', 'Comedy'] } But this select seems to be exclusive: it searches for movies that are both "Drama" and "Comedy". Is there a way to do that in one line or

Arrays error filling array with class instances in swift

Using Swift I am trying to create an array that is full of objects. I keep getting this error instance member joe(first value) cannot be used on type 'Friend'(the class) then i want to print the value of name for every object. Here is my code. import UIKit class Friend { var name:String = "aName" var athletic = 0 var brains = 0 var male:Bool = false init (name:String, brains:Int, athletic:Int, male:Bool){ self.athletic=athletic se

Arrays Perl calculate average from randomly populated array

I have a school assignment I need help with. Now, I know what you're thinking, but my teacher is out of town and hasn't answered my e-mails, and my other classmates have no clue how to solve this problem. A few pointers and tips would be greatly appreciated! The assignment is this: We're supposed to create an array, populate it with 20 to 30 random integers in the range of 1-100. Then, by the help of subroutines, we're supposed to calculate the average of these numbers. The problem occurs whe

Arrays Match against substrings in array

I have an array: my_arr = ["PR", "PM", "EM", "SM", "ST"] and a string: my_str = "5012PR152" I would like to see if the string includes any of the strings in the array. If the strings in the array was just one, this would work: my_str.include?("PR") but I can't pass the array of strings as an argument to include?. How can I go about this?

Arrays Iterate Array and add each consecutive array value

I have an amount. I want to iterate the array starting from the first value and if I add the next value and it equals amount then those two values in the array should be returned. If it doesn't equal the value, try to add the next one after that one and check if it equals the amount. And then return the array of values that when added up equals the amount example Lets say I have an array of [1,2,3,4,7] and an amount 6 I know that I can make 6 by adding 1+2+3 so I want to return [1,2,3] b

Arrays Why I am not getting right value when pushing it to an array?

I have some data in the following format. # AB Tests # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - abTests: productRanking: version: 4 groups: [ ratio: default: 1 us: 0.90 me: 0.0 value: "LessPopularityEPC" , ratio: default: 0 us: 0.1 value: "CtrEpcJob" , ratio: default: 0 me: 1.0 value: "RandomPerVisitor" ] # Routes I w

Arrays Automic UC4 script: Storing user-input into an array

First: I'm using UC4 - dialog version 9.00A Build 234-162. I'm trying to read a variable number of input fields (via :READ) and want to store their values into an array: :DEFINE &FILE#, string, 10 :PUBLISH &FILE#[], , "WORKFLOW" :BEGINREAD "Files" : READ &CNT#, , "Number of files", "3" :ENDREAD :SET &IDX# = 1 :BEGINREAD "Files" : WHILE &IDX# LE &CNT# : SET &IDX# = ADD(&IDX#, 1) : READ &FILE#[&IDX#], ,"???" : ENDWHILE :ENDREAD Problem is: Now

Arrays Deselect from collectionView and cancel item from array

I have the following code: var selectedIndexPaths = [NSDate]() func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) as? PartExpense if cell?.selected == true { cell?.layer.borderWidth = 4.0 cell?.layer.borderColor = UIColor.greenColor().CGColor selectedIndexPaths.append(cell!.idPartecipant) print(selectedIndex

Arrays Find duplicated values in an Array of Hashes

I am looking for a way to select only duplicate entries from multiple Arrays of Hashes. Say I have a project with an attribute called "exchange_rate": project.exchange_rate #=> [{"name"=>"USD", "rate"=>1.0}, {"name"=>"EUR", "rate"=>0.91}, {"name"=>"CNY", "rate"=>6.51}, {"name"=>"NOK", "rate"=>1}, {"name"=>"DKK", "rate"=>1}, {"name"=>"JPY", "rate"=>113.24}] Now I have multiple projects which have the same construct, just with

Arrays PowerShell split string into two dimensional array

TL:DR Using PowerShell I want to split a string of text first by the new line character (\n), store it into an array, then split those array entries with a comma into a two-dimensional array. I am having trouble accessing (or possibly creating) any information in the second dimension. INFO: I have the following string (stored as $services): SUPER-PC,Microsoft Office ClickToRun Service,ClickToRunSvc,C:\Program Files\Microsoft Office 15\ClientX64\OfficeClickToRun.exe /service,Auto SUPER-PC,Ado

Arrays Append to JSON array within an JSON array ColdFusion

This is a follow up question to: Append to JSON array with ColdFusion, taking Null values into consideration? That question was answered yesterday and worked perfectly (Thank you Kevin B. and Leigh!). However, the application I am pulling my JSON data from threw me a curve ball this morning. Sometimes, depending on the data I am requesting, it returns the entire JSON as an array like this: [ { "loginHosts": [ "" ], "sudoHosts": [ "ser

Arrays VBA Declared variable not allowed as public members of object modules

"Global" Indexed variables and arrays has to be in a module and make sure ThisWorkbook and the different sheets do not contain any of those variables. Hello, This is my first time asking a question here. I have only been programing in VBA for about 3 weeks and have no prior experiance of programing. The Question: My question is if it´s possible to declare indexed variables and arrays as Public which can be used by several subroutines and if so, how? The problem: I have got stuck on tryin

Arrays Finding particles in the same cell on a 2d grid

It's a sort of an algorithmic question, without a bond to any of the particular languages. Let's say I have Np point particles with continuous (read double) x, y coordinates on a 2d plane. The 2d plane is divided into N ⨉ N cells. For each particle I want a quick way (faster than O(Np^2)) to find other particles in the same cell. Also, I don't want to go too far in memory usage, so I don't want another N ⨉ N + Np array to store. I "invented" a tricky way to realize this, but I'm asking this

Arrays How to store a Swift array of custom objects in a text file?

I have a 2D generic array, with about 50 of these things: [string, string, string, string, double, double] The values are all in the same order, and I have a custom class: class tramStop { var tramDirection: String? var stopCode: String? var nameEnglish: String? var nameChinese: String? var latitude: Double? var longitude: Double? init(direction: String, code: String, nameEn: String, nameCn: String, lat: Double, lon: Double) { tramDirection = direction

Arrays Finding a Particular Missing Array Element: O(n+k) Complexity

I have to create an algorithm which returns the largest missing element in an array of size n, which ranges from values 1-k. Example: If the array contained 1,1,3,1,3 then k=3, n=5, and the return should be 2. If time complexity isn't taken into account, this is relatively straightforward; simply iterate through the array searching for k-1, k-2,...2, and the first time a value isn't found, return that value (or -1 if no such value exists). However, this will be a loop inside a loop, resultin

Arrays TableView only showing Part of data read in from Firebase

I have the following code which adds a "Trip" to the Firbase Database @IBAction func addButtonPressed(_ sender: UIButton) { let ref = Database.database().reference().child("Users").child(user).child("Trips").childByAutoId() if Double(distanceText.text!) != nil { trip.distance = Double(distanceText.text!)! } else { print("invaliddouble") } if tripNameText != nil { trip.title = tripNameText.text! } let

Python: Finding a numpy array in a list of numpy arrays

I have a list of 50 numpy arrays called vectors: [array([0.1, 0.8, 0.03, 1.5], dtype=float32), array([1.2, 0.3, 0.1], dtype=float32), .......] I also have a smaller list (means) of 10 numpy arrays, all of which are from the bigger list above. I want to loop though each array in means and find its position in vectors. So when I do this: for c in means: print(vectors.index(c)) I get the error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.

Arrays SAS Put value from array if find value from array

My code and problem: data Scinamy; input Description $20. ; datalines; New old Active New Active Old ANother record Records with Gold Value with Gold ; Data Scinamy1; set Scinamy; array lista[3] $ _temporary_ ('Active','Gold','Prime'); do i = LBound(lista) To HBound(lista); if find(upcase(lista{i}),upcase(Description)) > 0 then do; AA= upcase(lista{i}); leave; end; else do; AA = 'not cont

Arrays How to specify multiple authors for a single post, then count the posts each author is related to?

I'm trying to create a list for the posts each author has written. This is a problem since each post should be able to specify multiple authors. Let's say we have 3 posts in total and 3 authors in total. Edit 1: as suggested in the answers this is best done by listing the authors in a front matter list instead of a CSV string. So, Like this Post: --- title: post authors: - foo - bar --- instead of like this: Post: --- title: post authors: [foo, bar] --- Problem setup: (edited, ac

Arrays How to concatenate an optional array to another array in Swift?

I know this sounds ridiculous but I am seriously confused now. Basically I have two vars, one is [Data] and one is Array<Data>? I need to combine these two. I've tried do var1+var2, which is giving me errors say can't do binary operations on these two. So I googled, I can use append method, now there comes more questions: the append method is crossed out in autofill, so I am not sure if I should use it. Even if I try to use it (while it's being crossed out), it is still giving me erro

Arrays VBA FormulaArray range class error when the Characters are less than 255

The VBA .FormulaArray seems to have a problem with my range. I've read that it can't handle over 255 characters, but mine is only about 108, but I could be understanding it wrong. It gives an Error 1004: Unable to set FormulaArray property of the Range class. I've tried leaving the formula in the table column and let it automatically populate when the table is filled with the Macro, but the problem is that the Index array table doesn't exist yet before the Macro starts running. Also

Arrays How to convert json objects to json array in flutter

This is my json response data. I would like to display this data in listview using map but i dont know how to convert the objects of objects to array of data. { "success": true, "data": { "addresses": { "abc": { "address_id": "121", "firstname": "Demo", "lastname": "User", "company": "Demo Company name", "telephone": "1-541-754-3011",

Arrays Swift: What is the proper implementation to construct an object that will handle JSON/Dictionalry parsing

I've managed to get very confused with regard to Swift Codeable, struct vs. class, and JSON parsing. I am trying to manage data for various bundles of images, of which multiple bundles can be assigned to a given slate. I want to be able to append additional image bundles to a slate if it already exists. The JSON format would look something like: { slate: "S1A:, imageBundles: [ { timestamp: "2019-10-11_23:00", fileUrls: [ "files/R0010514.JPG", "fi

Arrays AppScript: 'number of columns in the data does not match the number of columns in the range.' setValues method not reading array correctly?

I'm trying to automate the collection of phone numbers from an API into a Google Sheet with app script. I can get the data and place it in an array with the following code: const options = { method: 'GET', headers: { Authorization: 'Bearer XXXXXXXXXXXXXXX', Accept: 'Application/JSON', } }; var serviceUrl = ""; var data=UrlFetchApp.fetch(serviceUrl, options); if(data.getResponseCode() == 200) { var response = JSON.parse(data.getContentText());

Arrays How to group an array within React Native

I have an array of objects called "directory" which include a list of people and their job. The problem is that a person can cover more than 1 role and I'd like to group the "job" under the same "id" during rendering. This is my array: "directory": [ { "id": 37, "job": "Electrician", "name": "Alan" }, { "id": 32, "job": "Writer", "name": "Mark" }, { "id": 37, "job": "DIY", "name": "Alan" }, { "i

Arrays Importing a 2d array into a class with delphi

I am trying to create a class with a 2d array(arrscore) within the create method, I have done some research on this and this is as far as I have come. constructor create(spriority, sSelOne, sSeltwo, sSelthree: string; arrcountry: array of string; arrscore: array of real); Here is my declaration of my classes variables type tMap = class private // variables priority, selone, seltwo, selthree: string; country: array of string; score: array of real; This is my create code beg

Arrays Excel: checking 2 lists to see if they contain values, and counting the number of times that they are paired with each other

I have 2 columns, with values that are paired with each other (col1 is A:A, col2 is B:B): col1 | col2 Harry Potter | Voldemort Harry Potter | Draco Malfoy Michael Corner| Draco Malfoy Ernie Mac | Hannah Abbot I want to check col1 to see if this name exists in List 1: List1: Harry Potter Dumbledore Ginny Weasley Godric Gryffindor I also want to check col 2 to see if this name exists in List 2: List2: Salazar Slytherin Draco Malfoy Voldemort Severus Snape Vincent Crabbe Then I wa

Arrays C - Comparing a float to an array to see if the value is in the array

I have a program where I need to take a value and compare it to 12 values in an array. If this value lies within the array, I need to return a true value to the main function so that it prints something if this true value is returned. I can post some of my code, but I am confused on how to return this true value. void resistor (void) // Function to input resistor and capacitor values { float ra, rb, c; // Float variables for two resistor values and capacitor while(1) // While loop to gathe

Arrays in perl, why does push cause a regex created by qr to be changed when not put into double quotes?

I am defining regexes inside a script, using qr, and pushing them onto an array. But now it appears that if I do not put the regex inside double quotes, the action of pushing it onto the array changes it. Example: #!/usr/bin/perl use strict; use warnings; use Data::Dumper qw(Dumper); use Data::Dumper::Concise; my @regexes; my $rgx = 'dog'; my $mdf = 'i'; $rgx = join ( '', '(?', $mdf, ')', $rgx ) if ($mdf); # in production, $mdf could be empty eval { $rgx = qr/$rgx/ }; if ($@) # catch illegitimat

Arrays How to cast an [u8] array larger than 8 bytes to an integer?

Because of the length of the array, I can't use i32::from_ne_bytes(), but of course, the following works especially since the code will run only on a cpu architecture supporting unaligned access (or that because of the small length, the whole array might get stored accross several cpu registers). fn main() { let buf: [u8; 10] = [0, 0, 0, 1, 0x12, 14, 50, 120, 250, 6]; println!("1 == {}", unsafe{std::ptr::read(&buf[1])} as i32); } But is there a cleaner way to do it while s

Arrays How to sort an array using stack in assembly

I want to sort an array while using the stack: so first things first I pushed it all into the stack. then I'm locating the minimum element in the stack, swapping it with the top element popping it out and move it back to the array. but something isn't right and about halfway there it got messed up (DI is one index below than what it should really be) data segment a db 5h,12h,6h,4h,9h len equ $-a loop_counter db len min_index dw 0 min db ? ends stack segment dw 128 dup(0)

  1    2   3   4   5   6  ... 下一页 最后一页 共 235 页