Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

2015-01-18

Level Up - Blogger: How to add formatted code to post (with highlighting)

In many of my posts, I like to add code snippets. Blogger doesn't have good native support for displaying code with syntax and line highlighting, so I found a way to add that feature using GitHub Gists and gist-embed project on GitHub.

The following steps can mostly be used with any blog.

Step 1: Include jQuery and gist-embed within your header tags.

<head>
  ...
  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/gist-embed/2.0/gist-embed.min.js"></script>
</head>


Step 2: Add a code element to where you want your Gist code to appear.

<code data-gist-id=""></code>


Example:



Source:
<code data-gist-file="PrimeNumbers.cpp" data-gist-hide-footer="true"
   data-gist-highlight-line="9,12,35-42" data-gist-id="5789439"></code>


Nice features also included, but not shown above:

  • Ability to show GitHub footer
  • Remove line numbers
  • Load multiple files from a Gist
  • Load a signal file from a Gist
  • Show only certain lines from a file


This article was mainly written for myself in the future, but I hope others can benefit from it, as well.

Links:



~ Danial Goodwin ~



2015-01-17

Level Up - Android Dev: How to get started with AndroidAnnotations (easy) (and build Chuck Norris app)

AndroidAnnotations is an open source framework for Android. Basically, you provide Java annotations for things, and the framework will auto-generate the necessary boilerplate code so you don't have to write it yourself. Runs at compile-time! (Read: No reflection or startup time impact) And, there's a lot of code AndroidAnnotations saves you from writing manually.

For example, want to run something in a background thread? Annotate the method with `@Background`. Want to run something in the main/UI thread? (rub some bacon on it) Annotate the method with `@UiThread`.

In this article, I provide a quick walkthrough for creating a very simple Chuck Norris facts app. I'll assume that you already have basic Android knowledge (and using Android Studio + Gradle). Then, at the end, I'll explain in more details some issues/gotchas I ran into while using AndroidAnnotations for the first time, and mention other goodies.

Getting started..

2014-12-05

Level Up - Android Studio: How to Boost Productivity By Auto-Generating Getters and Setters

A best practice in Java is to encapsulate field variables by making them private and creating a "getter" and "setter" for each of them, as needed. Doing this with many fields can be a lot of boilerplate code to write. But, thankfully, modern IDEs, like Android Studio provide ways to auto-generate code so that you don't have to manually write it.

For example, if you have a class like the following:

public class MyClass {
    private int mId;
    private String mName;
}

Instead of manually writing each accessor (getter) and mutator (setter), go to the menu and click Code->Generate.. (hotkey `alt+insert), then choose the "Getter and Setter" option.

Done. That was fast. And, it will be just as fast with 20+ fields also.

But, wait! By default, Android Studio will include that "m" prefix (stands for "member" variable) in each of the generated method names, so you'll have method names like "setmId" and "getmId". There is a quick permanent fix for this also!

Go to File->Settings->Code Style->Java->Code Generation, then type a single "m" into the "Field", "Name prefix" field. Hit apply, then you are gone. All future code generations will take those "m" prefixes for field into account. Here's a screenshot to what this sentence means visually.

So easy to save a lot of time with Android Studio

That's it for this post. There are lots of other useful code generators also. If you are doing mindless work, it's probably been automated (or should be). ;)

~ Danial Goodwin ~



2014-11-13

Level Up - Java: What is Vararg?

I like to remember vararg as "variable-length arguments". You may see them parameterized as "foo(Object... objects)" or "foo(int... ints)" or maybe "main(String... args)". The triple-dot signifies the vararg, and the method that has them uses it as an array.

Example code:

/** Returns input as a comma-separated list. If input if null
  * or empty, then this returns an empty string. */
public static String convertToString(Object... objects) {
    if (objects == null || objects.length == 0) { return ""; }
    StringBuilder sb = new StringBuilder();
    for (Object object : objects) {
        sb.append(object.toString()).append(", ");
    }
   return sb.substring(0, sb.length() - 2).

2014-08-13

Level Up - Android: How to get started with Android Wear and the Wearables Emulator

Recently, I started working on Android Wear for the first time. It's been fun playing around with the new platform and form factor. And, of course, the official Android docs that I read could be condensed further for absolute newcomers. So, in the typical fashion, I've created myself a cheat sheet that I would use next time I would want to learn the easiest way for how to best create Wearable apps.

I've open sourced all my code so far on GitHub. It includes how to first set up the virtual Wear device, connect to the handheld device, and how to have the app send and open a notification on the wearable.

https://github.com/danialgoodwin/android-wear

~ Danial Goodwin ~



2014-07-02

Level Up - Dev: Modular Code

Modular code means that the code is easily reusable; It does not mean that the code has to all be in one file. That's what modules and libraries are for. ;)

~ Danial Goodwin ~



2014-06-27

Level Up - Dev: Codestyle Quote

    "Any fool can write code that a computer can understand.
    Good programmers write code that humans can understand."
    
      --- Martin Fowler, Refactoring: Improving the Design of Existing Code

~ Danial Goodwin ~



2014-06-18

Level Up - Dev: Integer Overflow Not Overflowing

An integer overflow (or wraparound) occurs when a number larger than the max integer value or smaller than the min integer value is tried to be stored in the integer's memory. You could imagine a circular number line.

Ex: If you have an integer at the max positive value and add one, then the integer will wraparound and be set to the most negative value (if using a signed int. An unsigned int will wraparound to 0). And, vise-versa.

Today, I experienced a bug where I wanted to get a (signed) integer overflow, but unfortunately the int value was just going to zero instead of going to the negative numbers. Thankfully, I knew the memory/bit representation of int and was able to figure out what was going on.

Here is some simplified code, with only one small change:

    // Test #1 - has wraparound
    int wrap = 1;
    for (int i = 0; i < 34; i++) {
        print(i + ": wrap: " + wrap);
        wrap = wrap * 3;
    }

    // Test #2 - no wraparound
    int wrap = 1;
    for (int i = 0; i < 34; i++) {
        print(i + ": wrap: " + wrap);
        wrap = wrap * 2;
    }

Here is the relevant output from running the code above:

// Test #1 - has wraparound
...
13: wrap: 1594323
14: wrap: 4782969
15: wrap: 14348907
16: wrap: 43046721
17: wrap: 129140163
18: wrap: 387420489
19: wrap: 1162261467
20: wrap: -808182895
21: wrap: 1870418611
22: wrap: 1316288537
23: wrap: -346101685
24: wrap: -1038305055
25: wrap: 1180052131
26: wrap: -754810903
27: wrap: 2030534587
28: wrap: 1796636465
29: wrap: 1094942099
30: wrap: -1010140999
31: wrap: 1264544299
32: wrap: -501334399
33: wrap: -1504003197

// Test #2 - no wraparound
...
20: wrap: 1048576
21: wrap: 2097152
22: wrap: 4194304
23: wrap: 8388608
24: wrap: 16777216
25: wrap: 33554432
26: wrap: 67108864
27: wrap: 134217728
28: wrap: 268435456
29: wrap: 536870912
30: wrap: 1073741824
31: wrap: -2147483648
32: wrap: 0

33: wrap: 0

If test #1 were to continue, then the values would keep wrapping. If test #2 were to continue, then the values would stay the same at 0.

The easiest way for me to make sense of this experiment was to know that multiplying by a power of 2 (2, 4, 8, 16, 32..) is the exact same as a bit shift in the binary computer. And, the bits that made up the int were all just getting pushed out of memory in test #2 until there were no more set bits to manipulate. In test #1, more int memory bits are being flipped in order to continue the wraparound.

I would explain this at a lower level, but there are already many great resources for "bit representation of integer".


~ Danial Goodwin ~

ps - This post was mainly for myself and written quickly. If there are any questions about this, then I'd be happy to elaborate.



2014-06-04

Level Up - Android Dev: KeyboardlessEditTest

Today, I've released a new open source project that has help me build my latest app. I needed an EditText with full capabilities, except for the keyboard showing up. All of the possible answers that I found on StackOverflow and GitHub all had their limitations, especially the lack of native editing (cut/copy/select/paste) options.

All of the problems have been abstracted out to a simple subclass of EditText that you can use easily in any project.

You can try it out on GitHub now: https://github.com/danialgoodwin/android-widget-keyboardless-edittext
Or, you can go directly to test the APK: https://play.google.com/store/apps/details?id=net.simplyadvanced.simplytonegenerator

If you have any questions or need clarifications on how to use the project, then please let me know.



~ Danial Goodwin ~



2014-03-12

Level Up - Puzzles: Four Random Cards, Turn All Face-Up, Blindfolded (Solution)

Problem:
You have four cards placed in a 2x2 grid pattern. Each card is randomly placed either face up or face down. Your goal is to flip all the cards face-up. But, there are a few restrictions:

  • You are blindfolded and never know which cards are face up or face down. Nor do you know how many cards are flipped either way.
  • Your movements for flipping cards are limited. Each turn you can flip either one or two cards.
  • You will only be told when all cards are face up. You will get no other notification on how the cards are orientated.

What are the fewest amount of turns required to ensure all four cards are (eventually) flipped face up? And how?


Ascii art on how the layout may look. Each card represents a card:
1 2
3 4

Sidenote: When this brain teaser was first told to me last week, the person explained the possible limited card movements as, roughly, "you can either flip the diagonal cards, a column of cards, or a row of cards. Or, you can flip just a single card.". I'm pretty sure the way I explained it ("each turn, you can only flip one or two cards") is the same and much easier to understand, so I guess that lowers the puzzle difficulty a little bit for you, the reader.


Solution: 

2014-02-27

Level Up - Android Dev: How To Automatically Extract Hardcoded Strings To res/values/strings.xml

This is just one of the many refactoring features of Eclipse. Using this extract feature, you won't even need to open res/values/strings.xml to add the String resources nor manually write out reference to the resource.

This saves a lot of time, and allows the best practice of putting String constants away from the UI/Java files so that localization can be performed easier. This method I'm about to show you is especially productive because it can change all instances of that particular String to point to the xml string resource so that you don't have to do it individually one-by-one. (I'm doing maintenance on code that has everything hardcoded, so this is a lifesaver.)

To automatically extract the String, it's easy enough:

Step 1: Highlight the entire String that you would like extracted and sent to res/values*/strings.xml
Step 2: From the menu bar, select Refactor->Android->"Extract Android String..."
Step 3: Preview options and confirm changes.

Step 2: Automatically extracting string menu option.


Step 3: Many different great refactoring options to choose from.


This works in the XML and Java files for your Android application. And, this is much quicker than manually changing all instances of hardcoded Strings to getString() and @string/.


~ Danial Goodwin ~



2014-02-15

Level Up - Webmaster: How To Shorten Default MediaWiki URL to Short (Canonical) URL Form

This was my first time shortening the URL for MediaWiki to canonical form and it literally took me less than five minutes to fully complete and test. I bet you can do it in two minutes.



Quick and easy directions:
1. Go to MediaWiki ShortURL Builder (Your wiki will have to be temporarily public)
2. Type in your current URL, for me it was " http://danialgoodwin.com/mediawiki/w/"
3. When you click "Go", make sure the article path says "/wiki/$1" or wherever you would like your MediaWiki to appear to users.
4. You now have all the code at your fingertips to place on your server. I used a GUI FTP client (like FileZilla) to transfer the new data because that was the quickest for me.


The Code:
If your configuration is the exact same as mine, then you can use these following sections of code to enable the shortcodes.

At the root of your domain, in the .htaccess file (make it if you don't have it), include (I added the "REGION" comments just for readability and future maintenance):
# REGION Redirects for MediaWiki Short Canonical URLs
RewriteEngine OnRewriteRule ^/?wiki(/.*)?$ %{DOCUMENT_ROOT}/mediawiki/w/index.php [L]RewriteRule ^/?$ %{DOCUMENT_ROOT}/mediawiki/w/index.php [L]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-fRewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-dRewriteRule ^/?mediawiki/w/images/thumb/[0-9a-f]/[0-9a-f][0-9a-f]/([^/]+)/([0-9]+)px-.*$ %{DOCUMENT_ROOT}/mediawiki/w/thumb.php?f=$1&width=$2 [L,QSA,B]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-fRewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-dRewriteRule ^/?mediawiki/w/images/thumb/archive/[0-9a-f]/[0-9a-f][0-9a-f]/([^/]+)/([0-9]+)px-.*$ %{DOCUMENT_ROOT}/mediawiki/w/thumb.php?f=$1&width=$2&archived=1 [L,QSA,B]
# ENDREGION Redirects for MediaWiki Short Canonical URLs

In your MediaWiki's LocalSettings.php file, insert the following lines (preferably right under "$wgScriptPath" and "$wgScriptExtension" just to keep things organized):
## Added for short URLs.$wgArticlePath = "/wiki/$1";$wgUsePathInfo = true;
## Added for short URLs because .htaccess on root includes 404 thumbnail handler config.$wgGenerateThumbnailOnParse = false;


Note: With this method, you don't even need a /wiki/ directory to make it appear that all the files are there. You should use this method so that when you make changes to the backend, the frontend will still be the same for users, search engines, and SEO. It also makes URLs easier to remember and more.

More detailed information: Manual:Short_URL

~ Danial Goodwin ~



2014-02-02

Level Up - Windows 8: How to Create a Batch File

Batch (*.bat) files are useful because they allow you to save and reuse commands for the command prompt (or CLI, command-line interface). Also, it is easier to send multiple commands at once, fix typos, and edit the commands.

Batch files are available for Windows 7, 8, and 8.1. Any command that you can put in the CLI, you should be able to put into the BAT file.


Method 1:
- Right-click on your desktop (or in File Explorer), and select New->Text Document. Now, rename the file to something ending with .bat.


Method 2:
- Open Notepad, then when you save the file, make sure to end it with ".bat".

Saving a Batch file requires a .bat ending.
Test the Batch file:
Now that you have the BAT file, you can easily test that it works by putting in the following code, then double-click to run the file.
echo Hello, World!


Here's some more things you can try out: Windows Command Prompt Cheat Sheet


Note: If method 1 didn't work for you, then try method 2.

~ Danial Goodwin ~



2014-01-24

The Progression of Learning How To Write Code

Quote:

"The ugliest code I ever saw was the junk I wrote two months ago. The greatest code I ever saw is the stuff I'm writing today. This statement will still be true two months from now."

Unfortunately, I haven't been able to find a good source to reference this quote to.

~ Danial Goodwin ~



2013-11-09

Danial Versus Games

Whenever I get the sudden thought to play a game, I think how much more satisfying it will be to just create a game instead. Or at least create another app.

--
Random story that I remember:

I first got into computer programming in high school by editing the source code of a popular MMORPG (Runescape) in order to make it better. The language was Java, but at that time I just knew it as code. And, with no prior coding experience I could understand and walk through much of source code without looking up what different words meant. I just thought that was cool, it felt great how everything just clicked together. But, it actually wasn't until a few years later as a sophomore in college that I actually decided to get into computer engineering and take my first real logic and programming class (basically, the school said I choose a specific degree to work towards. I just wanted to learn everything).
--

Coding has the elements that playing games offer:

  • There are highs and lows
  • There are easy parts and hard parts
  • You can save and resume at any time. Or even start over

And coding has even more great elements only available in some games:

  • Levels are always evolving
  • They can be single player/coder or multiplayer/coder
  • As you work on more parts, you "level up"
  • Instead of spending money, you make money ;)


~ Simply Advanced ~

ps - I like how originally this was just going to be a 1-2 sentence post.. ;]



2013-09-22

Microsoft's App Studio

Today, I wrote two blog posts regarding a new product from Microsoft that allows anybody to easily and quickly create and publish Windows Phone apps.

Learn about it: What Is Microsoft’s App Studio?

Learn more about it: How To Edit App Studio Code

~ Simply Advanced ~



2013-05-18

Cross-Platform Tools For Mobile App Development

This summer I'll be experimenting with different cross-platform tools in order to be more efficient with my time. The development tools that I'm mainly looking at will create native code code for each platform that the app runs on. The biggest reason for this is performance and having a native UI that users are used to with their platform.

So, the collection that follows are my notes I took when researching many of different cross-platform tools.

In doing background research for the cross-platform tools, they are great for basic app creation. But, app can quickly become non-basic as soon as they start accessing native APIs that are only available for a specific platform. Some of the biggest pain points with the cross-platform tools may be integrating other open-source codes, using multi-touch, gestures, and native UI features/paradigms. But, there are cross-platform mobile development tools that help with those features.

A big note on using cross-platform tools to create native apps: It is not "write once, run anywhere" (WORA). The idea of creating these native apps is to maximize code reuse and/or provide a higher abstraction level for development. Up to 50-95% of the code you write can be reused depending on the type of app you are creating.

My Results:
These final choices I made are bias because I didn't want to spend over $1000 for Unity3D. I don't even want to spend $200 for MonoDroid/MonoTouch, but I will if I don't care for the free options as follows. I chose these options mainly because of their documentation, sample APIs, developer communities, and active development. Both of the following are free up to a certain point, but because I am in academia I get to go a little further with the tools.
1. MoSync
2. Titanium by Appcelerator

The following I'm not trying the following until at mid- to late- summer likely (because of cost, it can wait longer...)
1. MonoDroid/MonoTouch: ($99 academic rate per developer, per platform) The regular Mono library is free, but it is just an open source implementation of the .NET framework. It does not include tools for integrating with iOS or Android. Both of these tools integrate Mono into them.

More Specific Notes: (I take a lot of notes directly in Notepad++/Notepad)
/* Cross-platform SDK */

- Mono (native app, C#) (open source): This is just an open source version of the .NET framework to be used anywhere, like in Apple and Linux OS. http://www.mono-project.com
  - Mono for Android (proprietary): Free version only allows small apps and no access to 3rd-party libraries. Lowest paid version is $199 per platform/developer. Academic cost is $99 per platform, per developer (http://support.xamarin.com/customer/portal/articles/177042-do-you-have-any-student-or-academic-pricing-)
  - MonoTouch (for iOS) (proprietary): 
Conclusion: Good if already have much code in C#, or prefer the .NET framework.
- Unity3D - high costs
- Marmalade (native app, C++) ($15 per seat/month;$149 per seat/year): http://www.madewithmarmalade.com/
- Rhodes (HTML/Ruby): Says native app, but seems to be web app with just a native UI. http://www.motorolasolutions.com/US-EN/RhoMobile+Suite/Rhodes
- MoSync (native app, HTML/JS w/optional C/C++ extensions) (open source | Free): Seems promising. Needs Mac for iOS publishing.
- Titanium by Appcelerator (native app, JS) (Free): Uses JavaScript mainly, but it is not a web app. It is translated to native code (but, a web UI ‘could’ be made instead of a native UI). Android, iOS, and web only.
- PhoneGap (web app, HTML/JS): Very limited, though has basic access to camera, contacts, some sensors.

Conclusion: For free, use possibly MoSync or Titanium. For paid, use Xamarin’s MonoTouch/MonoDroid ($99 per developer, per platform)

Wikipedia also has a very long list of potential cross-platform tools to choose from. It may be helpful if you are trying to do more background research into the many different types of development tools that provide non-native code when compiling for different platforms.

Source: I originally put this on my developer blog.

~ Simply Advanced ~



2013-03-19

How To Collapse/Fold Code in Eclipse

The attached screenshot has everything you need to know about collapsing all the code and comments. The official name of it is called folding code.

If Ctrl+Shift+NumPad_Divide doesn't work, then you may have to remap the key via the Window->Preferences->Android->Key as seen on the left side of the screenshot.

If your device doesn't have a NumPad_Divide, then you may right-click on the narrow vertical bar where the little (+) looking things appear and the option will appear as show.



~ Simply Advanced ~