text:
package gov.hhs.onc.sdcct.transform.location.impl;

import com.fasterxml.jackson.core.JsonLocation;
import gov.hhs.onc.sdcct.beans.LocationBean;
import gov.hhs.onc.sdcct.transform.content.path.ContentPath;
import gov.hhs.onc.sdcct.utils.SdcctStringUtils.SdcctToStringBuilder;
import javax.annotation.Nullable;
import javax.xml.stream.Location;
import javax.xml.transform.SourceLocator;
import net.sf.saxon.expr.parser.ExplicitLocation;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.tree.AttributeLocation;
import net.sf.saxon.type.Type;
import org.codehaus.stax2.XMLStreamLocation2;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMLocator;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.Locator;
import org.xml.sax.SAXParseException;

public class SdcctLocation extends ExplicitLocation implements Location, LocationBean, XMLStreamLocation2 {
    private String publicId;
    private String sysId;
    private int lineNum;
    private int colNum;
    private int charOffset;
    private XMLStreamLocation2 context;
    private QName attrQname;
    private QName elemQname;
    private ContentPath contentPath;

    public SdcctLocation(@Nullable JsonLocation jsonLoc) {
        this();

        this.initializeJsonLocation(jsonLoc);
    }

    public SdcctLocation(@Nullable NodeInfo nodeInfo) {
        this(((net.sf.saxon.expr.parser.Location) nodeInfo));

        this.initializeNodeInfo(nodeInfo);
    }

    public SdcctLocation(@Nullable net.sf.saxon.expr.parser.Location loc) {
        this(((SourceLocator) loc));
    }

    public SdcctLocation(@Nullable SourceLocator srcLocator) {
        this();

        this.initializeSourceLocator(srcLocator);
        this.initializeAttributeLocation(srcLocator);
    }

    public SdcctLocation(@Nullable DOMLocator domLocator) {
        this();

        if (domLocator != null) {
            this.initializeNode(domLocator.getRelatedNode());
        }
    }

    public SdcctLocation(@Nullable SAXParseException cause) {
        this();

        this.initializeSaxParseException(cause);
    }

    public SdcctLocation(@Nullable Locator locator) {
        this();

        this.initializeLocator(locator);
        this.initializeAttributeLocation(locator);
    }

    public SdcctLocation(@Nullable Location loc) {
        this();

        this.initializeLocation(loc);
    }

    public SdcctLocation() {
        this(null, -1, -1);
    }

    public SdcctLocation(@Nullable String sysId, int lineNum, int colNum) {
        this(null, sysId, lineNum, colNum);
    }

    public SdcctLocation(@Nullable String publicId, @Nullable String sysId, int lineNum, int colNum) {
        this(publicId, sysId, lineNum, colNum, -1);
    }

    public SdcctLocation(@Nullable String publicId, @Nullable String sysId, int lineNum, int colNum, int charOffset) {
        super(null, -1, -1);

        this.publicId = publicId;
        this.sysId = sysId;
        this.lineNum = lineNum;
        this.colNum = colNum;
        this.charOffset = charOffset;
    }

    @Override
    public SdcctLocation saveLocation() {
        return this;
    }

    @Override
    public String toString() {
        SdcctToStringBuilder builder = new SdcctToStringBuilder();
        builder.append("publicId", this.publicId);
        builder.append("sysId", this.sysId);
        builder.append("lineNum", this.lineNum);
        builder.append("colNum", this.colNum);
        builder.append("charOffset", this.charOffset);

        if (this.hasContext()) {
            builder.append("context", this.context);
        }

        if (this.hasElementQname()) {
            builder.append("elemQname", this.elemQname);
        }

        if (this.hasAttributeQname()) {
            builder.append("attrQname", this.attrQname);
        }

        if (this.hasContentPath()) {
            builder.appendContent("contentPath", this.contentPath);
        }

        return builder.build();
    }

    private void initializeJsonLocation(@Nullable JsonLocation jsonLoc) {
        if (jsonLoc == null) {
            return;
        }

        this.charOffset = ((int) jsonLoc.getCharOffset());
        this.colNum = jsonLoc.getColumnNr();
        this.lineNum = jsonLoc.getLineNr();
    }

    private void initializeNodeInfo(@Nullable NodeInfo nodeInfo) {
        if (nodeInfo == null) {
            return;
        }

        int nodeKind = nodeInfo.getNodeKind();
        NodeInfo elemInfo = null;

        if (nodeKind == Type.ATTRIBUTE) {
            this.attrQname = new QName(nodeInfo.getPrefix(), nodeInfo.getURI(), nodeInfo.getLocalPart());

            elemInfo = nodeInfo.getParent();
        } else if (nodeKind == Type.ELEMENT) {
            elemInfo = nodeInfo;
        }

        if (elemInfo == null) {
            return;
        }

        this.elemQname = new QName(elemInfo.getPrefix(), elemInfo.getURI(), elemInfo.getLocalPart());
    }

    private void initializeSourceLocator(@Nullable SourceLocator srcLocator) {
        if (srcLocator == null) {
            return;
        }

        this.colNum = srcLocator.getColumnNumber();
        this.lineNum = srcLocator.getLineNumber();
        this.publicId = srcLocator.getPublicId();
        this.sysId = srcLocator.getSystemId();

        if (srcLocator instanceof javax.xml.transform.dom.DOMLocator) {
            this.initializeNode(((javax.xml.transform.dom.DOMLocator) srcLocator).getOriginatingNode());
        }
    }

    private void initializeNode(@Nullable Node node) {
        if (node == null) {
            return;
        }

        Element elem = null;

        if (node instanceof Attr) {
            Attr attr = ((Attr) node);

            this.attrQname = new QName(attr.getPrefix(), null, attr.getLocalName());

            elem = attr.getOwnerElement();
        } else if (node instanceof Element) {
            elem = ((Element) node);
        }

        if (elem == null) {
            return;
        }

        this.elemQname = new QName(elem.getPrefix(), null, elem.getLocalName());
    }

    private void initializeSaxParseException(@Nullable SAXParseException cause) {
        if (cause == null) {
            return;
        }

        this.colNum = cause.getColumnNumber();
        this.lineNum = cause.getLineNumber();
        this.publicId = cause.getPublicId();
        this.sysId = cause.getSystemId();
    }

    private void initializeLocator(@Nullable Locator locator) {
        if (locator == null) {
            return;
        }

        this.colNum = locator.getColumnNumber();
        this.lineNum = locator.getLineNumber();
        this.publicId = locator.getPublicId();
        this.sysId = locator.getSystemId();
    }

    private void initializeAttributeLocation(@Nullable Object loc) {
        if ((loc == null) || !(loc instanceof AttributeLocation)) {
            return;
        }

        AttributeLocation attrLoc = ((AttributeLocation) loc);
        StructuredQName nodeQname = attrLoc.getAttributeName();

        if (nodeQname != null) {
            this.attrQname = new QName(nodeQname);
        }

        if ((nodeQname = attrLoc.getElementName()) != null) {
            this.elemQname = new QName(nodeQname);
        }
    }

    private void initializeLocation(@Nullable Location loc) {
        if (loc == null) {
            return;
        }

        this.charOffset = loc.getCharacterOffset();
        this.colNum = loc.getColumnNumber();
        this.lineNum = loc.getLineNumber();
        this.publicId = loc.getPublicId();
        this.sysId = loc.getSystemId();

        if (loc instanceof XMLStreamLocation2) {
            this.context = ((XMLStreamLocation2) loc).getContext();
        }
    }

    public boolean hasAttributeQname() {
        return (this.attrQname != null);
    }

    @Nullable
    public QName getAttributeQname() {
        return this.attrQname;
    }

    public void setAttributeQname(@Nullable QName attrQname) {
        this.attrQname = attrQname;
    }

    public boolean hasCharacterOffset() {
        return (this.charOffset > 0);
    }

    @Override
    public int getCharacterOffset() {
        return this.charOffset;
    }

    public void setCharacterOffset(int charOffset) {
        this.charOffset = charOffset;
    }

    public boolean hasColumnNumber() {
        return (this.colNum > 0);
    }

    @Override
    public int getColumnNumber() {
        return this.colNum;
    }

    public void setColumnNumber(int colNum) {
        this.colNum = colNum;
    }

    public boolean hasContentPath() {
        return (this.contentPath != null);
    }

    @Nullable
    public ContentPath getContentPath() {
        return this.contentPath;
    }

    public void setContentPath(@Nullable ContentPath contentPath) {
        this.contentPath = contentPath;
    }

    public boolean hasContext() {
        return (this.context != null);
    }

    @Nullable
    @Override
    public XMLStreamLocation2 getContext() {
        return this.context;
    }

    public void setContext(@Nullable XMLStreamLocation2 context) {
        this.context = context;
    }

    public boolean hasElementQname() {
        return (this.elemQname != null);
    }

    @Nullable
    public QName getElementQname() {
        return this.elemQname;
    }

    public void setElementQname(@Nullable QName elemQname) {
        this.elemQname = elemQname;
    }

    public boolean hasLineNumber() {
        return (this.lineNum > 0);
    }

    @Override
    public int getLineNumber() {
        return this.lineNum;
    }

    public void setLineNumber(int lineNum) {
        this.lineNum = lineNum;
    }

    public boolean hasPublicId() {
        return (this.publicId != null);
    }

    @Nullable
    @Override
    public String getPublicId() {
        return this.publicId;
    }

    public void setPublicId(@Nullable String publicId) {
        this.publicId = publicId;
    }

    public boolean hasSystemId() {
        return (this.sysId != null);
    }

    @Nullable
    @Override
    public String getSystemId() {
        return this.sysId;
    }

    public void setSystemId(@Nullable String sysId) {
        this.sysId = sysId;
    }
}


text:
import { debug, log } from "builder-util"
import { FileTransformer } from "builder-util/out/fs"
import { readFile } from "fs-extra-p"
import * as path from "path"
import { deepAssign } from "read-config-file/out/deepAssign"
import { Packager } from "./packager"

/** @internal */
export function isElectronCompileUsed(info: Packager): boolean {
  if (info.config.electronCompile != null) {
    return info.config.electronCompile
  }

  // if in devDependencies - it means that babel is used for precompilation or for some reason user decided to not use electron-compile for production
  return hasDep("electron-compile", info)
}

/** @internal */
export function hasDep(name: string, info: Packager) {
  const deps = info.metadata.dependencies
  return deps != null && name in deps
}

/** @internal */
export function createTransformer(srcDir: string, extraMetadata: any): FileTransformer {
  const mainPackageJson = path.join(srcDir, "package.json")
  return file => {
    if (file === mainPackageJson) {
      return modifyMainPackageJson(file, extraMetadata)
    }
    else if (file.endsWith("/package.json") && file.includes("/node_modules/")) {
      return readFile(file, "utf-8")
        .then(it => cleanupPackageJson(JSON.parse(it), false))
        .catch(e => log.warn(e))
    }
    else {
      return null
    }
  }
}

/** @internal */
export interface CompilerHost {
  compile(file: string): any

  saveConfiguration(): Promise<any>
}

/** @internal */
export function createElectronCompilerHost(projectDir: string, cacheDir: string): Promise<CompilerHost> {
  const electronCompilePath = path.join(projectDir, "node_modules", "electron-compile", "lib")
  return require(path.join(electronCompilePath, "config-parser")).createCompilerHostFromProjectRoot(projectDir, cacheDir)
}

const ignoredPackageMetadataProperties = new Set(["dist", "gitHead", "keywords", "build", "scripts", "jspm", "ava", "xo", "nyc", "eslintConfig", "contributors", "bundleDependencies", "bugs", "tags"])

function cleanupPackageJson(data: any, isMain: boolean): any {
  const deps = data.dependencies
  // https://github.com/electron-userland/electron-builder/issues/507#issuecomment-312772099
  const isRemoveBabel = deps != null && typeof deps === "object" && !Object.getOwnPropertyNames(deps).some(it => it.startsWith("babel"))
  try {
    let changed = false
    for (const prop of Object.getOwnPropertyNames(data)) {
      // removing devDependencies from package.json breaks levelup in electron, so, remove it only from main package.json
      if (prop[0] === "_" || ignoredPackageMetadataProperties.has(prop) || (isMain && prop === "devDependencies") || (isRemoveBabel && prop === "babel")) {
        delete data[prop]
        changed = true
      }
    }

    if (changed) {
      return JSON.stringify(data, null, 2)
    }
  }
  catch (e) {
    debug(e)
  }

  return null
}

async function modifyMainPackageJson(file: string, extraMetadata: any) {
  const mainPackageData = JSON.parse(await readFile(file, "utf-8"))
  if (extraMetadata != null) {
    deepAssign(mainPackageData, extraMetadata)
  }

  // https://github.com/electron-userland/electron-builder/issues/1212
  const serializedDataIfChanged = cleanupPackageJson(mainPackageData, true)
  if (serializedDataIfChanged != null) {
    return serializedDataIfChanged
  }
  else if (extraMetadata != null) {
    return JSON.stringify(mainPackageData, null, 2)
  }
  return null
}

redpajama_set_name: RedPajamaGithub


text:
require 'rubygems'
require 'bundler/setup'
require 'libusb'
# require 'itunes_observer'
load 'dcled_ruby.rb'

Dcled.new.message(`osascript CurrentTrack.scpt`)

# observer = ITunesObserver.new
# observer.on_play {|result|
#  puts '%s - %s' % [result['Artist'], result['Name']]
# }
# observer.run

# usb = LIBUSB::Context.new
# usb.devices(idVendor: 0x1d34, idProduct: 0x0013).each do |device|
#
# end #(:idVendor => 0x1d34, :idProduct => 0x0013)
# # device.open_interface(0) do |handle|
# #   # handle.control_transfer(:bmRequestType => 0x40, :bRequest => 0xa0, :wValue => 0xe600, :wIndex => 0x0000, :dataOut => 1.chr)
# # end


text:
<?php

/**
 * Customer Address Postal/Zip Code Attribute Data Model
 * This Data Model Has to Be Set Up in additional EAV attribute table
 *
 * @category    Mage
 * @package     Mage_Customer
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Customer_Model_Attribute_Data_Postcode extends Mage_Eav_Model_Attribute_Data_Text
{
    /**
     * Validate postal/zip code
     * Return true and skip validation if country zip code is optional
     *
     * @param array|string $value
     * @return boolean|array
     */
    public function validateValue($value)
    {
        $countryId      = $this->getExtractedData('country_id');
        $optionalZip    = Mage::helper('directory')->getCountriesWithOptionalZip();
        if (!in_array($countryId, $optionalZip)) {
            return parent::validateValue($value);
        }
        return true;
    }
}


text:
(function () {

    "use strict";

    angular.module('structural001', [])
        .controller('ControllerStructural001', ['$scope', function ($scope) {
            $scope.numbers = [1,2,3];

        }])
        .directive('structural001', function () {
            return {
                restrict: 'A',
                transclude: 'element',
                link: function (scope, element, attributes, controller, transclude) {

                    transclude(scope, function(cloneOfTranscluded) {
                        element.after(cloneOfTranscluded);
                    })

                }
            }

        })

}());


text:
<?php
namespace app\models;

/**
 * BaseModel
 *
 */
class BaseModel extends \yii\db\ActiveRecord
{
    public function getLastError()
    {
        $errors = $this->errors;
        $error = $errors[array_keys($errors)[0]][0];
        return $error;
    }

    public function saveAndCheckResult()
    {
        $result = parent::save();
        if(!$result){
            throw new \Exception("Save Error: " . var_export($this->errors, true));
        }

        return $result;
    }
}


