Is it possible to format the colour of parts of my git branch name inside the prompt? - regex

In my .zshrc file I have the following lines that parse my current git branch and display it in the terminal, the .zshrc file looks like this:
# Load version control information
autoload -Uz vcs_info
precmd() { vcs_info }
# Set up the prompt (with git branch name)
setopt PROMPT_SUBST
PROMPT='%n in ${PWD/#$HOME/~} ${vcs_info_msg_0_} > '
# Format the vcs_info_msg_0_ variable
zstyle ':vcs_info:git:*' formats '(%b)'
So my terminal ends up looking like this:
me in ~/repos/myrepo (feat/MYISSUE-123/fix-the-broken-stuff) >
I would like to modify the script above so MYISSUE-123 has a different colour to the rest of the branch name.
How can I do that?

Try this ... change precmd to:
precmd() {
vcs_info
psvar=(${(s:/:)vcs_info_msg_0_})
# in case there are more than three components:
psvar[3]=${(j:/:)psvar[3,-1]}
}
Make sure precmd() is being called prior to each prompt display by adding it to the hook:
autoload -Uz add-zsh-hook
add-zsh-hook precmd precmd
And change PROMPT to:
PROMPT='%n in ${PWD/#$HOME/~} %1v/%F{red}%2v%f/%3v > '
There are some notes about psvar in this answer: https://stackoverflow.com/a/64094551/9307265.
The (s) and (j) parameter expansion flags are documented in the zshexpn man page.
Please let me know if there are any issues.

Related

Applscript- Use List to Select Specifc Photoshop Action

Ive been trying to write a Applescript using the bits of knowledge I have
current stumbling blocks are
-getting the returned list selection to run the photoshop action
-how to repeat the action on multiple images.
Aim
I want to use a list to extract different cobinations of files (with set naming conventions) from a defined folder,
I would then like that same list selection to choose between mutliple photoshop actions and run the extracted file combination through that action.
Stage 1
-on running open a list
-List to conatain a set of names relating to photoshop actions
-select from list
Stage 2
-choose folder with source images (always 14 images always with the same last 9 characters _0000.tif to _0013.tif)
-Choose a save folder
Stage 3
-dependant on original list selection, automatically gather files from source image folder and run them through a coresponsing photoshop action
e.g If "Action 1" selceted from List select image "_0001.tiff & _0010.tif" from source folder and do photoshop action "Action1"
Stage4
save in chosen "save folder"
The Script So Far
--Stage 1--
set PhotoshopActionList to {"Action1", "Action2", "Action3", "Action4", "Action5"}
set ActionrequiredAnswer to choose from list PhotoshopActionList with title "Actions Picker" with prompt "Choose Action?"
if ActionrequiredAnswer is false then
error number -128 (* user cancelled *)
else
set ActionrequiredAnswer to ActionrequiredAnswer's item 1 (* extract choice from list*)
end if
end run
--Stage 2--
property SourceFolder : missing value
property destinationFolder : missing value
if SourceFolder = missing value then
set SourceFolder to (choose folder with prompt "Choose Base Images:")
set destinationFolder to (choose folder with prompt "Choose Save Location:")
else
tell application "Finder"
set theFolders to every item of entire contents of SourceFolder as list
repeat with thisFolder in theFolders
make new alias file at destinationFolder to thisFolder
end repeat
end tell
end if
--Stage 3--
tell application "Finder"
set filesList to {files of entire contents of SourceFolder contains "_001", "_002", "003"} as alias list
end tell
tell application "Adobe Photoshop"
repeat with aFile in filesList
open aFile
do action "Action1" from "Actionsfolder"
end tell
--Stage 4--
save currentDocument in folder destinationFolder as JPEG
I did not found a way to select entire contents of folder AND filter extension 'tif', 'tiff',.. AND filter files whose name contains your patterns.
As work around, I did 2 steps:
1) select in entire contents only files with target extensions.
2)I loop through these files to check is file name contains the target pattern. This is done by routine FnameOK.
You need to complete the script bellow with your Photoshop action and the 'save as':
set PhotoshopActionList to {"Action1", "Action2", "Action3", "Action4", "Action5"}
set ListOK to {"_001", "_002", "003"}
set ActionRequiredAnswer to choose from list PhotoshopActionList with title "Actions Picker" with prompt "Choose Action?"
if ActionRequiredAnswer is false then
error number -128 (* user cancelled *)
else
set ActionRequiredAnswer to ActionRequiredAnswer's item 1 (* extract choice from list*)
end if
set SourceFolder to (choose folder with prompt "Choose Base Images:")
set DestinationFolder to (choose folder with prompt "Choose Save Location:")
tell application "Finder" to set filesList to files of entire contents of SourceFolder whose name extension is in {"tiff", "tif"}
repeat with aFile in filesList
tell application "Finder" to set NameF to name of aFile
if FNameOK(NameF, ListOK) then -- the file name contains a valid pattern, then process the file
tell application "Adobe Photoshop"
open (aFile as alias)
-- perform action selected
-- save as to Destination Folder
end tell
end if
end repeat
on FNameOK(Local_Name, LocalList) -- check if the file name contains an element of the list
set LocalCheck to false
repeat with OneItem in LocalList
if Local_Name contains OneItem then
return true
end if
end repeat
return false
end FNameOK

Does webstorm have some shortcut for console.log or console.info?

Just tired of typing console.log again and again, and do not find a way like Sysout + Control + Space in Eclipse will create System.out.println().
There's a predefined Postfix template that allows you to type .log after a JavaScript expression or string and hit Tab to transform it to console.log().
You can also create a Live template (see Preferences | Editor | Live templates) that would expand into a code snippet once you type the selected abbreviation and hit Tab.
Update: there's now also a plugin that allows you to add console.log with a shortcut: https://plugins.jetbrains.com/plugin/10986-console-log
Yes it does,
<anything>.log and press Tab key. This will result in console.log(<anything>);
ie,
<anything>.log + Tab => console.log(<anything>);
eg1: variable
let my_var = 'Hello, World!';
my_var.log + Tab => console.log(my_var);
eg2: string
'hello'.log + Tab => console.log('hello');
eg3: string and variable
'hello', my_var.log + Tab => console.log('hello', my_var);
[UPDATE 2020]
Typing log + Enter autocompletes to console.log()
I made my own template that seems to work.
It may be useful for somebody.
Abbreviation: ll
Template text:
console.log('$NAME$ ', $VALUE$);
$END$
Variables: (just select the given field values by clicking drop down box)
NAME - jsDefineParameter()
VALUE - jsSuggestVariableName
I'm including what I find to be the most efficient, which I added via live templates -> javascript -> applicable to "Everything". Hopefully someone finds it useful.
console.log('L$LINE$ $MYSTRING$ ===', $MYVAR$);$END$
What it does:
When I type cl and press tab, it creates the log and the first thing you type fills both MYSTRING and MYVAR variables. If you tab again, it selects MYVAR where you can rewrite/delete as desired. The third time you hit tab will take you to the end of the line at $END.
This snippet also prints the line number like L123 but you can easily remove that if it isn't helpful because obviously most browsers show line number anyway.
You also have to set the variables' behaviour as seen in the image below:
Edit variables setup
use Macros!
https://www.jetbrains.com/help/webstorm/using-macros-in-the-editor.html
I recorded a macro that takes the name my cursor is on and create
console.log("#### name = ", name);
on the next line.
and assigned a keyboard shortcut to it :)
super easy, and couldn't get Live Template to get the same result with 1 action.
to create a new macro: Edit -> Macros -> Start Macro Recording. then record your next moves and create the desired result.
this is mine:
This is my solution, it somewhat mimics a turbo-console approach and gives you certain freedoms to build on it.
Step 1: Go to Editor > General > Postfix Completion;
Step 2: Click on JavaScript, click the + button, select JavaScript and TypeScript;
Step 3: In the Key input, type a alias for your command, I choose 'cl' for mine;
Step 4: In the 'Minimum language level' select your desired preference, I choose ECMAScript 6+;
Step 5: In the bellow text area, add your logic, for me it is console.log('$EXPR$', $EXPR$, '$END$');
Step 6: Customize however you like.
So what does all of this do?
Lets consider the following:
const willNeedToBeLogged = 'some value you want to check';
All you need to do for a console long is type
willNeedToBeLogged.cl + press (Tab, Enter or Spance)
And you will get this
console.log('willNeedToBeLogged', willNeedToBeLogged, '');
With your cursor being on the $END$ variable, where you could write, a line, or anything you like.
Have fun!
I made a custom template. This can help you.
Abbreviation: clog
Template code:
console.log("\n\n--------------------------------");
console.log($END$);
console.log("--------------------------------\n\n");
Simplest live template text:
console.log($END$);
Maybe it is a recent addition but you can write log and hit tab and console.log() will appear with the caret in between the braces.
The answer from Ekaterina Prigara (https://stackoverflow.com/a/32975087/5653914) was very useful to me but if you want to log a string like "Test" this method is quicker.
Try a logit plugin. It provides the next logging pattern by default:
const data = 'data';
console.log('-> data', data);
You can configure it.
Try Dot Log (vscode extension), It can automatically transfer aaa.log to console.log('aaa', aaa )

Excel VBA script or macro for linking to new Excel document using a template in it

I have a small family-operated shop and, in the process of speeding things up and/or automating them, I need help on the following matter (will try to explain as well as possible, since I am at a novice level on this kind of stuff.)
So, in my shop we offer a certain service (taking specific measurements of body dimensions along with weight/sugar levels etc etc). I have created an .xlsx document that contains all required fields and saved it as a template for future use. What I need to do is this:
I want to have a "master" Excel file with the names of our customers. From there, each name when clicked should open a new Excel file, using the aforementioned template, which would eventually be saved as each customer's record. I've tried a script for linking to the template but opening it as a new file (with the template in it) but, the problem is that each time I click on the name on the master file it opens a new document altogether, while I need it to open a new document named after the name in the original cell, with the template in it. As far as I can think, this is the best "automation" I can accomplish. Is it plausible? If so, how can I do it?
edit: this is the code, as i found it elsewhere:
'File:
' OfficeTemplate.vbs
'
'Problem:
' A hyperlink from an Office application to an Office template opens the template,
' instead of creating a new file.
' The proposed solution
' support.microsoft.com/kb/278627
' did not work.
'
'Solution:
' Create a hyperlink to a VBS file that starts the process.
'
'Instructions:
' Copy this VBScript into the same directory of your template.
' Rename it so that the VBS file name has the name of the template file in front.
' Example:
' Template name: test.dotx
' VBScript name: test.dotx.vbs
' Create the hyperlink to the VBS file.
Set fso = CreateObject("Scripting.FileSystemObject")
'Get the name of the template
OurName = fso.GetBaseName(WScript.ScriptName)
'Find all files in our directory
For Each File In fso.GetFolder(fso.GetParentFolderName(WScript.ScriptFullName)).Files
'Did we found the template?
If StrComp(OurName, File.Name, vbTextCompare) = 0 Then
'Invoke the default verb
CreateObject("Shell.Application").Namespace(0).ParseName(File.Path).InvokeVerb
'Wait a second to let the application start
WScript.Sleep 1000
'Done
Exit For
End If
Next
this is my template:
http://i215.photobucket.com/albums/cc55/psyclone_tread/templ.jpg
this is the master file, just a column with names and one with phone numbers, i want the names to link to each customer's individual file.
http://i215.photobucket.com/albums/cc55/psyclone_tread/master.jpg
Let me give you a very simple answer for this. Use VBA instead of VBS, and write code inside your master excel as per following illustration.
When you click on the cell with the name,
If File.Exists ("YourFolder\" & ActiveCell.Value & ".xlsx") Then
Workbooks.Open("YourFolder\" & ActiveCell.Value & ".xlsx")
Else
WorkBooks.Add(YourTemplate)
Fill in the details already present in the master sheet to new workbook if needed
NewWorkbook.Save("YourFolder\" & ActiveCell.Value & ".xlsx")
End If

How to create a C/C++ program that generates an XML and runs a DOS command afterwards?

I need to come up with a program that generates an xml file like this:
<?xml version="1.0"?>
<xc:XmlCache xmlns:xc="XmlCache" xc:action="Update">
<xc:XmlCacheArea xc:target="AllSubFields" xc:value="MarketParameters">
<mp:nickName xmlns:mp="mx.MarketParameters" xc:value="MDS">
<mp:date xc:value="TODAY">
<fx:forex xmlns:fx="mx.MarketParameters.Forex">
<fxsp:spot xmlns:fxsp="mx.MarketParameters.Forex.Spot">
<fxsp:pair type="Fields" value="USD/BRL">
<mp:ask xc:type="Field" xc:keyFormat="N">1.890</mp:ask>
<mp:bid xc:type="Field" xc:keyFormat="N">1.800</mp:bid>
</fxsp:pair>
</fxsp:spot>
</fx:forex>
</mp:date>
</mp:nickName>
</xc:XmlCacheArea>
</xc:XmlCache>
with the values in the nodes mp:ask and mp:bid randomly generated but between two predefined values (1.65 and 1.99).
After the xml is generated in the same directory of the program, the program should run a command in the cmd command line that states:
cachetool.bat -i cacheBody.xml -u REALTIME
where cachetool.bat is an already done bash script that cannot be changed and that is also place in the same directory of the program, and where cacheBody.xml is that previously generated xml.
The trick here is that this should run repeatedly overwriting the xml file with new values each time and then running the command again calling the xml with the new values.
There should be a way to easy interrupt the loop, but besides that, this should run indefinitely.
Note: there isn't a strict rule to use c or c++, if it isn't feasible in these languages or if there other ways to do it easily, please feel free to suggest. My initial proposal is in these languages because these are the two that I'm a little used to deal with.
I'm learning how to use javascript for Windows local scripting, so here's a solution in javascript.
It looks like you don't really need to generate the XML dynamically, but rather the XML structure is static and only a couple data fields are dynamic. With that in mind, I approached the problem with search-and-replace using a template file.
The template file (template.xml) contains xml content with some variables to search and replace. The format variable format is $RANDOM_X_Y$, where X and Y are the lower and upper bounds for the random number. To help the example, I generated the ask and bid prices slightly differently in the template file:
<?xml version="1.0"?>
<xc:XmlCache xmlns:xc="XmlCache" xc:action="Update">
<xc:XmlCacheArea xc:target="AllSubFields" xc:value="MarketParameters">
<mp:nickName xmlns:mp="mx.MarketParameters" xc:value="MDS">
<mp:date xc:value="TODAY">
<fx:forex xmlns:fx="mx.MarketParameters.Forex">
<fxsp:spot xmlns:fxsp="mx.MarketParameters.Forex.Spot">
<fxsp:pair type="Fields" value="USD/BRL">
<mp:ask xc:type="Field" xc:keyFormat="N">1.$RANDOM_65_99$0</mp:ask>
<mp:bid xc:type="Field" xc:keyFormat="N">1.$RANDOM_650_990$</mp:bid>
</fxsp:pair>
</fxsp:spot>
</fx:forex>
</mp:date>
</mp:nickName>
</xc:XmlCacheArea>
</xc:XmlCache>
The javascript file is called replace.js. All versions of Windows should be able to execute it natively without installing any extra components.
if( WScript.Arguments.Count() != 2 || WScript.Arguments.Item(0) == WScript.Arguments.Item(1) )
{
WScript.Echo("Usage: replace.js <template> <output filename>");
WScript.Quit();
}
var template_filename = WScript.Arguments.Item(0);
var output_filename = WScript.Arguments.Item(1);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1;
var file, file_contents, lower, upper;
var var_regex = /\$RANDOM_(\d+)_(\d+)\$/g;
if( fso.FileExists(template_filename) )
{
file = fso.OpenTextFile(template_filename, ForReading, false);
file_contents = file.ReadAll().replace(var_regex,
function(str, lower, upper) {
return Math.floor(
Math.random() * (+upper - +lower + 1)) + +lower;
});
file.Close();
file = fso.CreateTextFile(output_filename, true);
file.Write(file_contents);
file.Close();
}
else
{
WScript.Echo("Template does not exist: " + template_filename);
}
Now to run your scripts indefinitely, just create a batch file called run.bat or whatever and have it run the javascript and batch files in a loop. CTRL-C will exit the script.
#echo off
echo Starting. Press CTRL-C to exit.
:loop
replace.js template.xml cacheBody.xml
cachetool.bat -i cacheBody.xml -u REALTIME
goto loop
Well, to create the random value, you can use the rand() function, and just scale it so it's between the two values you want.
To call the command line, try system("cachetool.bat -i cacheBody.xml -u REALTIME");
And for the xml, if it's all the same except for the numbers, you can just hardcode it. If not, you'll need an xml library.

Get full directory contents with AppleScript

I need to get the entire (visible) contents of a folder and its subfolders as a list. Is this possible?
see how easy this can be
tell application "Finder"
set file_list to entire contents of (choose folder with prompt "Please select directory.")
end tell
if you want a list of file names then you could do this
tell application "Finder"
set file_list to name of every file of entire contents of (choose folder with prompt "Please select directory.")
end tell
Yes, entire contents does exactly what you say -- but it easily chokes on
large folders, and takes forever. It's OK for
small things, like extracting all the files of one kind out of a folder you
know will only contain a small number of files.
The recursive method also works well -- but it's using "list folder", and
the dictionary listing for it says it's deprecated and we shouldn't use it
any more.
I'm sure there is a shell command that can do this faster, but here is one way in pure Applescript that gives you total control over formatting what info you would like displayed.
property kFileList : {}
tell application "Finder"
set source_folder to choose folder with prompt "Please select directory."
my createList(source_folder)
end tell
on createList(item_list)
set the the_items to list folder item_list without invisibles
set item_list to item_list as string
repeat with i from 1 to number of items in the the_items
set the_item to item i of the the_items
set the_item to (item_list & the_item) as alias
set this_info to info for the_item
set file_name to name of this_info
set end of kFileList to file_name
if folder of this_info is true then
my createList(the_item)
end if
end repeat
end createList
On a side note, there are also a number file listing applications that can do this faster than Applescript.
UPDATE: As a result of this discussion, here is the function again, but this time using the updated API. This could probably could use some cleaning up, but it works cataloging my Desktop handily enough (and that's a deep, deep folder for me):
property kFileList : {}
tell application "Finder"
set source_folder to choose folder with prompt "Please select directory."
my createList(source_folder)
end tell
return kFileList
on createList(mSource_folder)
set item_list to ""
tell application "System Events"
set item_list to get the name of every disk item of mSource_folder
end tell
set item_count to (get count of items in item_list)
repeat with i from 1 to item_count
set the_properties to ""
set the_item to item i of the item_list
set the_item to ((mSource_folder & the_item) as string) as alias
tell application "System Events"
set file_info to get info for the_item
end tell
if visible of file_info is true then
set file_name to displayed name of file_info
set end of kFileList to file_name
if folder of file_info is true then
my createList(the_item)
end if
end if
end repeat
end createList
Wow this is quite late but I checked and it works.
tell application "Finder" to set folder_root to (choose folder with prompt "Please select directory.")
set fl to {}
dump_folder(folder_root)
on dump_folder(f)
global fl
tell application "System Events" to set end of fl to (get the POSIX path of f)
tell application "Finder" to set nfl to (the items of the contents of f)
repeat with nf in nfl
dump_folder(nf as alias)
end repeat
end dump_folder
fl