text:
package main

import (
	"bufio"
	"fmt"
	"github.com/heatxsink/go-hue/configuration"
	"github.com/heatxsink/go-hue/portal"
	"net"
	"net/url"
	"os"
	"strings"
)

func ssdpDiscover() string {
	service := "239.255.255.250:1900"
	mac_address, err := net.ResolveUDPAddr("udp4", service)
	if err != nil {
		fmt.Println("Discover Error: ", err)
	}
	send, err := net.DialUDP("udp4", nil, mac_address)
	if err != nil {
		fmt.Println("Discover Error: ", err)
	}
	defer send.Close()
	// Send SSDP Message
	ssdp_discovery_message := []byte("M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: ssdp:discover\r\nMX: 10\r\nST: \"ssdp:all\"\r\n\r\n")
	_, err = send.Write(ssdp_discovery_message)
	if err != nil {
		fmt.Println("Discover Error: ", err)
	}
	fmt.Println("Searching for Philip Hue Hub (Could take up to 30 secs)...")
	// Listen for SSDP/HTTP NOTIFY over UDP
	listen, err := net.ListenMulticastUDP("udp4", nil, mac_address)
	if err != nil {
		fmt.Println("Discover Error: ", err)
	}
	defer listen.Close()
	description_url := ""
	for {
		b := make([]byte, 256)
		_, _, err := listen.ReadFromUDP(b)
		if err != nil {
			fmt.Println("Discover Error: ", err)
		}
		payload_message := string(b)
		headers := strings.Split(payload_message, "\r\n")
		for _, header := range headers {
			datum := strings.Split(header, ": ")
			if len(datum) > 1 {
				if datum[0] == "LOCATION" {
					if strings.Contains(datum[1], "description.xml") {
						description_url = datum[1]
						break
					}
				}
			}
		}
		if strings.Contains(description_url, "description.xml") {
			break
		}
	}
	u, err := url.Parse(description_url)
	if err != nil {
		fmt.Println("Discover Error: ", err)
	}
	hostname := ""
	if strings.Contains(u.Host, ":") {
		h := strings.Split(u.Host, ":")
		hostname = h[0]
	} else {
		hostname = u.Host
	}
	fmt.Printf("Found Hub at %s\n", hostname)
	return hostname
}

func main() {
	//hubHostname := ssdpDiscover()
	pp, err := portal.GetPortal()
	if err != nil {
		fmt.Println("Error: ", err)
		os.Exit(1)
	}
	hubHostname := pp[0].InternalIPAddress
	reader := bufio.NewReader(os.Stdin)
	fmt.Println("Please press the link button on your hub, then press [enter] to continue.")
	reader.ReadLine()
	fmt.Println("Please enter your application name:")
	data, _, _ := reader.ReadLine()
	applicationName := string(data)
	fmt.Println("Please enter your device type:")
	data1, _, _ := reader.ReadLine()
	deviceType := string(data1)
	c := configuration.New(hubHostname)
	response, err := c.CreateUser(applicationName, deviceType)
	if err != nil {
		fmt.Println("Error: ", err)
		os.Exit(1)
	}
	username := response[0].Success["username"].(string)
	fmt.Printf("Your username is %s\n", username)
}


text:
@interface BaseXibView : UIView

+ (id)loadFromXib;

- (UIView*)viewForView:(UIView *)view;

@end

redpajama_set_name: RedPajamaGithub


text:
"""
@file
@brief Defines different a set of sphinx themes.
"""
import sys
from ..installhelper.module_install import ModuleInstall

