Inércia Sensorial

25 de January de 2017

Custom Protractor Flake shard parser

Filed under: Javascript — inerte @ 23:29

PR #45 on Protractor Flake added the ability to specify custom parsers. On my project we’re sharding (running multiple instances of) Protractor and using the following parser to re-run only the failing spec files.

You’ll want to replace the /test/functional/specs/ and the browser name (chrome) below with your actual values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const _ = require('lodash');
 
// If only one spec file fails, on the next re-run, we don't get the filename on the output. So
// if it fails again, we need re-use the filename from the previous run
let previousSpecFileNames = [];
 
module.exports = {
  parse: function (protractorTestOutput) {
    if (previousSpecFileNames.length === 1) {
      return previousSpecFileNames;
    }
 
    const lines = protractorTestOutput.split(`\n`);
    // At the end of the output there's a summary of which shards failed
    const failedLines = lines.filter(line =>
      line.startsWith('[launcher] chrome')
      && line.includes('failed')
      && line.includes('test(s)'));
 
    // regex matches #number and #number-number (ie #1 or #1-1, #1-2, #1-3...)
    const testNumberRegExp = new RegExp(/#[0-9](-[0-9]+)?/);
 
    const failedSpecsLines = failedLines.map(failedLine => {
      const match = testNumberRegExp.exec(failedLine);
 
      if (match) {
        // Lines with "#number-number ]" (space followed by closing bracket) and "Specs: "
        return lines.filter(line => line.includes(`${match[0]}] `) && line.includes('Specs: '));
      }
 
      return null;
    }).reduce(function (a, b) { // Flatten the array
      return a.concat(b);
    }, []);
 
    const specFileNames = _.compact(failedSpecsLines).map(line => {
      const startingPathPosition = line.indexOf('/test/functional/specs/');
      return line.substr(startingPathPosition + 1);
    });
 
    previousSpecFileNames = specFileNames;
 
    return specFileNames;
  },
 
  name: 'Your custom parser name',
};

07 de May de 2013

Download file using WinJS.xhr

Filed under: Javascript — Tags: , , — inerte @ 15:00

Snippet to download a file using WinJS.xhr and save it. The file variable below is a StorageFile, result of pickSaveFileAsync.

Note the usage of responseType: “blob” as an option to xhr, and how it is copied to the file stream with msDetachStream.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
WinJS.xhr({
    responseType: "blob",
    type: "GET",
    url: "http://example.com/",
}).then(function (response) {
    var fileContents = response.response;
 
    return file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (stream) {
        return Windows.Storage.Streams.RandomAccessStream.copyAsync(fileContents.msDetachStream(), stream).then(function () {
            return stream.flushAsync().then(function () {
                stream.close();
                fileContents.msClose();
            });
        });
    });
});

I tried to use replaceWithStreamedFileFromUriAsync and writeBufferAsync, but never managed to make it work. If you do, leave a comment!

13 de April de 2013

PCH file built from a different branch ((clang-425.0.24)) than the compiler ((clang-425.0.27))

Filed under: Programação — Tags: , — inerte @ 10:44

Atualizei o XCode da versão 4.6.0 para 4.6.01 e de repente meus projetos não construíam mais, dando o erro:

PCH file built from a different branch ((clang-425.0.24)) than the compiler ((clang-425.0.27))

A solução foi simplesmente limpar o projeto. Vá ao menu “Product” e selecione “Clean”.

06 de December de 2012

Powershell script to snap an app in Windows 8

Filed under: Programação — Tags: , , — inerte @ 13:52

You can not, from inside a Windows 8 application, snap it.

That doesn’t mean there is no other way 🙂

At work, we have to test our app in a snapped state, so we need a way to programmatically make it happen. We discovered that there are two keyboard shortcuts for this action. Windows Key + . (the period key) snaps to the right edge, and Windows Key + Shift + . snaps to the left edge.

So all we have to do is send these keys to the operating system. Sending the Windows Key is tricky, and not supported using only [System.Windows.Forms.SendKeys]::SendWait.

So here’s an alternative:

Download InputSimulator.dll

Run the following commands on a Powershell prompt:

1
2
[Reflection.Assembly]::LoadFile("C:\path\to\InputSimulator.dll")
[WindowsInput.InputSimulator]::SimulateModifiedKeyStroke('LWIN', 'OEM_PERIOD')

And your app will snap to the right edge. I am still researching how to snap to the left edge, it’s a more complicated call to SimulateModifiedKeyStroke, but will keep researching.

Get current session id on Ruby Selenium WebDriver

Filed under: Programação — Tags: , , — inerte @ 10:36
1
@browser.instance_variable_get('@bridge').instance_variable_get('@session_id')

08 de November de 2012

Javascript function to find background task by name on Windows 8

Filed under: Javascript — Tags: — inerte @ 15:59
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
FindTask: function (taskName) {
    var background = Windows.ApplicationModel.Background;
    var iter = background.BackgroundTaskRegistration.allTasks.first();
    var hascur = iter.hasCurrent;
 
    while (hascur) {
        var cur = iter.current.value;
 
        if (cur.name === taskName) {
            return cur;
        }
 
        hascur = iter.moveNext();
    }
 
    return null;
}

01 de June de 2012

MD5 in YQL in hexadecimal form using Javascript

Filed under: Javascript — Tags: , , — inerte @ 14:54

Undocumented YQL crypto method to return a hexadecimal representation of the MD5 encoding of a string:

1
y.crypto.encodeMd5Hex('some string');

05 de December de 2011

Leiningen, ClojureScript e REPL no navegador

Filed under: Clojure,Javascript — Tags: , — inerte @ 07:48

REPL do Clojure no navegador http://nakkaya.com/2011/12/04/leiningen-clojurescript-and-browser-repl/

06 de October de 2011

Plugin do Eclipse para editar scripts bash

Filed under: Programação — Tags: , — inerte @ 13:47

Meu projeto atual tem arquivos .php, .pm e .sh no mesmo diretório. Aos poucos fui achando os plugins para o Eclipse, e às vezes até múltiplos para a mesma linguagem de programação. E para bash, eu achei o ShellEd. Por enquanto está muito bom. Mesmo o projeto tendo sido criado para PHP, os arquivos .sh estão sendo abertos pelo ShellEd.

21 de September de 2011

Clojure script to parse IIS logs from a directory and show slowest pages

Filed under: Clojure — Tags: , — inerte @ 15:56

Just having some fun today. The code runs actually pretty fast: It reads over 1.5 million lines from 1.1GB of logs and sorts them by time-taken in 5 seconds. I bet there’s room for improvement but it was enough for my needs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
(ns iis_log
  (:require clojure.contrib.duck-streams clojure.contrib.io clojure.string clojure.test))
 
(def #^{:doc "Where the log files reside."} logs-directory "D:/userdata/jnetto/Desktop/zina_inside/W3SVC93479707")
 
(def #^{:doc "How many lines to show from logs."} top-to-show 25)
 
;; IIS log lines starting with # are comments
(defn is-not-comment?
  [^String s]
  (not= (.substring s 0 1) "#"))
 
(defn remove-comments
  [file-contents]
  (filter is-not-comment? file-contents))
 
;; Values on logs are separated by a space. Therefore, "-" is shown as a value when there is nothing there, instead of a space,
;; which would mess up the separator.
(defn nil-if-hyphen
  [s]
  (if (not= s "-") s))
 
(defstruct token :uri :time-taken :username)
 
(defn relevant-line-info
  "Returns a map with the path + querystring, time-taken and username from a log line."
  [line]
  (let [line-tokens (clojure.string/split line #" ")
        cs-uri-stem (nth line-tokens 6)
        cs-uri-query (nth line-tokens 7)
        cs-username (nth line-tokens 9)]
    (struct-map token :uri (str cs-uri-stem (nil-if-hyphen cs-uri-query))
                      :time-taken (read-string (nth line-tokens 20))
                      :username (nil-if-hyphen cs-username))))
 
(def accesses (ref []))
 
(doseq [child (.listFiles (clojure.contrib.io/file logs-directory))]
  (println "Processing" child) ;; Just for debugging purposes, to show something is happening
  (let [file-contents (clojure.contrib.duck-streams/read-lines child)
        file-without-comments (remove-comments file-contents)
        tokens (map relevant-line-info file-without-comments)]
    (dosync (alter accesses concat (take top-to-show tokens))))) ;; We 'take 'top-to-show here as an optimization. If we will print
                                                                 ;; only top-to-show, why take more from each file?
 
;; Until here it's actually pretty fast. 'sort-by and 'reverse are actually the slowest parts of this script.
(doseq [line (take top-to-show (reverse (sort-by :time-taken @accesses)))] 
  (println line))
Older Posts »

Powered by WordPress