teleren/devto huggingface dataset:
Using pcal to create monthly calendars in landscape format
Tags: productivity, tools
Published: 2019-08-01 17:30:16

---
title: Using pcal to create monthly calendars in landscape format
published: true
tags: productivity,tools
canonical_url: https://ofdigitalwater.postach.io/post/using-pcal-to-create-monthly-calendars-in-landscape-format
---

Would you like to have a monthly calendar, printed using DIN A4 landscape format, like [this one](https://wincent.balin.at/files/june.pdf)?

If you would, there is a utility for creating such calendars, called `pcal`. If your preferred operating system is an incarnation of Windows, you may download executables from [  
http://pcal.sourceforge.net/  
](http://pcal.sourceforge.net/) and run them on the command line with the options provided below. If your operating system of choice is Linux, most, if not all, major distributions will provide a corresponding package (in Ubuntu, just run `sudo apt-get install pcal`).

To create the calendar above, I simply ran these commands:

```
pcal -o june.ps -P a4 -M -F 1 -E
ps2pdf june.ps
```

The first command, which runs `pcal` to produce the aforementioned calendar in Postscript format, uses a lot of options, which shall be explained:

- `-o june.ps` This option lets the program write calendar into the file `june.ps`.
- `-P a4` specifies the paper size of DIN A4.
- `-M` adds pictograms of Moon phases to the calendar.
- `-F 1` sets Monday as the first day of the week; usual for continental Europe.
- `-E` further Europeanizes the calendar, setting date convention to, well, European `day/month` (instead of the American `month/day`).

Run as is, the command above produces calendar of the current month. To produce calendars for a specified month, add _`month year`_ to the `pcal` command line (for example, `07 2013` for July of 2013).

You will need the second command only if you will copy the resulting calendar to systems, which may not have a Postscript-compatible printer. This command converts the calendar from Postscript into the Portable Document Format, more widely known by it's abbreviation, PDF. The program `ps2pdf` is a part of ghostscript package, which processes Postscript files.

Of course `pcal` does have many more options, but if you are content with the calendar at the beginning of this article, just use the commands above.
Easily bypass Same Origin Policy
Tags: jquery, javascript, ajax, json
Published: 2013-07-03 15:54:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Easily bypass Same Origin Policy
slug: easily-bypass-same-origin-policy
date: 2013-07-03 15:54
tags: 
 - jquery
 - javascript
 - ajax
 - json
---
If you've ever tried to use AJAX or an iFrame to load another website in javascript and been unable to, it will have been because of the Same Origin Policy. To quote Wikipedia:

> In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site – a combination of scheme, hostname, and port number – to access each other's methods and properties with no specific restrictions, **but prevents access to most methods and properties across pages on different sites.**

This means that you can only grab files/scripts which are on your current site, which stops you from grabbing external resources. This can be a pain when you're actually trying to do something legitimate. 

If you have backend access, you could always have a PHP page which grabs the URL and prints out the contents, or you could send out ` Access-Control-Allow-Origin:` headers allowing certain sites or even wildcard to open it up fully. But when you don't have this access, when you only have HTML and JS at your disposal, what do you do?

You can use jQuery's `getJSON` function to grab JSON from an external source, and an external provider such as [AnyOrigin](http://anyorigin.com/) or [whateverorigin](http://whateverorigin.org/) will grab the contents for you and return them in a JSON object. Amazing.

    // use jQuery to grab the contents of an url
    var url = encodeURIComponent("http://www.google.com");
    $.getJSON('http://whateverorigin.org/get?url=' + url + '&callback=?', 
        function(data) {
            var html = data.contents;
            // your code here
        }
    );

Works great, though you do have to rely on a third-party. 

If you're okay with that, then this should be okay with you!
ImageMagick эксперименты #8
Tags: fun, imagemagick
Published: 2013-05-04 14:53:00

---
date: "2013-05-04 20:53:00 +0600"
canonical_url: "https://vk.com/wall38057738_954"
series: "Эксперименты с картинками"
---

Привет!
Сегодня у нас уроки кирпичизма. Надеюсь m$oft не наедет на меня за использование прямоугольников. Итак, что будет если мы разобьем матрицу на много подматриц произвольной формы? А если при этом произведем какую-нибудь операцию над подматрицей? Так вот, написал я тут алгоритм, наверное очень тупо, так как картинку 1900*1200 он обрабатывает десяток секунд, который перемешивает каналы у данной подматрицы. Не переживайте, я разовью эту идею дальше и будет очень забавно.

# Генерация матриц

Существует 2 вида подматриц- синие зеленые и красны. Размер выбирается как случайное число.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/daegq1c3dbdvhgupp8y3.jpeg)

А здесь размер выбирается как половина от ширины матрицы. Очевидно прогрессия {% katex inline %}(\frac{1}{2})^n{% endkatex %}. Ну или почти такая. Не суть.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/g3il2xvxdvl1hbqfntk9.jpeg)