def sphinx_theme_set():
    """
    list of sphinx themes, it requires the modules in set *small*
    """
    mod = [
        ModuleInstall(
            'sphinxjp.themes.basicstrap', 'pip', purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall('sphinxjp.themecore', 'pip',
                      purpose="A sphinx theme plugin extension.", usage="SPHINX"),
        ModuleInstall('solar_theme', 'pip',
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall('cloud_sptheme', 'pip',
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall(
            'sphinx_readable_theme', 'pip', purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall(
            "hachibee-sphinx-theme", "pip", mname="hachibee_sphinx_theme", purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("wild_sphinx_theme", "pip",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinx_bootstrap_theme", "pip",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall(
            "sphinxjp.themes.sphinxjp", "pip", purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall(
            "sphinx_py3doc_enhanced_theme", "pip", purpose="sphinx theme", usage="SPHINX") if sys.version_info[0] >= 3 else None,
        ModuleInstall(
            "sphinx-better-theme", "pip", mname="better", purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("guzzle_sphinx_theme", "pip",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("flyingsphinx", "pip",
                      purpose="sphinx theme", usage="SPHINX/PY2") if sys.version_info[0] == 2 else None,
        ModuleInstall("itcase_sphinx_theme", "pip",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinxtrap", "pip",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinxcontrib-lunrsearch", "pip", mname="sphinxcontrib.lunrsearch",
                      purpose="simple autocompletion for the sphinx documentation", usage="SPHINX"),
        ModuleInstall("sphinxcontrib-imagesvg", "pip", mname="sphinxcontrib.imagesvg",
                      purpose="support svg in Sphinx", usage="SPHINX"),
        ModuleInstall("zerovm-sphinx-theme", "pip", mname="zerovm_sphinx_theme",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinx-corlab-theme", "pip", mname="sphinx_corlab_theme",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinxjp.themes.htmlslide", "pip",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinxjp.themes.gopher", "pip",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinx-gallery", "pip", mname="sphinx_gallery",
                      purpose="gallery for examples", usage="SPHINX"),
        ModuleInstall("docrepr", "pip",
                      purpose="docrepr renders Python docstrings in HTML", usage="SPHINX"),
        ModuleInstall("foundation-sphinx-theme", "pip", mname="foundation_sphinx_theme",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinx_theme_pd", "pip",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("mdn-sphinx-theme", "pip", mname="mdn_theme",
                      purpose="A Sphinx theme for the Mozilla Developer Network", usage="SPHINX"),
        ModuleInstall("sphinx-redactor-theme", "pip", mname="sphinx_redactor_theme",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinx-ioam-theme", "pip", mname="sphinx_ioam_theme",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinx-bulma-theme", "pip", mname="sphinx_bulma_theme",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("yummy-sphinx-theme", "pip", mname="yummy_sphinx_theme",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinx-modern-theme", "pip", mname="sphinx_modern_theme",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinx-materialdesign-theme", "pip", mname="sphinx_materialdesign_theme",
                      purpose="sphinx theme", usage="SPHINX"),
        ModuleInstall("sphinx_modern_theme_modified", "pip",
                      purpose="sphinx theme", usage="SPHINX"),
    ]
    return [_ for _ in mod if _ is not None]


text:
import prism from "prismjs";
import "prismjs/components/prism-markup";
import "prismjs/components/prism-javascript";
import "prismjs/components/prism-css";
import "prismjs/components/prism-diff";
import "prismjs/components/prism-jsx";
import "prismjs/components/prism-java";
import "prismjs/components/prism-ruby";
import "prismjs/themes/prism-okaidia.css";

export default prism;


text:
#ifndef SYSTEMMESSAGE_H
#define SYSTEMMESSAGE_H

#include <wchar.h>

extern char *SystemMessageA(const DWORD message_id);
extern wchar_t *SystemMessageW(const DWORD message_id);

#if defined(UNICODE) || defined(_UNICODE)
#define SystemMessage(x) SystemMessageA(x)
#else
#define SystemMessage(x) SystemMessageA(x)
#endif

#endif // SYSTEMMESSAGE_H


text:
//
//   Copyright 2015 Blu Age Corporation - Plano, Texas
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

//   This file has been modified.
//   Original copyright notice :

namespace Summer.Batch.Core
{
    /// <summary>
    /// Strategy interface for the generation of the key used in identifying
    /// unique <see cref="JobInstance"/> .
    /// </summary>
    /// <typeparam name="T"> </typeparam>
    public interface IJobKeyGenerator<in T>
    {
        /// <summary>
        /// Method to generate the unique key used to identify a job instance.
        /// </summary>
        /// <param name="source">Source information used to generate the key</param>
        /// <returns>a unique string identifying the job based on the information</returns>
        string GenerateKey(T source);
    }
}


text:
package androidx.webkit;

import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.concurrent.futures.ResolvableFuture;

import com.google.common.util.concurrent.ListenableFuture;

import org.junit.Assume;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Helper methods for common webkit test tasks.
 *
 *

 * This should remain functionally equivalent to android.webkit.cts.WebkitUtils.
 * Modifications to this class should be reflected in that class as necessary. See
 * http://go/modifying-webview-cts.
 */
public final class WebkitUtils {

    /**
     * Arbitrary timeout for tests. This is intended to be used with {@link TimeUnit#MILLISECONDS}
     * so that this can represent 20 seconds.
     *
     *
Note: only use this timeout value for the unexpected case, not for the
     * correct case, as this exceeds the time recommendation for {@link
     * androidx.test.filters.MediumTest}.
     */
    public static final long TEST_TIMEOUT_MS = 20000L; // 20s.

    // A handler for the main thread.
    private static final Handler sMainHandler = new Handler(Looper.getMainLooper());

    /**
     * Executes a callable asynchronously on the main thread, returning a future for the result.
     *
     * @param callable the {@link Callable} to execute.
     * @return a {@link ListenableFuture} representing the result of {@code callable}.
     */
    @NonNull
    public static <T> ListenableFuture<T> onMainThread(final @NonNull Callable<T> callable)  {
        return onMainThreadDelayed(0, callable);
    }

    /**
     * Executes a runnable asynchronously on the main thread.
     *
     * @param runnable the {@link Runnable} to execute.
     */
    public static void onMainThread(final @NonNull Runnable runnable)  {
        onMainThreadDelayed(0, runnable);
    }

    /**
     * Executes a callable on the main thread after a delay, returning a future for the result.
     *
     * @param delayMs the delay in milliseconds
     * @param callable the {@link Callable} to execute.
     * @return a {@link ListenableFuture} representing the result of {@code callable}.
     */
    @NonNull
    public static <T> ListenableFuture<T> onMainThreadDelayed(
            long delayMs, final @NonNull Callable<T> callable)  {
        final ResolvableFuture<T> future = ResolvableFuture.create();
        sMainHandler.postDelayed(() -> {
            try {
                future.set(callable.call());
            } catch (Throwable t) {
                future.setException(t);
            }
        }, delayMs);
        return future;
    }

    /**
     * Executes a runnable asynchronously on the main thread after a delay.
     *
     * @param delayMs the delay in milliseconds
     * @param runnable the {@link Runnable} to execute.
     */
    public static void onMainThreadDelayed(long delayMs, final @NonNull Runnable runnable) {
        sMainHandler.postDelayed(runnable, delayMs);
    }

    /**
     * Executes a callable synchronously on the main thread, returning its result. This re-throws
     * any exceptions on the thread this is called from. This means callers may use {@link
     * org.junit.Assert} methods within the {@link Callable} if they invoke this method from the
     * instrumentation thread.
     *
     *
Note: this should not be called from the UI thread.
     *
     * @param callable the {@link Callable} to execute.
     * @return the result of the {@link Callable}.
     */
    public static <T> T onMainThreadSync(final @NonNull Callable<T> callable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            throw new IllegalStateException("This cannot be called from the UI thread.");
        }
        return waitForFuture(onMainThread(callable));
    }

    /**
     * Executes a {@link Runnable} synchronously on the main thread. This is similar to {@link
     * android.app.Instrumentation#runOnMainSync(Runnable)}, with the main difference that this
     * re-throws exceptions on the calling thread. This is useful if {@code runnable} contains any
     * {@link org.junit.Assert} methods, or otherwise throws an Exception.
     *
     *
Note: this should not be called from the UI thread.
     *
     * @param runnable the {@link Runnable} to execute.
     */
    public static void onMainThreadSync(final @NonNull Runnable runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            throw new IllegalStateException("This cannot be called from the UI thread.");
        }
        final ResolvableFuture<Void> exceptionPropagatingFuture = ResolvableFuture.create();
        onMainThread(() -> {
            try {
                runnable.run();
                exceptionPropagatingFuture.set(null);
            } catch (Throwable t) {
                exceptionPropagatingFuture.setException(t);
            }
        });
        waitForFuture(exceptionPropagatingFuture);
    }

    /**
     * Throws {@link org.junit.AssumptionViolatedException} if the device does not support the
     * particular feature, otherwise returns.
     *
     *

     * This provides a more descriptive error message than a bare {@code assumeTrue} call.
     *
     *

     * Note that this method is AndroidX-specific, and is not reflected in the CTS class.
     *
     *

     * This method does not actually require API 21, but it will always fail for API < 21, so the
     * annotation has been added to make it easier to spot instances where this is being called
     * in a test. AffectedTests should be annotated with
     * {@code @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP)}
     *
     * @param featureName the feature to be checked
     */
    @RequiresApi(21)
    public static void checkFeature(@NonNull String featureName) {
        final String msg = "This device does not have the feature '" +  featureName + "'";
        final boolean hasFeature = WebViewFeature.isFeatureSupported(featureName);
        Assume.assumeTrue(msg, hasFeature);
    }

    /**
     * Waits for {@code future} and returns its value (or times out). If {@code future} has an
     * associated Exception, this will re-throw that Exception on the instrumentation thread
     * (wrapping with an unchecked Exception if necessary, to avoid requiring callers to declare
     * checked Exceptions).
     *
     * @param future the {@link Future} representing a value of interest.
     * @return the value {@code future} represents.
     */
    public static <T> T waitForFuture(@NonNull Future<T> future) {
        try {
            return future.get(TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            // ExecutionException means this Future has an associated Exception that we should
            // re-throw on the current thread. We throw the cause instead of ExecutionException,
            // since ExecutionException itself isn't interesting, and might mislead those debugging
            // test failures to suspect this method is the culprit (whereas the root cause is from
            // another thread).
            Throwable cause = e.getCause();
            // If the cause is an unchecked Throwable type, re-throw as-is.
            if (cause instanceof Error) throw (Error) cause;
            if (cause instanceof RuntimeException) throw (RuntimeException) cause;
            // Otherwise, wrap this in an unchecked Exception so callers don't need to declare
            // checked Exceptions.
            throw new RuntimeException(cause);
        } catch (InterruptedException | TimeoutException e) {
            // Don't call e.getCause() for either of these. Unlike ExecutionException, these don't
            // wrap the root cause, but rather are themselves interesting. Again, we wrap these
            // checked Exceptions with an unchecked Exception for the caller's convenience.
            //
            // Although we might be tempted to handle InterruptedException by calling
            // Thread.currentThread().interrupt(), this is not correct in this case. The interrupted
            // thread was likely a different thread than the current thread, so there's nothing
            // special we need to do.
            throw new RuntimeException(e);
        }
    }

    /**
     * Takes an element out of the {@link BlockingQueue} (or times out).
     */
    public static <T> T waitForNextQueueElement(@NonNull BlockingQueue<T> queue) {
        try {
            T value = queue.poll(TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
            if (value == null) {
                // {@code null} is the special value which means {@link BlockingQueue#poll} has
                // timed out (also: there's no risk for collision with real values, because
                // BlockingQueue does not allow null entries). Instead of returning this special
                // value, let's throw a proper TimeoutException to stay consistent with {@link
                // #waitForFuture}.
                throw new TimeoutException(
                        "Timeout while trying to take next entry from BlockingQueue");
            }
            return value;
        } catch (TimeoutException | InterruptedException e) {
            // Don't handle InterruptedException specially, since it indicates that a different
            // Thread was interrupted, not this one.
            throw new RuntimeException(e);
        }
    }

    /**
     * Write a string to a file, and create the whole parent directories if they don't exist.
     */
    public static void writeToFile(@NonNull File file, @NonNull String content)
                  throws IOException {
        file.getParentFile().mkdirs();
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(content.getBytes("utf-8"));
        }
    }

    /**
     * Delete the given File and (if it's a directory) everything within it.
     * @param currentFile The file or directory to delete. Does not need to exist.
     * @return Whether currentFile does not exist afterwards.
     */
    public static boolean recursivelyDeleteFile(@NonNull File currentFile) {
        if (!currentFile.exists()) {
            return true;
        }
        if (currentFile.isDirectory()) {
            File[] files = currentFile.listFiles();
            if (files != null) {
                for (File file : files) {
                    recursivelyDeleteFile(file);
                }
            }
        }

        return currentFile.delete();
    }

    /**
     * Check if the given looper is the current thread.
     *
     *

     * Note that this method is AndroidX-specific, and is not reflected in the CTS class.
     *
     * Backwards-compatible implementation of {@link Looper#isCurrentThread()}
     * @return {@code true} if the current thread is the loopers thread
     */
    static boolean isCurrentThread(@NonNull Looper looper) {
        return Thread.currentThread().equals(looper.getThread());
    }

    // Do not instantiate this class.
    private WebkitUtils() {}
}


text:
[![No Maintenance Intended](http://unmaintained.tech/badge.svg)](http://unmaintained.tech/)

pip
===

[![Build Status](https://travis-ci.org/kbrebanov/ansible-pip.svg?branch=master)](https://travis-ci.org/kbrebanov/ansible-pip)

Installs pip

Requirements
------------

This role requires Ansible 1.9 or higher.

Role Variables
--------------

None

Dependencies
------------

None

Example Playbook
----------------

Install pip
```yaml
- hosts: all
  roles:
    - kbrebanov.pip
```

License
-------

BSD

Author Information
------------------

Kevin Brebanov


text:
<!-- toc -->
- [Summary](#summary)
- [Motivation](#motivation)
  - [Goals](#goals)
- [Proposal](#proposal)
  - [User Stories](#user-stories)
- [Design](#design)
  - [Test Plan](#test-plan)
    - [Needed Tests](#needed-tests)
  - [Graduation Criteria](#graduation-criteria)
- [Proposed roadmap](#proposed-roadmap)
  - [1.15](#115)
  - [1.16](#116)
  - [1.18](#118)
- [Implementation History](#implementation-history)
<!-- /toc -->

## Summary

[AWS Network Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html) is an L4 Load Balancer on AWS platform, that can be used to declare a Kubernetes Service with type: LoadBalancer.

## Motivation

[AWS Network Load Balancer](https://aws.amazon.com/blogs/opensource/network-load-balancer-support-in-kubernetes-1-9/) has been supported in Kubernetes as Alpha feature since v1.9. Since then, the code and API has been stabilized. Therefore, we would like to graduate NLB support from Alpha to Beta.

### Goals

* Promote AWS Network Load Balancer support to beta version.

## Proposal

### User Stories
* An application developer or infrastructure engineer who wants to use AWS Network Load balancer can declare their Kubernetes Service with type: Load Balancer for any Kubernetes clusters running in the AWS cloud.

## Design

### Test Plan

#### Needed Tests

- Add E2E tests to allow usage of NLB to declare Kubernetes Service with type: LoadBalancer.

### Graduation Criteria
- [x] Support Cross-zone Load Balancing
- [x] Support TLS termination
- [] Have documentation for NLB annotations
- [ ] Have E2E test
- [x] Have roadmap for future development

## Proposed roadmap
### 1.15
* [ ] Graduate AWS Network Load Balancer support to beta
### 1.16
* [ ] Deprecate usage of AWS Classic Load Balancer as the default implementation for Service with LoadBalancerType on AWS
* [ ] Notify users to migrate to use NLB instead
### 1.18
* [ ] Use AWS Network Load Balancer as the default implementation for Service with LoadBalancer Type on aws

## Implementation History

- AWS Network Load Balancer Support was introduced as alpha in kubernetes 1.9
- [support cross-zone load balancing](https://github.com/kubernetes/kubernetes/pull/61064)
- [support TLS termination](https://github.com/kubernetes/kubernetes/pull/74910)
- [Bug fix - SecurityGroup rule removed incorrectly](https://github.com/kubernetes/kubernetes/pull/68422)
- [Bug fix - LoadBalancerSourceRanges not working](https://github.com/kubernetes/kubernetes/pull/74692)


text:
import json
import os
import requests
import xml.etree.ElementTree as ET

from common.basedir import BASEDIR
from selfdrive.ui.tests.test_translations import UNFINISHED_TRANSLATION_TAG
from selfdrive.ui.update_translations import LANGUAGES_FILE, TRANSLATIONS_DIR

TRANSLATION_TAG = "<translation"
BADGE_HEIGHT = 20 + 8
SHIELDS_URL = "https://img.shields.io/badge"

if __name__ == "__main__":
  with open(LANGUAGES_FILE, "r") as f:
    translation_files = json.load(f)

  badge_svg = []
  max_badge_width = 0  # keep track of max width to set parent element
  for idx, (name, file) in enumerate(translation_files.items()):
    with open(os.path.join(TRANSLATIONS_DIR, f"{file}.ts"), "r") as tr_f:
      tr_file = tr_f.read()

    total_translations = 0
    unfinished_translations = 0
    for line in tr_file.splitlines():
      if TRANSLATION_TAG in line:
        total_translations += 1
      if UNFINISHED_TRANSLATION_TAG in line:
        unfinished_translations += 1

    percent_finished = int(100 - (unfinished_translations / total_translations * 100.))
    color = "green" if percent_finished == 100 else "orange" if percent_finished > 90 else "red"

    # Download badge
    badge_label = f"LANGUAGE {name}"
    badge_message = f"{percent_finished}% complete"
    if unfinished_translations != 0:
      badge_message += f" ({unfinished_translations} unfinished)"

    r = requests.get(f"{SHIELDS_URL}/{badge_label}-{badge_message}-{color}", timeout=10)
    assert r.status_code == 200, "Error downloading badge"
    content_svg = r.content.decode("utf-8")

    xml = ET.fromstring(content_svg)
    assert "width" in xml.attrib
    max_badge_width = max(max_badge_width, int(xml.attrib["width"]))

    # Make tag ids in each badge unique to combine them into one svg
    for tag in ("r", "s"):
      content_svg = content_svg.replace(f'id="{tag}"', f'id="{tag}{idx}"')
      content_svg = content_svg.replace(f'"url(#{tag})"', f'"url(#{tag}{idx})"')

    badge_svg.extend([f'<g transform="translate(0, {idx * BADGE_HEIGHT})">', content_svg, "</g>"])

  badge_svg.insert(0, f'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="{len(translation_files) * BADGE_HEIGHT}" width="{max_badge_width}">')
  badge_svg.append("</svg>")

  with open(os.path.join(BASEDIR, "translation_badge.svg"), "w") as badge_f:
    badge_f.write("\n".join(badge_svg))


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

namespace Shuttle.Core.Infrastructure
{
	public class ReflectionService : IReflectionService
	{
        private readonly List<string> _assemblyExtensions = new List<string>
        {
            ".dll",
            ".exe"
        };

		private readonly ILog _log;

		public ReflectionService()
		{
			_log = Log.For(this);
		}

		public string AssemblyPath(Assembly assembly)
		{
			Guard.AgainstNull(assembly, "assembly");

			return !assembly.IsDynamic
				? new Uri(Uri.UnescapeDataString(new UriBuilder(assembly.CodeBase).Path)).LocalPath
				: string.Empty;
		}

		public Assembly GetAssembly(string assemblyPath)
		{
            var result = AppDomain.CurrentDomain.GetAssemblies()
                .FirstOrDefault(assembly => AssemblyPath(assembly)
                    .Equals(assemblyPath, StringComparison.InvariantCultureIgnoreCase));

			if (result != null)
			{
				return result;
			}

			try
			{
				switch (Path.GetExtension(assemblyPath))
				{
					case ".dll":
					case ".exe":
						{
							result = Path.GetDirectoryName(assemblyPath) == AppDomain.CurrentDomain.BaseDirectory
								? Assembly.Load(Path.GetFileNameWithoutExtension(assemblyPath))
								: Assembly.LoadFile(assemblyPath);
							break;
						}

					default:
						{
							result = Assembly.Load(assemblyPath);

							break;
						}
				}
			}
			catch (Exception ex)
			{
				_log.Warning(string.Format(InfrastructureResources.AssemblyLoadException, assemblyPath, ex.Message));

				var reflection = ex as ReflectionTypeLoadException;

				if (reflection != null)
				{
					foreach (var exception in reflection.LoaderExceptions)
					{
                        _log.Trace($"'{exception.AllMessages()}'.");
					}
				}
				else
				{
                    _log.Trace($"{ex.GetType()}: '{ex.AllMessages()}'.");
				}

				return null;
			}

			return result;
        }

        public Assembly FindAssemblyNamed(string name)
        {
            Guard.AgainstNullOrEmptyString(name, nameof(name));

            var assemblyName = name;
            var hasFileExtension = false;

            if (name.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase)
                ||
                name.EndsWith(".exe", StringComparison.CurrentCultureIgnoreCase))
            {
                assemblyName = Path.GetFileNameWithoutExtension(name);
                hasFileExtension = true;
            }

            var result = AppDomain.CurrentDomain.GetAssemblies()
                .FirstOrDefault(assembly => assembly.GetName()
                    .Name.Equals(assemblyName, StringComparison.InvariantCultureIgnoreCase));

            if (result != null)
            {
                return result;
            }

            var privateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                AppDomain.CurrentDomain.RelativeSearchPath ?? string.Empty);

            var extensions = new List<string>();

            if (hasFileExtension)
            {
                extensions.Add(string.Empty);
            }
            else
            {
                extensions.AddRange(_assemblyExtensions);
            }

            foreach (var extension in extensions)
            {
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Concat(name, extension));

                if (File.Exists(path))
                {
                    return GetAssembly(path);
                }

                if (!privateBinPath.Equals(AppDomain.CurrentDomain.BaseDirectory))
                {
                    path = Path.Combine(privateBinPath, string.Concat(name, extension));

                    if (File.Exists(path))
                    {
                        return GetAssembly(path);
                    }
                }
            }

            return null;
        }

        public IEnumerable<Assembly> GetAssemblies(string folder)
        {
            return GetMatchingAssemblies(string.Empty, folder);
        }

        public IEnumerable<Assembly> GetAssemblies()
        {
            return GetMatchingAssemblies(string.Empty);
        }

        public IEnumerable<Assembly> GetMatchingAssemblies(string regex, string folder)
        {
            var expression = new Regex(regex, RegexOptions.IgnoreCase);
            var result = new List<Assembly>();

            if (Directory.Exists(folder))
            {
                result.AddRange(
                    Directory.GetFiles(folder, "*.exe")
                        .Where(file => expression.IsMatch(Path.GetFileNameWithoutExtension(file)))
                        .Select(GetAssembly)
                        .Where(assembly => assembly != null));
                result.AddRange(
                    Directory.GetFiles(folder, "*.dll")
                        .Where(file => expression.IsMatch(Path.GetFileNameWithoutExtension(file)))
                        .Select(GetAssembly)
                        .Where(assembly => assembly != null));
			}

			return result;
		}

        public IEnumerable<Assembly> GetMatchingAssemblies(string regex)
        {
            var assemblies = new List<Assembly>(AppDomain.CurrentDomain.GetAssemblies());

			foreach (
				var assembly in
                GetMatchingAssemblies(regex, AppDomain.CurrentDomain.BaseDirectory)
						.Where(assembly => assemblies.Find(candidate => candidate.Equals(assembly)) == null))
			{
				assemblies.Add(assembly);
			}

			var privateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
				AppDomain.CurrentDomain.RelativeSearchPath ?? string.Empty);

			if (!privateBinPath.Equals(AppDomain.CurrentDomain.BaseDirectory))
			{
				foreach (
					var assembly in
                    GetMatchingAssemblies(regex, privateBinPath)
							.Where(assembly => assemblies.Find(candidate => candidate.Equals(assembly)) == null))
				{
					assemblies.Add(assembly);
				}
			}

			return assemblies;
		}

		public IEnumerable<Type> GetTypes<T>()
		{
			return GetTypes(typeof(T));
		}

		public IEnumerable<Type> GetTypes(Type type)
		{
			var result = new List<Type>();

			foreach (var assembly in GetAssemblies())
			{
				GetTypes(type, assembly)
					.Where(candidate => result.Find(existing => existing == candidate) == null)
					.ToList()
					.ForEach(add => result.Add(add));
			}

			return result;
		}

		public IEnumerable<Type> GetTypes<T>(Assembly assembly)
		{
			return GetTypes(typeof(T), assembly);
		}

		public IEnumerable<Type> GetTypes(Type type, Assembly assembly)
		{
			Guard.AgainstNull(type, "type");
			Guard.AgainstNull(assembly, "assemblyPath");

			return GetTypes(assembly).Where(candidate => candidate.IsAssignableTo(type) && candidate != type).ToList();
		}

		public IEnumerable<Type> GetTypes(Assembly assembly)
		{
			Type[] types;

			try
			{
				_log.Trace(string.Format(InfrastructureResources.TraceGetTypesFromAssembly, assembly));

				types = assembly.GetTypes();
			}
			catch (Exception ex)
			{
				var reflection = ex as ReflectionTypeLoadException;

				if (reflection != null)
				{
					foreach (var exception in reflection.LoaderExceptions)
					{
                        _log.Error($"'{exception.AllMessages()}'.");
					}
				}
				else
				{
                    _log.Error($"{ex.GetType()}: '{ex.AllMessages()}'.");
				}

				return new List<Type>();
			}

			return types;
		}
	}
}


text:
<?php
/**
 * License handler for GEO my WP
 *
 * This class should simplify the process of adding license information
 * to GEO my WP add-ons.
 *
 * @author Eyal Fitoussi. Inspired by a class written by Pippin Williamson
 * @version 1.1
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) )
	exit;

//abort if this page already loaded
if ( !class_exists( 'GMW_License' ) ) :

/**
 * GMW_License Class
 *
 * Responsiable for updates of the premium add-ons as well for the action links
 * of the Plugins page.
 *
*/
class GMW_License {

	private $file;
	private $license;
	private $item_name;
	private $version;
	private $author;
	private $api_url = 'https://geomywp.com';

	/**
	 * Class constructor
	 *
	 * @param string  $_file
	 * @param string  $_item_name
	 * @param string  $_version
	 * @param string  $_author
	 * @param string  $_optname
	 * @param string  $_api_url
	 */
	function __construct( $_file, $_item_name, $_license, $_version, $_author = 'Eyal Fitoussi' , $_api_url = null, $_item_id = null ) {

		$this->licenses 	= get_option( 'gmw_license_keys' );
		$this->statuses 	= get_option( 'gmw_premium_plugin_status' );
		$this->file         = $_file;
		$this->item_name    = $_item_name;
		$this->item_id      = $_item_id;
		$this->license_name = $_license;
		$this->license      = isset( $this->licenses[$_license] ) ? trim( $this->licenses[$_license] ) : '';
		$this->version      = $_version;
		$this->author       = $_author;
		$this->api_url      = is_null( $_api_url ) ? $this->api_url : $_api_url;

		//action links
		add_filter( 'plugin_action_links_' . plugin_basename( $this->file ) , array( $this, 'addon_action_links' ), 10 );
		add_action( 'after_plugin_row_' . plugin_basename( $this->file ), array( $this, 'license_key_input' ), 10 );

		// Setup hooks
		$this->includes();
		$this->auto_updater();
	}

	/**
	 * add gmw add-ons action links in plugins page
	 * @param  $links
	 * @return $links
	 */
	public function addon_action_links( $links ) {

		//if license is not activated display the "Activate License" message
		if ( empty( $this->licenses[$this->license_name] ) || !isset( $this->statuses[$this->license_name] ) || $this->statuses[$this->license_name] != 'valid' ) {
			return $links;
		}

		//if license activate display "Diactivate license before...." message
		$links['deactivate'] = __( 'Please deactivate the license key before deactivating the plugin', 'GMW' );

		return $links;
	}

	/**
	 * Append license key input box in plugins page
	 * @return [type] [description]
	 */
	public function license_key_input() {
		$license_key = new GMW_License_Key( $this->file, $this->item_name, $this->license_name );
		$license_key->license_key_output();
	}

	/**
	 * Include the updater class
	 *
	 * @access  private
	 * @return  void
	 */
	private function includes() {
		if ( ! class_exists( 'GMW_Premium_Plugin_Updater' ) ) {
			require_once 'geo-my-wp-updater.php';
		}
	}

	/**
	 * Auto updater
	 *
	 * @access  private
	 * @return  void
	 */
	private function auto_updater() {

		if ( empty( $this->license ) )
			return;

		if ( !isset( $this->statuses[$this->license_name] ) || 'valid' !== $this->statuses[$this->license_name] )
			return;

		// Setup the updater
		$gmw_updater = new GMW_Premium_Plugin_Updater(
			$this->api_url,
			$this->file,
			array(
				'version'   => $this->version,
				'license'   => $this->license,
				'item_name' => $this->item_name,
				'item_id'	=> $this->item_id,
				'author'    => $this->author
			)
		);
	}
}

/**
 * GMW_License_Key input field Class
 *
 * create input field for a license key
 */
class GMW_License_Key {

	private $file;
	private $license_name;

	/**
	 * Class constructor
	 *
	 */
	function __construct( $file ,$item_name, $license_name, $item_id = null ) {

		$this->licenses	 	= get_option( 'gmw_license_keys' );
		$this->statuses  	= get_option( 'gmw_premium_plugin_status' );
		$this->basename		= plugin_basename( $file );
		$this->file      	= basename( dirname( $file ) );
		$this->item_name	= $item_name;
		$this->item_id		= $item_id;
		$this->license_name = $license_name;
		$this->messages		= gmw_update_key_api_notices();
	}

	/**
	 * Display license key field
	 *
	 */
	public function license_key_output() {

		?>
		<tr id="<?php echo esc_attr( $this->file ); ?>-license-key-row" class="active gmw-license-key-wrapper">

					<form method="post" action="">

						<?php if ( gmw_is_license_valid( $this->license_name ) ) { ?>

								<?php _e( 'License Key:', 'GMW' ); ?>
								<input
									class="gmw-license-key-input-field"
									disabled="disabled"
									type="text"
									size="30"
									value="<?php if ( !empty( $this->licenses[$this->license_name] ) ) echo esc_attr( sanitize_text_field( $this->licenses[$this->license_name] ) ); ?>" />

								<input
									type="hidden"
									name="gmw_license_key"
									value="<?php if ( !empty( $this->licenses[$this->license_name] ) ) echo esc_attr( sanitize_text_field( $this->licenses[$this->license_name] ) ); ?>" />

								<input
									type="submit"
									name="gmw_update_key_submit"
									class="button-secondary activate-license-btn"
									style="padding: 0 9px !important;"
									title="<?php _e( 'Deactivate License Key', 'GMW' ); ?>"
									value="<?php _e( 'Deactivate License Key', 'GMW' ); ?>" />

<?php echo esc_html( $this->messages['valid'] ); ?>

								<input type="hidden" name="gmw_update_key_api_action" value="deactivate" />

						<?php } else { ?>

							<?php
							$class   = '';
							$message = $this->messages['activate'];

							if ( !empty( $this->licenses[$this->license_name] ) && isset( $this->statuses[$this->license_name] ) ) {
								$class 	  = 'gmw-license-error';
								$message  = ( array_key_exists( $this->statuses[$this->license_name], $this->messages ) ) ? $this->messages[$this->statuses[$this->license_name]] : $this->messages['missing'];
								$message .= '
';
								$message .= $this->messages['retrieve_key'];
							}
							?>

							<div class="gmw-license-wrapper gmw-license-invalid-wrapper <?php echo $class; ?>">

								<?php _e( 'License Key:', 'GMW' ); ?>
								<input
									onkeydown="if (event.keyCode == 13) { jQuery(this).closest('form').find('.activate-license-btn').click(); return false; }"
									class="gmw_license_keys gmw-addon-short-input"
									name="gmw_license_key"
									type="text"
									class="regular-text"
									size="30"
									placeholder="<?php _e( 'Enter license key', 'GMW' ); ?>"
									value="<?php if ( !empty($this->licenses[$this->license_name] ) ) echo esc_attr( sanitize_text_field( $this->licenses[$this->license_name] ) ); ?>" />

								<input
									type="submit"
									name="gmw_update_key_submit"
									class="gmw-license-key-button button-secondary activate-license-btn button-primary"
									title="<?php _e( 'Activate License Key', 'GMW'); ?>"
									style="padding: 0 8px !important;"
									value="<?php _e( 'Activate License', 'GMW' ); ?>" />

								<input type="hidden" name="gmw_update_key_api_action" value="activate" />

								<?php $allow = array(
									'a' => array(
										'href' => array(),
										'title' => array()
									),
									'br' => array()
								);
								?>

<?php echo wp_kses( $message, $allow ); ?>

						<?php } ?>

						<input type="hidden" name="gmw_item_name" value ="<?php echo esc_attr( $this->item_name ); ?>" />
						<input type="hidden" name="gmw_item_id" value ="<?php echo esc_attr( $this->item_id ); ?>" />
						<input type="hidden" name="gmw_update_key_api" value ="<?php echo esc_attr( $this->license_name ); ?>" />

						<?php wp_nonce_field( $this->license_name, $this->license_name ); ?>

						<?php $gmw_plugin = ( isset( $_GET['gmw_plugin'] ) ) ? $_GET['gmw_plugin'] : false; ?>
					</form>

		<?php
	}
}

/**
 * GMW messages for license status and notices
 *
 * @since  2.5
 * @author Eyal Fitoussi
 */
function gmw_update_key_api_notices() {

	return $messages = apply_filters( 'gmw_update_key_api_notices', array(
			'activate'				=> __( 'Please enter your license key and click "Activate License". The license key is required in order to receive automatic updated for the plugin.', 'GMW' ),
			'activated'				=> __( 'Your license for %s plugin successfully activated. Thank you for your support!', 'GMW' ),
			'deactivated'			=> __( 'Your license for %s plugin successfully deactivated.', 'GMW' ),
			'valid'					=> __( 'License is activated. Thank you for your support!', 'GMW' ),
			'no_key_entered'		=> __( 'No license key entered. Please enter the license key and try again.', 'GMW' ),
			'expired' 				=> __( 'Your license has expired. Please renew your license in order to keep getting its updates and support.', 'GMW' ),
			'no_activations_left' 	=> sprintf( __( 'Your license has no activations left. Click here to manager your license activations.', 'GMW' ), 'href="http://geomywp.com/purchase-history/" target="_blank"' ),
			'missing'				=> __( 'Something is wrong with the key you entered. Please verify the key and try again.', 'GMW' ),
			'retrieve_key'			=> sprintf( __( 'Lost or forgot your license key? Retrieve it here.', 'GMW' ), 'href="http://geomywp.com/purchase-history/" target="_blank"' ),
			'activation_error'		=> __( 'Your license for %s plugin could not be activated. See error message below!', 'GMW' ),
			'item_name_mismatch'	=> __( 'An error occurred while trying to activate your %s license. ERROR item_name_mismatch', 'GMW' )
	) );

}

/**
 * Check license status
 * @param unknown_type $addon
 * @return boolean
 */
function gmw_is_license_valid( $addon ) {

	$licenses	= get_option( 'gmw_license_keys' );
	$statuses 	= get_option('gmw_premium_plugin_status');

	if ( !empty( $statuses[$addon] ) && $statuses[$addon] == 'valid' && !empty( $licenses[$addon] ) ) {
		return true;
	} else {
		return false;
	}
}

/**
 * GMW Cheack Licenses
 *
 * Do check of licenses every 72 hours to varify that thier status is correct
 *
 * @since  2.5
 * @author Eyal Fitoussi
 */
function gmw_check_license() {

	//run licenses check every 96 hours just to make sure that their status is correct
	if ( get_transient( 'gmw_licenses_check_transient' ) == true )
		return;

	//set new transient
	set_transient( 'gmw_licenses_check_transient' , true, 60*60*96 );

	$licenses = get_option( 'gmw_license_keys' );

	if ( empty( $licenses ) )
		return;

	$statuses = get_option( 'gmw_premium_plugin_status' );

	foreach ( $licenses as $license_name => $license ) {

		if ( isset( $statuses[$license_name] ) && $statuses[$license_name] == 'valid' ) {

			$this_license = trim( $license );
			$this_name    = ucwords( str_replace( '_', ' ', $license_name ) );

			$api_params = array(
					'edd_action' => 'check_license',
					'license'    => $this_license,
					'item_name'  => urlencode( $this_name )
			);

			// Call the custom API.
			$response = wp_remote_get( add_query_arg( $api_params, GMW_REMOTE_SITE_URL ), array(
					'timeout' 	=> 15,
					'sslverify' => false
			));

			if ( is_wp_error( $response ) )
				return false;

			$license_data = json_decode( wp_remote_retrieve_body( $response ) );

			if ( !isset( $license_data ) ) {
				$statuses[$license_name] = 'inactive';
			} else {
				$statuses[$license_name] = $license_data->license;
			}

			// $license_data->license will be either "active" or "inactive"
			update_option( 'gmw_premium_plugin_status', $statuses );

		}
	}
}
add_action( 'admin_init', 'gmw_check_license');

/**
 * GMW Update license key API activate/deactivate
 *
 * @since  2.5
 * @author Eyal Fitoussi
 */
function gmw_update_key_api() {

	//check if updating license key
	if ( empty( $_POST['gmw_update_key_submit'] ) || empty( $_POST['gmw_update_key_api'] ) )
		return;

	//get the license being updated
	$license_name = $_POST['gmw_update_key_api'];

	// run a quick security check
	if ( !check_admin_referer( $license_name, $license_name ) )
		return;

	$licenses	 = get_option( 'gmw_license_keys' );
	$statuses  	 = get_option( 'gmw_premium_plugin_status' );
	$license_key = sanitize_text_field( trim( $_POST['gmw_license_key'] ) );
	$action		 = $_POST['gmw_update_key_api_action'];
	$page 		 = ( isset( $_GET['page'] ) && $_GET['page'] == 'gmw-add-ons' ) ? 'admin.php?page=gmw-add-ons' : 'plugins.php?';
	$item_name	 = $_POST['gmw_item_name'];
	$item_id	 = ( !empty( $_POST['gmw_item_id'] ) ) ? $_POST['gmw_item_id'] : false;

	//if license key field is empty
	if ( empty( $license_key ) && $action == 'activate' ) {

		unset( $licenses[$license_name] );
		update_option( 'gmw_license_keys', $licenses );

		wp_safe_redirect( admin_url( $page.'&gmw_license_status_notice=no_key_entered&license_name='.$license_name.'&item_name='.str_replace( ' ', '-', $item_name ).'&gmw_notice_status=error' ) );
		exit;
	}

	if ( empty( $_POST['gmw_license_key'] ) )
		return;

	// data to send in our API request
	$api_params = array(
			'edd_action' => $action .'_license',
			'license'    => $license_key,
			'item_name'  => urlencode( $item_name ), // the name of our product in EDD
			'item_id'	 => $item_id
	);

	// Call the custom API.
	$response = wp_remote_get( add_query_arg( $api_params, GMW_REMOTE_SITE_URL ), array( 'timeout' => 15, 'sslverify' => false ) );

	// make sure the response came back okay
	if ( is_wp_error( $response ) )
		return false;

	// decode the license data
	$license_data = json_decode( wp_remote_retrieve_body( $response ) );

	if ( $license_data->license == 'valid' ) {

		$license_notice 			= 'activated';
		$notice_status  			= 'updated';
		$statuses[$license_name] 	= $license_data->license;
		$licenses[$license_name]  	= $license_key;

		// $license_data->license will be either "active" or "inactive"
		update_option( 'gmw_premium_plugin_status', $statuses );
		update_option( 'gmw_license_keys', $licenses );

	} elseif ( $license_data->license == 'invalid' ) {

		$license_notice 			= $license_data->error;
		$notice_status  			= 'error';
		$statuses[$license_name] 	= $license_data->error;
		$licenses[$license_name]  	= $license_key;

		// $license_data->license will be either "active" or "inactive"
		update_option( 'gmw_premium_plugin_status', $statuses );
		update_option( 'gmw_license_keys', $licenses );

	} elseif ( $license_data->license == 'deactivated' || $license_data->license == 'failed' ) {

		$license_notice = 'deactivated';
		$notice_status  = 'updated';

		unset( $statuses[$license_name] );
		update_option( 'gmw_premium_plugin_status', $statuses );

	}

	//reload the page to prevent resubmission
	wp_safe_redirect( admin_url( $page.'&gmw_license_status_notice='.$license_notice.'&license_name='.$license_name.'&item_name='.str_replace( ' ', '-', $item_name ).'&gmw_notice_status='.$notice_status ) );
	exit;

}
add_action( 'admin_init', 'gmw_update_key_api');

/**
 * License API status Notices
 *
 */
function gmw_update_api_notices() {

	//check if updating license key
	if (  empty( $_GET['gmw_license_status_notice'] ) )
		return;

	$statuses  	 	= get_option( 'gmw_premium_plugin_status' );
	$messages  		= gmw_update_key_api_notices();
	$item_name 		= str_replace( '-', ' ', $_GET['item_name'] );
	$license_name 	= $_GET['license_name'];

	?>
	<div class="<?php echo $_GET['gmw_notice_status']; ?>">

		<?php esc_html( printf( $messages[$_GET['gmw_license_status_notice']], $item_name ) ); ?>

	<?php
}
add_action( 'admin_notices', 'gmw_update_api_notices' );

endif;


text:
<?php

namespace Hoa\Realdom;

use Hoa\Math;

/**
 * Class \Hoa\Realdom\Date.
 *
 * Realistic domain: date.
 *
 * @copyright  Copyright © 2007-2015 Hoa community
 * @license    New BSD License
 */
class Date extends Realdom
{
    /**
     * Realistic domain name.
     *
     * @const string
     */
    const NAME = 'date';

    /**
     * Constants that represent defined formats.
     * As examples, you could see \DateTime constants.
     *
     * @var array
     */
    protected static $_constants = null;

    /**
     * Realistic domain defined arguments.
     *
     * @var array
     */
    protected $_arguments        = [
        'RealdomString  format'    => 'c',
        'Integer        timestamp' => -1
    ];

    /**
     * Construct a realistic domain.
     *
     * @return  void
     */
    protected function construct()
    {
        if (null === static::$_constants) {
            $reflection         = new \ReflectionClass('DateTime');
            static::$_constants = $reflection->getConstants();
        }

        $constants               = &static::$_constants;
        $this['format']['value'] = preg_replace_callback(
            '#__(\w+)__#',
            function (Array $matches) use (&$constants) {
                $c = $matches[1];

                if (!isset($constants[$c])) {
                    return $matches[0];
                }

                return $constants[$c];
            },
            $this['format']->getConstantValue()
        );

        if ($this['timestamp'] instanceof Constinteger &&
            -1 === $this['timestamp']->getConstantValue()) {
            $this['timestamp'] = new Constinteger(time());
        }

        return;
    }

    /**
     * Predicate whether the sampled value belongs to the realistic domains.
     *
     * @param   mixed  $q    Sampled value.
     * @return  boolean
     */
    protected function _predicate($q)
    {
        $format = $this['format']->getConstantValue();

        try {
            $datetime = \DateTime::createFromFormat($format, $q);
        } catch (\Exception $e) {
            return false;
        }

        return
            false !== $datetime &&
            $this['timestamp']->predicate(intval($datetime->format('U')));
    }

    /**
     * Sample one new value.
     *
     * @param   \Hoa\Math\Sampler  $sampler    Sampler.
     * @return  mixed
     */
    protected function _sample(Math\Sampler $sampler)
    {
        return date(
            $this['format']->getConstantValue(),
            $this['timestamp']->sample($sampler)
        );
    }
}


text:
package edu.cmu.lti.oaqa.baseqa.answer.score.scorers;

import edu.cmu.lti.oaqa.baseqa.learning_base.AbstractScorer;
import edu.cmu.lti.oaqa.baseqa.learning_base.Scorer;
import edu.cmu.lti.oaqa.type.answer.Answer;
import edu.cmu.lti.oaqa.type.answer.CandidateAnswerOccurrence;
import edu.cmu.lti.oaqa.type.nlp.Token;
import edu.cmu.lti.oaqa.util.TypeUtil;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toSet;

/**
 * An instance of an {@link AbstractScorer} for {@link Answer}s that counts the number (and ratio)
 * of the answer's occurrences in the question.
 * In contrast to {@link ConceptOverlappingCountAnswerScorer}, the {@Token} counts, which means
 * a synonym of the same question concept is used in the passage is ignored.
 *
 * @see ConceptOverlappingCountAnswerScorer
 * @see FocusOverlappingCountAnswerScorer
 *
 * @author Zi Yang created on 4/30/15
 */
public class TokenOverlappingCountAnswerScorer extends AbstractScorer<Answer> {

  private Set<String> qtokens;

  @Override
  public void prepare(JCas jcas) throws AnalysisEngineProcessException {
    qtokens = TypeUtil.getOrderedTokens(jcas).stream()
            .flatMap(token -> Stream.of(token.getCoveredText(), token.getLemmaForm()))
            .map(String::toLowerCase).collect(toSet());
  }

  @Override
  public Map<String, Double> score(JCas jcas, Answer answer) {
    Set<CandidateAnswerOccurrence> caos = TypeUtil.getCandidateAnswerVariants(answer).stream()
            .map(TypeUtil::getCandidateAnswerOccurrences).flatMap(Collection::stream)
            .collect(toSet());
    double[] qtokenOverlappingRatios = caos.stream()
            .map(cao -> JCasUtil.selectCovered(Token.class, cao)).mapToDouble(tokens -> Scorer
                    .safeDividedBy(countMatchingToken(tokens, qtokens), tokens.size())).toArray();
    return Scorer.generateSummaryFeatures(qtokenOverlappingRatios, "token-overlap", "avg",
            "pos-ratio", "any-one");
  }

  private static int countMatchingToken(Collection<Token> tokens, Set<String> qtokens) {
    return (int) tokens.stream().filter(token -> qtokens.contains(token.getLemmaForm()) ||
            qtokens.contains(token.getCoveredText().toLowerCase())).count();
  }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>external.simplegeneric — IPython v0.10 documentation</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="top" title="IPython v0.10 documentation" href="../../index.html" />
    <link rel="up" title="The IPython API" href="../index.html" />
    <link rel="next" title="external.validate" href="IPython.external.validate.html" />
    <link rel="prev" title="external.pretty" href="IPython.external.pretty.html" />

Navigation

          index

          modules |

          next |

          previous |

IPython v0.10 documentation »

The IPython API »

external.simplegeneric¶

Module: <tt class="xref docutils literal">external.simplegeneric</tt>¶

Functions¶

<tt class="descclassname">IPython.external.simplegeneric.</tt><tt class="descname">generic</tt><big>(</big>func<big>)</big>¶

Create a simple generic function

<tt class="descclassname">IPython.external.simplegeneric.</tt><tt class="descname">test_suite</tt><big>(</big><big>)</big>¶

Table Of Contents

external.simplegeneric

Module: <tt class="docutils literal">external.simplegeneric</tt>

Functions

Previous topic

external.pretty

Next topic

external.validate

This Page

Show Source

Quick search

            <form class="search" action="../../search.html" method="get">
              <input type="text" name="q" size="18" /> <input type="submit" value="Go" />
              <input type="hidden" name="check_keywords" value="yes" />
              <input type="hidden" name="area" value="default" />
            </form>

Navigation

          index

          modules |

          next |

          previous |

IPython v0.10 documentation »

The IPython API »

      © Copyright 2008, The IPython Development Team.
      Last updated on Aug 04, 2009.
      Created using Sphinx 0.5.2.


text:
class CreateChampions < ActiveRecord::Migration
  def change
    create_table :champions do |t|
      t.string :name
      t.decimal  "ad", precision: 16, scale: 8
      t.decimal  "ap", precision: 16, scale: 8
      t.decimal  "armor", precision: 16, scale: 8
      t.decimal  "mr", precision: 16, scale: 8
      t.decimal  "hp", precision: 16, scale: 8
      t.decimal  "crit", precision: 1, scale: 8
      t.decimal  "adPerLv", precision: 16, scale: 8
      t.decimal  "apPerLv", precision: 16, scale: 8
      t.decimal  "armorPerLv", precision: 16, scale: 8
      t.decimal  "mrPerLv", precision: 16, scale: 8
      t.decimal  "hpPerLv", precision: 16, scale: 8
      t.decimal  "critPerLv", precision: 16, scale: 8
      t.timestamps null: false
    end
  end
end


text:
/*
 * Created on 02/03/2007
 */
package llvmmop.parser.ast.expr;

import llvmmop.parser.ast.visitor.GenericVisitor;
import llvmmop.parser.ast.visitor.VoidVisitor;

/**
 * @author Julio Vilmar Gesser
 */
public final class NullLiteralExpr extends LiteralExpr {

    public NullLiteralExpr(int line, int column) {
        super(line, column);
    }

    @Override
    public <A> void accept(VoidVisitor<A> v, A arg) {
        v.visit(this, arg);
    }

    @Override
    public <R, A> R accept(GenericVisitor<R, A> v, A arg) {
        return v.visit(this, arg);
    }
}


text:
package cmri.snapshot.api.controller;

import cmri.snapshot.api.domain.ModelType;
import cmri.snapshot.api.domain.ResponseMessage;
import cmri.snapshot.api.helper.LikeHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by zhuyin on 1/28/16.
 */
@RestController
@RequestMapping("/specialShotLike")
public class SpecialShotLikeController {

    /**
     * 用户对活动点赞
     *
     * @param uid 用户id
     * @param shotId 对哪个活动点赞
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseMessage add(long uid, long shotId){
        return LikeHelper.add(uid, shotId, ModelType.Shot);
    }

    /**
     * 用户取消对活动点赞
     *
     * @param uid 用户id
     * @param shotId 被取消点赞的活动id
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResponseMessage delete(long uid, long shotId){
        return LikeHelper.delete(uid, shotId, ModelType.Shot);
    }
}


text:
package com.enstage.wibmo.sdk.inapp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.enstage.wibmo.sdk.R;
import com.enstage.wibmo.sdk.WibmoSDK;
import com.enstage.wibmo.sdk.WibmoSDKConfig;
import com.enstage.wibmo.sdk.inapp.pojo.W2faInitRequest;
import com.enstage.wibmo.sdk.inapp.pojo.W2faInitResponse;
import com.enstage.wibmo.sdk.inapp.pojo.WPayInitRequest;
import com.enstage.wibmo.sdk.inapp.pojo.WPayInitResponse;
import com.enstage.wibmo.util.WibmoAnalyticsHelper;
import com.wibmo.analytics.entiry.AnalyticsEvent;
import com.wibmo.analytics.test.RestClientHelper;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * Created by akshath on 20/10/14.
 */
public class InAppBrowserActivity extends Activity {
    private static final String TAG = "wibmo.sdk.InAppBrowser";

    public static final int REQUEST_CODE = 0x0000c0c0; // Only use bottom 16 bits

    private View view = null;

    private Context context = null;

    private String qrMsg;

    private FrameLayout mainView;
    private WebView webView;

    private W2faInitRequest w2faInitRequest;
    private W2faInitResponse w2faInitResponse;

    private WPayInitRequest wPayInitRequest;
    private WPayInitResponse wPayInitResponse;

    private boolean resultSet;
    private boolean isViewSmall = true;
    private boolean isDebuggable = false; //make it false in prod

    //tracking
    private String lastUrl;
    private StringBuilder comments = new StringBuilder();

    private AnalyticsEvent wibmoAnalyticsEvent;
    private Activity activity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = (Context) this;
        activity = this;
        InAppUtil.addBreadCrumb(InAppUtil.BREADCRUMB_InAppBrowserActivity);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {

            w2faInitRequest = (W2faInitRequest) extras
                    .getSerializable("W2faInitRequest");
            w2faInitResponse = (W2faInitResponse) extras
                    .getSerializable("W2faInitResponse");

            wPayInitRequest = (WPayInitRequest) extras
                    .getSerializable("WPayInitRequest");
            wPayInitResponse = (WPayInitResponse) extras
                    .getSerializable("WPayInitResponse");

            if (w2faInitRequest != null && w2faInitResponse!=null) {
                qrMsg = "Wibmo InApp payment";
            } else if (wPayInitRequest != null && wPayInitResponse!=null) {
                qrMsg = "Wibmo InApp payment";
            } else {
                sendAbort(WibmoSDK.RES_CODE_FAILURE_SYSTEM_ABORT, "SDK Browser - InitReq was null");
                return;
            }
        }

        resultSet = false;

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setProgressBarIndeterminateVisibility(false);

        LayoutInflater inflator = getLayoutInflater();
        view = inflator.inflate(R.layout.activity_inapp_browser, null, false);
        view.startAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.slide_in_left));
        setContentView(view);

        webView = (WebView) findViewById(R.id.webView);
        mainView = (FrameLayout) findViewById(R.id.layout_root);
        if(isDebuggable) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                WebView.setWebContentsDebuggingEnabled(true);
            }
        }

        final Activity activity = this;

        webView.setWebViewClient(new WebViewClient() {
            boolean stopCalled = false;

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.i(TAG, "onPageStarted: ->" + url+"<-");
                lastUrl = url;
                if(lastUrl!=null) {
                    int i = lastUrl.indexOf("?");
                    if(i!=-1) {
                        lastUrl = lastUrl.substring(0, i);
                    }
                }
            }

            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {

                boolean disableRetryOnWebviewPost = WibmoSDK.isRetryDisabledForWebviewPost();
                if(disableRetryOnWebviewPost) {
                    Log.i(TAG, "POST refresh not enabled!");
                    return;
                } else {
                    resend.sendToTarget();
                }
            }

            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                comments.append("bad certificate : ").append(error.toString());
                if(WibmoSDKConfig.isTestMode()) {
                    Log.w(TAG, "We have bad certificate.. but this is test mode so okay");
                    Toast.makeText(activity, "Test Mode!! We have bad certificate.. but this is test mode so okay",
                            Toast.LENGTH_SHORT).show();
                    handler.proceed(); // Ignore SSL certificate errors
                } else {
                    InAppUtil.manageWebViewReceivedSslError(activity, view, handler, error);
                }
            }

            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                Log.e(TAG, "errorCode: "+errorCode+"; description: " + description + "; " + failingUrl);
                comments.append("onReceivedError : ").append(description);
                InAppUtil.manageWebViewOnError(activity, webView, errorCode, description, failingUrl, null);
            }

            public void onPageFinished(WebView view, String url) {
                Log.i(TAG, "onPageFinished: ->" + url+"<-" + stopCalled);
                if(WibmoSDKConfig.isTestMode()) {
                    /*
                    Toast.makeText(activity, "Url " + url,
                            Toast.LENGTH_SHORT).show();
                    */
                }

                view.zoomOut();
            }
        });

        //---
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        //webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);

        //webSettings.setLoadWithOverviewMode(true);
        //webSettings.setUseWideViewPort(true);

        //webView.setPadding(0, 0, 0, 0);
        //webView.setInitialScale(1);

        Log.d(TAG, "Webview: " + webView);
        //--

        final ProgressBar webViewProgressBar = (ProgressBar) findViewById(R.id.web_view_progress_bar);

        webView.setWebChromeClient(new WebChromeClient() {

            public void onProgressChanged(WebView view, int progress) {
                // Activities and WebViews measure progress with different
                // scales.
                // The progress meter will automatically disappear when we
                // reach 100%
                Log.i(TAG, "progress: " + progress);
                webViewProgressBar.setProgress(progress);
                if(progress==100) {
                    webViewProgressBar.setVisibility(View.GONE);
                } else if(webViewProgressBar.getVisibility()!=View.VISIBLE) {
                    webViewProgressBar.setVisibility(View.VISIBLE);
                }

                String url = view.getUrl();
                if(url!=null) {
                    if (isViewSmall && url.indexOf(WibmoSDKConfig.getWibmoNwDomainOnly()) == -1) {
                        changeSizeToFull();
                    } else if (isViewSmall == false && url.indexOf(WibmoSDKConfig.getWibmoNwDomainOnly()) != -1) {
                        changeSizeToSmall();
                    }
                }
            }
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                Log.i(TAG, "onJsConfirm");
                AlertDialog dialog = new AlertDialog.Builder(activity)
                        .setMessage(message)
                        .setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                result.cancel();
                            }
                        })
                        .setNegativeButton(activity.getString(R.string.label_cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.cancel();
                            }
                        })
                        .setPositiveButton(activity.getString(R.string.label_ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        })
                        .create();
                dialog.show();
                return true;
            }
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                Log.i(TAG, "onJsAlert");
                AlertDialog dialog = new AlertDialog.Builder(activity)
                        .setMessage(message)
                        .setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                result.cancel();
                            }
                        })
                        .setPositiveButton(activity.getString(R.string.label_ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        })
                        .create();
                dialog.show();
                return true;
            }
        });

        class MyJavaScriptInterface {
            @android.webkit.JavascriptInterface
            @SuppressWarnings("unused")
            public void notifyAbort() {
                sendAbort(WibmoSDK.RES_CODE_FAILURE_USER_ABORT, "SDK Browser - JS");
            }

            @android.webkit.JavascriptInterface
            @SuppressWarnings("unused")
            public void notifyFailure(String resCode, String resDesc) {
                if(WibmoSDKConfig.isTestMode()) {
                    /*
                    Toast.makeText(activity, "notifyFailure called",
                            Toast.LENGTH_SHORT).show();
                            */
                }
                sendFailure(resCode, resDesc);
            }

            @android.webkit.JavascriptInterface
            @SuppressWarnings("unused")
            public void notifySuccess(String resCode, String resDesc,
                    String dataPickUpCode, String wTxnId, String msgHash) {
                if(WibmoSDKConfig.isTestMode()) {
                    /*
                    Toast.makeText(activity, "notifySuccess called",
                            Toast.LENGTH_SHORT).show();
                            */
                }
                _recordSuccess(resCode, resDesc,
                        dataPickUpCode, wTxnId, msgHash);
                _notifyCompletion();
            }

            @android.webkit.JavascriptInterface
            @SuppressWarnings("unused")
            public void recordSuccess(String resCode, String resDesc,
                                      String dataPickUpCode, String wTxnId, String msgHash) {
                if(WibmoSDKConfig.isTestMode()) {
                    /*
                    Toast.makeText(activity, "notifySuccess called",
                            Toast.LENGTH_SHORT).show();
                            */
                }
                _recordSuccess(resCode, resDesc,
                        dataPickUpCode, wTxnId, msgHash);
            }

            @android.webkit.JavascriptInterface
            @SuppressWarnings("unused")
            public void notifyCompletion() {
                if(WibmoSDKConfig.isTestMode()) {
                    /*
                    Toast.makeText(activity, "notifySuccess called",
                            Toast.LENGTH_SHORT).show();
                            */
                }
                _notifyCompletion();
            }

            @android.webkit.JavascriptInterface
            @SuppressWarnings("unused")
            public void toast(String msg) {
                Log.d(TAG, "alert: " + msg);
                InAppUtil.showToast(activity, msg);
            }

            @android.webkit.JavascriptInterface
            @SuppressWarnings("unused")
            public void alert(String msg) {
                Log.d(TAG, "alert: "+msg);
                showMsg(msg);
            }

            @android.webkit.JavascriptInterface
            @SuppressWarnings("unused")
            public void log(String msg) {
                Log.v(TAG, "log: " + msg);
            }

            @android.webkit.JavascriptInterface
            @SuppressWarnings("unused")
            public void userCancel() {
                Log.d(TAG, "userCancel");
                onBackPressed();
            }
        }
        webView.addJavascriptInterface(new MyJavaScriptInterface(), "WibmoSDK");
        //webView.clearCache(true);

        if(savedInstanceState!=null) {
            if(savedInstanceState.getBoolean("wasSaved", false)) {
                Log.i(TAG, "was restored activity.. lets stop here");
                return;
            }
        }

        if(w2faInitResponse!=null) {
            webView.postUrl(w2faInitResponse.getWebUrl(), "a=b".getBytes());
            Log.i(TAG, "web posting to " + w2faInitResponse.getWebUrl());
        }

        if(wPayInitResponse!=null) {
            webView.postUrl(wPayInitResponse.getWebUrl(), "a=b".getBytes());
            Log.i(TAG, "web posting to " + wPayInitResponse.getWebUrl());
        }

        //webView.requestFocus();
    }

    private void askRetryOnError(final  WebView webView) {
        String msg = getString(com.enstage.wibmo.sdk.R.string.msg_internet_issue);

        final Activity activity = this;

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setMessage(msg)
                .setCancelable(false)
                .setPositiveButton(
                        activity.getString(com.enstage.wibmo.sdk.R.string.label_try_again),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Log.v(TAG, "Calling reload");
                                Toast.makeText(activity, activity.getString(R.string.label_pl_wait_reloading),
                                        Toast.LENGTH_SHORT).show();
                                webView.reload();
                            }
                        })
                .setNegativeButton(
                        activity.getString(com.enstage.wibmo.sdk.R.string.label_cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (dialog != null) {
                                    try {
                                        dialog.dismiss();
                                    } catch (IllegalArgumentException e) {
                                        Log.e(TAG, "Error: " + e);
                                    }
                                }
                            }
                        });

        Dialog dialog = builder.create();
        try {
            dialog.show();
        } catch (Throwable e) {
            Log.e(TAG, "Error: " + e, e);
        }
    }

    private void changeSizeToFull() {
        Log.i(TAG, "changeSizeToFull "+webView.getUrl());

        isViewSmall = false;
        mainView.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        webView.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));

        /*
        //webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.setInitialScale(1);
        webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
        */
    }

    private void changeSizeToSmall() {
        Log.i(TAG, "changeSizeToSmall "+webView.getUrl());

        isViewSmall = true;
        mainView.setLayoutParams(new FrameLayout.LayoutParams(
                getResources().getDimensionPixelSize(R.dimen.activity_inapp_browser_width), ViewGroup.LayoutParams.MATCH_PARENT));
        webView.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));

        /*
        //webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setLoadWithOverviewMode(false);
        webView.getSettings().setUseWideViewPort(false);
        webView.setInitialScale(0);
        webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        */
    }

    private void sendAbort() {
        sendAbort(WibmoSDK.RES_CODE_FAILURE_USER_ABORT, "sdk browser - user abort");
    }

    private void sendAbort(String resCode, String resDesc) {
        //webView.destroy();

        Intent resultData = new Intent();
        resultData.putExtra(InAppUtil.EXTRA_KEY_RES_CODE, resCode);
        resultData.putExtra(InAppUtil.EXTRA_KEY_RES_DESC, resDesc);

        if(w2faInitResponse!=null) {
            resultData.putExtra(InAppUtil.EXTRA_KEY_WIBMO_TXN_ID, w2faInitResponse.getWibmoTxnId());
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_TXN_ID, w2faInitResponse.getTransactionInfo().getMerTxnId());
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_APP_DATA, w2faInitResponse.getTransactionInfo().getMerAppData());
        } else if(wPayInitResponse!=null) {
            resultData.putExtra(InAppUtil.EXTRA_KEY_WIBMO_TXN_ID, wPayInitResponse.getWibmoTxnId());
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_TXN_ID, wPayInitResponse.getTransactionInfo().getMerTxnId());
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_APP_DATA, wPayInitResponse.getTransactionInfo().getMerAppData());
        }

        resultData.putExtra(InAppUtil.EXTRA_KEY_LAST_URL, lastUrl);
        resultData.putExtra(InAppUtil.EXTRA_KEY_COMMENTS, comments.toString());

        sendWibmoAnalyticsData(false);

        setResult(Activity.RESULT_CANCELED, resultData);
        finish();
    }

    private void sendWibmoAnalyticsData(boolean isTxnSuccess) {
        boolean isChargeLater;

        wibmoAnalyticsEvent = new AnalyticsEvent();
        wibmoAnalyticsEvent.setEventTxnId(UUID.randomUUID().toString());
        wibmoAnalyticsEvent.setEventName(WibmoAnalyticsHelper.IAP_WEB_RESPONSE);

        if(wPayInitRequest!=null) {
            if(wPayInitRequest.getTransactionInfo() != null) {
                isChargeLater = wPayInitRequest.getTransactionInfo().isChargeLater();
                wibmoAnalyticsEvent.setExtraKey4(WibmoSDK.VERSION + "|" + isChargeLater + "|" + wPayInitRequest.getTransactionInfo().isTxnAmtKnown()+"|"+W2faInitRequest.version);
            } if(wPayInitRequest.getCustomerInfo() != null) {
                wibmoAnalyticsEvent.setCustomerInfo(WibmoAnalyticsHelper.makeCustomerInfo(wPayInitRequest.getCustomerInfo()));
            }
            createWAData(wibmoAnalyticsEvent, wPayInitRequest);
        } else if(w2faInitRequest!=null) {
            if(w2faInitRequest.getTransactionInfo() != null) {
                isChargeLater = w2faInitRequest.getTransactionInfo().isChargeLater();
                wibmoAnalyticsEvent.setExtraKey4(WibmoSDK.VERSION + "|" + isChargeLater + "|" + w2faInitRequest.getTransactionInfo().isTxnAmtKnown()+"|"+W2faInitRequest.version);
            } if(w2faInitRequest.getCustomerInfo() != null) {
                wibmoAnalyticsEvent.setCustomerInfo(WibmoAnalyticsHelper.makeCustomerInfo(w2faInitRequest.getCustomerInfo()));
            }
            createWAData(wibmoAnalyticsEvent, w2faInitRequest);
        }
        if(wPayInitResponse != null) {
            wibmoAnalyticsEvent.setExtraKey2(wPayInitResponse.getWibmoTxnId());
            if(wPayInitResponse.getMerchantInfo() != null) {
                wibmoAnalyticsEvent.setMerchantInfo(WibmoAnalyticsHelper.makeMerchantInfo(wPayInitResponse.getMerchantInfo()));
            }
        } else if(w2faInitResponse != null) {
            wibmoAnalyticsEvent.setExtraKey2(w2faInitResponse.getWibmoTxnId());
            if(w2faInitResponse.getMerchantInfo() != null) {
                wibmoAnalyticsEvent.setMerchantInfo(WibmoAnalyticsHelper.makeMerchantInfo(w2faInitResponse.getMerchantInfo()));
            }
        }
        if(isTxnSuccess) {
            wibmoAnalyticsEvent.setStatus(true);
        } else {
            wibmoAnalyticsEvent.setStatus(false);
        }
        wibmoAnalyticsEvent.setIntermediate(false);
        wibmoAnalyticsEvent.setDateTime(new Date());
        wibmoAnalyticsEvent.setFunnelId(WibmoAnalyticsHelper.IAP_FUNNEL_ID);
        wibmoAnalyticsEvent.setFunnelStepId(WibmoAnalyticsHelper.IAP_WEB_RESPONSE_EVENT);
        wibmoAnalyticsEvent.setIp("NA");
        HashMap extraDataForWA = new HashMap<>(10);
        extraDataForWA.put("extraKey1", getString(R.string.lbl_mer_txn_id));
        extraDataForWA.put("extraKey2", getString(R.string.lbl_wibmo_txn_id));
        extraDataForWA.put("extraKey4", "SDKVer|ChargeLater|TxnAmtKnown|IAPVersion");
        extraDataForWA.put("extraKey5", "SDKType");
        HashMap<String, Object> nwInfoData = RestClientInitializer.getNetworkInfo(activity);
        extraDataForWA.putAll(nwInfoData);
        wibmoAnalyticsEvent.setExtraKv(extraDataForWA);
        wibmoAnalyticsEvent.setExtraKey5("Android");
        RestClientHelper.postEvent(wibmoAnalyticsEvent, "upsert");
    }

    private void createWAData(AnalyticsEvent wibmoAnalyticsEvent, W2faInitRequest initReq) {
        try {
            wibmoAnalyticsEvent.setCurrency(initReq.getTransactionInfo().getTxnCurrency());
            wibmoAnalyticsEvent.setAmount(Long.parseLong(initReq.getTransactionInfo().getTxnAmount()));
            wibmoAnalyticsEvent.setExtraKey1(initReq.getTransactionInfo().getMerTxnId());
            wibmoAnalyticsEvent.setCustomerInfo(RestClientInitializer.makeCustInfo(initReq));
            wibmoAnalyticsEvent.setMerchantInfo(RestClientInitializer.makeMerInfo(initReq));
            if(initReq.getDeviceInfo() != null) {
                wibmoAnalyticsEvent.setAppInfo(RestClientInitializer.makeAppInfo(initReq));
            }
        } catch(Exception e) {
            Log.e(TAG, "Error: "+e , e);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private void sendFailure(String resCode, String resDesc) {
        //webView.destroy();

        Intent resultData = new Intent();
        resultData.putExtra(InAppUtil.EXTRA_KEY_RES_CODE, resCode);
        resultData.putExtra(InAppUtil.EXTRA_KEY_RES_DESC, "sdk browser - "+resDesc);

        if(w2faInitResponse!=null) {
            resultData.putExtra(InAppUtil.EXTRA_KEY_WIBMO_TXN_ID, w2faInitResponse.getWibmoTxnId());
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_TXN_ID, w2faInitResponse.getTransactionInfo().getMerTxnId());
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_APP_DATA, w2faInitResponse.getTransactionInfo().getMerAppData());
        } else if(wPayInitResponse!=null) {
            resultData.putExtra(InAppUtil.EXTRA_KEY_WIBMO_TXN_ID, wPayInitResponse.getWibmoTxnId());
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_TXN_ID, wPayInitResponse.getTransactionInfo().getMerTxnId());
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_APP_DATA, wPayInitResponse.getTransactionInfo().getMerAppData());
        }

        resultData.putExtra(InAppUtil.EXTRA_KEY_LAST_URL, lastUrl);
        resultData.putExtra(InAppUtil.EXTRA_KEY_COMMENTS, comments.toString());

        sendWibmoAnalyticsData(false);

        setResult(Activity.RESULT_CANCELED, resultData);
        finish();
    }

    private void _recordSuccess(String resCode, String resDesc,
            String dataPickUpCode, String wTxnId, String msgHash) {
        //webView.destroy();

        Intent resultData = new Intent();
        resultData.putExtra(InAppUtil.EXTRA_KEY_RES_CODE, resCode);
        resultData.putExtra(InAppUtil.EXTRA_KEY_RES_DESC, resDesc);

        resultData.putExtra(InAppUtil.EXTRA_KEY_DATA_PICKUP_CODE, dataPickUpCode);
        resultData.putExtra(InAppUtil.EXTRA_KEY_WIBMO_TXN_ID, wTxnId);
        resultData.putExtra(InAppUtil.EXTRA_KEY_MSG_HASH, msgHash);

        if(w2faInitResponse!=null) {
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_TXN_ID, w2faInitResponse.getTransactionInfo().getMerTxnId());
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_APP_DATA, w2faInitResponse.getTransactionInfo().getMerAppData());
        } else if(wPayInitResponse!=null) {
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_TXN_ID, wPayInitResponse.getTransactionInfo().getMerTxnId());
            resultData.putExtra(InAppUtil.EXTRA_KEY_MER_APP_DATA, wPayInitResponse.getTransactionInfo().getMerAppData());
        }

        setResult(Activity.RESULT_OK, resultData);

        resultSet = true;
    }

    private void _notifyCompletion() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        setResult(resultCode, data);
        finish();
    }

    public void processBackAction() {
        if(resultSet) {
            Log.v(TAG, "resultSet was true");
            _notifyCompletion();
        } else {
            Log.v(TAG, "resultSet was false");
            sendAbort(WibmoSDK.RES_CODE_FAILURE_USER_ABORT, "sdk browser - back press");
        }
    }

    @Override
    public void onBackPressed() {
        final Activity activity = this;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setMessage(
                activity.getString(R.string.confirm_cancel))
                .setPositiveButton(
                        activity.getString(R.string.label_yes),
                        new DialogInterface.OnClickListener() {
                            public void onClick(
                                    DialogInterface dialog, int id) {
                                processBackAction();
                            }
                        })
                .setNegativeButton(
                        activity.getString(R.string.label_no),
                        new DialogInterface.OnClickListener() {
                            public void onClick(
                                    DialogInterface dialog, int id) {
                                // User cancelled the dialog
                                if (dialog != null) {
                                    try {
                                        dialog.dismiss();
                                    } catch (IllegalArgumentException e) {
                                        Log.e(TAG, "Error: " + e);
                                    }
                                }
                            }
                        });

        Dialog dialog = builder.create();
        dialog.setCancelable(false);
        try {
            dialog.show();
        } catch (Throwable e) {
            Log.e(TAG, "Error: " + e, e);

            processBackAction();
        }
    }

    @SuppressLint("NewApi")
    protected void showMsg(String msg) {
        Log.d(TAG, msg);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(msg);
        builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();

            }
        });

        AlertDialog alert = builder.create();
        alert.setIcon(android.R.drawable.ic_dialog_alert);
        alert.setCancelable(false);
        try {
            alert.show();
        } catch(Throwable e) {
            Log.e(TAG, "error: " + e, e);
            InAppUtil.showToast(this, msg);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        Log.v(TAG, "onSaveInstanceState");
        super.onSaveInstanceState(outState);

        outState.putBoolean("wasSaved", true);
    }
}


