Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

タグ: Numbers

Numbersで選択中のデータを2D Listで取得し、ユニーク化

Posted on 12月 3, 2018 by Takaaki Naganoya

Numbersの最前面の書類の選択中のシートの選択中のセルの値を2D List(Array)で取り出して、ユニーク化するAppleScriptです。

上記のような状態で本AppleScriptを実行すると、

{{"iMac4,1", "Yonah"}, {"iMac4,2", "Yonah"}, {"iMac5,2", "Merom"}, {"iMac5,1", "Merom"}, {"iMac6,1", "Merom"}, {"iMac7,1", "Merom"}, {"iMac8,1", "Penryn"}, {"iMac9,1", "Penryn"}, {"iMac10,1", "Wolfdale"}, {"iMac11,1", "Wolfdale, Lynnfield"}......} 

のような2D Listで結果が得られます。Numbersの選択中のセルからそのまま情報を取得すると1D Listとして結果が返ってきますが、別途selection rangeの情報を取得し、それをもとに2D Listに変換。得られた2D Listに対して重複データの除去をCocoaの機能を用いて行なっています。

特定のフィールド上の選択中のデータを1D Listとして取得し、重複データを検出するようなScriptは日常的に使っていますが、行データをすべて取得して2D Listとして取り出し、重複データ部分を除去するようなものは使っていませんでした。

AppleScript名:Numbersで選択中のデータを2D Listで取得し、ユニーク化
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aList to get2DListFromNumbersSelection() of me
if aList = "" then return "No Selection"

set bList to uniquifyList(aList) of me

on get2DListFromNumbersSelection()
  –Numbersで選択範囲を縦に区切ったリストを返す
  
tell application "Numbers"
    tell front document
      tell active sheet
        try
          set theTable to first table whose class of selection range is range
        on error
          return "" –何も選択されてなかった場合
        end try
        
        
tell theTable
          set selList to value of every cell of selection range –選択範囲のデータを取得
          
          
set selName to name of selection range –選択範囲のrange情報を取得
          
set {s1, s2} to parseByDelim(selName, ":") of me
          
          
–始点の情報を取得する
          
set s1Row to (address of row of range s1) as integer
          
set s1Column to (address of column of range s1) as integer
          
          
–終点の情報を取得する
          
set s2Row to (address of row of range s2) as integer
          
set s2Column to (address of column of range s2) as integer
          
          
–選択範囲の情報を取得する
          
set selHeight to s2Row – s1Row + 1 –高さ(Height of selection range)
          
set selWidth to s2Column – s1Column + 1 –幅(Width of selection range)
          
        end tell
      end tell
    end tell
  end tell
  
  
set aLen to length of selList
  
set aaLen to selHeight
  
  
set bList to {}
  
repeat with i from 1 to aaLen
    set aHoriList to {}
    
    
repeat with ii from 1 to selWidth
      set j1 to ii + (i – 1) * selWidth
      
set tmpCon to contents of item j1 of selList
      
      
set aClass to class of tmpCon
      
if aClass = number or aClass = integer or aClass = real then
        set tmpCon to tmpCon as integer
      end if
      
      
set the end of aHoriList to tmpCon
    end repeat
    
    
set the end of bList to aHoriList
  end repeat
  
  
return bList
end get2DListFromNumbersSelection

–テキストを指定デリミタでリスト化
on parseByDelim(aData, aDelim)
  set aText to current application’s NSString’s stringWithString:aData
  
set aList to aText’s componentsSeparatedByString:aDelim
  
return aList as list
end parseByDelim

–1D/2D Listのユニーク化
on uniquifyList(aList as list)
  set aArray to current application’s NSArray’s arrayWithArray:aList
  
set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self"
  
return bArray as list
end uniquifyList

★Click Here to Open This Script 

Posted in list | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSArray NSString Numbers | Leave a comment

squeezeNetで画像のオブジェクト認識を行い、結果をCSV出力してNumbersでオープン

Posted on 11月 12, 2018 by Takaaki Naganoya

Core MLモデル「squeezeNet.mlmodel」を用いて画像のオブジェクト認識を行い、結果をデスクトップにCSV形式でデータ書き出しを行い、NumbersでオープンするAppleScriptです。

–> Download squeezeNetKit.framework (To ~/Library/Frameworks)

macOS 10.13上ではスクリプトエディタ、Script Debugger上で、macOS 10.14上ではScript Debugger上で動作します(AppleScript Appletでも動作)。

さまざまなCore MLモデルを用いて画像認識を行わせてはみたものの、最もスコアの高いもののラベルだけを返させても、結果がまったく内容にそぐわないケースが多く見られます。


▲機械学習の評価値が1.0に近いものは確度が高く、0.0に近いものは判断に迷った末に消極的に出した値。経験則でいえば、最高スコアの項目が0.7以上のスコアでないといまひとつのようです(0.7以上でもダメな時はダメなわけで、、、)

画像認識については、結果があまりに的外れで「なんじゃこら?」というケースが多いので、確認のためにCSVデータ出力させてNumbers上で確認させてみることにしてみました。そのためにありあわせのサブルーチンを組み合わせて作ったものです。

スコアが高い順に結果を並べて確認してみると、最も高いスコアの値であっても0.0に近い評価値であることがあり、「何も考えずに最高スコアのラベルだけ取ってくるのはものすごく危険」なことがよくわかります。


▲squeezeNet.mlmodelをNetronでビジュアライズしたところ(一部抜粋)

AppleScript名:SqueezeNetでオブジェクト判定して結果をCSV書き出ししてNumbersでオープン.scpt
–  Created by: Takaaki Naganoya
–  Created on: 2018/11/11
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use framework "AppKit"
use framework "squeezeNetKit"
use scripting additions

property NSUUID : a reference to current application’s NSUUID
property NSArray : a reference to current application’s NSArray
property NSImage : a reference to current application’s NSImage
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

set aFile to POSIX path of (choose file of type {"public.image"})
set aImage to NSImage’s alloc()’s initWithContentsOfFile:aFile
set resDict to (current application’s imageClassifier’s alloc()’s init()’s ImageClassifierWithImageAndRetDict:aImage)

set kArray to (resDict’s allKeys())
set vArray to (resDict’s allValues())
set aLen to kArray’s |count|()

set anArray to NSMutableArray’s new()

repeat with i from 0 to (aLen – 1)
  set tmpKey to (kArray’s objectAtIndex:i) as string
  
set tmpVal to (vArray’s objectAtIndex:i) as real
  (
anArray’s addObject:{aKey:tmpKey, aVal:tmpVal})
end repeat

–Sort by value
set bList to sortRecListByLabel(anArray, "aVal", false) of me

–record in list –> 2D list
set cList to convRecInListTo2DList(bList) of me

–デスクトップにCSVファイルを書き出してNumbersでオープン
set aPath to (((path to desktop) as string) & (NSUUID’s UUID()’s UUIDString()) as string) & ".csv"
set fRes to saveAsCSV(cList, aPath) of me
tell application "Numbers"
  open (aPath as alias)
end tell

–リストに入れたレコードを、指定の属性ラベルの値でソート
on sortRecListByLabel(aRecList as list, aLabelStr as string, ascendF as boolean)
  set aArray to NSArray’s arrayWithArray:aRecList
  
set sortDesc to NSSortDescriptor’s alloc()’s initWithKey:aLabelStr ascending:ascendF
  
set sortDescArray to NSArray’s arrayWithObjects:sortDesc
  
set sortedArray to aArray’s sortedArrayUsingDescriptors:sortDescArray
  
set bList to (sortedArray) as anything
  
return bList
end sortRecListByLabel

on convRecInListTo2DList(aList)
  set anArray to NSMutableArray’s arrayWithArray:aList
  
set fItem to anArray’s objectAtIndex:0
  
set keyList to fItem’s allKeys() as list
  
set aCount to anArray’s |count|()
  
  
set allArray to NSMutableArray’s new()
  
  
repeat with i from 1 to aCount
    set anItem to (anArray’s objectAtIndex:(i – 1))
    
set tmpItem to {}
    
    
repeat with ii in keyList
      set tmpDat to (anItem’s valueForKeyPath:(contents of ii))
      
if tmpDat is not equal to missing value then
        set the end of tmpItem to tmpDat
      else
        set the end of tmpItem to ""
      end if
    end repeat
    (
allArray’s addObject:tmpItem)
  end repeat
  
  
set allList to allArray as list
  
set the beginning of allList to keyList
  
return allList
end convRecInListTo2DList

–CSV Kit

–2D List to CSV file
on saveAsCSV(aList, aPath)
  –set crlfChar to (ASCII character 13) & (ASCII character 10)
  
set crlfChar to (string id 13) & (string id 10)
  
set LF to (string id 10)
  
set wholeText to ""
  
  
repeat with i in aList
    set newLine to {}
    
    
–Sanitize (Double Quote)
    
repeat with ii in i
      set jj to ii as text
      
set kk to repChar(jj, string id 34, (string id 34) & (string id 34)) of me –Escape Double Quote
      
set the end of newLine to kk
    end repeat
    
    
–Change Delimiter
    
set aLineText to ""
    
set curDelim to AppleScript’s text item delimiters
    
set AppleScript’s text item delimiters to "\",\""
    
set aLineList to newLine as text
    
set AppleScript’s text item delimiters to curDelim
    
    
set aLineText to repChar(aLineList, return, "") of me –delete return
    
set aLineText to repChar(aLineText, LF, "") of me –delete lf
    
    
set wholeText to wholeText & "\"" & aLineText & "\"" & crlfChar –line terminator: CR+LF
  end repeat
  
  
if (aPath as string) does not end with ".csv" then
    set bPath to aPath & ".csv" as Unicode text
  else
    set bPath to aPath as Unicode text
  end if
  
  
write_to_file(wholeText, bPath, false) of me
  
end saveAsCSV

on write_to_file(this_data, target_file, append_data)
  tell current application
    try
      set the target_file to the target_file as text
      
set the open_target_file to open for access file target_file with write permission
      
if append_data is false then set eof of the open_target_file to 0
      
write this_data to the open_target_file starting at eof
      
close access the open_target_file
      
return true
    on error error_message
      try
        close access file target_file
      end try
      
return error_message
    end try
  end tell
end write_to_file

on repChar(origText as text, targChar as text, repChar as text)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to targChar
  
set tmpList to text items of origText
  
set AppleScript’s text item delimiters to repChar
  
set retText to tmpList as string
  
set AppleScript’s text item delimiters to curDelim
  
return retText
end repChar

★Click Here to Open This Script 

Posted in file Image list Machine Learning Record Sort | Tagged 10.13savvy 10.14savvy NSArray NSImage NSMutableArray NSSortDescriptor NSUUID Numbers | Leave a comment

Table 1の全セルを選択する v3

Posted on 11月 5, 2018 by Takaaki Naganoya

Numbersで選択中のセルがなければ、最前面の書類の選択中のワークシートのうちのTable 1を全選択するAppleScriptです。

選択部分からデータを取得する処理はよく行いますが、プログラム側から選択部分を作成するというのはやっていなかったので、試行錯誤してみました。

AppleScript名:Table 1の全セルを選択する v3.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/11/05
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

tell application "Numbers"
  tell front document
    tell active sheet
      try
        –選択セルがある場合
        
set theTable to first table whose class of selection range is range
      on error
        –選択セルがない場合はTable 1を全選択
        
set tCount to count every table
        
if tCount = 0 then error "There is no table in active sheet"
        
        
tell table 1
          set selection range to cell range
        end tell
        
      end try
    end tell
  end tell
end tell

★Click Here to Open This Script 

Posted in How To | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy Numbers | Leave a comment

Numbersの表の選択範囲をHTML化 v2

Posted on 11月 1, 2018 by Takaaki Naganoya

Numbersの最前面の書類で選択中の表の範囲をHTML化してファイルに書き出すAppleScriptです。

Numbers v5.1+macOS 10.12.6、Numbers v5.2+macOS 10.13.6、Numbers v5.2+macOS 10.14.1で確認しています。

Numbers v5.xでは書類の書き出し(export)形式にPDF、Microsoft Excel、CSV、Numbers 09の4形式を指定できるようになっていますが、HTMLの表(table)に書き出してくれたりはしません。

GUI側(↑)にその機能がありませんし、AppleScript用語辞書(↓)にもそういう機能は見当たりません。

ただ、HTMLの表に書き出すという処理自体はとても初歩的で簡単な内容なので、「なければ作ればいい」ということになるでしょう。

そこで、ありもののルーチンを組み合わせて、選択範囲をHTMLの表(table)として書き出すScriptを書いて、OS標準装備のScript Menuに入れて利用しています。書き出すHTMLの内容は個人の趣味や用途に応じて大きく変わってきますので、そのあたりは自由に書き換えるとよいと思われます。

本Scriptは、電子書籍「AppleScript最新リファレンス」の正誤表(2018/1のBlog消失事件の影響で、書籍内で参照していたURLリンクが切れてしまったことへの対処)を作成するために、すでに存在していたものにほんの少しの修正を加えたものです。

データベースやデータからHTMLを作成するという処理は、自分がAppleScriptを覚えようと思ったきっかけでもあり(当時は、FileMaker Pro Server経由でLAN上でデータを共有して処理)、感慨深いものがあります。

AppleScript名:表の選択範囲をHTML化 v2
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use bPlus : script "BridgePlus"

script spd
  property uniqList : {}
end script

set (uniqList of spd) to {}

–Numbersからデータを取得する
set aList to get2DListFromNumbersSelection() of me
if aList = false then return

set colCount to (length of first item of first item of aList) + 1

set aHeader to "<!DOCTYPE html><html lang=\"ja\" ><head><meta charset=\"utf-8\"><title>First</title><style>table , td, table , tr, th{border:1px solid #333333;padding:1px;}</style></head><body><table >"
set aTable to "<tr><td>%@</td><td> </td><td>%@</td><td>%@</td><td>%@</td></tr>"
set aFooter to "</table></body></html>"

set aHTMLres to retTableHTML(aList, aHeader, aTable, aFooter) of me

set tFile to choose file name with prompt "Select Output File Name and Folder"
set fRes to writeToFileAsUTF8(aHTMLres, tFile, false) of me

on retTableHTML(aList, aHeaderHTML, aTableHTML, aFooterHTML)
  set allHTML to current application’s NSMutableString’s stringWithString:aHeaderHTML
  
  
set aCounter to 1
  
repeat with i in aList
    set j to contents of i
    
    
set aRowHTML to "<tr>"
    
repeat with ii in j
      set jj to contents of ii
      
if jj = missing value then
        set jj to " "
      else
        try
          set aURL to (current application’s |NSURL|’s URLWithString:jj)
          
if aURL is not equal to missing value then
            set jj to "<a href=\"" & jj & "\">" & jj & "</a>"
          end if
        end try
      end if
      
      
set aTmpHTML to "<td>" & jj & "</td>"
      
set aRowHTML to aRowHTML & aTmpHTML
    end repeat
    
set aRowHTML to aRowHTML & "</tr>"
    
    (
allHTML’s appendString:aRowHTML)
    
set aCounter to aCounter + 1
  end repeat
  
  (
allHTML’s appendString:aFooterHTML)
  
  
return allHTML as list of string or string
end retTableHTML

–テキストを指定デリミタでリスト化
on parseByDelim(aData, aDelim)
  set aText to current application’s NSString’s stringWithString:aData
  
set aList to aText’s componentsSeparatedByString:aDelim
  
return aList as list
end parseByDelim

on get2DListFromNumbersSelection()
  –Numbersで選択範囲を縦に区切ったリストを返す
  
tell application "Numbers"
    tell front document
      tell active sheet
        set theTable to first table whose class of selection range is range
        
        
tell theTable
          try
            set selList to value of every cell of selection range –選択範囲のデータを取得
          on error
            return "" –何も選択されてなかった場合
          end try
          
          
set selName to name of selection range –選択範囲のrange情報を取得
          
set {s1, s2} to parseByDelim(selName, ":") of me
          
          
–始点の情報を取得する
          
set s1Row to (address of row of range s1) as integer
          
set s1Column to (address of column of range s1) as integer
          
          
–終点の情報を取得する
          
set s2Row to (address of row of range s2) as integer
          
set s2Column to (address of column of range s2) as integer
          
          
–選択範囲の情報を取得する
          
set selHeight to s2Row – s1Row + 1 –高さ(Height of selection range)
          
set selWidth to s2Column – s1Column + 1 –幅(Width of selection range)
          
        end tell
      end tell
    end tell
  end tell
  
  
set aLen to length of selList
  
set aaLen to selHeight
  
  
set bList to {}
  
repeat with i from 1 to aaLen
    set aHoriList to {}
    
    
repeat with ii from 1 to selWidth
      set j1 to ii + (i – 1) * selWidth
      
set tmpCon to contents of item j1 of selList
      
      
set aClass to class of tmpCon
      
if aClass = number or aClass = integer or aClass = real then
        set tmpCon to tmpCon as integer
      end if
      
      
set the end of aHoriList to tmpCon
    end repeat
    
    
set the end of bList to aHoriList
  end repeat
  
  
return bList
  
end get2DListFromNumbersSelection

on writeToFileAsUTF8(this_data, target_file, append_data)
  tell current application
    try
      set the target_file to the target_file as text
      
set the open_target_file to open for access file target_file with write permission
      
if append_data is false then set eof of the open_target_file to 0
      
write this_data as «class utf8» to the open_target_file starting at eof
      
close access the open_target_file
      
return true
    on error error_message
      try
        close access file target_file
      end try
      
return error_message
    end try
  end tell
end writeToFileAsUTF8

★Click Here to Open This Script 

Posted in Internet list | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy Numbers | Leave a comment

Skimで表示中のページ数を現在のNumbersのセルに入れて、選択セルを下にひとつ移動

Posted on 8月 18, 2018 by Takaaki Naganoya

Skimで現在表示中のPDFの現在のページ番号を、Numbers書類で選択中のセルに入れて、Numbersの選択中のセルを1つ下に移動させるAppleScriptです。

–> Watch Demo Movie

作業をちょっとだけ楽にするために作成したAppleScriptです。本来は、すべてのワークフローを自動化するのが筋ですが、限られた時間で限られた範囲の作業のみを自動化するだけでも十分な効果が得られる場合があります。

複数のアプリケーションをまたいでデータのコピー&ペーストを行うようなケースだと、ちょっとした複合作業を自動化することで作業が圧倒的に楽になります。

PDFビューワー「Skim」上でPDFを表示、Numbers上の表にページ数のデータを入れたい。

本AppleScriptを実行すると、

Numbersの選択セルにデータを突っ込んで、選択セルを1つ下に移動させます。

こうして、PDFにTOCをつけてみました(Blogアーカイブ書籍のマイナーバージョンアップ版のため。再ダウンロードでアップデート可能になります)。元データがあるんだから、TOCごと自動で作ってもいいようなものですが、久しぶりだったので(TOC用データを)手で作ってみました。

ここで、意地でもGUI Scriptingを使わないで処理すると、バックグラウンドでも安全に処理できるので大きなメリットがあります。GUI Scriptingだと最前面(フォアグラウンド)でしか操作が保証されていないので、バックグラウンドで操作できたとしてもそれは「ラッキー」でしかありません。

AppleScript名:Skimで表示中のページ数を現在のNumbersのセルに入れて、選択セルを下にひとつ移動
— Created 2018-08-18 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Skim"
  tell front document
    set curPage to index of current page
  end tell
end tell

set curPageStr to curPage as string

tell application "Numbers"
  tell front document
    tell active sheet
      tell table 1
        set mySelectedRanges to properties of selection range
        
set value of cells of selection range to {curPageStr}
        
        
set selName to name of selection range –選択範囲のrange情報を取得
        
set {s1, s2} to parseByDelim(selName, ":") of me
        
        
set s1Row to (address of row of range s1) as integer
        
set colStr to (name of column of range s1) as string
        
        
set rowStr to (s1Row + 1) as string
        
        
set adrStr to colStr & rowStr
        
set rangeStr to adrStr & ":" & adrStr
        
try
          set selection range to range rangeStr
        on error
          –Range Over Error from table 1
          
display dialog "表の範囲をオーバーします"
          
return
        end try
      end tell
    end tell
  end tell
end tell

–テキストを指定デリミタでリスト化
on parseByDelim(aData, aDelim)
  set aText to current application’s NSString’s stringWithString:aData
  
set aList to aText’s componentsSeparatedByString:aDelim
  
return aList as list
end parseByDelim

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy NSString Numbers Skim | Leave a comment

オープン中のNumbers書類のすべてのシート上のテーブルのデータを連結して新規書類に入れる v2

Posted on 7月 10, 2018 by Takaaki Naganoya

オープン中のNumbers書類のうち最前面のものを対象に、すべてのシート上のテーブル1のデータを連結して新規書類に入れるAppleScriptです。

(↑)Numbers書類中のテーブルのカラム数がすべて同じことが本Scriptの前提条件。

データ結合まではすぐに処理が終わるものの、結合したデータを新規Numbers書類にAppleScriptから順次突っ込むと、データ数の増加にともなって処理時間が大幅に増えるので、そのやり方はやるべきではありません(経験のない素人がやりそうな処理)。

なので、本ScriptではCSVファイルを組み立てて、デスクトップに書き出し、それをNumbersにオープンさせます。

これだと処理は一瞬です。開発環境では、シート9枚&総合計263行のデータを連結してCSVに書き出してNumbers上でオープンするのに1.6秒しかかかりません。

AppleScript名:オープン中のNumbers書類のすべてのシート上のテーブルのデータを連結して新規書類に入れる v2
— Created 2018-07-09 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

script spd
  property allData : {} –Numbersから取得したデータをストアしておく
  
property all2DData : {} –取得したデータを2D Arrayに変換した際にデータをストアしておく
end script

set (allData of spd) to {}
set (all2DData of spd) to {}

set dataWidth to 2

tell application "Numbers"
  tell front document
    set aList to every sheet
    
    
repeat with i in aList
      tell i
        tell table 1
          –テーブル中のセルの値をすべて取得(1D Listで帰ってくる)
          
set aList to value of every cell
          
          
–1D ListをSweep(missing valueの入っているアイテムを削除)
          
set bList to sweep1DList(aList) of me
          
          
–取得してSweepしたデータを連結
          
set (allData of spd) to (allData of spd) & (bList as list)
        end tell
      end tell
    end repeat
    
  end tell
end tell

–1D Listを2D Listに変換
set (all2DData of spd) to conv1DListTo2DList((allData of spd), dataWidth) of me

–まとめたデータをCSVファイルとして書き出し
set aPath to ((path to desktop) as string) & (do shell script "uuidgen") & ".csv"
saveAsCSV((all2DData of spd), aPath) of me

do shell script "sync" –SSDで処理している場合には必要ないが、、、
set anAlias to aPath as alias

–書き出したCSVファイルをNumbersでオープン
tell application "Numbers"
  open anAlias
  
activate
end tell

on sweep1DList(aList)
  load framework
  
return (current application’s SMSForder’s arrayByDeletingBlanksIn:aList) as list
end sweep1DList

on conv1DListTo2DList(aList, groupingNum)
  load framework
  
return (current application’s SMSForder’s subarraysFrom:aList groupedBy:groupingNum |error|:(missing value)) as list
end conv1DListTo2DList

–2D List to CSV file
on saveAsCSV(aList, aPath)
  set crlfChar to (string id 13) & (string id 10)
  
set LF to (string id 10)
  
set wholeText to ""
  
  
repeat with i in aList
    set newLine to {}
    
    
–Sanitize (Double Quote)
    
repeat with ii in i
      set jj to ii as text
      
set kk to repChar(jj, string id 34, (string id 34) & (string id 34)) of me –Escape Double Quote
      
set the end of newLine to kk
    end repeat
    
    
–Change Delimiter
    
set aLineText to ""
    
set curDelim to AppleScript’s text item delimiters
    
set AppleScript’s text item delimiters to "\",\""
    
set aLineList to newLine as text
    
set AppleScript’s text item delimiters to curDelim
    
    
set aLineText to repChar(aLineList, return, "") of me –delete return
    
set aLineText to repChar(aLineText, LF, "") of me –delete lf
    
    
set wholeText to wholeText & "\"" & aLineText & "\"" & crlfChar –line terminator: CR+LF
  end repeat
  
  
if (aPath as string) does not end with ".csv" then
    set bPath to aPath & ".csv" as Unicode text
  else
    set bPath to aPath as Unicode text
  end if
  
  
writeToFile(wholeText, bPath, false) of me
  
end saveAsCSV

on writeToFile(this_data, target_file, append_data)
  tell current application
    try
      set the target_file to the target_file as text
      
set the open_target_file to open for access file target_file with write permission
      
if append_data is false then set eof of the open_target_file to 0
      
write this_data to the open_target_file starting at eof
      
close access the open_target_file
      
return true
    on error error_message
      try
        close access file target_file
      end try
      
return error_message
    end try
  end tell
end writeToFile

on repChar(origText as text, targChar as text, repChar as text)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to targChar
  
set tmpList to text items of origText
  
set AppleScript’s text item delimiters to repChar
  
set retText to tmpList as string
  
set AppleScript’s text item delimiters to curDelim
  
return retText
end repChar

★Click Here to Open This Script 

Posted in list | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

Numbersのアクティブシート上の表の行数をデータに合わせる

Posted on 6月 13, 2018 by Takaaki Naganoya

Numbersの最前面の書類の選択中のシート(アクティブシート)上の「表」の行数をデータに合わせて変更するAppleScriptです。


▲Before


▲After

表データ上の空白部分を末尾(下)から先頭(上)に向かってサーチし、空白ではない箇所を見つけるまで繰り返します。

AppleScript名:Numbersのアクティブシート上の表の行数をデータに合わせる
— Created 2018-06-12 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

set tCount to getTableCount() of me

repeat with tableID from 1 to tCount
  
  
–Numbersからデータを取得する
  
set aList to getDataFromNumbersDoc(tableID) of me
  
if aList = false then error "No Data in table " & (tableID as string)
  
  
–Numbersの対象の表の情報を取得
  
set aWidth to getColumnCount(tableID) of me
  
set aHeaderCount to getHeaderCount(tableID) of me
  
set aFooterCount to getFooterCount(tableID) of me
  
  
–Numbersから取得した2D Listのデータからデータの末尾を見つける
  
set aDataRowCount to findDataEnd(aWidth, aHeaderCount, aFooterCount, aList) of me
  
  
tell application "Numbers"
    tell front document
      tell active sheet
        tell table tableID
          set row count to aDataRowCount
        end tell
      end tell
    end tell
  end tell
  
end repeat

–Numbersでオープン中の書類の選択中のシートの表1からデータを取得して2D Listに
on getDataFromNumbersDoc(tableNum as integer)
  
  
load framework
  
  
tell application "Numbers"
    if (count every document) = 0 then return false
    
    
tell front document
      if (count every sheet) = 0 then return false
      
      
tell active sheet
        tell table tableNum
          set colCount to column count
          
set rowCount to row count
          
set headerCount to header row count
          
set footerCount to footer row count
          
          
set dList to value of every cell of cell range
        end tell
      end tell
      
    end tell
  end tell
  
  
–Convert 1D List to 2D List
  
set bList to (current application’s SMSForder’s subarraysFrom:dList groupedBy:colCount |error|:(missing value)) as list
  
set sItem to 1 + headerCount
  
set eItem to rowCount – footerCount
  
set cList to items sItem thru eItem of bList
  
  
return cList
  
end getDataFromNumbersDoc

on getTableCount()
  tell application "Numbers"
    set dCount to count every document
    
if dCount = 0 then error "Numbers: There is No Document"
    
    
tell front document
      tell active sheet
        return (count every table)
      end tell
    end tell
  end tell
end getTableCount

on getHeaderCount(tableID as integer)
  tell application "Numbers"
    tell front document
      tell active sheet
        tell table tableID
          return (header row count)
        end tell
      end tell
    end tell
  end tell
end getHeaderCount

on getFooterCount(tableID as integer)
  tell application "Numbers"
    tell front document
      tell active sheet
        tell table tableID
          return (footer row count)
        end tell
      end tell
    end tell
  end tell
end getFooterCount

on getColumnCount(tableID as integer)
  tell application "Numbers"
    tell front document
      tell active sheet
        tell table tableID
          return (column count)
        end tell
      end tell
    end tell
  end tell
end getColumnCount

–Numbersから取得した2D Arrayのデータ末尾を見つける(ただし、高速化処理を一切していないのでデータ数が数千件を超えると遅くなる)
on findDataEnd(aWidth as integer, aHeaderCount as integer, aFooterCount as integer, aList as list)
  set rAList to reverse of aList –get reverse order list
  
  
set anItem to {}
  
repeat aWidth times
    set the end of anItem to missing value
  end repeat
  
  
set aCount to length of aList
  
set hitF to false
  
  
repeat with i in rAList
    set j to contents of i
    
if j is not equal to anItem then
      set hitF to true
      
exit repeat
    end if
    
set aCount to aCount – 1
  end repeat
  
  
if hitF = false then return false –すべて空(missing value)だった場合には処理打ち切り
  
  
return aCount + aHeaderCount + aFooterCount
end findDataEnd

★Click Here to Open This Script 

Posted in list | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

Numbersで選択範囲のセルのデータを取得して重複データを抽出

Posted on 6月 7, 2018 by Takaaki Naganoya

Numbersの表データの選択範囲のセルのデータを取得し、重複データがあれば重複データのみ表示するAppleScriptです。

# NumbersというApple社製の表計算アプリケーションを操作する話であって、宝くじの話ではありません。また、本BlogはScriptでMac上のアプリケーションやOS内のサービスを呼び出して処理する話を紹介しているものであって、単に画面上から削除する方法を紹介するものではありません。また、データのユニーク化処理ができないわけがありません。とっくの昔に書いています。

macOS標準装備のScript Menuに入れて便利に使っています。Numbers上の選択範囲内に重複データがあれば、ダイアログでデータを表示します。

AppleScript名:Numbersで選択範囲のセルのデータを取得して重複データを抽出
— Created 2018-01-13 by Takaaki Naganoya
— Modified 2018-06-06 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSCountedSet : a reference to current application’s NSCountedSet

script spd
  property uniqList : {}
end script

set (uniqList of spd) to {}

tell application "Numbers"
  tell front document
    tell active sheet
      try
        set theTable to first table whose class of selection range is range
      on error
        display notification "Numbers: There is no selection"
        
return
      end try
      
      
tell theTable
        set (uniqList of spd) to value of cells of selection range
      end tell
    end tell
  end tell
end tell

if (uniqList of spd) = {} then
  display notification "Numbers: There is no selection"
  
return
end if

set aRes to returnDuplicatesOnly(uniqList of spd) of me
if aRes is not equal to {} then
  choose from list aRes with prompt "Duplicated Data:"
else
  display notification "No Duplicated Data"
end if

–1D Listから重複項目のみを抽出して返す
on returnDuplicatesOnly(aList as list)
  set aSet to NSCountedSet’s alloc()’s initWithArray:aList
  
set bList to (aSet’s allObjects()) as list
  
  
set dupList to {}
  
repeat with i in bList
    set aRes to (aSet’s countForObject:i)
    
if aRes > 1 then
      set the end of dupList to (contents of i)
    end if
  end repeat
  
  
return dupList
end returnDuplicatesOnly

★Click Here to Open This Script 

Posted in list | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

Numbersの選択中の表を取得してMarkdown書式の表に変換する v2

Posted on 3月 30, 2018 by Takaaki Naganoya

Numbers上の選択中のテーブルの内容をMarkdown形式のデータに書き出して、書き出したデータをMacDownでオープンしてHTMLのソース文字列を取得するAppleScriptです。

Numbersの表の内容をHTMLに書き出すのに、2D Arrayの内容を直接HTML Tableに変換するScriptが手元に見当たらなかったので、いったんMarkdown書類を経由させてみました。

MarkdownのレンダラーのFrameworkもいくつかチェックはしていますが、なぜかどれもこれもTableタグをサポートしていません(ーー;;

AppleScript名:Numbersの選択範囲を取得してMarkdown書式の表に変換する v2
— Created 2016-05-12 by Takaaki Naganoya
— Modified 2018-03-29 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSUUID : a reference to current application’s NSUUID
property NSString : a reference to current application’s NSString
property NSFileManager : a reference to current application’s NSFileManager

set htmlRes to selectedNumbersTableToHTML() of me

–選択中のNumbersのワークシート上で選択中のテーブルのデータをHTML化
on selectedNumbersTableToHTML()
  set aSeparator to "|"
  
set aCell to ":—" –Align Left Tag
  
set aLineTerminator to return
  
  
–Numbersの選択範囲からExcel仕様で2Dリストを返す
  
set aSel to get2DListFromNumbersSelection() of me
  
if aSel = "" then
    tell current application
      display dialog "Numbersのワークシート上で何も選択されていません" with icon 2 buttons {"OK"} default button 1 with title "選択範囲エラー"
      
return false
    end tell
  end if
  
  
–選択範囲の横幅チェック、ヘッダー部のデータ作成
  
set colNum to length of (contents of first item of aSel)
  
set sepList to {}
  
repeat colNum times
    set end of sepList to aCell
  end repeat
  
  
–ヘッダーセパレータを配列の2番目に挿入する
  
set newList to insListItem(aSel, sepList, 2) of me
  
  
–Markdown書式の表を文字列で作成する
  
set outStr to ""
  
repeat with i in newList
    set outStr to outStr & retStrFromArrayWithDelimiter(contents of i, aSeparator) of me & aLineTerminator
  end repeat
  
  
–Desktopにmarkdown書類を書き出してMacDownでオープンしてHTMLソースを取得する
  
set targFol to POSIX path of (path to desktop)
  
set fRes to savePlainText(targFol, outStr, "md") of me
  
  
tell application "MacDown"
    open ((POSIX file fRes) as alias)
    
    
tell front document
      set aProp to properties
      
set aHtmlDat to html of aProp
      
close
    end tell
  end tell
  
  
–デスクトップフォルダ上に作成したMarkdown書類を削除する
  
set aRes to deleteItemAt(fRes) of me
  
  
return aHtmlDat
end selectedNumbersTableToHTML

–指定のリスト(2次元配列)に、要素(1次元配列)を、指定箇所(1はじまり)にインサートする
on insListItem(aList as list, insList as list, insertItemNum as integer)
  set newList to {}
  
set itemCounter to 1
  
repeat with i in aList
    if itemCounter = insertItemNum then
      set the end of newList to insList
    end if
    
set end of newList to (contents of i)
    
set itemCounter to itemCounter + 1
  end repeat
  
return newList
end insListItem

–リストを指定デリミタをはさんでテキスト化
on retStrFromArrayWithDelimiter(aList as list, aDelim as string)
  set anArray to current application’s NSArray’s arrayWithArray:aList
  
set aRes to anArray’s componentsJoinedByString:aDelim
  
return aRes as text
end retStrFromArrayWithDelimiter

on retArrowText(aList as list, aDelim as string) –自分のASでよく使うハンドラ名称なので、同じものを用意
  return my retStrFromArrayWithDelimiter(aList, aDelim)
end retArrowText

–テキストを指定デリミタでリスト化
on parseByDelim(aData, aDelim)
  set aText to current application’s NSString’s stringWithString:aData
  
set aList to aText’s componentsSeparatedByString:aDelim
  
return aList as list
end parseByDelim

on get2DListFromNumbersSelection()
  –Numbersで選択範囲を縦に区切ったリストを返す
  
tell application "Numbers"
    tell front document
      tell active sheet
        set theTable to first table whose class of selection range is range
        
tell theTable
          try
            set selList to value of every cell of selection range –選択範囲のデータを取得
          on error
            return "" –何も選択されてなかった場合
          end try
          
          
set selName to name of selection range –選択範囲のrange情報を取得
          
set {s1, s2} to parseByDelim(selName, ":") of me
          
          
–始点の情報を取得する
          
set s1Row to (address of row of range s1) as integer
          
set s1Column to (address of column of range s1) as integer
          
          
–終点の情報を取得する
          
set s2Row to (address of row of range s2) as integer
          
set s2Column to (address of column of range s2) as integer
          
          
–選択範囲の情報を取得する
          
set selHeight to s2Row – s1Row + 1 –高さ(Height of selection range)
          
set selWidth to s2Column – s1Column + 1 –幅(Width of selection range)
          
        end tell
      end tell
    end tell
  end tell
  
  
set aLen to length of selList
  
set aaLen to selHeight
  
  
set bList to {}
  
repeat with i from 1 to aaLen
    set aHoriList to {}
    
    
repeat with ii from 1 to selWidth
      set j1 to ii + (i – 1) * selWidth
      
set tmpCon to contents of item j1 of selList
      
      
set aClass to class of tmpCon
      
if aClass = number or aClass = integer or aClass = real then
        set tmpCon to tmpCon as integer
      end if
      
      
set the end of aHoriList to tmpCon
    end repeat
    
    
set the end of bList to aHoriList
  end repeat
  
  
return bList
  
end get2DListFromNumbersSelection

–プレーンテキストを指定フォルダ(POSIX path)にUTF-8で書き出し
on savePlainText(targFol, aString, aExt)
  set aString to current application’s NSString’s stringWithString:aString
  
  
set theName to (NSUUID’s UUID()’s UUIDString())
  
set thePath to NSString’s stringWithString:targFol
  
set thePath to (thePath’s stringByAppendingPathComponent:theName)’s stringByAppendingPathExtension:aExt
  
  
set aRes to aString’s writeToFile:thePath atomically:false encoding:(current application’s NSUTF8StringEncoding) |error|:(missing value)
  
  
if aRes as boolean = true then
    return thePath as string
  else
    return false
  end if
end savePlainText

–指定のPOSIX pathのファイルを削除
on deleteItemAt(aPosixPath)
  set theNSFileManager to NSFileManager’s defaultManager()
  
set theResult to theNSFileManager’s removeItemAtPath:(aPosixPath) |error|:(missing value)
  
return (theResult as integer = 1) as boolean
end deleteItemAt

★Click Here to Open This Script 

Posted in Markdown Text | Tagged 10.11savvy 10.12savvy 10.13savvy MacDown Numbers | Leave a comment

Keynote, Pages, Numbersがアップデート

Posted on 3月 28, 2018 by Takaaki Naganoya

Keynote、Pages、Numbersがアップデートしました。

 Keynote:v7.3.1 –> v8.0.0
 Pages:v6.3.1 –> v 7.0.0
 Numbers:v4.3.1 –> v5.0.0

NumbersのCSV書き出し機能が強化・変更されたとのことなので、これまでNumbersで複数のシートを含む書類をCSV書き出ししたときの挙動とやや変わる可能性があります。

AppleScript用語辞書については、Pagesにのみ変更があります。これまで用語辞書には「ePub」と書かれていましたが、「EPUB」に変更されました。

また、PagesのEPUB書き出し設定(export options)で「fixed layout」という項目(boolean)が増えました。

Posted in 未分類 | Tagged 10.12savvy 10.13savvy Keynote Numbers Pages | Leave a comment

Numbers書類からPDF書き出し v2

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:Numbers書類からPDF書き出し v2
— Created 2017-03-28 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set tmpPath to (path to desktop) as string
set aRes to exportNumbersDocToPDF(tmpPath)

–Pages書類からPDF書き出し
on exportNumbersDocToPDF(targFolderPath as string)
  tell application "Numbers"
    set dCount to count every document
    
if dCount = 0 then
      return false
    end if
    
set aPath to file of document 1
  end tell
  
  
set curPath to (current application’s NSString’s stringWithString:(POSIX path of aPath))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".pdf"
  
set outPath to (targFolderPath & curPath)
  
  
  
tell application "Numbers"
    set anOpt to {class:export options, image quality:Best}
    
export document 1 to file outPath as PDF with properties anOpt
  end tell
end exportNumbersDocToPDF

★Click Here to Open This Script 

Posted in file PDF | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

Numbers上のデータにもとづいてセル上で色プレビュー

Posted on 2月 25, 2018 by Takaaki Naganoya

–> Demo Movie

AppleScript名:Numbers上のデータにもとづいてセル上で色プレビュー

tell application "Numbers"
  tell front document
    tell active sheet
      tell table 1
        set hCount to header row count
        
set fCount to footer row count
        
        
set aRange to address of row of cell range
        
set bRange to items (1 + hCount) thru ((length of aRange) – fCount) of aRange
        
–> {2, 3, 4, 5, 6}
        
        
repeat with i in bRange
          tell row i
            set vList to value of cells 1 thru 3
            
if vList does not contain missing value then
              set bList to chengeColor255to65535(vList) of me
              
              
ignoring application responses
                tell cell 4
                  set background color to bList
                end tell
              end ignoring
              
            end if
          end tell
        end repeat
      end tell
    end tell
  end tell
end tell

on chengeColor255to65535(aColList)
  set aTmpList to {}
  
repeat with i in aColList
    set the end of aTmpList to i * 256
  end repeat
  
return aTmpList
end chengeColor255to65535

★Click Here to Open This Script 

Posted in Color | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

Numbers上で選択中の列のデータからIPアドレスを抽出(NSPredicate)

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:Numbers上で選択中の列のデータからIPアドレスを抽出(NSPredicate)
— Created 2018-01-03 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–http://piyocast.com/as/archives/5080

property NSPredicate : a reference to current application’s NSPredicate
property NSArray : a reference to current application’s NSArray

set aList to getSelectionDataFromNumbers() of me
set anArray to NSArray’s arrayWithArray:aList
set aPred to NSPredicate’s predicateWithFormat:"SELF MATCHES ’[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}’"
set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
–>  {​​​​​"XX.XX.XX.XXX", ​​​​​"XXX.XX.XXX.XXX", ​​​​​"XXX.XXX.XX.XXX", …..}

on getSelectionDataFromNumbers()
  tell application "Numbers"
    tell front document
      tell active sheet
        tell table 1
          set aList to value of every cell of selection range
        end tell
      end tell
    end tell
  end tell
  
return aList
end getSelectionDataFromNumbers

★Click Here to Open This Script 

Posted in regexp Text | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

Numbersから緯度経度情報を取得して地図にプロット v3(プログレスバー+セグメント)

Posted on 2月 6, 2018 by Takaaki Naganoya

Numbers書類上に記載した緯度経度情報を取得して、動的に作成したウィンドウの地図上にプロット表示するAppleScriptです。

実行には、「場所名」「緯度」「経度」がワンセットとなったNumbers書類をNumbersでオープンした状態で、本AppleScriptをスクリプトエディタ上でオープンし、Control-Command-Rを実行します。

ひととおり地図上の指定位置へのピンの作成が終わると、普通に地図アプリなどと同様に拡大や縮小、3D表示、マップ表示、航空写真表示などを切り替えてブラウズすることが可能です。

–> Demo Movie

AppleScript名:Numbersから緯度経度情報を取得して地図にプロット v3(プログレスバー+セグメント)
— Created 2017-12-20 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "MapKit"
use framework "CoreLocation"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#BridgePlus

property NSView : a reference to current application’s NSView
property NSScreen : a reference to current application’s NSScreen
property NSButton : a reference to current application’s NSButton
property SMSForder : a reference to current application’s SMSForder
property NSWindow : a reference to current application’s NSWindow
property MKMapView : a reference to current application’s MKMapView
property MKMapTypeHybrid : a reference to current application’s MKMapTypeHybrid
property MKPointAnnotation : a reference to current application’s MKPointAnnotation
property MKMapTypeSatellite : a reference to current application’s MKMapTypeSatellite
property NSWindowController : a reference to current application’s NSWindowController
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property MKMapTypeStandard : a reference to current application’s MKMapTypeStandard
property NSSegmentedControl : a reference to current application’s NSSegmentedControl
property NSNormalWindowLevel : a reference to current application’s NSNormalWindowLevel
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered
property NSSegmentStyleTexturedRounded : a reference to current application’s NSSegmentStyleTexturedRounded

property windisp : false
property selSeg : 0
property aMapView : missing value

–データを取得する
set locList to getDataFromNumbersDoc() of me

set aWidth to 800
set aHeight to 600

set segTitleList to {"Map", "Satellite", "Satellite + Map"}
set tableTitle to retCurNumbersDocsTableName() of me
dispMapView(aWidth, aHeight, tableTitle, "OK", 180, locList, segTitleList) of me

on dispMapView(aWidth as integer, aHeight as integer, aTitle as text, aButtonMSG as text, timeOutSecs as number, locList, segTitleList)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    error "This script must be run from the main thread (Command-Control-R in Script Editor)."
  end if
  
  
set selSeg to 0
  
set (my windisp) to true
  
  
  
  
–NSViewをつくる
  
set aNSView to NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aHeight, aWidth))
  
  
aNSView’s setNeedsDisplay:true
  
  
set aWin to makeWinWithView(aNSView, aWidth, aHeight, aTitle, 1.0)
  
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
wController’s showWindow:me
  
aWin’s makeKeyAndOrderFront:me –Windowを表示状態に
  
  
  
–Progress Barをつくる
  
set aPBar to current application’s NSProgressIndicator’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 40, aWidth, 40))
  
aPBar’s setMaxValue:(length of locList)
  
aPBar’s setMinValue:1
  
aPBar’s setIndeterminate:false
  
aPBar’s setControlSize:(current application’s NSProgressIndicatorPreferredLargeThickness)
  
aPBar’s setDoubleValue:(1.0 as real)
  
aNSView’s addSubview:aPBar
  
  
  
–MKMapViewをつくる
  
set aMapView to MKMapView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 40, aWidth, aHeight – 40))
  
aMapView’s setMapType:(current application’s MKMapTypeStandard)
  
  
aMapView’s setZoomEnabled:true
  
aMapView’s setScrollEnabled:true
  
aMapView’s setPitchEnabled:true
  
aMapView’s setRotateEnabled:false
  
aMapView’s setShowsCompass:true
  
aMapView’s setShowsZoomControls:true
  
aMapView’s setShowsScale:true
  
aMapView’s setShowsUserLocation:true
  
aMapView’s setDelegate:me
  
  
  
–MapにPinを追加
  
set aCount to 1
  
repeat with i in locList
    (aPBar’s setDoubleValue:(aCount as real)) –Update Progress Bar
    
    
copy i to {tmpAdr, tmpLat, tmpLong}
    
    
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
    
set anAnnotation to MKPointAnnotation’s alloc()’s init()
    (
anAnnotation’s setCoordinate:aLocation)
    (
anAnnotation’s setTitle:tmpAdr)
    (
aMapView’s addAnnotation:anAnnotation)
    
    
set aCount to aCount + 1
  end repeat
  
  
aPBar’s removeFromSuperview() –Remove Progress Bar
  
  
–Segmented Controlをつくる
  
set aSeg to makeSegmentedControl(segTitleList, aWidth, aHeight) of me
  
aNSView’s addSubview:aSeg
  
  
–MapViewをWindow上に表示  
  
copy middle item of locList to {tmpAdr, tmpLat, tmpLong}
  
set aLocation to current application’s CLLocationCoordinate2DMake(tmpLat, tmpLong)
  