Теперь случайное перемешивание в подматрицах. Обычный рандом дает не очень клевый результат.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pdr32slb9rdg286vfi8u.jpeg)

Тут волей случая первая подматрица оказалась очень большой. FIX IT!!!!
Вот то-то же. Нам нужен был true_random. Здесь выбирается средний размер квадратов с некоторой дельтой. Вот так красить машины надо. Это я понимаю искусство.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0o59xkji5ryopzodz2t1.jpeg)

Теперь перекрасим няшку.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/r06gl4lyb2iufc2ltwur.jpeg)

> Тебя теперь интел засудит, у них вся реклама в таком стиле)

# Смешивание картинок

Нет времени объяснять, прямоугольники захватывают мир……………

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/swc95wnehq27ectw3t0c.jpeg)

От сложения няшек, няшность не возросла T_T.

# Исходники

https://github.com/senior-sigan/magick/blob/master/brick.h
Check for valid url with JavaScript + RegEx
Tags: javascript, regex
Published: 2013-07-03 14:52:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Check for valid url with JavaScript + RegEx
slug: check-for-valid-url-with-javascript-regex
date: 2013-07-03 14:52
tags: 
 - javascript
 - regex
---
This next snippet is going to look hideous. If you're eating right now, swallow first. If you're drinking, put down the coffee and empty your mouth of fluid.

I am henceforth borrowing the following regex from `jquery.validation.js`. The plugin requires a form to validate, but I want access to it without a form, or without the rest of the plugin for that matter. So here we are, url validation, it looks horrible, but it works.

	var validUrl = function(value) {
		return /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);		
	}