text:
package com.androiddomainmentor.rovirunner.model.impl;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;

import com.androiddomainmentor.rovirunner.model.IMediaStoreObserver;
import com.androiddomainmentor.rovirunner.model.IRRDBUpdater;

public class MediaStoreObserver extends ContentObserver implements IMediaStoreObserver
{
    private static final int QUERY_MEDIASTORE = 0;

    private IRRDBUpdater m_rrdbUpdater = null;

    private Context m_context = null;
    private static final class QueryHandler extends AsyncQueryHandler
    {
        private IMediaStoreObserver m_observer = null;

        public QueryHandler( ContentResolver cr,
                             IMediaStoreObserver observer )
        {
            super( cr );
            m_observer = observer;
        }

        @Override
        protected void onQueryComplete( int token,
                                        Object cookie,
                                        Cursor cursor )
        {
            if ( QUERY_MEDIASTORE == token )
            {
                m_observer.updateRRDB( cursor );
            }
        }

    }
    private QueryHandler m_queryHandler = null;

    public MediaStoreObserver( Handler handler,
                               Context context )
    {
        super( handler );
        m_context = context;
        m_queryHandler = makeNewQueryHandler();
    }

    public QueryHandler makeNewQueryHandler()
    {
        ContentResolver cr = m_context.getContentResolver();
        return new QueryHandler( cr,
                                 this );
    }

