Search Results

Search found 3545 results on 142 pages for 'arrays'.

Page 16/142 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Array-size macro that rejects pointers

    - by nneonneo
    The standard array-size macro that is often taught is #define ARRAYSIZE(arr) (sizeof(arr) / sizeof(arr[0])) or some equivalent formation. However, this kind of thing silently succeeds when a pointer is passed in, and gives results that can seem plausible at runtime until things mysteriously fall apart. It's all-too-easy to make this mistake: a function that has a local array variable is refactored, moving a bit of array manipulation into a new function called with the array as a parameter. So, the question is: is there a "sanitary" macro to detect misuse of the ARRAYSIZE macro in C, preferably at compile-time? In C++ we'd just use a template specialized for array arguments only; in C, it seems we'll need some way to distinguish arrays and pointers. (If I wanted to reject arrays, for instance, I'd just do e.g. (arr=arr, ...) because array assignment is illegal).

    Read the article

  • Why use third-party vector libraries at all?

    - by Patrick Powns
    So I'm thinking of using the Eigen matrix library for a project I'm doing (2D space simulator). I just went ahead and profiled some code with Eigen::Vector2d, and with bare arrays. I noticed a 10x improvement in assigning values to elements in the array, and a 40x improvement in calculating the dot products. Here is my profiling if you want to check it out, basically it's ~4.065s against ~0.110s. Obviously bare arrays are much more efficient at dot products and assigning stuff. So why use the Eigen library (or any other library, Eigen just seemed the fastest)? Is it stability? Complicated maths that would be hard to code by yourself efficiently?

    Read the article

  • Enumerate all k-partitions of 1d array with N elements?

    - by user301217
    This seems like a simple request, but google is not my friend because "partition" scores a bunch of hits in database and filesystem space. I need to enumerate all partitions of an array of N values (N is constant) into k sub-arrays. The sub-arrays are just that - a starting index and ending index. The overall order of the original array will be preserved. For example, with N=4 and k=2: [ | a b c d ] (0, 4) [ a | b c d ] (1, 3) [ a b | c d ] (2, 2) [ a b c | d ] (3, 1) [ a b c d | ] (4, 0) I'm pretty sure this isn't an original problem (and no, it's not homework), but I'd like to do it for every k <= N, and it'd be great if the later passes (as k grows) took advantage of earlier results. If you've got a link, please share.

    Read the article

  • New Perl user: using a hash of arrays

    - by Zach H
    I'm doing a little datamining project where a perl script grabs info from a SQL database and parses it. The data consists of several timestamps. I want to find how many of a particular type of timestamp exist on any particular day. Unfortunately, this is my first perl script, and the nature of perl when it comes to hashes and arrays is confusing me quite a bit. Code segment: my %values=();#A hash of the total values of each type of data of each day. #The key is the day, and each key stores an array of each of the values I need. my @proposal; #[drafted timestamp(0), submitted timestamp(1), attny approved timestamp(2),Organiziation approved timestamp(3), Other approval timestamp(4), Approved Timestamp(5)] while(@proposal=$sqlresults->fetchrow_array()){ #TODO: check to make sure proposal is valid #Increment the number of timestamps of each type on each particular date my $i; for($i=0;$i<=5;$i++) $values{$proposal[$i]}[$i]++; #Update rolling average of daily #TODO: To check total load, increment total load on all dates between attourney approve date and accepted date for($i=$proposal[1];$i<=$proposal[2];$i++) $values{$i}[6]++; } I keep getting syntax errors inside the for loops incrementing values. Also, considering that I'm using strict and warnings, will Perl auto-create arrays of the right values when I'm accessing them inside the hash, or will I get out-of bounds errors everywhere? Thanks for any help, Zach

    Read the article

  • Declaration of arrays before "normal" variables in c?

    - by bjarkef
    Hi We are currently developing an application for a msp430 MCU, and are running into some weird problems. We discovered that declaring arrays withing a scope after declaration of "normal" variables, sometimes causes what seems to be undefined behavior. Like this: foo(int a, int *b); int main(void) { int x = 2; int arr[5]; foo(x, arr); return 0; } foo sometimes is passed a pointer as the second variable, that does not point to the arr array. We verify this by single stepping through the program, and see that the value of the arr variable in the main scope is not the same as the value of the b pointer variable in the foo scope. And no, this is not really reproduceable, we have just observed this behavior once in a while. Changing the example seems to solve the problem, like this: foo(int a, int *b); int main(void) { int arr[5]; int x = 2; foo(x, arr); return 0; } Does anybody have any input or hints as to why we experience this behavior? Or similar experiences? The MSP430 programming guide specifies that code should conform to the ANSI C89 spec. and so I was wondering if it says that arrays has to be declared before non-array variables? Any input on this would be appreciated.

    Read the article

  • Checking for empty arrays: count vs empty

    - by Dan McG
    This question on 'How to tell if a PHP array is empty' had me thinking of this question Is there a reason that count should be used instead of empty when determining if an array is empty or not? My personal thought would be if the 2 are equivalent for the case of empty arrays you should use empty because it gives a boolean answer to a boolean question. From the question linked above, it seems that count($var) == 0 is the popular method. To me, while technically correct, makes no sense. E.g. Q: $var, are you empty? A: 7. Hmmm... Is there a reason I should use count == 0 instead or just a matter of personal taste? As pointed out by others in comments for a now deleted answer, count will have performance impacts for large arrays because it will have to count all elements, whereas empty can stop as soon as it knows it isn't empty. So, if they give the same results in this case, but count is potentially inefficient, why would we ever use count($var) == 0?

    Read the article

  • Please help with passing multidimensional arrays

    - by nn
    Hi, I'm writing a simple test program to pass multidimensional arrays. I've been struggling to get the signature of the callee function. void p(int (*s)[100], int n) { ... } In the code I have: int s1[10][100], s2[10][1000]; p(s1, 100); This code appears to work, but it's not what I intended. I want to the function p to be oblivious whether the range of values is 100 or 1000, but it should know there are 10 pointers. I tried as a first attempt: void p(int (*s)[10], int n) // n = # elements in the range of the array and also: void p(int **s, int n) // n = # of elements in the range of the array But to no avail can I seem to get this correct. I don't want to hardcode the 100 or 1000, but instead pass it in, but there will always be 10 arrays. Obviously, I want to avoid having to declare the function: void p(int *s1, int *s2, int *s3, ..., int *s10, int n) FYI, I'm looking at the answers to a similar question but still confused.

    Read the article

  • merging javascript arrays for json

    - by Nat
    I serially collect information from forms into arrays like so: list = {"name" : "John", "email" : "[email protected]", "country" : "Canada", "color" : "blue"}; identifier = "first_round"; list = {"name" : "Harry", "email" : "[email protected]", "country" : "Germany"}; identifier = "second_round"; I want to combine them into something (I may have braces where I need brackets) like: list_all = { "first_round" : {"name" : "John", "email" : "[email protected]", "country" : "Canada", "color" : "blue"} , "second_round" : {"name" : "Harry", "email" : "[email protected]", "country" : "Germany"} }; so I can access them like: alert(list_all.first_round.name) -> John (Note: the name-values ("name", "email", "color") in the two list-arrays are not quite the same, the number of items in each list-array is limited but not known in advance; I need to serially add only one array to the previous structure each round and there may be any number of rounds, i.e. "third-round" : {...}, "fourth-round" : {...} and so on.) Ultimately, I'd like it to be well-parsed for JSON. I use the jquery library, if that helps.

    Read the article

  • Need to sort 3 arrays by one key array

    - by jeff6461
    I am trying to get 3 arrays sorted by one key array in objective c for the iphone, here is a example to help out... Array 1 Array 2 Array 3 Array 4 1 15 21 7 3 12 8 9 6 7 8 0 2 3 4 8 When sorted i want this to look like Array 1 Array 2 Array 3 Array 4 1 15 21 7 2 3 4 8 3 12 8 9 6 7 8 0 So array 2,3,4 are moving with Array 1 when sorted. Currently i am using a bubble sort to do this but it lags so bad that it crashes by app. The code i am using to do this is int flag = 0; int i = 0; int temp = 0; do { flag=1; for(i = 0; i < distancenumber; i++) { if(distance[i] > distance[i+1]) { temp = distance[i]; distance[i]=distance[i + 1]; distance[i + 1]=temp; temp = FlowerarrayNumber[i]; FlowerarrayNumber[i] = FlowerarrayNumber[i+1]; FlowerarrayNumber[i + 1] = temp; temp = BeearrayNumber[i]; BeearrayNumber[i] = BeearrayNumber[i + 1]; BeearrayNumber[i + 1] = temp; flag=0; } } }while (flag==0); where distance number is the amount of elements in all of the arrays, distance is array 1 or my key array. and the other 2 are getting sorted. If anyone can help me get a merge sort(or something faster, it is running on a iPhone so it needs to be quick and light) to do this that would be great i cannot figure out how the recursion works in this method and so having a hard time to get the code to work. Any help would be greatly appreciated

    Read the article

  • accessing values in two dimensional arrays

    - by BrainLikeADullPencil
    In some code I'm trying to learn from, the Maze string below is turned into an array (code not shown for that) and saved in the instance variable @maze. The starting point of the Maze is represented by the letter 'A' in that Maze, which can be accessed at @maze[1][13]---row 1, column 13. However, the code I'm looking at uses @maze[1][13,1] to get the A, which you can see returns the same result in my console. If I do @maze[1][13,2], it returns the letter "A " with two blank spaces next to it, and so on. [13,3] returns "A " with three blank spaces. Does the 2 in [13,2] mean, "return two values starting at [1][13]? If so, why? Is this some feature of arrays or two dimensional arrays that I don't get? [20] pry(#<Maze>):1> @maze[1][13] => "A" [17] pry(#<Maze>):1> @maze[1][13,1] => "A" [18] pry(#<Maze>):1> @maze[1][13,2] => "A " [19] pry(#<Maze>):1> @maze[1][13,3] => "A " Maze String MAZE1 = %{##################################### # # # #A # # # # # # # # # ####### # ### # ####### # # # # # # # # # # # ##### # ################# # ####### # # # # # # # # # ##### ##### ### ### # ### # # # # # # # # # # # # B# # # # # # # # ##### ##### # # ### # # ####### # # # # # # # # # # # # # # ### ### # # # # ##### # # # ##### # # # # # # # # #####################################}

    Read the article

  • Unexpected ArrayIndexOutOfBoundsException in JavaFX application, refering to no array

    - by Eugene
    I have the following code: public void setContent(Importer3D importer) { if (DEBUG) { System.out.println("Initialization of Mesh's arrays"); } coords = importer.getCoords(); texCoords = importer.getTexCoords(); faces = importer.getFaces(); if (DEBUG) { System.out.println("Applying Mesh's arrays"); } mesh = new TriangleMesh(); mesh.getPoints().setAll(coords); mesh.getTexCoords().setAll(texCoords); mesh.getFaces().setAll(faces); if (DEBUG) { System.out.println("Initialization of the material"); } initMaterial(); if (DEBUG) { System.out.println("Setting the MeshView"); } meshView.setMesh(mesh); meshView.setMaterial(material); meshView.setDrawMode(DrawMode.FILL); if (DEBUG) { System.out.println("Adding to 3D scene"); } root3d.getChildren().clear(); root3d.getChildren().add(meshView); if (DEBUG) { System.out.println("3D model is ready!"); } } The Imporeter3D class part: private void load(File file) { stlLoader = new STLLoader(file); } public float[] getCoords() { return stlLoader.getCoords(); } public float[] getTexCoords() { return stlLoader.getTexCoords(); } public int[] getFaces() { return stlLoader.getFaces(); } The STLLoader: public class STLLoader{ public STLLoader(File file) { stlFile = new STLFile(file); loadManager = stlFile.loadManager; pointsArray = new PointsArray(stlFile); texCoordsArray = new TexCoordsArray(); } public float[] getCoords() { return pointsArray.getPoints(); } public float[] getTexCoords() { return texCoordsArray.getTexCoords(); } public int[] getFaces() { return pointsArray.getFaces(); } private STLFile stlFile; private PointsArray pointsArray; private TexCoordsArray texCoordsArray; private FacesArray facesArray; public SimpleBooleanProperty finished = new SimpleBooleanProperty(false); public LoadManager loadManager;} PointsArray file: public class PointsArray { public PointsArray(STLFile stlFile) { this.stlFile = stlFile; initPoints(); } private void initPoints() { ArrayList<Double> pointsList = stlFile.getPoints(); ArrayList<Double> uPointsList = new ArrayList<>(); faces = new int[pointsList.size()*2]; int n = 0; for (Double d : pointsList) { if (uPointsList.indexOf(d) == -1) { uPointsList.add(d); } faces[n] = uPointsList.indexOf(d); faces[++n] = 0; n++; } int i = 0; points = new float[uPointsList.size()]; for (Double d : uPointsList) { points[i] = d.floatValue(); i++; } } public float[] getPoints() { return points; } public int[] getFaces() { return faces; } private float[] points; private int[] faces; private STLFile stlFile; public static boolean DEBUG = true; } And STLFile: ArrayList<Double> coords = new ArrayList<>(); double temp; private void readV(STLParser parser) { for (int n = 0; n < 3; n++) { if(!(parser.ttype==STLParser.TT_WORD && parser.sval.equals("vertex"))) { System.err.println("Format Error:expecting 'vertex' on line " + parser.lineno()); } else { if (parser.getNumber()) { temp = parser.nval; coords.add(temp); if(DEBUG) { System.out.println("Vertex:"); System.out.print("X=" + temp + " "); } if (parser.getNumber()) { temp = parser.nval; coords.add(temp); if(DEBUG) { System.out.print("Y=" + temp + " "); } if (parser.getNumber()) { temp = parser.nval; coords.add(temp); if(DEBUG) { System.out.println("Z=" + temp + " "); } readEOL(parser); } else System.err.println("Format Error: expecting coordinate on line " + parser.lineno()); } else System.err.println("Format Error: expecting coordinate on line " + parser.lineno()); } else System.err.println("Format Error: expecting coordinate on line " + parser.lineno()); } if (n < 2) { try { parser.nextToken(); } catch (IOException e) { System.err.println("IO Error on line " + parser.lineno() + ": " + e.getMessage()); } } } } public ArrayList<Double> getPoints() { return coords; } As a result of all of this code, I expected to get 3d model in MeshView. But the present result is very strange: everything works and in DEBUG mode I get 3d model is ready! from setContent(), and then unexpected ArrayIndexOutOfBoundsException: File readed Initialization of Mesh's arrays Applying Mesh's arrays Initialization of the material Setting the MeshView Adding to 3D scene 3D model is ready! java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 32252 at com.sun.javafx.collections.ObservableFloatArrayImpl.rangeCheck(ObservableFloatArrayImpl.java:276) at com.sun.javafx.collections.ObservableFloatArrayImpl.get(ObservableFloatArrayImpl.java:184) at javafx.scene.shape.TriangleMesh.computeBounds(TriangleMesh.java:262) at javafx.scene.shape.MeshView.impl_computeGeomBounds(MeshView.java:151) at javafx.scene.Node.updateGeomBounds(Node.java:3497) at javafx.scene.Node.getGeomBounds(Node.java:3450) at javafx.scene.Node.getLocalBounds(Node.java:3432) at javafx.scene.Node.updateTxBounds(Node.java:3510) at javafx.scene.Node.getTransformedBounds(Node.java:3350) at javafx.scene.Node.updateBounds(Node.java:516) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.SubScene.updateBounds(SubScene.java:556) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2309) at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:329) at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:479) at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:459) at com.sun.javafx.tk.quantum.QuantumToolkit$13.run(QuantumToolkit.java:326) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39) at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:101) at java.lang.Thread.run(Thread.java:724) Exception in thread "JavaFX Application Thread" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 32252 at com.sun.javafx.collections.ObservableFloatArrayImpl.rangeCheck(ObservableFloatArrayImpl.java:276) at com.sun.javafx.collections.ObservableFloatArrayImpl.get(ObservableFloatArrayImpl.java:184) The stranger thing is that this stack doesn't stop until I close the program. And moreover it doesn't point to any my array. What is this? And why does it happen?

    Read the article

  • How to implement dynamic binary search for search and insert operations of n element (C or C++)

    - by iecut
    The idea is to use multiple arrays, each of length 2^k, to store n elements, according to binary representation of n.Each array is sorted and different arrays are not ordered in any way. In the above mentioned data structure, SEARCH is carried out by a sequence of binary search on each array. INSERT is carried out by a sequence of merge of arrays of the same length until an empty array is reached. More Detail: Lets suppose we have a vertical array of length 2^k and to each node of that array there attached horizontal array of length 2^k. That is, to the first node of vertical array, a horizontal array of length 2^0=1 is connected,to the second node of vertical array, a horizontal array of length 2^1= 2 is connected and so on. So the insert is first carried out in the first horizontal array, for the second insert the first array becomes empty and second horizontal array is full with 2 elements, for the third insert 1st and 2nd array horiz. array are filled and so on. I implemented the normal binary search for search and insert as follows: int main() { int a[20]= {0}; int n, i, j, temp; int *beg, *end, *mid, target; printf(" enter the total integers you want to enter (make it less then 20):\n"); scanf("%d", &n); if (n = 20) return 0; printf(" enter the integer array elements:\n" ); for(i = 0; i < n; i++) { scanf("%d", &a[i]); } // sort the loaded array, binary search! for(i = 0; i < n-1; i++) { for(j = 0; j < n-i-1; j++) { if (a[j+1] < a[j]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } printf(" the sorted numbers are:"); for(i = 0; i < n; i++) { printf("%d ", a[i]); } // point to beginning and end of the array beg = &a[0]; end = &a[n]; // use n = one element past the loaded array! // mid should point somewhere in the middle of these addresses mid = beg += n/2; printf("\n enter the number to be searched:"); scanf("%d",&target); // binary search, there is an AND in the middle of while()!!! while((beg <= end) && (*mid != target)) { // is the target in lower or upper half? if (target < *mid) { end = mid - 1; // new end n = n/2; mid = beg += n/2; // new middle } else { beg = mid + 1; // new beginning n = n/2; mid = beg += n/2; // new middle } } // find the target? if (*mid == target) { printf("\n %d found!", target); } else { printf("\n %d not found!", target); } getchar(); // trap enter getchar(); // wait return 0; } Could anyone please suggest how to modify this program or a new program to implement dynamic binary search that works as explained above!!

    Read the article

  • Using IF statements to find string length in array for alignment (Visual Basic)

    - by Brodoin
    My question is just as it says in the title. How would one use IF statements to find the string-length of content in an array, and then make it so that they show up in a Rich Text Box with the left sides aligned? Noting that one value in my array is a Decimal. Imports System.IO Imports System.Convert Public Class frmAll 'Declare Streamreader Private objReader As StreamReader 'Declare arrays to hold the information Private strNumber(24) As String Private strName(24) As String Private strSize(24) As String Private decCost(24) As Integer Private Sub frmAll_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Set objReader objReader = New StreamReader("products.csv") 'Call the FillArray sub to fill the array Call FillArray() End Sub Private Sub FillArray() 'Declare variables and arrays Dim decCost(24, 1) As Decimal Dim strFields() As String Dim strRec As String Dim intCount As Integer = 0 Dim chrdelim As Char = ToChar(",") 'Set strRec to read the lines strRec = objReader.ReadLine 'Do while loop to fill array. Do While strRec <> Nothing strFields = strRec.Split(chrdelim) strNumber(intCount) = strFields(0) strName(intCount) = strFields(1) strSize(intCount) = strFields(2) decCost(intCount, 0) = ToDecimal(strFields(3)) decCost(intCount, 1) = ToDecimal(strFields(4)) 'Set strRec to read the lines again strRec = objReader.ReadLine 'increment the index intCount += 1 Loop 'Call the Calculate sub for calculation Call Calculate(decCost) End Sub Private Sub Calculate(ByVal numIn(,) As Decimal) 'Define arrays to hold total cost Dim decRowTotal(24) As Decimal 'Define variables to hold the counters for rows and columns Dim intR As Integer Dim intC As Integer 'Calcualte total cost For intC = 0 To 1 For intR = 0 To 24 decRowTotal(intR) += numIn(intR, intC) * 1 Next Next 'Call the Output sub to configure the output. Call Output(numIn, decRowTotal) End Sub Private Sub Output(ByVal NumIn(,) As Decimal, _ ByVal RowTotalIn() As Decimal) 'Variables Dim strOut As String Dim intR As Integer = 0 Dim intC As Integer = 0 'Set header for output. strOut = "ID" & vbTab & "Item" & vbTab & vbTab & vbTab & "Size" & _ vbTab & vbTab & vbTab & vbTab & "Total Price" & _ vbCrLf & "---------- ... -------------------------" & vbCrLf 'For loop to add each line to strOut, setting 'the RowTotalIn to currency. For intC = 0 To 24 strOut &= strNumber(intC) & vbTab strOut &= strName(intC) & vbTab strOut &= strSize(intC) & vbTab strOut &= RowTotalIn(intC).ToString("c") & vbCrLf Next 'Add strOut to rbtAll rtbAll.Text = strOut End Sub End Class Output It shows up with vbTabs in my output, but still, it looks similar in that they are not aligned. The first two do, but after that they are not, and I am totally lost. P0001 Coffee - Colombian Supreme 24/Case: Pre-Ground 1.75 Oz Bags $16.50 P0002 Coffee - Hazelnut 24/Case: Pre-Ground 1.75 Oz Bags $24.00 P0003 Coffee - Mild Blend 24/Case: Pre-Ground 1.75 Oz Bags $20.50 P0004 Coffee - Assorted Flavors 18/Case. Pre-Ground 1.75 Oz Bags $23.50 P0005 Coffee - Decaf 24/Case: Pre-Ground 1.75 Oz Bags $20.50

    Read the article

  • 19" Rackmountable fast storage arrays

    - by Eruditass
    I'm in need of some fast (15+ GB/s write) and somewhat large (50 TB+) storage subsystem with a standard storage interface. I'd prefer something other than Fibre Channel, which admittedly appears to be the most standard interface. RAID 5 is sufficient. What are the cheapest / smallest products from vendors to look at for building this subsystem? I've looked at DDN and TMS so far. Small: Under 20U Cheap: Under a million Edit: I'd really like to cut back costs as much as possible at the expense of capacity. How cheap can these bandwidth requirements be met?

    Read the article

  • In MATLAB, how can 'preallocating' cell arrays improve performance?

    - by Alex McMurray
    I was reading this article on MathWorks about improving MATLAB performance and you will notice that one of the first suggestions is to preallocate arrays, which makes sense. But it also says that preallocating Cell arrays (that is arrays which may contain different, unknown datatypes) will improve performance. But how will doing so improve performance because the datatypes are unknown so it doesn't know how much contiguous memory it will require even if it knows the shape of the cell array, and therefore it can't preallocate the memory surely? So how does this result in any improvement in performance? I apologise if this question is better suited for StackOverflow than Programmers but it isn't asking about a specific problem so I thought it fit better here, please let me know if I am mistaken though. Any explanation would be greatly appreciated :)

    Read the article

  • arrays in puppet

    - by paweloque
    I'm wondering how to solve the following puppet problem: I want to create several files based on an array of strings. The complication is that I want to create multiple directories with the files: dir1/ fileA fileB dir2/ fileA fileB fileC The problem is that the file resource titles must be unique. So if I keep the file names in an array, I need to iterate over the array in a custom way to be able to postfix the file names with the directory name: $file_names = ['fileA', 'fileB'] $file_names_2 = [$file_names, 'fileC'] file {'dir1': ensure => directory } file {'dir2': ensure => directory } file { $file_names: path = 'dir1', ensure =>present, } file { $file_names_2: path = 'dir2', ensure =>present, } This wont work because the file resource titles clash. So I need to append e.g. the dir name to the file title, however, this will cause the array of files to be concatenated and not treated as multiple files... arghh.. file { "${file_names}-dir1": path = 'dir1', ensure =>present, } file { "${file_names_2}-dir2": path = 'dir1', ensure =>present, } How to solve this problem without the necessity of repeating the file resource itself. Thanks

    Read the article

  • Reusing slot numbers in Linux software RAID arrays

    - by thkala
    When a hard disk drive in one of my Linux machines failed, I took the opportunity to migrate from RAID5 to a 6-disk software RAID6 array. At the time of the migration I did not have all 6 drives - more specifically the fourth and fifth (slots 3 and 4) drives were already in use in the originating array, so I created the RAID6 array with a couple of missing devices. I now need to add those drives in those empty slots. Using mdadm --add does result in a proper RAID6 configuration, with one glitch - the new drives are placed in new slots, which results in this /proc/mdstat snippet: ... md0 : active raid6 sde1[7] sdd1[6] sda1[0] sdf1[5] sdc1[2] sdb1[1] 25185536 blocks super 1.0 level 6, 64k chunk, algorithm 2 [6/6] [UUUUUU] ... mdadm -E verifies that the actual slot numbers in the device superblocks are correct, yet the numbers shown in /proc/mdstat are still weird. I would like to fix this glitch, both to satisfy my inner perfectionist and to avoid any potential sources of future confusion in a crisis. Is there a way to specify which slot a new device should occupy in a RAID array? UPDATE: I have verified that the slot number persists in the component device superblock. For the version 1.0 superblocks that I am using that would be the dev_number field as defined in include/linux/raid/md_p.h of the Linux kernel source. I am now considering direct modification of said field to change the slot number - I don't suppose there is some standard way to manipulate the RAID superblock?

    Read the article

  • Matched or unmatched drives for RAID arrays?

    - by Will
    Looking around there is conflciting information on this, with some strongly suggesting one or the other. From my understanding the issue with matched drives is that the wear on both drives is more or less the same, so the potential for the second drive failing with or very soon after the first is pretty high. People also claim matched drives give substianatally higher performance however assuming the unmatched drives are more or less the same (eg 2, 1 TB STATA II 7200rpm drives with 32MB cache), would the minor differences between say a Seagate and a Western Digital one (say one has a 128MB/s read rate, and the other a 150MB/s read rate, as well as I guess various other minor differences) actually cause any notable performance loss, ie potentialy worse than two matched 128MB/s drives, or does RAID not really care and give you essentially an optimal solution (eg upto 278MB/s total read speed for RAID 0 and 1) and similar for other RAID with more "unmatched" drives (5 and 1+0 come to mind as possibilities)? Also I couldnt find much info on how this is different on different RAID setups, eg RAID 0 or RAID 1, software or hardware RAID, etc. I'm assuming such things have an effect, and thats it's not all the same for RAID in general?

    Read the article

  • Matched or unmatched drives for RAID arrays?

    - by Will
    Looking around there is conflciting information on this, with some strongly suggesting one or the other. From my understanding the issue with matched drives is that the wear on both drives is more or less the same, so the potential for the second drive failing with or very soon after the first is pretty high. People also claim matched drives give substianatally higher performance however assuming the unmatched drives are more or less the same (eg 2, 1 TB STATA II 7200rpm drives with 32MB cache), would the minor differences between say a Seagate and a Western Digital one (say one has a 128MB/s read rate, and the other a 150MB/s read rate, as well as I guess various other minor differences) actually cause any notable performance loss, ie potentialy worse than two matched 128MB/s drives, or does RAID not really care and give you essentially an optimal solution (eg upto 278MB/s total read speed for RAID 0 and 1) and similar for other RAID with more "unmatched" drives (5 and 1+0 come to mind as possibilities)? Also I couldnt find much info on how this is different on different RAID setups, eg RAID 0 or RAID 1, software or hardware RAID, etc. I'm assuming such things have an effect, and thats it's not all the same for RAID in general?

    Read the article

  • Add an array of buttons to a GridView in an Android application

    - by Tai Squared
    I have an application that will have 5-15 buttons depending on what is available from a backend. How do I define the proper GridView layout files to include an array of buttons that will each have different text and other attributes? Each button will essentially add an item to a cart, so the onClick code will be the same except for the item it adds to the cart. How can I define an array so I can add a variable number of buttons, but still reference each of them by a unique ID? I've seen examples of the arrays.xml, but they have created an array of strings that are pre-set. I need a way to create an object and not have the text defined in the layout or arrays xml file. Update - Added info about adding to a GridView I want to add this to a GridView, so calling the addView method results in an UnsupportedOperationException. I can do the following: ImageButton b2 = new ImageButton(getApplicationContext()); b2.setBackgroundResource(R.drawable.img_3); android.widget.LinearLayout container = (android.widget.LinearLayout) findViewById(R.id.lay); container.addView(b2); but that doesn't layout the buttons in a grid like I would like. Can this be done in a GridView?

    Read the article

  • How to optimize this algorithm?

    - by Bakhtiyor
    I have two sets of arrays like this for example. $Arr1['uid'][]='user 1'; $Arr1['weight'][]=1; $Arr1['uid'][]='user 2'; $Arr1['weight'][]=10; $Arr1['uid'][]='user 3'; $Arr1['weight'][]=5; $Arr2['uid'][]='user 1'; $Arr2['weight'][]=3; $Arr2['uid'][]='user 4'; $Arr2['weight'][]=20; $Arr2['uid'][]='user 5'; $Arr2['weight'][]=15; $Arr2['uid'][]='user 2'; $Arr2['weight'][]=2; The size of two arrays could be different of course. $Arr1 has coefficient of 0.7 and $Arr2 has coefficient of 0.3. I need to calculate following formula $result=$Arr1['weight'][$index]*$Arr1Coeff+$Arr2['weight'][$index]*$Arr2Coeff; where $Arr1['uid']=$Arr2['uid']. So when $Arr1['uid'] doesn't exists in $Arr2 then we need to omit $Arr2 and vice versa. And, here is an algorithm I am using now. foreach($Arr1['uid'] as $index=>$arr1_uid){ $pos=array_search($arr1_uid, $Arr2['uid']); if ($pos===false){ $result=$Arr1['weight'][$index]*$Arr1Coeff; echo "<br>$arr1_uid has not found and RES=".$result; }else{ $result=$Arr1['weight'][$index]*$Arr1Coeff+$Arr2['weight'][$pos]*$Arr2Coeff; echo "<br>$arr1_uid has found on $pos and RES=".$result; } } foreach($Arr2['uid'] as $index=>$arr2_uid){ if (!in_array($arr2_uid, $Arr1['uid'])){ $result=$Arr2['weight'][$index]*$Arr2Coeff; echo "<br>$arr2_uid has not found and RES=".$result; }else{ echo "<br>$arr2_uid has found somewhere"; } } The question is how can I optimize this algorithm? Can you offer other better solution for this problem? Thank you.

    Read the article

  • php - replace array elements with another array's elements?

    - by Simpson88Keys
    Not sure how to go about this... But, I have two arrays, one with updated information, another with outdated information... There are a lot more elements in the second array, but I'm looking to "update" the outdated one with the updated information. Here's what the arrays look like: //Outdated Array ( [0] => Array ( [anum] => 3236468462 [cid] => 4899097762 [mid] => 1104881401 [na_title] => [na_fname] => JOHN [m_initial] => [na_lname] => DOE [na_suffix] => [na_addr1] => 1234 SAMPLE AVENUE [na_addr2] => [na_city] => NORWALK [state] => OH [zip] => [zip_plus_4] => [route] => R002 [dma_code] => 510334 ) ) //Updated Array ( [1] => Array ( [0] => YUD990 [1] => 98 [2] => 1234 Sample Avenue [3] => [4] => Norwalk [5] => OH [6] => 44857-9215 [7] => 3236468462 ) ) To clarify, I want to: (1) Match up the value for [7] from the updated array with the value for [anum] in the outdated array, and then update [na_addr1], [na_addr2], [na_city], [state], [zip], [zip_plus_4] in the outdated array with the values for [2],[3],[4],[5],[6] (I know I'll need to split the updated [6] in order to get it to map corrected to the outdated) Feel like I'm making this very confusing... sorry about that...

    Read the article

  • How to set up single array or dictionary for use in multiple datasources?

    - by Roman
    I have multiple TableViewDatasources that need to display list of objects form same pool depending of certain property. E.g. object.flag1 is set- it will show up in TableView1 object.flag2 is set- it will show up in TableView2 The obvious way would be to have separate arrays for each TableView, But same object may appear in different arrays. Also I need to update objects very often or access all objects through same array. How do I setup a single dictionary or array to have all objects in one structure? To put it in another way: When table view or selection changes, application need to redraw TableViews with the new data. Application have to access the pool of objects and search through them using iterator and accessing each object and its properties. I think that this is an expensive operation and want to avoid that. Perhaps maybe by making a global pool of objects a dictionary and exposing objects properties as dictionary fields. So instead of iterating global pool of objects I could access global pool Dicitonary in a manner of database by selecting objects that has fields that match particular criteria. Anyone know any example of doing that?

    Read the article

  • How does one create and use a pointer to an array of an unknown number of structures inside a class?

    - by user1658731
    Sorry for the confusing title... I've been playing around with C++, working on a project to parse a game's (Kerbal Space Program) save file so I can modify it and eventually send it over a network. I'm stuck with storing an unknown number of vessels and crew members, so I need to have an array of unknown size. Is this possible? I figured having a pointer to an array would be the way to go. I have: class SaveFileSystem { string version; string UT; int activeVessel; int numCrew; ??? Crews; // !! int numVessels; ??? Vessels; // !! } Where Crews and Vessels should be arrays of structures: struct Crew { string name; //Other stuff }; struct Vessel { string name; //Stuff }; I'm guessing I should have something like: this->Crews = new ???; this->Vessels = new ???; in my constructor to initialize the arrays, and attempt to access it with: this->Crews[0].name = "Ship Number One"; Does this make any sense??? I'd expect the "???"'s to involve a mess of asterisk's, like "*struct (*)Crews" but I have no real idea. I've got normal pointers down and such, but this is a tad over my head... I'd like to access the structures like in the last snippet, but if C++ doesn't like that I could do pointer arithmetic. I've looked into vectors, but I have an unhealthy obsession with efficiency, and it really pains me how you don't know what's going on behind it.

    Read the article

  • How do I return an array from a method?

    - by dwwilson66
    I'm trying to create a deck of cards for my homework. Code is posted below. I need to create four sets of cards (the four suits) and am create a multidimensional array. When I print the results instead of trying to pass the array, I can see that the data in the array is as expected. However, when I try to pass the array card, I get an error cannot find symbol. I've got this modeled after texbook and Java tutorial examples, and I need some help figuring out what I'm missing. I've over-documented to give an idea of how I'm thinking this SHOULD work...please let me know where I've gone horribly wrong in my understanding. import java.util.*; import java.lang.*; // public class CardGame { public static int[][] main(String[] args) { int[][] startDeck = deckOfCards(); /* cast new deck as int[][], calling method deckOfCards System.out.println(" /// from array: " + Arrays.deepToString(startDeck)); } public static int[][] deckOfCards() /* method to return a multi-dimensional array */ { int rank; int suit; for(rank=1;rank<14;rank++) /* cards 1 - 13 .... */ { for(suit=1;suit<5;suit++) /* suits 1 - 4 .... */ { int[][] card = new int[][] /* define a new card... */ { {rank,suit} /* with rank/suit from for... loops */ }; System.out.println(" /// from array: " + Arrays.deepToString(card)); } } return card; /* Error: cannot find symbol } }

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >