Arrays - counting occurence
Hello everyone :)
A practical at college is requiring me to create a program that simulates throwing 3 dice a total of 5000 times and for it to tally the number of times that all possible answers have occurred. For example, with 3 dice the lowest you can get is 3 (three 1's) and highest, 18 (three 6's). Roll the three dice, see which of the 16 different outcomes (3-18) you have, and add 1 to the total number of occurrences that outcome has produced. After 5000 throws, I will need to see which outcome happened most often. I've been told I must use an array for counting the occurrences and it's the array part which is confusing me.
Implementing the 3 dice and a method that simulates them being thrown was easy but I just do not have a clue how to:
1) get it to be done 5000 times and
2) the outcomes be tallied
Heres the code I have so far..
import java.lang.Math;
public class ThreeDice
public static int throwDie()
double x = Math.random();
double x2 = Math.random();
double x3 = Math.random();
x = (x * 6.0) + 1.0;
x2 = (x2 * 6.0) +1.0;
x3 = (x3 * 6.0) +1.0;
int dice1 = (int)Math.floor(x);
int dice2 = (int)Math.floor(x2);
int dice3 = (int)Math.floor(x3);
return dice1 + dice2 + dice3;
public static void main(String args[])
}the throwDie method has to be used in main method but I'm stuck as for what to do next I'm afraid.
Hello Looce and thank you for the welcome,
Using my (very limited) knowledge I've managed to get the first part done (roll the 3 dice 5000 times) and for now I've just set it to print all 5000 results and alas it indeed prints 5000 results.
The second part though I'm still stuck on, I was hoping google would be my savior but sadly not this time.
I should have probably said in my first post that I'm a complete beginner for Java but with it being used both this year and next year for college, I hope to be fairly skilled in the use of it one day :)
An update of the code:
import java.lang.Math;
public class ThreeDice
public static int throwDie()
double x = Math.random();
double x2 = Math.random();
double x3 = Math.random();
x = (x * 6.0) + 1.0;
x2 = (x2 * 6.0) +1.0;
x3 = (x3 * 6.0) +1.0;
int dice1 = (int)Math.floor(x);
int dice2 = (int)Math.floor(x2);
int dice3 = (int)Math.floor(x3);
return dice1 + dice2 + dice3;
public static void main(String args[])
for(int i=0; i<5000; i++){
System.out.println(throwDie());
}
Similar Messages
-
Can i use array.count in line?
All,
I have one small oracle program that take a ',' separated string as an input
and assigns the individual string to a nested table.
I am wondering if I can directly use array.count in my sql below
instead of assigning the count of the array 1st and then
using it.
l_cause_codes_array := util_pkg.tokenize_string(p_cause_codes_csv, ',');
l_count := l_cause_codes_array.count;
My current sql:
delete from po_complaint_cause p
where p.po_number = p_po_number
and p.comp_code = p_comp_code
and l_count > 1;
I would like to do something like:
delete from po_complaint_cause p
where p.po_number = p_po_number
and p.comp_code = p_comp_code
and l_l_cause_codes_array.count> 1;
I just want to reduce one context switch if possible.
Thanks.Hi,
did it give an error? Did you try? But it is possible.
But why not the next code:
l_cause_codes_array := util_pkg.tokenize_string(p_cause_codes_csv, ',');
if l_cause_codes_array.count >1
then
delete from po_complaint_cause p
where p.po_number = p_po_number
and p.comp_code = p_comp_code
end if;Do only the delete if it is bigger than 1, that is I think the fastest switch.
Herald ten Dam
http://htendam.wordpress.com -
Hello Experts,
I have the following query related to counting occurences of a particular characteristic related to the Calendar month
1) When I choose the option "Average of all values" within exception aggregation for the calculated keyfigure that I am using for the count, it counts all the values including duplicates .i.e. if the charcteristic has repeated occurences for a given month, then it is counted distinct occurence. However, in this case it is not showing me "0" for no occurence but just displaying a blank
2) But when I choose the option "Counting all values" within exception aggregation for the calculated keyfigure that I am using for the count, it does provides me "0" for no occurences but it counts the repeated value as single occurence
How can I get around this? I mean to get repeated values to be counted as separate occurences and also being able to show "0" for no occurence.
Any help will be appreciated
Thanks,
RishiHi ,
Please use exception aggregation as you already did with count all values.
But you need to select a specific reference chars to select the unique count.Plant or the Month can be a option.
In BI7.0 U have concept of nested aggregation:
Create a CKF1 with reference to one Char. and craete another CKF2 using the earlier CKF1 and put again a reference on some other char.
that will solve the problem.
Please take care of the selection of Char while doing reference char. -
Counting occurences of a string (in a cell)
This is a little like the topic "Counting occurences of a word," except I want to be able to count how many times a specified search string occurs in a cell, not count how many cells contain the string. I would also like a formula that gave the offset of the starting character of the search string into the cell, such that a zero signified that the search string did not occur.
Basically, I want a general set of tools to parse a cell's string data, enabling me to determine where in the cell's string data each occurrence of another string is located & to extract parts of the string data relative to where the search string occurs.
For example, if the cell contains the string, "1ab2cd2e" I want to be able to extract "cd" & "e" based on the characteristic that they follow "2."Here it is:
--(SCRIPT decoupeur.app]
Save the script as a Script, an Application or an Application Bundle named decoupeur
Put the file in the folder
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Numbers:
Maybe you would have to create the folder Numbers and even the folder Applications by yourself.
To use it,
Select the group of cells to convert
Copy to the clipboard
Select the destination cell
Goto Scripts > Numbers > decoupeur
You will be asked to define the separator to use.
Given the separator "2", the strings of the kind "1zer6sd2az2rt8aa2er7kkk5uu2a"
would be parsed and return az TAB rt TAB er TAB a
The converted values will be pasted at the cursor.
Yvan KOENIG 30juin 2008
property theApp : "Numbers"
property menuFenetre : 10
property premierNom : 6
property nomDuDocActif : ""
property theDelim : ""
property listeLignes : {}
property listeTemp : {}
property msg90 : ""
property msg91 : ""
property msg92 : ""
--=============
on run
tell application "System Events" to if not (UI elements enabled) then set (UI elements enabled) to true (*
Active le GUI scripting
• Enable GUI scripting *)
my nettoie()
my controleVersion()
set nomDuDocActif to my getFrontDoc()
if nomDuDocActif = "" then return
my prepareMessages()
try
set txtDatas to the clipboard as Unicode text
on error (*
The clipboard was empty *)
return
end try
set my listeLignes to every paragraph of txtDatas
set srcNbRows to count of my listeLignes
if txtDatas contains tab then (*
several columns *)
error "Can't treat several columns" number 8001
else (*
single column *)
tell application theApp
set choix to choose from list {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"} with prompt msg90 default items {"2"} OK button name msg91 cancel button name msg92
end tell
if choix is false then error -128
set theDelim to item 1 of choix
repeat with i from 1 to srcNbRows
if item i of my listeLignes is not "" then set item i of my listeLignes to my decipher(item i of my listeLignes)
end repeat
end if
set the clipboard to my recolle(listeLignes, return)
my pasteIt()
my nettoie()
end run
--=============
on pasteIt()
tell application theApp to activate
tell application "System Events" to tell (first process whose title is theApp)
click menu item nomDuDocActif of menu 1 of menu bar item menuFenetre of menu bar 1
keystroke "v" using {command down}
end tell
end pasteIt
--=============
on decoupeur(n)
local d, ms, m
set d to n div 1
set ms to (n - d) * 60
set m to round (ms)
return (d as text) & "°" & m & "’" & (round ((ms - m) * 60)) & "”"
end decoupeur
--=============
on decipher(source)
local i, itm, shortimem, j
set my listeTemp to my decoupe(source, theDelim)
set my listeTemp to items 2 thru -1 of my listeTemp
repeat with i from 1 to count of my listeTemp
set itm to item i of my listeTemp
set shortItem to ""
repeat with j from 1 to length of itm
if character j of itm is not in "1234567890" then
set shortItem to shortItem & character j of itm
else
exit repeat
end if
end repeat
set item i of my listeTemp to shortItem
end repeat
return my recolle(my listeTemp, tab)
end decipher
--=============
on getMinutesSeconds(t, d)
local ll
set ll to my decoupe(t, d)
return {(item 1 of ll) as integer, (item 2 of ll) as text}
end getMinutesSeconds
--=============
on decoupe(t, d)
local l
set AppleScript's text item delimiters to d
set l to text items of t
set AppleScript's text item delimiters to ""
return l
end decoupe
--=============
on recolle(l, d)
local t
set AppleScript's text item delimiters to d
set t to l as text
set AppleScript's text item delimiters to ""
return t
end recolle
--=============
on nettoie()
set AppleScript's text item delimiters to ""
set my listeLignes to {}
set my listeTemp to {}
set nomDuDocActif to ""
end nettoie
--=============
Get the name of the active document
on getFrontDoc()
local nw, mm
tell application theApp to activate
tell application "System Events" to tell (first process whose title is theApp)
set nw to name of every menu item of menu 1 of menu bar item menuFenetre of menu bar 1
if (count of nw) < premierNom then
set mm to ""
else
repeat with i from premierNom to count of nw
set mm to item i of nw
if (value of attribute "AXMenuItemMarkChar" of menu item mm of menu 1 of menu bar item menuFenetre of menu bar 1) is not in {"", "•"} then exit repeat
end repeat
end if -- (count of nw)…
end tell
return mm
end getFrontDoc
--=============
on controleVersion()
local v
try
set v to version of application theApp
set menuFenetre to 10 (* index of the Windows menu *)
set premierNom to 6 (* index of the first docName in the list of menu names
The list contains one more item than the displayed menu *)
on error (*
• We are here if Numbers ignores the instruction get version *)
tell application "System Events" to set v to get version of (get (application file of (get first process whose title is theApp)))
if v starts with "1" then
set menuFenetre to 10
set premierNom to 6
else (* ready for a Numbers v2 ignoring AppleScript *)
set menuFenetre to 10
set premierNom to 6
end if
end try
end controleVersion
--=============
on parleAnglais()
local z
try
tell application theApp to set z to localized string "Cancel"
on error
set z to "Cancel"
end try
return (z = "Cancel")
end parleAnglais
--=============
on prepareMessages()
if my parleAnglais() is false then
set msg90 to "Choisir le séparateur"
set msg91 to " OK "
set msg92 to "Annuler"
else
set msg90 to "Choose a separator"
set msg91 to " OK "
set msg92 to "Cancel"
end if
end prepareMessages
--=============
--[/SCRIPT]
Yvan KOENIG (from FRANCE lundi 30 juin 2008 11:16:52) -
I don't know nothing about NI image DAQ, I'm new to this, I'm a Labwindows/CVI programmer and recently a client asked me if its possible to count cells occurences in an image. Before investing money in such system (seems to be very expensive) I would like to know if NI VISION functions are powerfull enough to count occurences of a human cell in an image ?
Thank you,The short answer to your question is yes and there are similar examples on the IMAQ Vision demonstration CD. I would suggest you try and organize a demo from your local NI office.
Application Note 107 gives a good tutorial on this topic and you can get access to it at the following link:
http://zone.ni.com/devzone/conceptd.nsf/webmain/1D977AE5ED42CB0C86256869007215CC?opendocument&node=DZ52495_US
As far as support for LabWindows/CVI is concerned, you may see a lot more "traffic" regarding LabVIEW on Developer Zone, but rest assured the capability of the CVI version of IMAQ Vision is virtually identical and there should be enough help either direct from NI or through Developer Zone to help with your application.
With regards to questions about cost, t
he cost of the application will have to be considered versus the benefits of introducing an autonomous inspection system. Your customer may find that the increases in throughput i.e. number of samples/images per hour that can be inspected or the reliability of the results produced (most people will strive towards a 100% inspection imaging application) will offset the initial development costs. This is particularly true if your customer is currently manually inspecting the samples (for example under a microscope).
Jeremy -
Count Occurences within in an Array
Hi,
I have an array with numbers, I want to count how often the number 5 is stored in it, does anyone know the syntax?
thanks,
RichHi Jason,
Sorry, I think I am mising something really basic here,
I have an Array created in a subreport declared:
shared numbervar array RespondentArray1;
there is then various code which poulates it depending on which IF conditions are met as it cycles through the records.
In my main report I want to count the occurneces of say the number 5. But I was expecting to drop the array name only (RespondentArray1) into where you have {@Array}. But I get an error if I do that. The formula where the array is declared and populates is in a subreport.
Can you please advise of what I should be replacing in your code?
My looping would work, but I dont think it is very efficient especially as I have lots of counts to do on various numbers,
thanks,
Richard. -
I use LabView student Express 7 on a Windows XP system.
Time-frame: we are doing final integrations for our balloon experiment today. We just got told that the press wants to view real-time data, which we haven't programmed for. I need help to get a working VI at the latest by 25.02.2004 before 0800(morning) (GMT+1).
Note on license
It is a student balloon flight, and the data will not be used in scientific work, so the I am not breaking any license agreements (I hope).
Problem synopsis:
The balloon continually transmits data at 9600baud. The data is a semi-repeating header followed by a constant lenght data-package arranged like this:
BEXUS[h][m][s]BEXUS[h][m][s]
[Raw binary data, 7channels*8sub-channels*8bits]
What the groundstation is doing right now:
Take all incomming data and save (append) the data to a file without any data-handling. (We figured we would go post-processing).
What I need to change in less than 24 hours:
- Add a "package" counter
- Add a display of the clock data (RTC)
How I planned to implement the changes:
-RTC display:
The RTC data is in BCD format, since that means that if you look at the data as hex numbers, you get the hours and minutes and seconds out in "clear text". That is 12 hours is 0x12hex. I figured that I can do a match pattern BEXUS and pass the "after substring" to another match pattern BEXUS from which I feed the "before substring" to a type-cast VI (casting string to u8) and displaying that, which should give me a display of "123000" for the time 12:30:00... I couldn't get it to work at all when I tried out the supplied "beta" vi.
- Package counter:
Counting how many BEXUS that gets detected and dividing by 2. I don't know how to do this. I've looked on the forum (a good thread on the problem: "how do I count the number of *'s in a string") but these use either loops or arrays... and I'm not sure how this works when I'm getting the data in at realtime. I cant make an array and then count it, since then the array would grow fast and possibly interfere with saving of the data??? Saving the data is critical.. without that file we cant do post-processing.
Since my time is so limited (I'm not even supposed to do the groundstation software but they called on me in the last minute because no-one else had time/wanted too/could do it) I hope that you could make an exception and provide me with working VI's (based on the one I have attached) so that I can show something to the press! (Free comercial for NI!! Since the student version shows the National Instruments water-mark on all VI's!!! Possible TV time!!)
Thanks!
PS: even if you are to late (after 25) post anyway!
Why:
-I can learn from it
-the launch might be delayed due to weather conditions
-others might find it amusing!
Thanks again!
Attachments:
BexusII_groundstation.vi 46 KBI have a valid example data file attached to this thread.
If you open BEXTEST.bin in a hex-editor of your choice, you'll see the BEXUS as 42 45 58 55 53 and then the time as 00 28 09 etc.
I couldn't get Joe Guo's VI to work. It doesn't count packages correctly, and the time is not displayed correctly either.
The file was saved using a straight save to file VI.
The data is from actual launching area tests performed a few mintues ago. The time displayed is "On time" e.g. how long the gondola has been powered up.
I have a spare T-junction, so I can hook into the balloon real-time data as we fly, in case anyone care to see if they can figure out why the latest version of Joe Guo's program is not displaying correctly.
I will monitor this
thread during and after flight to see if anyone can make it in time!
Thanks for the great effort!!
Attachments:
bextest.bin 53 KB -
Any help for array question
Hello to All:
I want to tally or count some of the elements that I have in array but not sure how.
I have for example: int myArray[] = {90,93,80,81,71,72,73,74};My objective is to tally all of the 90's, tally all of the 80's and tally all of the 70's.
So, the result that I want to have would look something like the following:
System.out.println ("The total tally number of 90's is " 2 );
System.out.println ("The total tally number of 80's is " 2 );
System.out.println ("The total tally number of 70's is " 4 );I do not want to add these numbers, just want to count them.
Also I want to use a "forloop" to achieve the result intead of just declaring it at 2 or 4 etc..
Any help Thankyou[u]First , This is not exactly what I have to
do for homework. There is a lot more, a lot more
involved with the program that I am working on.
Second, this is an example, an example, an
example of something that I need to achieve.
Third, you are asking for a code, to me that
sounds as if your asking for homework. Fourth,
I did not ask for any rude comments. Fith, in
the future please do not reply to my messages at ALL
if you can not help!!!!
Sixth, We did not ask for lazy goofs to post here.
Seventh, In the future please do not post here. Take a hike - there's the virtual door. -
Help with arrays & counting characters in arrays
I am trying to figure out how to count how many times each characters appears in the array (but I have to do all the counts at once).
I am supposed to store the counts in an int[] array of 27 elements (26 letters & an extra count for everything else). How would I go about declaring the array, allocating it, & then setting each of the 27 elements zero?
Thanks so much the help.
public class CharCount {
public static void main(String[] args) {
new CharCount().process();
public void process() {
// This declares an array of char and then assigns it a value. The value comes from another one
// of my secret programs.
char[] countThese = Lab8.simple();
printChars(countThese);
for (int count =0; count < countThese.length; count++) {
System.out.println(countThese[count]);
// This method should print the characters in the array called print, one-by-one
// Use a println ONLY after all the chars have been printed.
public void printChars(char[] print) {
public int charToInt(char ch) {
if (ch >= 'A' && ch <= 'Z')
return ch - 'A';
else if (ch >= 'a' && ch <= 'z')
return ch - 'a';
else return 26;
}I take it the charToInt method was given to you. If you don't know what it does, it will give you a value from 0 to 26 depending on what char you pass as a parameter. So if you pass an 'a' or an 'A' it will return 0, 25 for 'z' or 'Z' and 26 for anything else. You use this value to access an array an increment the value (the number of times that letter has occured.
int value = charToInt('a');
arr[value]++;
System.out.println("Number of a's = " + arr[0]); -
Htmldb_application array count 0 when it shouldn't be
This was working until I made modifications to the application, i.e. tabs, menus and such. It uses a manually built tabular form - that part works and displays with correct values, but when I try to access the array with a loop it appears to be empty.
I also have an item P3_WHERE_CLAUSE that runs a similar loop to build a where clause for validation. I modified it to debug as shown below.
Any hints greatly appreciated - can't figure out how I broke it.
Here's the query for the tabular form:
select
htmldb_item.select_list_from_query(
1,key_id,
'select key_id, object_key from
val_object_key k,
VAL_OBJECT o
where o.object_name = :P3_OBJECT_NAME
and k.object_id = o.object_id') Key_id,
htmldb_item.select_list_from_query(2,object_key,
'select object_key, object_key from
val_object_key k,
VAL_OBJECT o
where o.object_name = :P3_OBJECT_NAME
and k.object_id = o.object_id') Key,
htmldb_item.text(3,'',50) Value
from VAL_OBJECT_KEY k,
VAL_OBJECT o
where o.object_name = :P3_OBJECT_NAME
and k.object_id = o.object_id;
Here's the code to save the page information (several items in a cascading form and then it loops to include values from the tabular form). The loop does not execute.
DECLARE P_KEY_ID NUMBER;
kvs_id NUMBER;
BEGIN
select prov_id.nextval into kvs_id from dual;
insert into key_val_set kvs_id values (kvs_id);
for i in 1..htmldb_application.g_f01.count
loop
insert into key_value (KV_ID,KEY_ID,KEY_VALUE,KVS_ID)
values
prov_id.nextval,
htmldb_application.g_f01(i),
htmldb_application.g_f03(i),
kvs_id)
end loop;
INSERT INTO PROV_INSTANCE
CLASS_ID,
SOURCE_ID,
DATE_OCCURED,
KVS_ID
VALUES
:P3_CLASS_NAME,
:P3_SRC_NAME,
:P3_DATE_OCCURED,
kvs_id
commit;
END;
Here's the test loop:
begin
:P3_WHERE_CLAUSE := 'begin test';
for i in 1..htmldb_application.g_f01.count
loop
:P3_WHERE_CLAUSE := 'where '||i;
end loop;
return :P3_WHERE_CLAUSE;
end;Never mind - it was a page flow misunderstanding.
-
i just want to count the number of occurence of character in string..
so i did this.. dont know whats wrong.. so someone help me
mport java.util.*;
public class CountChar {
public static void main(String[] args ) {
String input = args[0];
LinkedHashMap<Character, Integer> lhm = new LinkedHashMap<Character, Integer>();
for (int i =0; i<input.length(); i++) {
char currentChar = input.charAt(i);
if(lhm.containsKey(currentChar)) {
lhm.put(currentChar, lhm.get(currentChar) + 1);
} else {
lhm.put(currentChar, 1);
System.out.println(lhm.toString());
}raji10 wrote:
yes i did itWell, as I wrote already: it works fine for me, there must be something else you're doing wrong. What exactly doesn't work?
kind regards,
Jos -
AppleScript Class recognition and Array count
I have an application "SolarMaxOsX" written in Obj C
This app is scriptable
I have a class named Ups and in Ups.m I have written following methods:
- (id)init {
self = [super init];
NSLog(@"Init Ups at %p", self);
self.upsName = [NSString stringWithFormat:@"S2000"];
// upsPort = [NSNumber numberWithInteger:1];
self.upsPort = 1;
self.upsIpAddress= [NSString stringWithFormat:@"192.168.10.101"];
self.upsDataListToDisplayInTable = [self fillUpsListDictionary];
_uniqueID = [[NSUUID UUID] UUIDString];
return self;
/* For appleScript recognition */
- (BOOL)application: (NSApplication *) sender delegateHandlesKey:(NSString *)key {
if ([key isEqualToString: @"Ups"]) return YES;
if ([key isEqualToString: @"upsDescriptionDict"]) return YES;
if ([key isEqualToString: @"networkStatus"]) return YES;
if ([key isEqualToString: @"networkOk"]) return YES;
return NO;
- (NSUniqueIDSpecifier *)objectSpecifier {
NSScriptClassDescription *appDescription = (NSScriptClassDescription *)[NSApp classDescription];
return [[NSUniqueIDSpecifier alloc] initWithContainerClassDescription:appDescription containerSpecifier:nil key:@"Ups" uniqueID:self.uniqueID];
In AppDelegate.m:
There is an array : Upss declared as follows:
NSArray (Upss *) Ups; declared and initialised in AppDelegate.m file
self.Upss = [self initUpss];
sdef file for SolarMax Suite follows (compiles correctly)
<suite name="SolarMax Suite" code="SMap" description="Apple Events supportés par l'application SolarMaxMain">
<class name="Ups" code="SCup" description="An object UPS in SolarMaxOsX." >
<cocoa class="Ups" inherits="item" plural="Upss"/>
<property name="id" code="ID " type="text" access="r" description="The unique identifier of the note.">
<cocoa key="uniqueID"/>
</property>
</class>
<element description="List of Ups" type="Ups">
<cocoa key="Upss"/>
</element>
<class name="AppDelegate" code="SCad" description="main class in SolarMaxOsX.">
<cocoa class="AppDelegate" />
// Liste des Ups reconnus dans le fichier de configuration
<property name="Upss" code="SMno" type="Ups" access="r">
<cocoa key="Upss"/>
</property>
</class>
</suite>
I want to get a count for array Upss
Script follows
tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmtiegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app" to activate
-- delay 30
tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmtiegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app"
-- set nomAppli to the name of application
-- set theWindows to windows
set NbWin to the count of windows
set theWindow to first item of windows
properties of the theWindow
tell window "UPS Sumary"
--click on "Statistics button"
-- click on button 1 of theWindow
-- set enabled of button1 to true
end tell
--class of Upss
count of Upss
end tell
I get the following answers:
tell application "SolarMaxOsX"
activate
count every window of current application
--> 1
get item 1 of every window
--> window id 3113
get properties of window id 3113
--> {closeable:true, zoomed:false, class:window, index:1, visible:true, name:"UPS Sumary", miniaturizable:true, id:3113, miniaturized:false, resizable:true, bounds:{1485, 31, 1985, 579}, zoomable:true}
count every Ups of current application
--> error number -1728
Résultat :
error "Erreur dans SolarMaxOsX : Il est impossible d’obtenir every Ups." number -1728 from every Ups
What do I have missed ?
Logiciel OS X 10.9.5 (13F34) (Mavericks)
Xcode Version 6.1 (6A1052d)
Éditeur AppleScript Version 2.6.1 (152.1)
AppleScript 2.3.2Hi Hiroto
It is much better thanks
Now count of onduleurs works
Hi Hiro,
It is much better Thanks for your help
Now, count od onduleurs works
tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmt iegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app" to activate
-- delay 30
tell application "/Users/guydesbief/Library/Developer/Xcode/DerivedData/SolarMaxOsX-cgcuhyptmpmt iegixfnbbhpexjhn/Build/Products/Debug/SolarMaxOsX.app"
-- set nomAppli to the name of application
-- set theWindows to windows
class of onduleurs
count of onduleurs
-- get properties
set NbWin to the count of windows
set theWindow to first item of windows
properties of the theWindow
tell window "UPS Sumary"
--click on "Statistics button"
-- click on button 1 of theWindow
-- set enabled of button1 to true
end tell
get properties
get id of first onduleur of onduleurs
The results in appleScript:
tell application "SolarMaxOsX"
activate
get class of every onduleur
--> {onduleur, onduleur, onduleur}
count every onduleur of current application
--> 3
count every window of current application
--> 1
get item 1 of every window
--> window id 9796
get properties of window id 9796
--> {closeable:true, zoomed:false, class:window, index:1, visible:true, name:"UPS Sumary", miniaturizable:true, id:9796, miniaturized:false, resizable:true, bounds:{30, 28, 530, 576}, zoomable:true}
get properties
--> error number -10000
Résultat :
error "Erreur dans SolarMaxOsX : Le gestionnaire AppleEvent a échoué." number -10000
And the results of my logging in Objective C debugger:
My sdef file
2014-12-01 23:56:36.040 SolarMaxOsX[37551:303] Appdelegate handles onduleursArray
2014-12-01 23:56:36.040 SolarMaxOsX[37551:303] handles onduleursArray OK
2014-12-01 23:56:36.041 SolarMaxOsX[37551:303] Appdelegate handles onduleursArray
2014-12-01 23:56:36.041 SolarMaxOsX[37551:303] handles onduleursArray OK
2014-12-01 23:56:36.042 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
2014-12-01 23:56:36.042 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
2014-12-01 23:56:36.043 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
2014-12-01 23:56:36.043 SolarMaxOsX[37551:303] Appdelegate handles orderedWindows
2014-12-01 23:56:36.044 SolarMaxOsX[37551:303] Appdelegate handles scriptingProperties
2014-12-01 23:56:36.044 SolarMaxOsX[37551:303] Appdelegate handles classCode
2014-12-01 23:56:36.044 SolarMaxOsX[37551:303] Appdelegate handles onduleursArray
2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] handles onduleursArray OK
2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles terminologyVersion
2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles version
2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles name
2014-12-01 23:56:36.045 SolarMaxOsX[37551:303] Appdelegate handles isActive
2014-12-01 23:56:36.046 SolarMaxOsX[37551:303] An exception was thrown during execution of an NSScriptCommand...
2014-12-01 23:56:36.046 SolarMaxOsX[37551:303] Error while returning the result of a script command: the result object...
classCode = 1667330160;
isActive = 1;
name = SolarMaxOsX;
onduleursArray = (
"<Ups: 0x6000002c0bd0>",
"<Ups: 0x6100002c24c0>",
"<Ups: 0x6000000df100>"
terminologyVersion = 1;
version = "1.1";
...could not be converted to an Apple event descriptor of type 'application properties'. The 'onduleursArray' entry could not be converted to an Apple event descriptor of type 'onduleur'. This instance of the class '__NSArrayM' returned nil when sent -objectSpecifier (is it not overridden?) and there is no coercible type declared for the scripting class 'onduleur'.
It seems that my objectSpecifier method in Ups Category (or Ups class) is never called
My sdef File:
<!-- Suite Solar Max -->
<suite name="SolarMax Suite" code="SMap" description="Apple Events supportés par SolarMaxOsX">
<!-- suppress warning for missing "savable file format" type -->
<enumeration name="savable file format" code = "savf" hidden="yes">
<enumerator name= "dummy" code="VTdm"
description="A dummy file format."/>
</enumeration>
<class name="application" code="capp" description="SolarMaxOsX’s top level scripting object." plural="applications" inherits="application">
<cocoa class="NSApplication"/>
<element type="onduleur" access="r">
<cocoa key="onduleursArray"/>
</element>
<property name="onduleurs" code="SMor" description="Array of onduleurs." access="r">
<type type="onduleur" list="yes"/>
<cocoa key="onduleursArray"/>
</property>
<property name="name" code="pnam" description="The name of the application." type="text" access="r"/>
<property name="frontmost" code="pisf" description="Is this the frontmost (active) application?" type="boolean" access="r">
<cocoa key="isActive"/>
</property>
<property name="version" code="vers" description="The version of the application." type="text" access="r"/>
<property name="terminology version" code="TEvn" type="integer" access="r">
<cocoa key="terminologyVersion"/>
</property>
</class>
<class name="onduleur" code="SCup" description="An object onduleur in SolarMaxOsX." plural="onduleurs">
<cocoa class="Ups" inherits="item" />
<property name="id" code="ID " type="text" access="r" description="The unique identifier of the onduleur">
<cocoa key="uniqueID"/>
</property>
<property name="OnduleurName" code="pnam" description="The onduleur name. ." type="text">
<cocoa key="name"/>
</property>
</class>
// Class SolarMaxOsX to access to first window
<class name="SolarMaxOsX" code="SMos" description="main window in SolarMaxOsX.">
<cocoa class="SolarMaxOsX" />
</class>
</suite>
Categories for all classes in he same file: AppDelegate+AppleScriptExtensions.m (category file)
// SolarMaxOsX+AppleScriptExtensions.m
// SolarMaxOsX
// Created by Guy DESBIEF on 28/11/2014.
#import "AppDelegate+AppleScriptExtensions.h"
#import "Ups.h"
@implementation NSObject (MNscriptability)
- (void) returnError:(int)n string:(NSString*)s {
NSScriptCommand* c = [NSScriptCommand currentCommand];
[c setScriptErrorNumber:n];
if (s)
[c setScriptErrorString:s];
@end
@implementation AppDelegate (AppleScriptExtensions)
#define APPLESCRIPT_TERMINOLOGY_VERSION 1
#pragma mark ACCESSOR METHODS
-(NSNumber *) terminologyVersion {
return [NSNumber numberWithInt:APPLESCRIPT_TERMINOLOGY_VERSION];
// For appleScript recognition
-(NSUInteger) countOfOnduleursArray
MyLog(@"countOfOnduleursArray");
return [self.onduleursArray count];
- (Ups *) objectInOnduleursArrayAtIndex : (int) index {
MyLog(@"objectInOnduleursArrayAtIndex %index", index);
Ups *upsItem = [self.onduleursArray objectAtIndex:index];
if (upsItem != nil)
return upsItem;
} return nil;
- (Ups *) valueInOnduleursArrayAtIndex:(unsigned int)i {
MyLog(@"valueInOnduleursArrayAtIndex %i", i);
if (![[NSScriptCommand currentCommand] isKindOfClass:[NSExistsCommand class]])
if (i >= [onduleursArray count]) {
[self returnError:errAENoSuchObject string:@"No such Ups."];
return nil;
MyLog(@"valueInOnduleursArrayAtIndex index OK: %i", i);
return [onduleursArray objectAtIndex: i];
- (BOOL)application: (NSApplication *) sender delegateHandlesKey:(NSString *)key {
MyLog(@"Appdelegate handles %@",key);
if ([key isEqualToString: @"terminologyVersion"]) return YES;
if ([key isEqualToString: @"onduleursArray"]) {
MyLog(@"handles %@ OK",key);
return YES;
return NO;
@end
@implementation Ups (AppleScriptExtensions)
- (NSUniqueIDSpecifier *) objectSpecifier
MyLog(@"objectSpecifier (UPS) OK");
return [[NSUniqueIDSpecifier allocWithZone:[self zone]]
initWithContainerClassDescription: (NSScriptClassDescription *)[NSApp classDescription]
containerSpecifier: nil
key: @"onduleursArray"
uniqueID: uniqueID];
@end
AppDelegate+AppleScriptExtensions.h (category file)
// SolarMaxOsX+AppleScriptExtensions.h
// SolarMaxOsX
// Created by Guy DESBIEF on 28/11/2014.
#import <Foundation/Foundation.h>
#import "AppDelegate.h"
@class AppDelegate;
@class Ups;
@interface NSObject (MNscriptability)
- (void) returnError:(int)n string:(NSString*)s;
@end
@interface AppDelegate (AppleScriptExtensions)
#ifdef NDEBUG
#define MyLog(f, ...)
#else
#define MyLog(f, ...) NSLog(f, ## __VA_ARGS__)
#endif
- (BOOL)application: (NSApplication *) sender delegateHandlesKey:(NSString *)key;
- (NSUInteger) countOfOnduleursArray; -
hi everyone,
i'm just new to programming and i need some help from everyone that is willing to help me.
what's the statement or code that's counting the values of an array?how can you do it?
lets say i got 6 arrays and each has a diferent integer value.how can i write the code for having the totalvalue of the array?...keeping in mind that also there is into a for statement .....???.....lets say i got 6 arrays.....I hardly call this clearly defined. It seems the OP was simply using that as an example.
You should always write code that will work for all situations. What if the requirements were changed so that the array needed to hold 10 numbers, wrong answer calculated. Or worse if the array was < 6 numbers long, ArrayIndexOutOfBounds error. Or maybe the code needs to be dynamic ie the user enters a value for how many numbers are to be held in the array. All these will fail with your hard coded 6. -
Read Text file and count occurences of certain string
Hello,
I have a text file with lines of data in it. I would like to read this text file and count how many lines match a certain string of text.
For example my text file has this data in it.
dog,blue,big
dog,red,small
dog,blue,big
cat,blue,big
If the certain string of text is "dog,blue,big" then the count would return "2".
Thanks for your helpHello,
Thank you for your post.
I am afraid that the issue is out of support range of VS General Question forum which mainly discusses the usage issue of Visual Studio IDE such as
WPF & SL designer, Visual Studio Guidance Automation Toolkit, Developer Documentation and Help System
and Visual Studio Editor.
I am moving your question to the moderator forum ("Where is the forum for..?"). The owner of the forum will direct you to a right forum.
In addition, if you are working with Windows Forms app. please consult on Windows Forms Forum:http://social.msdn.microsoft.com/Forums/windows/en-US/home?category=windowsforms
If you are working with WPF app, please consult on WPF forum:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=wpf
If you are working with ASP.NET Web Application, I suggest that you can consult your issue on ASP.NET forum:
http://forums.asp.net/
for better solution and support.
Visual Studio Language Forums:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?category=vslanguages
Best regards,
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Count occurences of subsring in string
I am using cfhttp to return an hmtl table. I would like to
"count' the number of "<tr>" tags in the cfhttp.filecontent
variable I do not nessarily want to loop over it... is there a way
to do this?If your <tr> has white space on each side, you could
use the ListValueCountNoCase( ) function (
http://livedocs.macromedia.com/coldfusion/5.0/CFML_Reference/Functions155.htm#1108281)
Use a space as the list delimiter.
Maybe you are looking for
-
hI PP guys, I am getting runtime error in COR6N.i AM GETTING this message. "MESSAGE_TYPE_X" " " "SAPLKAID" or "LKAIDF0B" "MESSAGE_SEND" Kindly tell me pl. do ineed to apply any notes or patch for this What is the note is avilable? Regards Laxmikanth
-
I have an iMAC w/OS 10.7.5. I was working in Firefox today and as I was entering letters it changed to unrecognizable characters so I had to exit the application. Firefox froze up and after trying to re-open it many times, I finally tried uninstallin
-
I keep receiving Reset email password emails. The most recent one was actually addressed to someone else... i.e. the name in the email not the email address. why is this happening?? I am not requesting to reset my icloud email password.
-
I run OS Lion and Parallels, to run specific Windows apps. Recently, in finder I browsed to the Windows 7 file structure, and dragged a folder that I frequently access over to the Finder sidebar to create a shortcut. For a while it worked great. How
-
N8 - FourSquare and Twitter - Cannot Login
Hello, I have tried and tried to login via the FourSquare and Twitter app on my N8 - and always get an authentication error. If I log on to the web version on the N8 - I get in no problem. I have tried many times, so I doubt it is being typed in in