aMapView’s setCenterCoordinate:aLocation zoomLevel:7 animated:false
  
aNSView’s addSubview:aMapView
  
  
–Buttonをつくる
  
set bButton to (NSButton’s alloc()’s initWithFrame:(current application’s NSMakeRect(aWidth – 100, 0, 100, 40)))
  
bButton’s setTitle:aButtonMSG
  
bButton’s setButtonType:(current application’s NSMomentaryLightButton)
  
bButton’s setBezelStyle:(current application’s NSRoundedBezelStyle)
  
bButton’s setKeyEquivalent:(return)
  
bButton’s setTarget:me
  
bButton’s setAction:("clicked:")
  
aNSView’s addSubview:bButton
  
  
aWin’s makeFirstResponder:aMapView
  
  
set aCount to timeOutSecs * 10 –timeout seconds * 10
  
repeat aCount times
    if (my windisp) = false then
      exit repeat
    end if
    
delay 0.1
  end repeat
  
  
my closeWin:aWin
  
end dispMapView

–Button Clicked Event Handler
on clicked:aSender
  set (my windisp) to false
end clicked:

–make Window for Input
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle, alphaV)
  set aScreen to NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
set aBacking to NSTitledWindowMask
  
set aDefer to NSBackingStoreBuffered
  
  
— Window
  
set aWin to NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(NSNormalWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setAlphaValue:alphaV –append
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
aWin’s makeKeyAndOrderFront:(me)
  
  
— Set Custom View
  
aWin’s setContentView:aView
  
  
return aWin
end makeWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.02
  end repeat
  
aWindow’s |close|()
end closeWin:

on makeSegmentedControl(titleList, aWidth, aHeight)
  set aLen to length of titleList
  
  
set aSeg to NSSegmentedControl’s alloc()’s init()
  
aSeg’s setSegmentCount:aLen
  
  
set aCount to 0
  
repeat with i in titleList
    set j to contents of i
    (
aSeg’s setLabel:j forSegment:aCount)
    
set aCount to aCount + 1
  end repeat
  
  
aSeg’s setTranslatesAutoresizingMaskIntoConstraints:false
  
aSeg’s setSegmentStyle:(NSSegmentStyleTexturedRounded)
  
aSeg’s setFrame:(current application’s NSMakeRect(10, 5, 260, 30))
  
aSeg’s setTrackingMode:0
  
aSeg’s setTarget:me
  
aSeg’s setAction:"clickedSeg:"
  
aSeg’s setSelectedSegment:0
  
  
return aSeg
end makeSegmentedControl

–Numbersでオープン中の書類の選択中のシートの表1からデータを取得して2D Listに
on getDataFromNumbersDoc()
  
  
load framework
  
  
tell application "Numbers"
    if (count every document) = 0 then return false
    
    
tell front document
      if (count every sheet) = 0 then return false
      
      
tell active sheet
        tell table 1
          set colCount to column count
          
set rowCount to row count
          
set headerCount to header row count
          
set footerCount to footer row count
          
          
set dList to value of every cell of cell range
        end tell
      end tell
      
    end tell
  end tell
  
  
–Convert 1D List to 2D List
  
set bList to (SMSForder’s subarraysFrom:dList groupedBy:colCount |error|:(missing value)) as list
  
set sItem to 1 + headerCount
  
set eItem to rowCount – footerCount
  
set cList to items sItem thru eItem of bList
  
  
return cList
  
end getDataFromNumbersDoc

on retCurNumbersDocsTableName()
  tell application "Numbers"
    tell front document
      tell active sheet
        tell table 1
          return name
        end tell
      end tell
    end tell
  end tell
end retCurNumbersDocsTableName

on clickedSeg:aSender
  set aSel to aSender’s selectedSegment()
  
set selSeg to (aSel + 1)
  
set mapList to {MKMapTypeStandard, MKMapTypeSatellite, MKMapTypeHybrid}
  
set curMap to contents of item selSeg of mapList
  
aMapView’s setMapType:(curMap)
end clickedSeg:

★Click Here to Open This Script 

Posted in Require Control-Command-R to run | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

Numbersでセルのカラム幅を自動調整 v2

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:Numbersでセルのカラム幅を自動調整 v2
— Created 2018-1-11 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–http://piyocast.com/as/archives/5116

tell application "Numbers"
  tell front document
    tell sheet 1
      set tCount to count every table
      
if tCount = 0 then return
      
      
tell table 1
        set tableWidth to width
        
        
set cCount to count every column
        
set cWidth to width of every column
        
set aWidth to width –table width
        
        
set aveWidth to (aWidth – (first item of cWidth)) / (cCount – 1)
        
        
tell columns 2 thru cCount
          set width to aveWidth
        end tell
        
        
set wList to width of every column
      end tell
      
      
if tCount = 1 then return
      
      
set origCols to count every column of table 1
      
repeat with i from 2 to tCount
        if origCols is not equal to (count every column of table i) then
          display notification "Numbers: Column number is different in Table #" & (i as string)
          
return
        end if
      end repeat
      
      
repeat with i from 2 to tCount
        
        
tell table i
          set width to tableWidth
        end tell
        
        
set aCount to 1
        
        
tell table i
          repeat with ii from 1 to cCount
            tell column ii
              set width to (contents of item ii of wList)
            end tell
          end repeat
        end tell
        
      end repeat
    end tell
  end tell
end tell

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

Numbers書類からPDF書き出し v2

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:Numbers書類からPDF書き出し v2
— Created 2017-03-28 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set tmpPath to (path to desktop) as string
set aRes to exportNumbersDocToPDF(tmpPath)

–Pages書類からPDF書き出し
on exportNumbersDocToPDF(targFolderPath as string)
  tell application "Numbers"
    set dCount to count every document
    
if dCount = 0 then
      return false
    end if
    
set aPath to file of document 1
  end tell
  
  
set curPath to (current application’s NSString’s stringWithString:(POSIX path of aPath))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".pdf"
  
set outPath to (targFolderPath & curPath)
  
  
  
tell application "Numbers"
    set anOpt to {class:export options, image quality:Best}
    
export document 1 to file outPath as PDF with properties anOpt
  end tell
end exportNumbersDocToPDF

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

Post navigation

  • Newer posts

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • CotEditorで2つの書類の行単位での差分検出
  • macOS 15, Sequoia
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • AppleScriptによる並列処理
  • Cocoa Scripting Course 続刊計画
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • Keynote/Pagesで選択中の表カラムの幅を均等割
  • Keynote、Pages、Numbers Ver.14.0が登場
  • macOS 15 リモートApple Eventsにバグ?
  • デフォルトインストールされたフォント名を取得するAppleScript

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1392) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (190) 14.0savvy (142) 15.0savvy (120) CotEditor (66) Finder (51) iTunes (19) Keynote (116) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (76) Pages (54) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • diff
  • drive
  • Droplet
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2025年3月
  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC