Friday, December 21, 2018

Github: retrieve individual files from Github in a Dockerfile

FROM alpine:edge

ARG githubtoken=1852...

RUN apk add --no-cache curl wget

RUN curl -o /var/mbqt/lib/MBQT/Bootstrap.pm -H "Authorization: token $githubtoken" -H 'Accept: application/vnd.github.v3.raw' -L https://api.github.com/repos///contents/perl/lib/MBQT/Bootstrap.pm

Monday, December 17, 2018

PostgreSQL: output from multi-line pl/pgsql from psql from perl

#!/usr/bin/perl

my $cmd = "psql -Xq --set ON_ERROR_STOP=on --dbname crmmbqt <<'EOS'
";
$cmd .= <<'END';
do
$$
begin
    raise notice '%', pg_is_in_recovery();
end
$$
END
$cmd .= 'EOS
';

print `$cmd`;

PostgreSQL: see the age of locks

Source: https://wiki.postgresql.org/wiki/Lock_Monitoring
select a.pid, c.relname, l.transactionid, l.mode, l.granted, a.usename, a.query, a.query_start, age(now(), a.query_start) as "age" from pg_stat_activity a join pg_locks l on l.pid = a.pid join pg_class c on c.oid = l.relation order by a.query_start

Thursday, December 13, 2018

macOS: match PC keyboard with apple keyboard

In order to match the order of the modifier keys between both types of keyboards, we need to reverse the Option key (⌥) and the Command key (⌘) on the PC keyboard. This can be done in Settings | Keyboard.
This way, we can have, Ctrl, Windows, Alt
match ^, ⌥, ⌘

Wednesday, December 12, 2018

Docker: difference between container and image

Source: In Docker, what's the difference between a container and an image?
See explanation from cbare: "Images are frozen immutable snapshots of live containers..."

Wednesday, November 21, 2018

GitHub: search code

In order to search code in all the repo of a user, use e.g. OPERATOR_CONNECTION user:AirVantage

Thursday, November 15, 2018

Perl: shortest slurp

Source: Perl Slurp-Eaze
my $str = 'my '.do { local(@ARGV, $/) = $pl_filename; <> };

Sunday, November 11, 2018

macOS: installing High Sierra on a new combo

GigaByte Z370 HD3P - i7-8700 Coffee Lake - iGPU HD 630 - High Sierra

macOS: from 10.14 to 10.14.1

Steps:
  • Update Clover through Clover Configurator: pick custom install and check (default if already done once)
    • AptioMemoryFix-64,
    • ApfsDriverLoader-64 and
    • PartitionDxe-64
  • Update kexts in /Volumes/EFI/EFI/CLOVER/kexts/Other
  • Update macOS to 10.14.1 via Software Update
    and leave it reboot by default
  • As my config. was booting, but got stuck, not starting the macOS GUI, I changed the Clover options at boot time so as to replace iMac 17,1, which was working for 10.14, with iMac 18,3. This allowed to start the GUI but the display was flickering like hell. Multiple trials later, I found out iMac 14,2 was solving the flickering issue.
  • Follow [Guide] Creating a Custom SSDT for USBInjectAll.kext so as to solve USB3 ports issues.
    At first, I thought about following Intel FB-Patcher v1.6.3 | USB Port Patching, because less complicated, but I found out the FB-Patcher is not as reliable as the RehabMan's method for detecting ports.
    At least, FB-Patcher told me I was using a "USB controller - XHC - 8086:A2AF". So,
    • Removed all legacy High Sierra ACPI changes mentioned in my GigaByte Z370 HD3P - i7-8700 Coffee Lake - iGPU HD 630 - High Sierra page, that were useless in 10.14, i.e. Change HDAS to HDEF, Change HECI to IMEI and Change GFX0 to IGPU.
    • Copied USBInjectAll.kext into /Volumes/EFI/EFI/CLOVER/kexts/Other.
    • Copied XHCI-unsupported.kext (from USBInjectAll ZIP) into /Volumes/EFI/EFI/CLOVER/kexts/Other, like mentioned in OS-X-USB-Inject-All for a 8086:a2af USB controller.
    • EHCx renames and port limit patches, like in config_patches.plist.
    • 1st reboot with -uia_exclude_ss option at Clover boot
    • Test of HS ports, validating HS03, HS04, HS07,HS08,HS09,HS10,HS11,HS12,HS13,HS14 as USB3 ports.
    • 2nd reboot with uia_exclude=HS01,...,HS09,HS11,...,HS14,USR1 because proposed option (-uia_exclude_ss uia_include=HS10) was not keeping HS10 (my Dell screen USB hub where my keyboard and mouse are plugged in) active.
    • Test of SS ports, validating SS03, SS04, SS07, SS08 as USB3 ports.
    • Updated SSDT-UIAC-ALL.dsl so as to remove everything not concerning 8086_a2af, like in
      // SSDT-UIAC-ALL.dsl
      //
      // This SSDT can be used as a template to build your own
      // customization for USBInjectAll.kext.
      //
      // This SSDT contains all ports, so using it is the same as without
      // a custom SSDT.  Delete ports that are not connected or ports you
      // do not need.
      //
      // Change the UsbConnector or portType as needed to match your
      // actual USB configuration.
      //
      // Note:
      // portType=0 seems to indicate normal external USB2 port (as seen in MacBookPro8,1)
      // portType=2 seems to indicate "internal device" (as seen in MacBookPro8,1)
      // portType=4 is used by MacBookPro8,3 (reason/purpose unknown)
      //
      
      DefinitionBlock ("", "SSDT", 2, "hack", "_UIAC", 0)
      {
          Device(UIAC)
          {
              Name(_HID, "UIA00000")
      
              Name(RMCF, Package()
              {
                  "8086_a2af", Package()
                  {
                      "port-count", Buffer() { 26, 0, 0, 0 },
                      "ports", Package()
                      {
                          "HS03", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 3, 0, 0, 0 },
                          },
                          "HS04", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 4, 0, 0, 0 },
                          },
                          "HS07", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 7, 0, 0, 0 },
                          },
                          "HS08", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 8, 0, 0, 0 },
                          },
                          "HS09", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 9, 0, 0, 0 },
                          },
                          "HS10", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 10, 0, 0, 0 },
                          },
                          "HS11", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 11, 0, 0, 0 },
                          },
                          "HS12", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 12, 0, 0, 0 },
                          },
                          "HS13", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 13, 0, 0, 0 },
                          },
                          "HS14", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 14, 0, 0, 0 },
                          },
                          "SS03", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 19, 0, 0, 0 },
                          },
                          "SS04", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 20, 0, 0, 0 },
                          },
                          "SS07", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 23, 0, 0, 0 },
                          },
                          "SS08", Package()
                          {
                              "UsbConnector", 3,
                              "port", Buffer() { 24, 0, 0, 0 },
                          },
                      },
                  },
              })
          }
      }
      //EOF
      
    • Used MaciAS so as to compile SSDT-UIAC-ALL.dsl into SSDT-UIAC-ALL.aml by using File | Save As, format: ACPI Machine Language Binary.
    • Copied SSDT-UIAC-ALL.aml into /Volumes/EFI/EFI/CLOVER/ACPI/patched
    • Rebooted.

Monday, November 5, 2018

Clojure: load deps.edn aliases extra-deps from Cider

Let's say this is deps.edn:
{:paths ["src" "resources"]
 :deps {com.datomic/ion {:mvn/version "0.9.26"}
        org.clojure/data.json {:mvn/version "0.2.6"}
        org.clojure/clojure {:mvn/version "1.9.0"}}
 :mvn/repos {"datomic-cloud" {:url "s3://datomic-releases-1fc2183a/maven/releases"}}
 :aliases
 {:dev {:extra-deps {com.datomic/client-cloud {:mvn/version "0.8.63"}
                     com.datomic/ion-dev {:mvn/version "0.9.176"}}}}}

Then, if we use M-x cider-jack-in from Emacs, this will not load the aliases extra-deps.
In order to do so, invoke cider-jack-in interactively:
C-u M-x cider-jack-in

Then, when the REPL command is displayed, use C-a to go to the beginning of the line and add -R:dev (see Clojure Deps and CLI Guide) in order to take into account optional dependencies.

Sunday, October 21, 2018

Android O: identify battery sucking apps

Source: Android O: How to Identify and Bitch Slap Those Battery Sucking Apps
On my Oneplus 5T, Android 8.1:

List apps. running in background permanently
  • Settings > Dev. Options > Running Services 
Kill the background activity of an app.
  • Settings > Apps > Application list > Select app > Battery > Uncheck Background activity

Thursday, October 18, 2018

macOS mojave: bluetooth headphones keep on disconnecting

Uncheck "Allow Handoff between this Mac and your iCloud devices" in Preferences | General.

Thursday, October 4, 2018

macOS: xcrun: error: invalid active developer path

Source: macOS Mojave: invalid active developer path
If after upgrading from High Sierra to Mojave, you get the following error:
[jerome@jeroboam] > make
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools),
missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
Then re-install xcode developer tools like in:
[jerome@jeroboam] > xcode-select --install
xcode-select: note: install requested for command line developer tools

Saturday, September 29, 2018

macOS: from High Sierra to Mojave

Steps:
  • Download "Install macOS Mojave" application from the Mac App Store, and run it.
  • Reboot. At Clover boot screen, choose Boot macOS Install option. Multiple reboots expected. At some time, pick "Boot FileVault Prebooter from Preboot" option to finish the install.
  • Update Clover configuration in order to hide the 2 preboot options at boot time. For this, add "Preboot" in Clover Configurator | Gui | Hide Volume
  • And here it is.
  • Optional step: Create a Bootable USB with UniBeast

Monday, September 24, 2018

macOS: downloading .gz from Chrome turns into .cpgz

If you download a .gz from Chrome, and double-clicking it simply creates a .cpgz, then the downloaded file is not a .gz
Try
> file --mime-type ~/Desktop/42a3-909a-1b5bdb4a4b8b.gz
text/plain
Then simply rename it into .txt, and you will be able to open it.

Friday, September 21, 2018

macOS: turn text into links automatically

Use Edit > Substitutions > Smart Links

Tuesday, September 18, 2018

macOS: how to page up with byobu in Terminal.app

Source: How can I page up or down in tmux with Terminal.app?
Terminal.app captures PageUp / PageDown. So, in order to send them to byobu again:
If on a PC keyboard:
  • F7
  • Shift + PageUp / Shift + PageDown
Or if on a MacBookPro:
  • F7
  • Fn + Shift + Up / Fn + Shift + Down

Wednesday, September 12, 2018

Tuesday, September 4, 2018

git: merge files from another branch

Source: Git tip: How to "merge" specific files from another branch
git checkout [TARGET_BRANCH]
git checkout [SOURCE_BRANCH] my_file1 my_file2

Friday, August 31, 2018

Perl: slurp STDIN

Source: How can I slurp STDIN in Perl?
my $str = do { local $/;  };

Wednesday, August 1, 2018

git: rename a branch

Source: Rename a local and remote branch in git

Rename local branch.
git branch -m new-name
Delete the old-name remote branch and push the new-name local branch.
git push origin :old-name new-name
Reset the upstream branch for the new-name local branch.
git push origin -u new-name

Thursday, July 26, 2018

macOS: checking for OpenSSL... configure: error: not found

Source: Problem with openssl on macOS
If your ./configure (e.g. for pgbouncer) terminates with the following error despite openssl being installed:
checking for OpenSSL... configure: error: not found
Then, restart it like follows:
./configure --with-openssl=/usr/local/opt/openssl

macOS: listening ports

Source: How can I list my open network ports with netstat?
[jerome@jeroboam] > sudo lsof -PiTCP -sTCP:LISTEN | grep 6432
pgbouncer 10533 jerome    9u  IPv6 0x8678a9be8d9262f5      0t0  TCP *:6432 (LISTEN)
pgbouncer 10533 jerome   10u  IPv4 0x8678a9be9e2f23dd      0t0  TCP *:6432 (LISTEN)

Wednesday, July 25, 2018

ssh: ssh a remote host via a bastion

Source: SSH ProxyCommand example: Going through one host to reach another server

In order to reach remote1 through a bastion host, add the following lines in your .ssh/config:
Host bastion
HostName bastion-01.golgoth.com
User jgallinari

Host remote1
HostName remote1.toto.swir
User jgallinari
ProxyCommand ssh jgallinari@bastion -W %h:%p
Then ssh remote1 should do it.

Friday, July 20, 2018

macOS: find your CPU

[jerome@jeroboam] > sysctl -n machdep.cpu.brand_string
Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz

Thursday, July 19, 2018

AWS: Using environment variables in CodeBuild buildspec

Source: Using environment variables in AWS CodeBuild buildspec.yml
See S3_BUCKET below, which is first expanded from ImportValue, then used in BuildSpec.
  AvUsageQuarantineBuildProject:
    Type: AWS::CodeBuild::Project
    Condition: Preprod
    Properties:
      Name: av-usage-quarantine-build
      ServiceRole: !GetAtt AvUsageQuarantineBuildProjectRole.Arn
      Artifacts:
        Type: CODEPIPELINE
        Name: av-usage-quarantine
      Environment:
        Type: LINUX_CONTAINER
        ComputeType: BUILD_GENERAL1_SMALL
        Image: aws/codebuild/java:openjdk-8
        EnvironmentVariables:
          - Name: S3_BUCKET
            Value: !ImportValue delivery-AvDeliveryUtilsBucket
      Source:
        Type: CODEPIPELINE
        BuildSpec: !Sub |
          version: 0.2
          phases:
            install:
              commands:
                - cd ~; wget https://raw.github.com/technomancy/leiningen/stable/bin/lein; chmod +x lein; mv lein /bin
                - LEIN_ROOT=true lein
            build:
              commands:
                - cd $CODEBUILD_SRC_DIR
                - LEIN_ROOT=true lein uberjar
            post_build:
              commands:
                - aws cloudformation package --template template.yaml --s3-bucket $S3_BUCKET --s3-prefix lambda --output-template av-usage-quarantine-output-template.yaml

macOS: Terminal follow focus

Source: Set Terminal Focus to Follow the Mouse Cursor in Mac OS X
Follow focus ON
defaults write com.apple.Terminal FocusFollowsMouse -string YES
Follow focus OFF
defaults write com.apple.Terminal FocusFollowsMouse -string NO
Then, restart Terminal.

Working on High Sierra 10.13.6.

Clojure: transducers from the ground up

Clojure transducers from the ground up: the practice

AWS: !Sub |


Q: What does !Sub | mean ?
A: This means that you can enter normal looking text without having to use things like "\n" to mean end of line.

AWS: 7 Awesome CloudFormation Hacks

Source: 7 Awesome CloudFormation Hacks

Tuesday, July 17, 2018

Clojure: count truthy occurences

Count truthy occurences
(count (filter identity [nil 1 nil 4 nil]))
2
Count falsey occurences
(count (filter #(or (false? %) (nil? %)) [nil 1 false 4 nil]))
3

Saturday, July 14, 2018

macOS: know the previous shutdowns cause

centurion:~ jerome$ log show --predicate 'eventMessage contains "Previous shutdown cause"' --last 24h

Filtering the log data using "eventMessage CONTAINS "Previous shutdown cause""
Skipping info and debug messages, pass --info and/or --debug to include.
Timestamp                       Thread     Type        Activity             PID    TTL  
2018-07-14 11:14:28.111106+0200 0xe5       Default     0x0                  0      0    kernel: (AppleSMC) Previous shutdown cause: 5
2018-07-14 11:32:41.196172+0200 0xe3       Default     0x0                  0      0    kernel: (AppleSMC) Previous shutdown cause: 5
 --------------------------------------------------------------------------------------------------------------------
Log      - Default:          2, Info:                0, Debug:             0, Error:          0, Fault:          0
Activity - Create:           0, Transition:          0, Actions:           0

Tuesday, July 10, 2018

macOS: release C-left, C-right, C-up, C-top for Emacs

On Emacs, I use key bindings for ^↑ (C-up), ^↓ (C-down), ^← (C-left) and ^→ (C-right), but macOS by default maps them to Mission Control. In order to replace ^ with ⌘ for Mission Control shortcuts, use System Preferences > Keyboard > Shortcuts like in

macOS: install Apache2::Request mod_perl module

Sources:
Trying to install Apache2::Request on macOS from CPAN will cause multiple errors.
cpan Apache2::Request
First, we will need apxs (Apache Extension tool).
For this, install httpd from homebrew.
brew install httpd
Then, we will need Xcode.
So, install it from the Apple Store.

Then, Apache2::Request install will try to have access to multiple Xcode directories that do not exist.
So, create symbolic links and missing directory.
sudo ln -s /Applications/Xcode.app/Contents/Developer/Toolchains/ /Applications/Xcode.app/Contents/Developer/Toolchains/OSX10.13.xctoolchain

sudo mkdir -p /Applications/Xcode.app/Contents/Developer/Toolchains/OSX10.13.xctoolchain/usr/local/bin/

sudo ln -s /usr/local/bin/apxs /Applications/Xcode.app/Contents/Developer/Toolchains/OSX10.13.xctoolchain/usr/local/bin/apsx

sudo ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.Internal.sdk
Then install libapreq2 library.
  1. Download libapreq2-2.13
  2. Compile libapreq2 sources.
tar xvfz libapreq2-2.13.tar.gz
cd libapreq2-2.13
./configure
make
make install
Then install mod_perl 2.

svn checkout https://svn.apache.org/repos/asf/perl/modperl/trunk/ mod_perl-2.0
cd mod_perl-2.0
perl Makefile.PL MP_CCOPTS=-std=gnu89
make
make install
NB: mod_perl.so and mod_apreq2.so will be installed in /usr/local/lib/httpd/modules.

Then update Apache configuration.
vi /usr/local/etc/httpd/httpd.conf
LoadModule perl_module lib/httpd/modules/mod_perl.so
LoadModule apreq_module lib/httpd/modules/mod_apreq2.so
...
ServerName jeroboam:8080
...
PerlSwitches -I /Users/jerome/perl5/lib/perl5
PerlModule Apache::DBI
PerlModule ModPerl::Registry
PerlRequire /Users/jerome/src/connectmv/perl/lib/startup.pl
<Location /hlr_vas/>
    SetHandler perl-script
    PerlResponseHandler MBQT::mod_perl::HlrVas
</Location>

# PerlSetEnv DBG_FLG 1
Apache restart
/usr/local/bin/apachectl restart

Friday, July 6, 2018

macOS: iconify / deiconify shortcuts

  • Iconify: ⌘+M
  • Deiconify: ⌘+TAB, then select application, then press ⌥, then, release ⌘

macOS: paste without style

Instead of using ⌘+V , you can press ⌥+⇧+⌘+V to paste text without any formatting.

Thursday, July 5, 2018

macOS: triple click to select path in Terminal

Source: Is there a UNIX-style triple click to select path in Terminal.app?
The shortcut for Terminal.app is ⌘+⇧+doubleclick.

macOS: install postgreSQL 9.4

brew install postgresql@9.4 --with-python
brew link postgresql@9.4 --force

macOS: install sshpass

brew install http://git.io/sshpass.rb

macOS: Fixing HOME and END keys

Source: Fixing HOME and END keys, and more, on macOS
mkdir -p $HOME/Library/KeyBindings
echo '{
/* Remap Home / End keys to be correct */
"\UF729" = "moveToBeginningOfLine:"; /* Home */
"\UF72B" = "moveToEndOfLine:"; /* End */
"$\UF729" = "moveToBeginningOfLineAndModifySelection:"; /* Shift + Home */
"$\UF72B" = "moveToEndOfLineAndModifySelection:"; /* Shift + End */
"^\UF729" = "moveToBeginningOfDocument:"; /* Ctrl + Home */
"^\UF72B" = "moveToEndOfDocument:"; /* Ctrl + End */
"$^\UF729" = "moveToBeginningOfDocumentAndModifySelection:"; /* Shift + Ctrl + Home */
"$^\UF72B" = "moveToEndOfDocumentAndModifySelection:"; /* Shift + Ctrl + End */
}' > $HOME/Library/KeyBindings/DefaultKeyBinding.dict

Wednesday, July 4, 2018

Virtualbox: Connect to the host machine from a VirtualBox guest OS

Source: Connect to the host machine from a VirtualBox guest OS
See "Another way to do this is to use a "Host" type of virtual network."

The simplest to always get the same IP address @home and @office for your VM is to use the Host-only adapter.

git: use p4merge on macOS

Source: Customizing Git, section External Merge and Diff Tools.

macOS: -bash: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory

Source: nixCraft
Option #1 : Terminal > Preferences > Profiles
However, this may cause some issues with e.g. PostgreSQL psql displaying unicode characters, e.g. <e2><94><8c><e2><94><80>.
So, if the issue is only caused by ssh, I prefer option #2:
sudo vi /etc/ssh/ssh_config
#       SendEnv LANG LC_*

macOS: size of email data

Spark Email
Outlook 2016
Mail

Monday, July 2, 2018

byobu: Function keys in Macos terminal

In order to have F2 or F8 work as expected for byobu in Macos terminal, you need to configure it as xterm-256 :
Terminal | Preferences

Wednesday, June 27, 2018

Wednesday, June 20, 2018

Git: The art of rebase

Source: Always Squash and Rebase your Git Commits
[Edit]: Squash the Last X Commits Using Git

Clojure: create a Clojure docker

Use case: I need to run some Clojure tests that use a library depending on glibc 2.14.
Unfortunately, I use CentOS 6.9 that relies on glibc 2.12, that cannot be updated.
Solution: Use a Docker file to run the Clojure tests.

Source: https://store.docker.com/images/clojure
docker pull clojure
  • Dockerfile
  • FROM clojure
    RUN mkdir -p /usr/src/app
    WORKDIR /usr/src/app
    COPY project.clj /usr/src/app/
    RUN lein deps
    COPY . /usr/src/app
    RUN lein uberjar
    CMD ["lein", "test"]
  • docker.build.sh
  • set -x
    cd ~/av-usage
    cp ~/tmp/clojure/docker/Dockerfile Dockerfile.test
    docker build -f Dockerfile.test -t av-usage-test .
    rm Dockerfile.test
  • docker.run.sh
  • set -x
    docker run -it --rm --name my-av-usage-test av-usage-test

Git: Reset local branch to remote HEAD

Source: Reset local repository branch to be just like remote repository HEAD
git fetch origin
git reset --hard origin/master

Thursday, June 14, 2018

yum: installed package

yum list installed | grep glibc

Saturday, April 21, 2018

Macos: Hide extra partitions in Clover

List partitions :
List UUID of partitions to hide :
Hide the UUID in Clover Configurator | Gui | Hide Volume :

Sunday, April 15, 2018

Macos: Where is my Firefox profile ?

  • Suppose you want to retrieve your Firefox profile and move it because it has initially been installed on another HDD.
  • Copy your profile directory from your old HDD, e.g. :
/Volumes/osx/Users/jerome/Library/Application\ Support/Firefox/Profiles/2ii3i4a1.default/
  • Into the new disk at :
/Users/jerome/Library/Application\ Support/Firefox/Profiles/
  • Copy the name of the default profile that has been created on the new disk
  • Remove this default profile 
  • Rename the old default profile like the new one just copied.

Macos: how to tab between buttons

Wednesday, April 11, 2018

Linux: Find Out What Process Are Using Swap Space

Source : Linux: Find Out What Process Are Using Swap Space
for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -n -r | less

Wednesday, March 28, 2018

Perl: sort version numbers

Before :
perl  -e 'use version; @f= map {$_->[0]} sort map {[$_, /--([^-]+)--[^-]+\./]} ("toto--1.0--1.1.sql", "toto--1.10--1.11.sql", "toto--1.1--1.2.sql"); print "@f\n"'
toto--1.0--1.1.sql toto--1.10--1.11.sql toto--1.1--1.2.sql
After :
perl  -e 'use version; @f= map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, version->declare(/--([^-]+)--[^-]+\./)]} ("toto--1.0--1.1.sql", "toto--1.10--1.11.sql", "toto--1.1--1.2.sql"); print "@f\n"'
toto--1.0--1.1.sql toto--1.1--1.2.sql toto--1.10--1.11.sql

Tuesday, March 6, 2018

Clojure: print exception stack trace

(log/error (apply str (interpose "\n" (.getStackTrace e))))

Monday, February 26, 2018

Clojure: nth line of Pascal triangle

((fn [n] (last (take n (iterate #(map + `(0 ~@%) `(~@% 0)) [1])))) 4)
(1 3 3 1)

Wednesday, January 24, 2018

Clojure: simple closure

Given a positive integer n, return a function (f x) which computes x^n.
(((fn [n] (fn [x] (apply * (repeat n x)))) 2) 16)
256
or
((partial (fn [n x] (apply * (repeat n x))) 2) 16)
256

Tuesday, January 23, 2018

Clojure: intersection implementation

((comp set filter) #{0 1 2 3} #{2 3 4 5})
#{3 2}

Sunday, January 21, 2018

Clojure: map construction

((fn [kvect, vvect] (apply hash-map (interleave kvect vvect))) [:a :b :c] [1 2 3])
{:c 3, :b 2, :a 1}

Thursday, January 18, 2018

Clojure: split-at implementation

((juxt take drop) 2 [[1 2] [3 4] [5 6]])
[([1 2] [3 4]) ([5 6])]

Wednesday, January 17, 2018

Clojure: replicate elements in sequence

((fn [s n] (mapcat (fn [x] (repeat n x)) s)) [1 2 3] 2)
((1 1 2 2 3 3))

Clojure: interleave implementation

((fn interlive [s1 s2] (mapcat vector s1 s2)) [:a :b :c] [1 2 3])
(:a 1 :b 2 :c 3)

Clojure: flatten implementation

((fn flat [s] (if (sequential? s) (mapcat flat s) [s])) '((1 2) 3 [4 [5 6]]))
(1 2 3 4 5 6)

Monday, January 15, 2018

Clojure: remove consecutive duplicates from a sequence

(#(map first (partition-by identity %)) [1 1 2 3 3 2 2 3])
[1 2 3 2 3]

Clojure: factorial function

(#(reduce * (range 1 (+ 1 %))) 3)
6

Saturday, January 13, 2018

Clojure: generate Fibonacci sequence

((fn [n] (map second (take n (iterate (fn [[a b]] [b (+ a b)]) [0 1])))) 6)
(1 1 2 3 5 8)

Clojure: build map from value and keys sequence

((fn [defval vect] (reduce (fn [m k] (conj m {k defval})) {} vect)) 0 [:a :b])
{:a 0, :b 0}
or
((fn [defval vect] (zipmap vect (repeat defval))) 0 [:a :b :c])
{:a 0, :b 0, :c 0}

Clojure: inc map values

Source: Braveclojure
(reduce (fn [m [k v]] (assoc m k (inc v))) {} {:a 1 :b 2})
{:a 2, :b 3}
NB: In this example, reduce treats the argument {:a 1 :b 2} as a sequence of vectors, like ([:a 1] [:b 2])

or, with reduce-kv
(reduce-kv (fn [m k v] (assoc m k (inc v))) {} {:a 1 :b 2})
{:a 2, :b 3}