    @Override
    public void onChange( boolean selfChange )
    {
        this.onChange( selfChange,
                       null );
    }

    @Override
    public void onChange( boolean selfChange,
                          Uri uri )
    {
        // TODO [2014-01-13 KW] why would this be null?
        if ( null == uri )
        {
            uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }

        // query the DB asynchronously
        // TODO [2013-12-09 KW] can I get a cursor of removed rows?
        String[] projectionColumns = { MediaStore.Audio.Media._ID,
                                       MediaStore.Audio.Media.DATA, // path
                                       MediaStore.Audio.Media.ARTIST,
                                       MediaStore.Audio.Media.ALBUM,
                                       MediaStore.Audio.Media.TITLE,
                                       MediaStore.Audio.Media.MIME_TYPE };
        String whereClause =   MediaStore.Audio.Media.MIME_TYPE
                             + "=?"
                             + " OR "
                             + MediaStore.Audio.Media.MIME_TYPE
                             + "=?"
                             + " OR "
                             + MediaStore.Audio.Media.MIME_TYPE
                             + "=?";
        String[] whereParams = { "audio/mp3",
                                 "audio/mpeg",
                                 "audio/mp4" };

        m_queryHandler.startQuery( QUERY_MEDIASTORE,
                                   null,
                                   uri,
                                   projectionColumns,
                                   whereClause,
                                   whereParams,
                                   null );
    }

    @Override
    public void updateRRDB( Cursor input )
    {
        if ( null == m_rrdbUpdater )
        {
            m_rrdbUpdater = new RRDBUpdater( m_context );
        }

        m_rrdbUpdater.processResultsFromMediaStore( input );
    }
}


text:
package JavaBabyPrograms;

import java.util.Scanner;

public class Factorial {
public static void main(String[] param){
	int n = 0;
	Scanner i = new Scanner(System.in);
	System.out.println("Enter a number to find its factorial");
	n = i.nextInt();
	javaBabyProgramsUtils.FactorialUtil.factorialUtil(n);
	}
}