text:
Import-Module grouppolicy
$date = get-date -format M.d.yyyy
New-Item -Path \\backupserver\gpo\$date -ItemType directory
date >>  \\backupserver\gpo\$date.log
Backup-Gpo -All -Path \\backupserver\gpo\$date >> \\backupserver\gpo\$date.log


text:
import location_extractor
from re import findall, IGNORECASE
from .table import extract_locations_from_tables
from .webpage import extract_locations_from_webpage

# http://locallyoptimal.com/blog/2013/01/20/elegant-n-gram-generation-in-python/
def find_ngrams(input_list, n):
  return [" ".join(ngram) for ngram in zip(*[input_list[i:] for i in range(n)])]

# we're just casting a wide net and extracting
# all the capitalized words and other words that follow rules
def extract_locations_from_text(text, case_insensitive=None, debug=False):

    try:

        print("starting extract_locations_from_text")
        if debug:
            print("    [extractor] case_insensitive:", case_insensitive)

        pattern = "(?:[A-Z][a-z\u00ed]{1,15} )*(?:de )?[A-Z][a-z\u00ed]{1,15}"
        names = [name.lstrip("de ") for name in set(findall(pattern, text)) if len(name) > 3]
        if case_insensitive:
            names = [name.lstrip("de ") for name in set(findall(pattern, text, IGNORECASE)) if len(name) > 3]
        try: print("    [extractor] names from pattern:", [names])
        except: pass
        location_extractor.load_non_locations()
        nonlocations = [location.lower() for location in location_extractor.nonlocations]
        names = [name for name in names if name.lower() not in nonlocations]
        try: print("    names after filtering out nonlocations:", names)
        except: pass

        location_extractor.load_language_into_dictionary_of_keywords("English")
        for possible_abbreviation in list(set(findall("[A-Z]{2}", text))):
            print("possible_abbreviation:", possible_abbreviation)
            print("keys:", list(location_extractor.dictionary_of_keywords['English']['abbreviations'].keys()))
            #name = location_extractor.dictionary_of_keywords['English']['abbreviations'].get(possible_abbreviation, None)
            #if name:
            #    names.append({ "abbreviation": possible_abbreviation, "name": name })
            #if possible_abbreviation in location_extractor.dictionary_of_keywords['English']['abbreviations']:
            #    names.append(possible_abbreviation)

        # doing this because sometimes get grammatically incorrect tweets
        text_length = len(text)
        if text_length < 1e5:
            splat = text.split()
            names.extend([word.strip().strip(",").strip(";").strip(".")  for word in splat])

            if text_length < 500:
                names.extend([ngram.strip().strip(",").strip(";").strip(".") for ngram in find_ngrams(splat, 2)])

        #filter out nonlocations again
        names = [name for name in names if name.lower() not in nonlocations and len(name) > 3]

        # remove duplicates
        names = list(set(names))

        try: print("names are yeah:", names)
        except: pass

        results = location_extractor.extract_locations_with_context(text, names, debug=debug, return_abbreviations=True, case_insensitive=case_insensitive)

        try: print("results:", results)
        except: pass

        return results

    except Exception as e:
        print("EXCEPTION in extractor:", e)


text:
(function ($) {
    'use strict';

    $.widget('ui.map_location', {
        _create: function () {

        var element = $(this.element),
                me = this,
                options = jQuery.parseJSON(element.data('options')),
                map,
                panorama;

            me.options = options;
            me.element = element;

            me.panorama = panorama;
            me.map = map;

            me.checkGoogleVar();
        },

        checkGoogleVar: function() {

            var me = this;

            window.setTimeout(function () {

                if (window.google) {

                    var lat = me.element.data('lat'),
                        lng = me.element.data('lng'),
                        street = me.element.data('street').trim();

                    //if only the lat/lng values are known and no address is known, start the map with the given coordinates
                    //otherwise, look up the coordinates first

                    if (lat && lat != '' && lng && lng != '' && (!street || street=='') ) {

                        var latLng = new google.maps.LatLng(lat,lng);
                        me.initView(latLng);
                    } else {
                        me.geocodeAddress();
                    }

                } else {
                    me.checkGoogleVar();
                }
            }, 100);

        },

        geocodeAddress: function () {
            var me = this,
                geocoder = new google.maps.Geocoder(),
                address,
                street = me.element.attr('data-street').trim();

            if (!street || street == '') {
                address = [
                    me.element.attr('data-postcode'),
                    me.element.attr('data-city'),
                    me.element.attr('data-country')
                ];
            } else {
                address = [
                    /\s*[^0-9]+\d*/.exec(street)[0],
                    me.element.attr('data-postcode'),
                    me.element.attr('data-city'),
                    me.element.attr('data-country')
                ];
            }

            geocoder.geocode({
                address: address.join(', ')
            }, function(results, status) {
                if (status === google.maps.GeocoderStatus.OK && results.length > 0) {
                    me.initView(results[0].geometry.location);
                }
            });

        },

        initView: function(latLng) {
            var me = this,
                marker;

            if (me.options.type.toLowerCase() == "streetview") {
                me.buildStreetView(latLng);
            } else if (me.options.type.toLowerCase() == "map") {
                me.buildMap(latLng);
            }

        },

        buildMap: function(latLng) {

            var me = this,
                marker,
                options = {
                    zoom: 14,
                    center: latLng,
                    disableDoubleClickZoom: true,
                    disableDefaultUI: true,
                    keyboardShortcuts: false,
                    draggable: false,
                    scrollwheel: false,
                    panControl: false,
                    rotateControl: false,
                    scaleControl: false,
                    componentRestrictions: {}
                };

            if (me.options.blackwhite == true) {
                options.styles = [{
                   "stylers": [
                         { "saturation": -100 },
                         { "lightness": -8 },
                         { "gamma": 1.18 }
                     ]
                  }
                ];
            }

            options.draggable = false;

            me.map = new google.maps.Map(me.element[0], options);

            marker = new google.maps.Marker({
                map: me.map,
                draggable: false,
                position: latLng,
                icon: '/lib/images/marker-default.png'
            });

            if (me.options.recenter == true) {
                google.maps.event.addListenerOnce(me.map, "projection_changed", function() {
                    me.recenterMap(me.map);
                });
            }

        },

        buildStreetView: function(latLng) {

            var me = this,
                streetViewService = new google.maps.StreetViewService(),
                STREETVIEW_MAX_DISTANCE = 100;

                streetViewService.getPanoramaByLocation(latLng, STREETVIEW_MAX_DISTANCE, function (streetViewPanoramaData, status) {

                var panoramaLatLng = streetViewPanoramaData.location.latLng,
                    heading = google.maps.geometry.spherical.computeHeading(panoramaLatLng, latLng);

                if (status === google.maps.StreetViewStatus.OK) {

                      me.panorama = new google.maps.StreetViewPanorama(
                      me.element[0], {
                        position: latLng,
                        pov: {
                            heading: heading,
                            pitch: 0
                        },
                        zoom: 1,
                        disableDefaultUI: true,
                        panControl: false,
                        addressControl: false,
                        linksControl: false,
                        zoomControlOptions: false
                      });
                } else {
                    if (me.options.fallback == true) {
                        me.buildMap(latLng);
                    }
                }
            });

        },

        recenterMap: function(map) {

            var me = this,
                mainContentEl = $('.' + me.element.data('main-content-class'));

                if (mainContentEl.length == 0) return false;

                var masthead = $(me.element),
                mastheadHeight = masthead[0].clientHeight,
                mastheadOffsetTop = masthead[0].offsetTop,
                mainContentOffsetTop = mainContentEl[0].offsetTop,
                offsetY = (mastheadHeight / 2) - ((mainContentOffsetTop - mastheadOffsetTop) / 2),
                centerPoint = map.getProjection().fromLatLngToPoint(map.getCenter()),
                offsetPoint = new google.maps.Point(0, offsetY / Math.pow(2, map.getZoom())),
                newCenterPoint = new google.maps.Point(centerPoint.x, centerPoint.y + offsetPoint.y);

                map.setCenter(map.getProjection().fromPointToLatLng(newCenterPoint));
        }

    });
})(jQuery);


text:
package org.testng.internal.annotations;

import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class DefaultAnnotationTransformer extends IgnoreListener implements IAnnotationTransformer {

  @Override
  public void transform(
      ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
    super.transform(annotation, testClass, testConstructor, testMethod);
  }

  @Override
  public void transform(
      ITestAnnotation annotation, Class testClass, Constructor cons, Method tm, Class<?> clazz) {
    super.transform(annotation, testClass, cons, tm, clazz);
  }
}


text:
/**
 * This software is released as part of the Pumpernickel project.
 *
 * All com.pump resources in the Pumpernickel project are distributed under the
 * MIT License:
 * https://github.com/mickleness/pumpernickel/raw/master/License.txt
 *
 * More information about the Pumpernickel project is available here:
 * https://mickleness.github.io/pumpernickel/
 */
package com.pump.icon;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.Icon;

import com.pump.blog.ResourceSample;

/**
 * One of three icons used to toggle views in file browsers/dialogs.
 *
 *
 *

 *
 *
 * @see ColumnIcon
 * @see ListIcon
 * @see StackIcon
 */
@ResourceSample(sample = { "new com.pump.swing.resources.TileIcon(12, 12)" })
public class TileIcon implements Icon {
	final int w, h;

	public TileIcon(int width, int height) {
		w = width;
		h = height;
	}

	public int getIconHeight() {
		return h;
	}

	public int getIconWidth() {
		return w;
	}

	public void paintIcon(Component c, Graphics g0, int x, int y) {
		Graphics2D g = (Graphics2D) g0.create();

		g.setColor(Color.darkGray);
		g.translate(x, y);
		int rows = (h + 2) / 6;
		int columns = (w + 2) / 6;
		int dy = h / 2 - ((rows * 6 - 2) / 2);
		int dx = w / 2 - ((columns * 6 - 2) / 2);
		g.translate(dx, dy);
		for (int row = 0; row < rows; row++) {
			for (int col = 0; col < columns; col++) {
				g.drawRect(col * 6, row * 6, 3, 3);
			}
		}
		g.dispose();
	}
}


text:
    <meta charset="utf-8">
    <title>Modal</title>

    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
    <link rel="stylesheet" href="../../../../dist/css/ionic.css">

    <pane ng-controller="AppCtrl">

        <content has-header="true">
          <list>
            <item ng-repeat="contact in contacts">
              {{contact.name}}
            </item>
          </list>
        </content>
    </pane>


text:
import { PolymerElement } from '@polymer/polymer/polymer-element.js';
import './boardgame-fading-text.js';
import { html } from '@polymer/polymer/lib/utils/html-tag.js';