Thank you Scott Gonzalez ([http://projects.scottsplayground.com/iri/](http://projects.scottsplayground.com/iri/)).
KnockoutJS simple truncate text binding handler
Tags: javascript, web, knockoutjs
Published: 2020-05-04 15:24:11

---
title: KnockoutJS simple truncate text binding handler
published: true
date: 2013-06-24 09:07:05 UTC
tags: javascript,web,knockoutjs
canonical_url: 
---

Hello everyone,

On my current project I needed to truncate text in some titles. Since we’re using KnockoutJS, I decided to write custom binding handler. And so I did.

Custom binding handlers are great solution, that provides you with ability to control how your observables interact with DOM elements. In addition you encapsulate your custom behaviors, thus they became reusable. It’s very useful when you use third party widgets that need to be updated all the time when observable values are updated.

So here is an example of my truncate binding handler:

```
ko.bindingHandlers.truncatedText = {
 update: function (element, valueAccessor, allBindingsAccessor) {
 var originalText = ko.utils.unwrapObservable(valueAccessor()),
 // 10 is a default maximum length
 length = ko.utils.unwrapObservable(allBindingsAccessor().maxTextLength) || 20,
 truncatedText = originalText.length &gt; length ? originalText.substring(0, length) + “…” : originalText;
 // updating text binding handler to show truncatedText
 ko.bindingHandlers.text.update(element, function () {
 return truncatedText; 
 });
 }
};
```

You can try it [here](http://jsfiddle.net/dima_k/bZEQM/1/)

Use this binding handler and use binding handlers in general.

Enjoy.

* * *
Detect enter key hit using jQuery
Tags: jquery, javascript
Published: 2013-07-03 14:33:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Detect enter key hit using jQuery
slug: detect-enter-key-hit-using-jquery
date: 2013-07-03 14:33
published: true
tags: 
 - jquery
 - javascript
---
Just a little snippet today, for future reference more than anything. 

	$('.textbox').bind('onEnter', function(e) {	
		// your code here
	});
	$('.textbox').keyup(function(e) {
		if (e.keyCode == 13) 
			$(this).trigger('onEnter');
	});

It's pretty much self-explanatory. When enter is pressed, the above function fires.
jQuery Categories using isotope
Tags: javascript, jquery, isotope, design
Published: 2013-07-01 16:41:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: jQuery Categories using isotope
slug: jquery-categories-using-isotope
date: 2013-07-01 16:41
published: true
tags:
 - javascript
 - jquery
 - isotope
 - design
---

While I don't do much design stuff nowadays, I do enjoy it when I get the chance. After discussing a masonry style grid with dynamic categories with [my other half](http://www.kirstyrose.com) this weekend, I tried to find the implementation online. Failing that, I thought this was a great chance to do a bit of *design*.

What I wanted was a grid of divs which I could filter depending upon their class. This could be used for a portfolio for example, allowing the user to filter whether they wanted to see websites, code snippets or graphic designs.

![It's all just apples and oranges...and bananas](http://i.imgur.com/QeMkBmN.png)

I put the design together, and had it working fine with jQuery, but it didn't move nicely. I remember hearing about jQuery Masonry and decided to give it a go. To be honest with you it is pretty rubbish, it feels *old*. I was on StackOverflow looking for answers to the most ridiculous problems when I read about [isotope](http://isotope.metafizzy.co/).

I gave it a go and it's actually pretty neat!

Apart from a small issue where images weren't being loaded before size calculations were made -- which was quickly fixed by using [David DeSandro](http://desandro.com/)'s [imagesLoaded](https://github.com/desandro/imagesloaded) plugin -- everything worked fine. I highly recommend using isotope, and may have to come up with an excuse to use it again!

Find the project on GitHub: [https://github.com/Imdsm/jQuery.Categories](https://github.com/Imdsm/jQuery.Categories)
See a working demo: [http://imdsm.github.io/jQuery.Categories/](http://imdsm.github.io/jQuery.Categories/)
Resize Bitmap without major quality loss
Tags: bitmap, image, csharp
Published: 2013-06-27 16:31:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Resize Bitmap without major quality loss
slug: resize-bitmap-without-major-quality-loss
date: 2013-06-27 16:31
tags:
 - bitmap
 - image
 - csharp
---
I'm working on a [computer vision](https://en.wikipedia.org/wiki/Computer_vision) project at the moment. Whilst working on it, I've had to resize a few bitmaps due to the webcam library I'm using not being able to properly set the resolution of the camera.

I found this on StackOverflow, and it works quite well. There are a few quality differences, such loss of sharpness due to smoothing, but it's only noticeable when you put the two images side to side.

    Bitmap resized = new Bitmap(desiredHeight, desiredWidth);
    using (Graphics graphics = Graphics.FromImage(resized))
    {
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphics.DrawImage(originalImage,
            new Rectangle(0, 0, desiredHeight, desiredWidth));
    }
    pictureBox1.Image = resized;

Like I said, works quite well, and definitely one for the snippet bin!
Cross thread calls made easier
Tags: csharp, delegates, generics, threading
Published: 2013-06-27 14:19:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Cross thread calls made easier
slug: cross-thread-calls-made-easier
date: 2013-06-27 14:19
tags:
 - csharp
 - delegates
 - generics
 - threading
---
Back in 2010 I wrote a blog post about [cross thread calls](http://www.adamkdean.co.uk/blog/read/2/cross-thread-calls-made-easy), showing how to overcome invalid cross-thread operations and change windows forms from other threads. It was simple but a little bit messy.

Well, things are easier now, and have been for a while. Instead of declaring delegates and invoking them, you can now use generic delegates and save yourself the hassle of declaring new delegates for every method signature.

For example, where before you had to do this:

    private delegate void ObjectDelegate(object obj);

    private void UpdateTextBox(object obj)
    {
        if (InvokeRequired)
        {
            ObjectDelegate method = new ObjectDelegate(UpdateTextBox);
            Invoke(method, obj);
            return;
        }
    }

You can now do this:

    private void UpdateTextBox(string s)
    {
        if (InvokeRequired)
        {
            Action<string> action = new Action<string>(UpdateTextBox);
            Invoke(action, s);
            return;
        }
    }

Another great thing is if you have to pass multiple objects then it's as simple as adding more types within the angle brackets. You can also substitute `Action<T>` for `var` to save space. Let's say for example, you need to update a label from another thread, the follow works great:

    private void UpdateLabel(Label label, string s)
    {
        if (InvokeRequired)
        {
            var action = new Action<Label, string>(UpdateLabel);
            Invoke(action, label, s);
            return;
        }

        label.Text = s;
    }

This will save you a bunch of time, and is essentially identical to the previous method.

For more information on `Action<T> Delegate`s, see [this MSDN article](http://msdn.microsoft.com/en-us/library/018hxwa8.aspx).
Creating a chrome extension - an update
Published: 2022-05-09 13:59:27

---
title: Creating a chrome extension - an update
published: true
date: 2013-06-07 00:00:00 UTC
tags: 
canonical_url: https://carl-topham.com//articles/creating-a-chrome-extension-an-update
---

Since I wrote my last post on [creating a Chrome extension](/articles/creating-a-chrome-extension-that-uses-jquery-to-manipulate-the-dom-of-a-page/) , there have been a few changes to how the extensions are built - mainly that the manifest version has changed to version 2. The original post is still fine, but there are a few tweaks needed. This post is mean mainly as an update to the original, so rather than rehash the old content too much I will skim over the basics quickly.

- Create a folder for your plugin - name it after your extension so you can find it later!
- In a text editor create 4 documents.
- Save them as manifest.json, background.js, background.html and customStyles.css
- Create a 20px x 20px png file using your favorite image editor!
- [Get a copy of jQuery](http://docs.jquery.com/Downloading_jQuery) . and add it to the folder.

### Files

#### manifest.json

```
{ 
  "name": "plugin name", 
  "version": "0", 
  "description": "What do I do as an extension", 
  "background": {
    "page": "background.html"
  }, 
  "manifest_version": 2,
  "browser_action": {
    "name": "Manipulate DOM", 
    "icons": ["icon.png"],
    "default_icon": "icon.png"
   }, 
   "content_scripts": [ 
      { 
        "js": ["jquery-2.0.2.min.js", "background.js"], 
        "css": ["customStyles.css"], 
        "matches": ["http://*/*", "https://*/*"]
      }
   ]
}

```

#### jquery-2.0.2.min.js

A copy of jQuery. Might as well be minified.

#### background.html

Not always needed, but we are covering the basics so here it is!

#### background.js

Once the page has loaded the js in this file will be run. This happens after DOM load so no event listeners are needed.

### Add it to Chrome

Now all we need to do is add the extension to chrome.

- Tools > Extensions
- Tick the developer more checkbox
- Click 'Load unpacked extension' and select your folder. Any errors in your files will be shown. This doesn't include JS errors and is only things like missing files or malformed manifest.json

As you update your extension just keep clicking the 'reload' button, then refresh the webpage you are applying the extension too.

### TLDR:

I have created a [Chrome extension starting bundle](https://github.com/Designer023/Chrome-Extension-Starting-Bundle) on GitHub to get you started right away. Take a look and let me know what you think.
Coderbits Pie Charts
Tags: coderbits, raphael, graphael, javascript
Published: 2013-05-23 16:36:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: Coderbits Pie Charts
slug: coderbits-pie-charts
date: 2013-05-23 16:36
tags: 
 - coderbits
 - raphael
 - graphael
 - javascript
---
If you've taken a look at [my profile](http://www.adamkdean.co.uk/profile/index) you may have noticed that I've switched the GitHub/StackOverflow widgets out for a single Coderbits widget. Not only is this because my GitHub/ServerStack.NET API code broke, but also because I think it gives a better overview of my coding profile.

I used [Scott's Raphael pie graphs](http://jsfiddle.net/scottksmith95/wvVRY/) which Coderbits use, and mixed them with the request code from the [Coderbits js widget](https://github.com/scottksmith95/coderbits.widget). Add a little [SpiffyGif](http://spiffygif.com/) loading gif and you have yourself, in my opinion, a pretty nice looking and lightweight API-fed graph. 

You can find the code for this pie graph widget here: [https://github.com/Imdsm/Coderbits.PieCharts](https://github.com/Imdsm/Coderbits.PieCharts)  
You can try out the demo here: [http://imdsm.github.io/Coderbits.PieCharts/](http://imdsm.github.io/Coderbits.PieCharts/)

![A better profile overview](http://i.imgur.com/7MUIJEy.png)
ImageMagick эксперименты #9
Tags: fun, imagemagick
Published: 2013-05-16 08:36:00

---
date: "2013-05-16 14:36:00 +0600"
canonical_url: "https://vk.com/wall38057738_966"
series: "Эксперименты с картинками"
---

Продолжаем поиск чего-то необычного и вещественного.
В предыдущем посте я сделал “квадратное сложение” няшек. Настал час истины. Совершим же перекрёстное слияние няшек. И тут размер итогового изображения в два раза больше исходного. Для усиления умиления рекомендую смотреть как оригинал, а не превьюху!!!!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jvkjivomg6u8ozqmytsl.jpg)

Дополнительный бонус. Идеальное вмешивание картинок.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/flaj21d7bzk30zgt1s7i.jpeg)

# Исходники

https://github.com/blan4/magick/blob/master/diffusion.h
First time actually using uShowcase
Tags: ushowcase, umbraco
Published: 2013-05-13 15:10:00

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/y9hxcwi5y92j6zfcxbjx.jpg
title: First time actually using uShowcase
slug: first-time-actually-using-ushowcase
date: 2013-05-13 15:10
tags: 
 - ushowcase
 - umbraco
---
So today is the first time I've actually used my own project, uShowcase, to make a photo gallery. I have a few photo gallery websites to make in the coming months, and it gave me a great excuse to dive into Umbraco more. I learnt some things, chief among them: always use your own projects.

Back when I was making this website, I needed an easy to use authentication system as Microsoft's sucks and is *bulky*. I came up with [EasyAuth](http://www.adamkdean.co.uk/blog/tagged/34/easyauth), a simple and easy to use ASP.NET/MVC authentication library. When I designed it, it looked great, the idea was good, *all the tests passed*. But when I came to use it, I spotted features it lacked, things I wished it could do, stuff it needed to have. You don't see these until you use your product, oft times it's too late then.

Using [uShowcase](http://www.adamkdean.co.uk/blog/read/64/ushowcase-umbraco-photo-gallery) -- my first Umbraco project, a simple photo gallery starter pack -- I learned first and foremost that the default template sucks. It's not really a photography style website. It requires you to modify it and make it into a photography looking website, which isn't really fair when it's supposed to be a starter pack. 

I also learnt that Umbraco rocks. I've used more content management systems than I can even recall. I've made more websites than I can even list. But using Umbraco has to be one of the best experiences I've had. While I do love the control you get from making a website from scratch using PHP/LAMP or C#/ASP.NET, that all just takes so long compared to using Umbraco. I don't think I'll ever have to write a backend management portal ever again! (Yeah, right...)

So thanks Umbraco, you make me happy and less rushed. And thank you past-me, for saving me time by creating uShowcase. I'll be sure to update it over the next few weeks a push a better version to the Umbraco package system.

![First photo gallery using uShowcase](http://i.imgur.com/I0qmh6u.jpg)

(I do wish you could capture your cursor with print screen, it's over the wildlife thumbnail by the way!)