class BoardgameStatusText extends PolymerElement {
  static get template() {
    return html`

    [[message]]

      <slot id="content"></slot>

    <boardgame-fading-text trigger="[[message]]" auto-message="[[autoMessage]]" suppress="falsey"></boardgame-fading-text>
`;
  }

  static get is() {
    return "boardgame-status-text";
  }

  static get properties() {
    return {
      //The message to show. If autoMessage is set to something other than
      //'fixed' this will be set based on trigger.
      message: String,
      autoMessage: {
        type: String,
        value: "diff-up",
      },
      _textContentNode: Object,
      _observer: Object,
    }
  }

  ready() {
    super.ready();
    this.$.content.addEventListener("slotchanged", (e) => this._slotChanged(e));
    this._slotChanged();
  }

  _textContentChanged(rec) {

    let ele = rec[rec.length - 1].target;
    let message = ele.textContent ? ele.textContent : ele.innerText;
    if (!message) message = "";
    message = message.trim();
    this.message = message;
  }

  _slotChanged(e) {
    var nodes = this.$.content.assignedNodes();
    if (!nodes.length) return;
    for (var i = 0; i < nodes.length; i++) {
      let ele = nodes[i];
      let message = ele.textContent ? ele.textContent : ele.innerText;
      //This could happen if it's an empy text node for example.
      if (!message) message = "";
      message = message.trim();
      //We used to only register these if the message existed, but in many
      //real cases like the BUSTED line in blackjack it starts off as a
      //nil message.
      if (this._observer) {
        this._observer.disconnect();
        this._observer = null;
        this._node = null;
      }
      this._observer = new MutationObserver(rec => this._textContentChanged(rec));
      this._observer.observe(ele, {characterData: true});
      this.message = message;
      return;
    }
  }
}

customElements.define(BoardgameStatusText.is, BoardgameStatusText);


text:
import jQuery from "jquery";
import "jquery-ujs";
// make jQuery global
window.$ = window.jQuery = jQuery;


text:
- a standalone **app** for promoting and initiating '**Collective-Sustainable-Activism**'
- an integrative module/puzzle for the initial '**initiating phase**' of **CoLaboArthon**

## entry points

+ http://localhost:8888/users-profiling

# Structure

## Database

- 17 UN SDGs are connected to the node {"_id" : ObjectId("5b4a91d800ea790a4738a6e5"), "name" : "SDGs", "type" : "const.sdgs"}
- 17 cons SDG nodes are of type "type" : "const.sdgs.sdg"
-

# Install

Before running the App, you need to prepolate the database.

See the [INSTALL](INSTALL.md) file for details.

## Building. CLI

This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.5.0.

- **Development server**
  Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
- **Code scaffolding**
- Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
- **Build**
  Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build.
- **Further help**
  To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).

## Testing

- **Running unit tests**
  Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
- **Running end-to-end tests**
  Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/)


text:
layout: post
slug: mozilla-l10n-hackathon-ljubljana
title: Mozilla l10n hackathon Ljubljana
date: 2016-07-17 15:00:00 +01:00
image: /images/mozilla/L10n2016mozSerbiaTeam.jpg
tags:
  - mozilla
  - event
---

Every year, Mozilla organize events around the world, where many communities gather with mission to learn something new about Mozilla's plans for better and safer Internet, some new tools for easier localization, testing, etc. So this year, Mozilla Slovenia community organized l10n hackathon in Ljubljana, for eight other communities. This hackathon was specific, because each community that was invited, had to set goals for themselves, so my community choose to focus on Firefox Android SUMO articles. I can proudly say, that we manage to finish this task and translate Top 50 SUMO articles for Firefox Android, and we will continue working on translation of the rest.

![Mozilla Serbia l10n team](/images/mozilla/L10n2016mozSerbiaTeam.jpg)

##### _Mozilla Serbia l10n team_

### Sessions

#### _L20n_

[L20n](http://l20n.org/) was presented by Staś Małolepszy, who gave us good introduction to the this new localization framework developed by Mozilla for the Web. He showed us some examples of using l20n in live preview and we discussed about using it in different locales, specifically Balkans, as we have really complex grammars. For example recognizing gender or specific terms in different language. There is a really easy solution for each of these problems and that's the beauty of the l20n.

As a localizator, I can say that l20n is something really new and good for every localizator, for most people it will make a lot easier to localize things, so follow the news about it and it's progress.

#### _Pontoon_

For those who don't know, [Pontoon](https://pontoon.mozilla.org/) is an online platform for localization of Mozilla's projects. It is easy to use and it require only account registration to start with it. You can easily move from project to project, check how many translated, untranslated or missing strings some project have and many more things.

Matjaž Horvat, from Mozilla Slovenia community, gave us small introduction to Pontoon and he talked about new things they will add soon. He presented us some tools for tracking projects progress I didn't even knew exist, but are very powerful and easy to use. There are till more work to be done, but I'm sure you'll love it if you try it.

#### _Spectrograms_

Probably my favorite session. We all went outside and l10n drivers asked as couple of questions. If you agree with the question, or your answer is simply "Yes", you will move on one side (right for example). If you do not agree with the question, or your answer is "no", you would move to the other side (left). If you are not sure about it, if you agree and disagree at the same time, you would stay in the middle. Then l10n drivers would ask some of us why we sad yes, no, or why we are in the middle and this is actually a great way for them to see how volunteers feels about some things regarding the Mozilla. Maybe it doesn't sound special, but I definitely enjoyed it.

### Special surprise

Mozilla Slovenia community had special surprise for us on Saturday night - kart racing. It is something that's never been done before on any Mozilla's event. We were divided in many groups and each group members raced against each others. I must admit, I'm not a fan of driving, but I did enjoyed in this.

![Group photo](/images/mozilla/L10n2016groupPhoto.jpg)

##### _Group photo_

### Summary

I'm glad I had a chance to be a part of this amazing event and to visit Ljubljana, beautiful city full of nice people, historical monuments, bridges and nice food and beers. I truly hope I will visit again Ljubljana and I will see again people from hackathon.

I would also like to thank Gašper Deržanič, for excellent organization of this event. Form his experience I learned that it is not easy thing to organize something like this, but it is definitely worth it.

![Gašper Deržanič](/images/mozilla/L10n2016gasper.jpg)

##### _Gašper Deržanič_


text:
var get = [];
var constructor = Function();
constructor[Symbol.species] = Object;
var p = new Proxy({ constructor: constructor, flags: '', exec: function() { return /\ua796/iu; } }, { defineProperty: function(o, k) { get.push(k); return o[k]; }});

try {
  RegExp.prototype[Symbol.split].call(p, 7996);
  assert(false);
} catch (e) {
  assert(e instanceof TypeError);
}


text:
package org.bergefall.iobase.demo;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.time.LocalDateTime;

import org.bergefall.common.data.AccountCtx;
import org.bergefall.common.data.MarketDataCtx;
import org.bergefall.iobase.client.MetaTraderClientChannelInitializer;
import org.bergefall.iobase.client.MetaTraderTcpClientHandlerBase;
import org.bergefall.protocol.metatrader.MetaTraderMessageCreator;
import org.bergefall.protocol.metatrader.MetaTraderProtos.MetaTraderMessage;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class DemoClient {

	static final String HOST = System.getProperty("host", "127.0.0.1");
	static final int PORT = Integer.parseInt(System.getProperty("port", "8463"));

	private SecureRandom random = new SecureRandom();

	public static void main(String[] args) throws InterruptedException {

		DemoClient client = new DemoClient();
		client.runClient();
	}

	public void runClient() throws InterruptedException {
		EventLoopGroup group = new NioEventLoopGroup();

		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group).channel(NioSocketChannel.class).handler(new MetaTraderClientChannelInitializer());

			// Create connection
			Channel c = bootstrap.connect(HOST, PORT).sync().channel();

			// Get handle to handler so we can send message
			MetaTraderTcpClientHandlerBase handle = c.pipeline().get(MetaTraderTcpClientHandlerBase.class);
			String accountNamePrefix = getRandomString();
			for (int i = 1; i < 100; i++) {
				MetaTraderMessage msg = null;
				if (0 == i % 2) {
					MarketDataCtx mdCtx = new MarketDataCtx("CINN",
							LocalDateTime.now(),
							Long.valueOf(i), 1L, 2L, 3L, 4L, 5L, 7L, 6L, 8L, 9L);
					msg = MetaTraderMessageCreator.createMTMsg(mdCtx);
				} else {
					AccountCtx acc = new AccountCtx(accountNamePrefix + " -- "+ i, 0, "broker", "user");
					msg = MetaTraderMessageCreator.createMTMsg(acc);
				}
				handle.sendAsyncReq(msg);
				Thread.sleep(50);
			}
			Thread.sleep(5000);
			c.close();

		} finally {
			group.shutdownGracefully();
		}

	}

	private String getRandomString() {
		return new BigInteger(80, random).toString(32);
	}
}


text:
(function () {
    "use strict";

    WinJS.Namespace.define("codeShow.Pages.Demos", {
        pageDataLoaded: false,
        demosList: new WinJS.Binding.List(),
        Commands: {
            demoNavigate: util.markSupportedForProcessing(function (data) {
                data.detail.itemPromise.then(function (item) {
                    nav.navigate("/pages/demo/demo.html", { demo: item.data });
                });
            }),
        }
    });

    WinJS.UI.Pages.define("/pages/demos/demos.html", {
        init: function (element, options) {
            options = options || {};
            return Data.loaded.then(function () {
                //reset the demosList
                codeShow.Pages.Demos.demosList = new WinJS.Binding.List();

                //hydrate the demosList
                Data.demos
                    .sort(function(a, b) {
                        return (a.title < b.title ? -1 : 1);
                    })
                    .forEach(function(demo) {
                        codeShow.Pages.Demos.demosList.push(demo);
                    });

                //if a query was done, apply it
                codeShow.Pages.Demos.demosList = codeShow.Pages.Demos.demosList.createFiltered(function (i) {
                    var containsOptions = { behavior: "contains", caseSensitive: "false" };
                    return !options.queryText
                        || (i.name && (i.name.contains(options.queryText, { caseSensitive: false }) || i.name.split(" ").contains(options.queryText, containsOptions))
                            || i.keywords && i.keywords.contains(options.queryText, containsOptions)
                            || i.description && (i.description.contains(options.queryText, { caseSensitive: false }) || i.description.split(" ").contains(options.queryText, containsOptions)));
                });

            });
        }
    });
})();


text:
namespace llvm {

template <typename T, unsigned BitNum, typename BitVectorTy, bool isSigned>
class PackedVectorBase;

// This won't be necessary if we can specialize members without specializing
// the parent template.
template <typename T, unsigned BitNum, typename BitVectorTy>
class PackedVectorBase<T, BitNum, BitVectorTy, false> {
protected:
  static T getValue(const BitVectorTy &Bits, unsigned Idx) {
    T val = T();
    for (unsigned i = 0; i != BitNum; ++i)
      val = T(val | ((Bits[(Idx << (BitNum-1)) + i] ? 1UL : 0UL) << i));
    return val;
  }

  static void setValue(BitVectorTy &Bits, unsigned Idx, T val) {
    assert((val >> BitNum) == 0 && "value is too big");
    for (unsigned i = 0; i != BitNum; ++i)
      Bits[(Idx << (BitNum-1)) + i] = val & (T(1) << i);
  }
};

template <typename T, unsigned BitNum, typename BitVectorTy>
class PackedVectorBase<T, BitNum, BitVectorTy, true> {
protected:
  static T getValue(const BitVectorTy &Bits, unsigned Idx) {
    T val = T();
    for (unsigned i = 0; i != BitNum-1; ++i)
      val = T(val | ((Bits[(Idx << (BitNum-1)) + i] ? 1UL : 0UL) << i));
    if (Bits[(Idx << (BitNum-1)) + BitNum-1])
      val = ~val;
    return val;
  }

  static void setValue(BitVectorTy &Bits, unsigned Idx, T val) {
    if (val < 0) {
      val = ~val;
      Bits.set((Idx << (BitNum-1)) + BitNum-1);
    }
    assert((val >> (BitNum-1)) == 0 && "value is too big");
    for (unsigned i = 0; i != BitNum-1; ++i)
      Bits[(Idx << (BitNum-1)) + i] = val & (T(1) << i);
  }
};

/// \brief Store a vector of values using a specific number of bits for each
/// value. Both signed and unsigned types can be used, e.g
/// @code
///   PackedVector<signed, 2> vec;
/// @endcode
/// will create a vector accepting values -2, -1, 0, 1. Any other value will hit
/// an assertion.
template <typename T, unsigned BitNum, typename BitVectorTy = BitVector>
class PackedVector : public PackedVectorBase<T, BitNum, BitVectorTy,
                                            std::numeric_limits<T>::is_signed> {
  BitVectorTy Bits;
  typedef PackedVectorBase<T, BitNum, BitVectorTy,
                           std::numeric_limits<T>::is_signed> base;

public:
  class reference {
    PackedVector &Vec;
    const unsigned Idx;

    reference();  // Undefined
  public:
    reference(PackedVector &vec, unsigned idx) : Vec(vec), Idx(idx) { }

    reference &operator=(T val) {
      Vec.setValue(Vec.Bits, Idx, val);
      return *this;
    }
    operator T() const {
      return Vec.getValue(Vec.Bits, Idx);
    }
  };

  PackedVector() { }
  explicit PackedVector(unsigned size) : Bits(size << (BitNum-1)) { }

  bool empty() const { return Bits.empty(); }

  unsigned size() const { return Bits.size() >> (BitNum-1); }

  void clear() { Bits.clear(); }

  void resize(unsigned N) { Bits.resize(N << (BitNum-1)); }

  void reserve(unsigned N) { Bits.reserve(N << (BitNum-1)); }

  PackedVector &reset() {
    Bits.reset();
    return *this;
  }

  void push_back(T val) {
    resize(size()+1);
    (*this)[size()-1] = val;
  }

  reference operator[](unsigned Idx) {
    return reference(*this, Idx);
  }

  T operator[](unsigned Idx) const {
    return base::getValue(Bits, Idx);
  }

  bool operator==(const PackedVector &RHS) const {
    return Bits == RHS.Bits;
  }

  bool operator!=(const PackedVector &RHS) const {
    return Bits != RHS.Bits;
  }

  const PackedVector &operator=(const PackedVector &RHS) {
    Bits = RHS.Bits;
    return *this;
  }

  PackedVector &operator|=(const PackedVector &RHS) {
    Bits |= RHS.Bits;
    return *this;
  }

  void swap(PackedVector &RHS) {
    Bits.swap(RHS.Bits);
  }
};

// Leave BitNum=0 undefined.
template <typename T>
class PackedVector<T, 0>;

} // end llvm namespace

#endif


text:
var unirest = require('unirest');

exports.help = [
    [".google <terms>", "Search for something on Google"]
]

exports.onMessage = function(msg, dobby) {
    var terms = msg.split(" ");
    var command = terms.shift();
    terms = terms.join(" ");

    if (command == '.google' || command == '.g') {
        unirest.get("http://ajax.googleapis.com/ajax/services/search/web")
            .query({safe: "off",v: "1.0", q: terms})
            .end(function(response) {
                if (response.status == 200) {
                    var body = JSON.parse(response.body);
                    if (body){
                        var first = body.responseData.results[0];
                        if (typeof first != "undefined") {
                            dobby.respond("[URL]" + first.unescapedUrl + "[/URL]");
                        } else {
                            dobby.respond("No results.");
                        }
                    } else {
                        dobby.respond("No response.");
                    }
                } else {
                    dobby.respond("Failed!");
                }
            })
    }
}