text:
'''
'''
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you 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.

import os
Test.Summary = '''
Test tls server certificate verification options
'''

# Define default ATS
ts = Test.MakeATSProcess("ts", select_ports=True, enable_tls=True)
server_foo = Test.MakeOriginServer("server_foo", ssl=True, options = {"--key": "{0}/signed-foo.key".format(Test.RunDirectory), "--cert": "{0}/signed-foo.pem".format(Test.RunDirectory)})
server_bar = Test.MakeOriginServer("server_bar", ssl=True, options = {"--key": "{0}/signed-bar.key".format(Test.RunDirectory), "--cert": "{0}/signed-bar.pem".format(Test.RunDirectory)})
server = Test.MakeOriginServer("server", ssl=True)

request_foo_header = {"headers": "GET / HTTP/1.1\r\nHost: foo.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
request_bad_foo_header = {"headers": "GET / HTTP/1.1\r\nHost: bad_foo.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
request_bar_header = {"headers": "GET / HTTP/1.1\r\nHost: bar.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
request_bad_bar_header = {"headers": "GET / HTTP/1.1\r\nHost: bad_bar.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
server_foo.addResponse("sessionlog.json", request_foo_header, response_header)
server_foo.addResponse("sessionlog.json", request_bad_foo_header, response_header)
server_bar.addResponse("sessionlog.json", request_bar_header, response_header)
server_bar.addResponse("sessionlog.json", request_bad_bar_header, response_header)

# add ssl materials like key, certificates for the server
ts.addSSLfile("ssl/signed-foo.pem")
ts.addSSLfile("ssl/signed-foo.key")
ts.addSSLfile("ssl/signed-bar.pem")
ts.addSSLfile("ssl/signed-bar.key")
ts.addSSLfile("ssl/server.pem")
ts.addSSLfile("ssl/server.key")
ts.addSSLfile("ssl/signer.pem")
ts.addSSLfile("ssl/signer.key")

ts.Disk.remap_config.AddLine(
    'map https://foo.com/ https://127.0.0.1:{0}'.format(server_foo.Variables.SSL_Port))
ts.Disk.remap_config.AddLine(
    'map https://bad_foo.com/ https://127.0.0.1:{0}'.format(server_foo.Variables.SSL_Port))
ts.Disk.remap_config.AddLine(
    'map https://bar.com/ https://127.0.0.1:{0}'.format(server_bar.Variables.SSL_Port))
ts.Disk.remap_config.AddLine(
    'map https://bad_bar.com/ https://127.0.0.1:{0}'.format(server_bar.Variables.SSL_Port))
ts.Disk.remap_config.AddLine(
    'map / https://127.0.0.1:{0}'.format(server.Variables.SSL_Port))

ts.Disk.ssl_multicert_config.AddLine(
    'dest_ip=* ssl_cert_name=server.pem ssl_key_name=server.key'
)

# Case 1, global config policy=permissive properties=signature
#         override for foo.com policy=enforced properties=all
ts.Disk.records_config.update({
    'proxy.config.ssl.server.cert.path': '{0}'.format(ts.Variables.SSLDir),
    'proxy.config.ssl.server.private_key.path': '{0}'.format(ts.Variables.SSLDir),
    'proxy.config.ssl.server.cipher_suite': 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:RC4-SHA:RC4-MD5:AES128-SHA:AES256-SHA:DES-CBC3-SHA!SRP:!DSS:!PSK:!aNULL:!eNULL:!SSLv2',
    # set global policy
    'proxy.config.ssl.client.verify.server.policy': 'ENFORCED',
    'proxy.config.ssl.client.verify.server.properties': 'ALL',
    'proxy.config.ssl.client.CA.cert.path': '{0}'.format(ts.Variables.SSLDir),
    'proxy.config.ssl.client.CA.cert.filename': 'signer.pem',
    'proxy.config.exec_thread.autoconfig.scale': 1.0,
    'proxy.config.url_remap.pristine_host_hdr': 1
})

ts.Disk.sni_yaml.AddLine(
  'sni:')
ts.Disk.sni_yaml.AddLine(
  '- fqdn: bar.com')
ts.Disk.sni_yaml.AddLine(
  '  verify_server_policy: PERMISSIVE')
ts.Disk.sni_yaml.AddLine(
  '  verify_server_properties: SIGNATURE')
ts.Disk.sni_yaml.AddLine(
  '- fqdn: bad_bar.com')
ts.Disk.sni_yaml.AddLine(
  '  verify_server_policy: PERMISSIVE')
ts.Disk.sni_yaml.AddLine(
  '  verify_server_properties: SIGNATURE')
ts.Disk.sni_yaml.AddLine(
  '- fqdn: random.com')
ts.Disk.sni_yaml.AddLine(
  '  verify_server_policy: DISABLED')

tr = Test.AddTestRun("default-enforce")
tr.Setup.Copy("ssl/signed-foo.key")
tr.Setup.Copy("ssl/signed-foo.pem")
tr.Setup.Copy("ssl/signed-bar.key")
tr.Setup.Copy("ssl/signed-bar.pem")
tr.Processes.Default.Command = "curl -k -H \"host: foo.com\" https://127.0.0.1:{0}".format(ts.Variables.ssl_port)
tr.ReturnCode = 0
tr.Processes.Default.StartBefore(server_foo)
tr.Processes.Default.StartBefore(server_bar)
tr.Processes.Default.StartBefore(server)
tr.Processes.Default.StartBefore(Test.Processes.ts)
tr.StillRunningAfter = server
tr.StillRunningAfter = ts
tr.Processes.Default.Streams.stdout = Testers.ExcludesExpression("Could Not Connect", "Curl attempt should have succeeded")

tr2 = Test.AddTestRun("override-disabled")
tr2.Processes.Default.Command = "curl -k -H \"host: random.com\"  https://127.0.0.1:{0}".format(ts.Variables.ssl_port)
tr2.ReturnCode = 0
tr2.StillRunningAfter = server
tr2.StillRunningAfter = ts
tr2.Processes.Default.Streams.stdout = Testers.ExcludesExpression("Could Not Connect", "Curl attempt should have succeeded")

tr3 = Test.AddTestRun("override-permissive")
tr3.Processes.Default.Command = "curl -k -H \"host: bar.com\"  https://127.0.0.1:{0}".format(ts.Variables.ssl_port)
tr3.ReturnCode = 0
tr3.StillRunningAfter = server
tr3.StillRunningAfter = ts
tr3.Processes.Default.Streams.stdout = Testers.ExcludesExpression("Could Not Connect", "Curl attempt should have succeeded")

tr4 = Test.AddTestRun("override-permissive-bad-name")
tr4.Processes.Default.Command = "curl -k -H \"host: bad_bar.com\"  https://127.0.0.1:{0}".format(ts.Variables.ssl_port)
tr4.ReturnCode = 0
tr4.StillRunningAfter = server
tr4.StillRunningAfter = ts
tr4.Processes.Default.Streams.stdout = Testers.ExcludesExpression("Could Not Connect", "Curl attempt should have succeeded")

tr5 = Test.AddTestRun("default-enforce-bad-sig")
tr5.Processes.Default.Command = "curl -k -H \"host: random2.com\"  https://127.0.0.1:{0}".format(ts.Variables.ssl_port)
tr5.ReturnCode = 0
tr5.Processes.Default.Streams.stdout = Testers.ContainsExpression("Could Not Connect", "Curl attempt should have failed")
tr5.StillRunningAfter = server
tr5.StillRunningAfter = ts

tr6 = Test.AddTestRun("default-enforce-fail")
tr6.Processes.Default.Command = "curl -k -H \"host: bad_foo.com\"  https://127.0.0.1:{0}".format(ts.Variables.ssl_port)
tr6.ReturnCode = 0
tr6.Processes.Default.Streams.stdout = Testers.ContainsExpression("Could Not Connect", "Curl attempt should have failed")
tr6.StillRunningAfter = server
tr6.StillRunningAfter = ts

# No name checking for the sig-only permissive override for bad_bar
ts.Disk.diags_log.Content += Testers.ExcludesExpression("WARNING: SNI \(bad_bar.com\) not in certificate", "bad_bar name checked should be skipped.")
ts.Disk.diags_log.Content = Testers.ExcludesExpression("WARNING: SNI \(foo.com\) not in certificate", "foo name checked should be skipped.")
# No checking for the self-signed on random.com.  No messages
ts.Disk.diags_log.Content += Testers.ExcludesExpression("WARNING: Core server certificate verification failed for \(random.com\)", "signature check for random.com should be skipped")
ts.Disk.diags_log.Content += Testers.ContainsExpression("WARNING: Core server certificate verification failed for \(random2.com\)", "signature check for random.com should fail'")
ts.Disk.diags_log.Content += Testers.ContainsExpression("WARNING: SNI \(bad_foo.com\) not in certificate", "bad_foo name checked should be checked.")


text:
<?php

class Authentication extends CI_Controller
{
    /**
     * Authentication constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url_helper');
        $this->load->database();
    }

    /**
     * @apiGroup authentication
     *
     * @api {put} /object_name/:id user authorization
     *
     * @apiName authenticate
     *
     * @apiHeader {String} Authorization Bearer token or Basic username:password
     *
     * @apiHeaderExample {String} Header-Example:
     *     "Authorization: Bearer 123456789"
     *
     *  @apiHeaderExample {String} Header-Example:
     *     "Authorization: Basic test:test"
     *
     * @apiSuccess (Success 200) 200 OK
     *
     * @apiError 401 Unauthorized
     *
     *@apiDescription user authorization
     */
    public function authenticate()
    {
        // for all requests except request to add new user
        // and requests to resize image
        if ($this->input->method() == 'post' && $this->uri->segment(1) == 'users')
        {
            return true;
        }

        // get authorization header
        $headers = getallheaders();

        if (!isset($headers['Authorization']))
        {
            //ask to login
            header('WWW-Authenticate: Basic realm="REST API"');
            $this->output->set_header('HTTP/1.1 401 Unauthorized');
            exit();
        }

        $authMethod = substr($headers['Authorization'], 0, 6);

        if ($authMethod == 'Bearer')
        {
            // authorize user by token
            $token = substr($headers['Authorization'], 7);
            $this->getUserByToken($token);
            return;
        }
        else
        {
            // get user by username and password
            $user = $this->getUserByHeader();

            // authorize user by password
            if ($user['password'] != $this->input->server('PHP_AUTH_PW'))
            {
                header('WWW-Authenticate: Basic realm="REST API"');
                $this->output->set_header('HTTP/1.1 401 Unauthorized');
                exit();
            }
        }
    }

    /**
     * @param $token
     * @return bool
     */
    public function getUserByToken($token)
    {
        // get user by token
        $user = $this->db->get_where('users', array('token' => $token))->row_array();
        // if token not found, send response 401
        if ($user === NULL)
        {
            header('WWW-Authenticate: Basic realm="REST API"');
            $this->output->set_header('HTTP/1.1 401 Unauthorized');
            exit();
        }

        return true;
    }

    /**
     * @return mixed
     */
    public function getUserByHeader()
    {
        // get user from header
        $username = $this->input->server('PHP_AUTH_USER');
        // if username empty return 401 code and ask to log in
        if ($username === NULL)
        {
            $this->sendResponse(401);
            exit();
        }
        // get user by username
        $user = $this->db->get_where('users', array('username' => $username))->row_array();
        // if no user found return 404 code
        if ($user === NULL)
        {
            $this->sendResponse(404);
            exit();
        }
        else
        {
            $this->generateToken($username);
            return $user;
        }
    }

    /**
     * @param $username
     * @return bool
     */
    public function generateToken($username)
    {
        $token = bin2hex($this->security->get_random_bytes(32));

        $data = array('token' => $token);
        $this->db->where('username', $username);
        $this->db->update('users', $data);

        header("Authorization: Bearer $token");
        $this->output->set_header("Authorization: Bearer $token");
        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import os

import salt.cli.caller
import salt.defaults.exitcodes
import salt.utils.parsers
from salt.config import _expand_glob_path

class SaltCall(salt.utils.parsers.SaltCallOptionParser):
    """
    Used to locally execute a salt command
    """

    def run(self):
        """
        Execute the salt call!
        """
        self.parse_args()

        if self.options.file_root:
            # check if the argument is pointing to a file on disk
            file_root = os.path.abspath(self.options.file_root)
            self.config["file_roots"] = {"base": _expand_glob_path([file_root])}

        if self.options.pillar_root:
            # check if the argument is pointing to a file on disk
            pillar_root = os.path.abspath(self.options.pillar_root)
            self.config["pillar_roots"] = {"base": _expand_glob_path([pillar_root])}

        if self.options.states_dir:
            # check if the argument is pointing to a file on disk
            states_dir = os.path.abspath(self.options.states_dir)
            self.config["states_dirs"] = [states_dir]

        if self.options.local:
            self.config["file_client"] = "local"
        if self.options.master:
            self.config["master"] = self.options.master

        caller = salt.cli.caller.Caller.factory(self.config)

        if self.options.doc:
            caller.print_docs()
            self.exit(salt.defaults.exitcodes.EX_OK)

        if self.options.grains_run:
            caller.print_grains()
            self.exit(salt.defaults.exitcodes.EX_OK)

        caller.run()


text:
package com.tymons.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;

import javax.persistence.*;

/**
 * Created by tymons on 05.03.17.
 */
@Entity
@Table(name = "notification")
public class Notification {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "notification_id_seq")
    @SequenceGenerator(name = "notification_id_seq", sequenceName = "notification_id_seq", allocationSize = 1)
    @JsonIgnore
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    @JsonIgnore
    private User notificationOwner;

    @Column(name = "device")
    private String device;

    public Notification() {
    }

    public Notification(User notificationOwner, String device) {
        this.notificationOwner = notificationOwner;
        this.device = device;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public User getNotificationOwner() {
        return notificationOwner;
    }

    public void setNotificationOwner(User notificationOwner) {
        this.notificationOwner = notificationOwner;
    }

    public String getDevice() {
        return device;
    }

    public void setDevice(String device) {
        this.device = device;
    }
}


text:
package com.intellij.appengine.sdk.impl;

import com.intellij.appengine.facet.AppEngineWebIntegration;
import com.intellij.appengine.sdk.AppEngineSdk;
import com.intellij.appengine.sdk.AppEngineSdkManager;
import com.intellij.openapi.util.text.StringUtil;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Map;

/**
 * @author nik
 */
public class AppEngineSdkManagerImpl extends AppEngineSdkManager {
  private final Map<String, AppEngineSdkImpl> myPath2Sdk = new THashMap<String, AppEngineSdkImpl>();

  @NotNull
  @Override
  public AppEngineSdk findSdk(@NotNull String sdkPath) {
    sdkPath = StringUtil.trimEnd(sdkPath, "/");
    if (!myPath2Sdk.containsKey(sdkPath)) {
      myPath2Sdk.put(sdkPath, new AppEngineSdkImpl(sdkPath));
    }
    return myPath2Sdk.get(sdkPath);
  }

  @NotNull
  @Override
  public List<? extends AppEngineSdk> getValidSdks() {
    return AppEngineWebIntegration.getInstance().getSdkForConfiguredDevServers();
  }
}


text:
cask "disk-expert" do
  version "3.6.1,358"
  sha256 :no_check

  url "https://nektony.com/download/diskexpert/diskexpert.dmg"
  name "Disk Expert"
  desc "Disk space analyzer"
  homepage "https://nektony.com/disk-expert"

  livecheck do
    url "https://nektony.com/pro-support/disk-expert/update/update.xml"
    strategy :sparkle
  end

  depends_on macos: ">= :yosemite"

  app "Disk Expert #{version.major}.app"

  zap trash: [
    "~/Library/Application Scripts/com.nektony.Disk-Expert-SII",
    "~/Library/Application Support/Disk-Expert-SII",
    "~/Library/Caches/com.nektony.Disk-Expert-SII",
    "~/Library/Preferences/com.nektony.Disk-Expert-SII.plist",
    "~/Library/Cookies/com.nektony.Disk-Expert-SII.binarycookies",
  ]
end


text:
var clickHandlers = {
	add_to_list: undefined,
	seek: undefined,
	drive: undefined
}
$.setClickHandlers = function(handlers) {
	if (handlers.add_to_list) {
		clickHandlers.add_to_list = handlers.add_to_list;
	}
	if (handlers.seek) {
		clickHandlers.seek = handlers.seek;
	}
	if (handlers.drive) {
		clickHandlers.drive = handlers.drive;
	}
}
function addToList() {
	if (clickHandlers.add_to_list) {
		clickHandlers.add_to_list();
	}
}
function seekCache() {
	if (clickHandlers.seek) {
		clickHandlers.seek();
	}
}
function driveToCache() {
	if (clickHandlers.drive) {
		clickHandlers.drive();
	}
}


text:
<?php

namespace App\Models;

use App\Repo\ModelTrait;
use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    use ModelTrait;
    protected $guarded = [];

}


text:
package org.apache.velocity.runtime.resource.util;

/**
 * Wrapper for Strings containing templates, allowing to add additional meta
 * data like timestamps.
 *
 * @author Eelco Hillenius
 * @author Henning P. Schmiedehausen
 * @version $Id$
 * @since 1.5
 */
public final class StringResource
{
    /** template body */
    private String body;

    /** encoding */
    private String encoding;

    /** last modified ts */
    private long lastModified;

    /**
     * convenience constructor; sets body to 'body' and sets lastModified to now
     * @param body
     * @param encoding
     */
    public StringResource(final String body, final String encoding)
    {
        setBody(body);
        setEncoding(encoding);
    }

    /**
     * Sets the template body.
     * @return String containing the template body.
     */
    public String getBody()
    {
        return body;
    }

    /**
     * Returns the modification date of the template.
     * @return Modification date in milliseconds.
     */
    public long getLastModified()
    {
        return lastModified;
    }

    /**
     * Sets a new  value for the template body.
     * @param body New body value
     */
    public void setBody(final String body)
    {
        this.body = body;
        this.lastModified = System.currentTimeMillis();
    }

    /**
     * Changes the last modified parameter.
     * @param lastModified The modification time in millis.
     */
    public void setLastModified(final long lastModified)
    {
        this.lastModified = lastModified;
    }

    /**
     * Returns the encoding of this String resource.
     *
     * @return The encoding of this String resource.
     */
    public String getEncoding() {
        return this.encoding;
    }

    /**
     * Sets the encoding of this string resource.
     *
     * @param encoding The new encoding of this resource.
     */
    public void setEncoding(final String encoding)
    {
        this.encoding = encoding;
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/managedidentities/v1/managed_identities_service.proto

package com.google.cloud.managedidentities.v1;

public interface GetDomainRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.managedidentities.v1.GetDomainRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The domain resource name using the form:
   * `projects/{project_id}/locations/global/domains/{domain_name}`
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Required. The domain resource name using the form:
   * `projects/{project_id}/locations/global/domains/{domain_name}`
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();
}


text:
using MonoTouch.UIKit;
using Core.Application.Injection;

namespace Presentation.iOS.Themes.Default
{
	public class Theme
	{
		#region PROPERTIES

		private Images _images;
		public Images Images {
			get {
				if (_images == null)
					_images = new Images ();

				 return _images;
			}
		}

		private Colors _colors;
		public Colors Colors {
			get {
				if (_colors == null)
					_colors = new Colors ();

				return _colors;
			}
		}

		private Fonts _fonts;
		public Fonts Fonts {
			get {
				if (_fonts == null)
					_fonts = new Fonts ();

				return _fonts;
			}
		}

		#endregion

		#region SINGLETON

		private static Theme _instance;
		/// <summary>
		/// Singleton instance
		/// </summary>
		/// <value>The instance.</value>
		public static Theme Instance
		{
			get
			{
				if(_instance == null) {
					_instance = new Theme ();
				}

				return _instance;
			}
			private set {
				_instance = value;
			}
		}

		#endregion

		#region CTOR

		public Theme ()
		{

		}

		#endregion

		#region STATIC METHODS

		/// <summary>
		/// Apply UIAppearance to this application, this is iOS's version of "styling"
		/// </summary>
		public static void Apply ()
		{
			// Sets the loading indicator color (the spinner)
			//UIActivityIndicatorView.Appearance.Color = Colors.IndicatorColor;
			// Sets the status bar text to white
			//UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.LightContent, false);
//
//			#region Navigation bar and buttons
//
//			var navBarLabelStyle = UILabel.AppearanceWhenContainedIn (typeof(UINavigationBar));
//			var navBarStyle = UINavigationBar.Appearance;
//			var tabBarStyle = UITabBar.Appearance;
//
//			var titleTextAttributes = new UITextAttributes () {
//				Font = Theme.Fonts.FontOfSize (18f),
//				TextColor = UIColor.White
//			};
//
//			navBarStyle.SetTitleTextAttributes (titleTextAttributes);
//
//			// Only apply the following if it's pre-iOS7
//			//		This is just to match the default iOS7 style buttons
//			if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0))
//			{
//				// iOS 7 Only stuff
//				navBarStyle.SetBackgroundImage (Theme.Images.NavBarBackgroundiOS7, UIBarMetrics.Default);
//
//				// Set nav bar button text
//				navBarStyle.TintColor = Colors.Navigation.Font;
//
//				// Set up the tabbar so it's dark
//				tabBarStyle.TintColor = Colors.Navigation.Font;
//				tabBarStyle.BarTintColor = UIColor.Black;
//				tabBarStyle.BackgroundColor = UIColor.Black;
//
//
//			} else {
//				// Pre-iOS 7 styles
//				navBarStyle.SetBackgroundImage (Theme.Images.NavBarBackgroundLandscapeiOS6, UIBarMetrics.LandscapePhone);
//				navBarStyle.SetBackgroundImage (Theme.Images.NavBarBackground, UIBarMetrics.Default);
//
//				navBarLabelStyle.TextColor = Colors.DarkBackgroundTextColor;
//
//				var buttonTextAttributes = new UITextAttributes () {
//					Font = Theme.Fonts.FontOfSize (16f),
//					TextColor = Theme.Colors.Navigation.Font
//				};
//
//				// Sets up the navbar button styles to match the iOS 7 look
//				var navBarButtonStyle = UIBarButtonItem.AppearanceWhenContainedIn (typeof(UINavigationBar));
//				navBarButtonStyle.TintColor = Colors.Navigation.Font;
//				navBarButtonStyle.SetTitleTextAttributes (buttonTextAttributes, UIControlState.Normal);
//				navBarButtonStyle.SetBackgroundImage (Images.NavBarButtonBackground, UIControlState.Normal, UIBarMetrics.Default);
//				navBarButtonStyle.SetBackButtonBackgroundImage (Images.NavBarButtonBackground, UIControlState.Normal, UIBarMetrics.Default);
//
//			}
//
//			#endregion
		}

		// <summary>
		// Transitions a controller to the rootViewController, for a fullscreen transition
		// </summary>
		public static void TransitionController (UIViewController controller, bool animated = true)
		{
			var window = Injector.Resolve<UIWindow> ();

			//Return if it's already the root controller
			if (window.RootViewController == controller)
				return;

			//Set the root controller
			window.RootViewController = controller;

			//Peform an animation, note that null is not allowed as a callback, so I use delegate { }
			if (animated)
				UIView.Transition (window, .3, UIViewAnimationOptions.TransitionCrossDissolve, delegate { }, delegate { });
		}

		#endregion
	}
}


text:
try:
    import bluetooth
except ImportError:
    import lightblueglue as bluetooth
from nxt.brick import Brick

class BlueSock(object):

    bsize = 118  # Bluetooth socket block size
    PORT = 1     # Standard NXT rfcomm port

    type = 'bluetooth'

    def __init__(self, host):
        self.host = host
        self.sock = None
        self.debug = False

    def __str__(self):
        return 'Bluetooth (%s)' % self.host

    def connect(self):
        if self.debug:
            print 'Connecting via Bluetooth...'
        sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        sock.connect((self.host, BlueSock.PORT))
        self.sock = sock
        if self.debug:
            print 'Connected.'
        return Brick(self)

    def close(self):
        if self.debug:
            print 'Closing Bluetooth connection...'
        self.sock.close()
        if self.debug:
            print 'Bluetooth connection closed.'

    def send(self, data):
        if self.debug:
            print 'Send:',
            print ':'.join('%02x' % ord(c) for c in data)
        l0 = len(data) & 0xFF
        l1 = (len(data) >> 8) & 0xFF
        d = chr(l0) + chr(l1) + data
        self.sock.send(d)

    def recv(self):
        data = self.sock.recv(2)
        l0 = ord(data[0])
        l1 = ord(data[1])
        plen = l0 + (l1 << 8)
        data = self.sock.recv(plen)
        if self.debug:
            print 'Recv:',
            print ':'.join('%02x' % ord(c) for c in data)
        return data

def _check_brick(arg, value):
    return arg is None or arg == value

def find_bricks(host=None, name=None):
    for h, n in bluetooth.discover_devices(lookup_names=True):
        if _check_brick(host, h) and _check_brick(name, n):
            yield BlueSock(h)


text:
package com.mapzen.tangram;

import android.content.Context;
import android.os.SystemClock;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;

import com.almeros.android.multitouch.RotateGestureDetector;
import com.almeros.android.multitouch.ShoveGestureDetector;

import java.util.EnumMap;
import java.util.EnumSet;

/**
 * {@code TouchInput} collects touch data, applies gesture detectors, resolves simultaneous
 * detection, and calls the appropriate input responders.
 */
public class TouchInput implements OnTouchListener {

    /**
     * List of gestures that can be detected and responded to
     */
    public enum Gestures {
        TAP,
        DOUBLE_TAP,
        LONG_PRESS,
        PAN,
        ROTATE,
        SCALE,
        SHOVE,
        ;

        /**
         * Whether a gesture uses multiple touch points simultaneously
         * @return True if the gesture is multi-touch, otherwise false
         */
        public boolean isMultiTouch() {
            switch(this) {
                case ROTATE:
                case SCALE:
                case SHOVE:
                    return true;
                default:
                    return false;
            }
        }
    }

    /**
     * Interface for responding to a tap gesture
     */
    public interface TapResponder {
        /**
         * Called immediately after a touch is lifted in a tap gesture; may be part of a double tap
         * @param x The x screen coordinate of the tapped point
         * @param y The y screen coordinate of the tapped point
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onSingleTapUp(float x, float y);

        /**
         * Called after a touch is lifted and determined to not be part of a double tap
         *
         * The timeout duration for a double tap is determined by {@link ViewConfiguration}
         * @param x The x screen coordinate of the tapped point
         * @param y The y screen coordinate of the tapped point
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onSingleTapConfirmed(float x, float y);
    }

    /**
     * Interface for responding to a double-tap gesture
     */
    public interface DoubleTapResponder {
        /**
         * Called immediately after the second time a touch is lifted in a double tap gesture
         *
         * The allowable duration between taps is determined by {@link ViewConfiguration}
         * @param x The x screen coordinate of the tapped point
         * @param y The y screen coordinate of the tapped point
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onDoubleTap(float x, float y);
    }

    /**
     * Interface for responding to a long press gesture
     */
    public interface LongPressResponder {
        /**
         * Called immediately after a long press is detected
         *
         * The duration threshold for a long press is determined by {@link ViewConfiguration}
         * @param x The x screen coordinate of the pressed point
         * @param y The y screen coordinate of the pressed point
         */
        void onLongPress(float x, float y);
    }

    /**
     * Interface for responding to a panning (dragging) gesture
     */
    public interface PanResponder {
        /**
         * Called when a Panning Gesture begins
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onPanBegin();

        /**
         * Called repeatedly while a touch point is dragged
         * @param startX The starting x screen coordinate for an interval of motion
         * @param startY The starting y screen coordinate for an interval of motion
         * @param endX The ending x screen coordinate for an interval of motion
         * @param endY The ending y screen coordinate for an interval of motion
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onPan(float startX, float startY, float endX, float endY);

        /**
         * Called when Panning Gesture ends (Because of an ACTION_UP event)
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onPanEnd();

        /**
         * Called when a dragged touch point with non-zero velocity is lifted
         * @param posX The x screen coordinate where the touch was lifted
         * @param posY The y screen coordinate where the touch was lifted
         * @param velocityX The x velocity of the gesture in screen coordinates per second
         * @param velocityY The y velocity of the gesture in screen coordinates per second
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onFling(float posX, float posY, float velocityX, float velocityY);

        /**
         * Called when a Down event occurs, to potentially cancel a flinging action
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onCancelFling();
    }

    /**
     * Interface for responding to a scaling (pinching) gesture
     */
    public interface ScaleResponder {
        /**
         * Called when a Scale Gesture begins
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onScaleBegin();

        /**
         * Called repeatedly while two touch points are moved closer to or further from each other
         * @param x The x screen coordinate of the point between the two touch points
         * @param y The y screen coordinate of the point between the two touch points
         * @param scale The scale factor relative to the previous scaling event
         * @param velocity The rate of scale change in units per second
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onScale(float x, float y, float scale, float velocity);

        /**
         * Called when a Scale Gesture ends
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onScaleEnd();
    }

    /**
     * Interface for responding to a rotation gesture
     */
    public interface RotateResponder {
        /**
         * Called when a Rotation Gesture begins
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onRotateBegin();

        /**
         * Called repeatedly while two touch points are rotated around a point
         * @param x The x screen coordinate of the center of rotation
         * @param y The y screen coordinate of the center of rotation
         * @param rotation The change in rotation of the touch points relative to the previous
         * rotation event, in counter-clockwise radians
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onRotate(float x, float y, float rotation);

        /**
         * Called when Rotation Gesture ends
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onRotateEnd();
    }

    /**
     * Interface for responding to a shove (two-finger vertical drag) gesture
     */
    public interface ShoveResponder {
        /**
         * Called when Shove Gesture begins
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onShoveBegin();

        /**
         * Called repeatedly while two touch points are moved together vertically
         * @param distance The vertical distance moved by the two touch points relative to the last
         * shoving event, in screen coordinates
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onShove(float distance);

        /**
         * Called when Shove Gesture ends
         * @return True if the event is consumed, false if the event should continue to propagate
         */
        boolean onShoveEnd();
    }

    private static final long MULTITOUCH_BUFFER_TIME = 256; // milliseconds
    private static final long DOUBLE_TAP_TIMEOUT = ViewConfiguration.getDoubleTapTimeout(); // milliseconds

    private GestureDetector panTapGestureDetector;
    private ScaleGestureDetector scaleGestureDetector;
    private RotateGestureDetector rotateGestureDetector;
    private ShoveGestureDetector shoveGestureDetector;

    private TapResponder tapResponder;
    private DoubleTapResponder doubleTapResponder;
    private LongPressResponder longPressResponder;
    private PanResponder panResponder;
    private ScaleResponder scaleResponder;
    private RotateResponder rotateResponder;
    private ShoveResponder shoveResponder;

    private EnumSet<Gestures> enabledGestures;
    private EnumSet<Gestures> detectedGestures;
    private EnumMap<Gestures, EnumSet<Gestures>> allowedSimultaneousGestures;

    private long lastMultiTouchEndTime = -MULTITOUCH_BUFFER_TIME;

    /**
     * Construct a new touch input manager; this may only be called on the UI thread
     * @param context A {@link Context} whose {@code Handler} will be used for deferred events
     */
    public TouchInput(Context context) {

        this.panTapGestureDetector = new GestureDetector(context, new GestureListener());
        this.scaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureListener());
        this.rotateGestureDetector = new RotateGestureDetector(context, new RotateGestureListener());
        this.shoveGestureDetector = new ShoveGestureDetector(context, new ShoveGestureListener());

        this.enabledGestures = EnumSet.allOf(Gestures.class);
        this.detectedGestures = EnumSet.noneOf(Gestures.class);
        this.allowedSimultaneousGestures = new EnumMap<>(Gestures.class);

        // By default, all gestures are allowed to detect simultaneously
        for (Gestures g : Gestures.values()) {
            allowedSimultaneousGestures.put(g, EnumSet.allOf(Gestures.class));
        }
    }

    /**
     * Enable recognizing the given gesture type.
     * @param g The gesture type.
     */
    public void setGestureEnabled(Gestures g) {
        enabledGestures.add(g);
    }

    /**
     * Disable recognizing the given gesture type.
     * @param g The gesture type.
     */
    public void setGestureDisabled(Gestures g) {
        enabledGestures.remove(g);
    }

    /**
     * Get whether the given gesture type is enabled.
     * @param g The gesture type.
     * @return True if the gesture type is enabled, otherwise false.
     */
    public boolean isGestureEnabled(Gestures g) {
        return enabledGestures.contains(g);
    }

    /**
     * Enable recognizing all gesture types.
     */
    public void setAllGesturesEnabled() {
        enabledGestures = EnumSet.allOf(Gestures.class);
    }

    /**
     * Disable recognizing all gesture types.
     */
    public void setAllGesturesDisabled() {
        enabledGestures.clear();
    }

    /**
     * Set a {@link TapResponder}
     * @param responder The responder object, or null to leave these gesture events unchanged
     */
    public void setTapResponder(TapResponder responder) {
        this.tapResponder = responder;
    }

    /**
     * Set a {@link DoubleTapResponder}
     * @param responder The responder object, or null to leave these gesture events unchanged
     */
    public void setDoubleTapResponder(DoubleTapResponder responder) {
        this.doubleTapResponder = responder;
    }

    /**
     * Set a {@link LongPressResponder}
     * @param responder The responder object, or null to leave these gesture events unchanged
     */
    public void setLongPressResponder(LongPressResponder responder) {
        this.longPressResponder = responder;
    }

    /**
     * Set a {@link PanResponder}
     * @param responder The responder object, or null to leave these gesture events unchanged
     */
    public void setPanResponder(PanResponder responder) {
        this.panResponder = responder;
    }

    /**
     * Set a {@link ScaleResponder}
     * @param responder The responder object, or null to leave these gesture events unchanged
     */
    public void setScaleResponder(ScaleResponder responder) {
        this.scaleResponder = responder;
    }

    /**
     * Set a {@link RotateResponder}
     * @param responder The responder object, or null to leave these gesture events unchanged
     */
    public void setRotateResponder(RotateResponder responder) {
        this.rotateResponder = responder;
    }

    /**
     * Set a {@link ShoveResponder}
     * @param responder The responder object, or null to leave these gesture events unchanged
     */
    public void setShoveResponder(ShoveResponder responder) {
        this.shoveResponder = responder;
    }

    /**
     * Enable recognizing the gesture {@code second} while {@code first} is in progress
     * @param first Initial gesture type
     * @param second Subsequent gesture type
     */
    public void setSimultaneousDetectionEnabled(Gestures first, Gestures second) {
        allowedSimultaneousGestures.get(second).add(first);
    }

    /**
     * Disable recognizing the gesture {@code second} while {@code first} is in progress
     * @param first Initial gesture type
     * @param second Subsequent gesture type
     */
    public void setSimultaneousDetectionDisabled(Gestures first, Gestures second) {
        if (first != second) {
            allowedSimultaneousGestures.get(second).remove(first);
        }
    }

    /**
     * Get whether the gesture {@code second} can be recognized while {@code first} is in progress
     * @param first Initial gesture type
     * @param second Subsequent gesture type
     * @return True if {@code second} will be recognized, else false
     */
    public boolean isSimultaneousDetectionAllowed(Gestures first, Gestures second) {
        return allowedSimultaneousGestures.get(second).contains(first);
    }

    private boolean isDetectionAllowed(Gestures g) {
        if (!enabledGestures.contains(g)) {
            return false;
        }
        if (!allowedSimultaneousGestures.get(g).containsAll(detectedGestures)) {
            return false;
        }
        if (!g.isMultiTouch()) {
            // Return false if a multitouch gesture has finished within a time threshold
            long t = SystemClock.uptimeMillis() - lastMultiTouchEndTime;
            if (t < MULTITOUCH_BUFFER_TIME) {
                return false;
            }
        }
        return true;
    }

    private void setGestureStarted(Gestures g) {
        detectedGestures.add(g);
    }

    private void setGestureEnded(Gestures g) {
        detectedGestures.remove(g);
        if (g.isMultiTouch()) {
            lastMultiTouchEndTime = SystemClock.uptimeMillis();
        }
    }

    // View.OnTouchListener implementation
    // ===================================
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getActionMasked() == MotionEvent.ACTION_UP) {
            if (detectedGestures.contains(Gestures.PAN)) {
                setGestureEnded(Gestures.PAN);
                panResponder.onPanEnd();
            }
            detectedGestures.clear();
        }

        panTapGestureDetector.onTouchEvent(event);
        scaleGestureDetector.onTouchEvent(event);
        shoveGestureDetector.onTouchEvent(event);
        rotateGestureDetector.onTouchEvent(event);

        return true;
    }

    class GestureListener implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
        // GestureDetector.OnDoubleTapListener implementation
        // ==================================================
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (isDetectionAllowed(Gestures.TAP) && tapResponder != null) {
                return tapResponder.onSingleTapConfirmed(e.getX(), e.getY());
            }
            return false;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            // This event handles the second 'down' of a double tap, which is not a confirmed double tap
            // (e.g. it could be the start of a 'quick scale' gesture). We ignore this callback and
            // check for the 'up' event that follows.
            return false;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            int action = e.getActionMasked();
            long time = e.getEventTime() - e.getDownTime();
            if (action != MotionEvent.ACTION_UP || time > DOUBLE_TAP_TIMEOUT) {
                // The detector sends back only the first 'down' and the second 'up' so we only need to
                // respond when we receive an 'up' action. We also discard the gesture if the second tap
                // lasts longer than the permitted duration between taps.
                return false;
            }
            if (isDetectionAllowed(Gestures.DOUBLE_TAP) && doubleTapResponder != null) {
                return doubleTapResponder.onDoubleTap(e.getX(), e.getY());
            }
            return false;
        }

        // GestureDetector.OnGestureListener implementation
        // ================================================
        @Override
        public boolean onDown(MotionEvent e) {
            return panResponder.onCancelFling();
        }

        @Override
        public void onShowPress(MotionEvent e) {
            // Ignored
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (isDetectionAllowed(Gestures.TAP) && tapResponder != null) {
                return tapResponder.onSingleTapUp(e.getX(), e.getY());
            }
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            if (isDetectionAllowed(Gestures.PAN)) {

                if (!detectedGestures.contains(Gestures.PAN)) {
                    setGestureStarted(Gestures.PAN);
                    panResponder.onPanBegin();
                }

                if (panResponder == null) {
                    return false;
                }

                // TODO: Predictive panning
                // Use estimated velocity to counteract input->render lag

                float x = 0, y = 0;
                int n = e2.getPointerCount();
                for (int i = 0; i < n; i++) {
                    x += e2.getX(i) / n;
                    y += e2.getY(i) / n;
                }
                return panResponder.onPan(x + distanceX, y + distanceY, x, y);
            }
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            if (isDetectionAllowed(Gestures.LONG_PRESS) && longPressResponder != null) {
                longPressResponder.onLongPress(e.getX(), e.getY());
            }
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (isDetectionAllowed(Gestures.PAN) && panResponder != null) {
                return panResponder.onFling(e2.getX(), e2.getY(), velocityX, velocityY);
            }
            return false;
        }
    }

    class RotateGestureListener implements RotateGestureDetector.OnRotateGestureListener {
        @Override
        public boolean onRotate(RotateGestureDetector detector) {
            if (isDetectionAllowed(Gestures.ROTATE) && rotateResponder != null) {
                float rotation = -detector.getRotationRadiansDelta();
                float x = detector.getFocusX();
                float y = detector.getFocusY();
                return rotateResponder.onRotate(x, y, rotation);
            }
            return false;
        }

        @Override
        public boolean onRotateBegin(RotateGestureDetector detector) {
            if (isDetectionAllowed(Gestures.ROTATE)) {
                setGestureStarted(Gestures.ROTATE);
                return rotateResponder.onRotateBegin();
            }
            return false;
        }

        @Override
        public void onRotateEnd(RotateGestureDetector detector) {
            setGestureEnded(Gestures.ROTATE);
            rotateResponder.onRotateEnd();
        }
    }

    class ScaleGestureListener implements ScaleGestureDetector.OnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            if (isDetectionAllowed(Gestures.SCALE) && scaleResponder != null) {
                long ms = detector.getTimeDelta();
                float dt = ms > 0 ? ms / 1000.f : 1.f;
                float scale = detector.getScaleFactor();
                float velocity = (scale - 1.f) / dt;
                float x = detector.getFocusX();
                float y = detector.getFocusY();
                return scaleResponder.onScale(x, y, scale, velocity);
            }
            return false;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            if (isDetectionAllowed(Gestures.SCALE)) {
                setGestureStarted(Gestures.SCALE);
                return scaleResponder.onScaleBegin();
            }
            return false;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            setGestureEnded(Gestures.SCALE);
            scaleResponder.onScaleEnd();
        }
    }

    class ShoveGestureListener implements ShoveGestureDetector.OnShoveGestureListener {
        @Override
        public boolean onShove(ShoveGestureDetector detector) {
            if (isDetectionAllowed(Gestures.SHOVE) && shoveResponder != null) {
                return shoveResponder.onShove(detector.getShovePixelsDelta());
            }
            return false;
        }

        @Override
        public boolean onShoveBegin(ShoveGestureDetector detector) {
            if (isDetectionAllowed(Gestures.SHOVE)) {
                setGestureStarted(Gestures.SHOVE);
                return shoveResponder.onShoveBegin();
            }
            return false;
        }

        @Override
        public void onShoveEnd(ShoveGestureDetector detector) {
            setGestureEnded(Gestures.SHOVE);
            shoveResponder.onShoveEnd();
        }
    }

}


text:
package lnwire

import (
	"bytes"
	"reflect"
	"testing"

	"github.com/roasbeef/btcd/btcec"
	"github.com/roasbeef/btcd/chaincfg/chainhash"
)

func TestChannelAnnoucementEncodeDecode(t *testing.T) {
	ca := &ChannelAnnouncement{
		FirstNodeSig:     someSig,
		SecondNodeSig:    someSig,
		ChannelID:        someChannelID,
		FirstBitcoinSig:  someSig,
		SecondBitcoinSig: someSig,
		FirstNodeID:      pubKey,
		SecondNodeID:     pubKey,
		FirstBitcoinKey:  pubKey,
		SecondBitcoinKey: pubKey,
	}

	// Next encode the CA message into an empty bytes buffer.
	var b bytes.Buffer
	if err := ca.Encode(&b, 0); err != nil {
		t.Fatalf("unable to encode ChannelAnnouncement: %v", err)
	}

	// Ensure the max payload estimate is correct.
	serializedLength := uint32(b.Len())
	if serializedLength != ca.MaxPayloadLength(0) {
		t.Fatalf("payload length estimate is incorrect: expected %v "+
			"got %v", serializedLength, ca.MaxPayloadLength(0))
	}

	// Deserialize the encoded CA message into a new empty struct.
	ca2 := &ChannelAnnouncement{}
	if err := ca2.Decode(&b, 0); err != nil {
		t.Fatalf("unable to decode ChannelAnnouncement: %v", err)
	}

	// Assert equality of the two instances.
	if !reflect.DeepEqual(ca, ca2) {
		t.Fatalf("encode/decode error messages don't match %#v vs %#v",
			ca, ca2)
	}
}

func TestChannelAnnoucementValidation(t *testing.T) {
	getKeys := func(s string) (*btcec.PrivateKey, *btcec.PublicKey) {
		return btcec.PrivKeyFromBytes(btcec.S256(), []byte(s))
	}

	firstNodePrivKey, firstNodePubKey := getKeys("node-id-1")
	secondNodePrivKey, secondNodePubKey := getKeys("node-id-2")
	firstBitcoinPrivKey, firstBitcoinPubKey := getKeys("bitcoin-key-1")
	secondBitcoinPrivKey, secondBitcoinPubKey := getKeys("bitcoin-key-2")

	var hash []byte

	hash = chainhash.DoubleHashB(firstNodePubKey.SerializeCompressed())
	firstBitcoinSig, _ := firstBitcoinPrivKey.Sign(hash)

	hash = chainhash.DoubleHashB(secondNodePubKey.SerializeCompressed())
	secondBitcoinSig, _ := secondBitcoinPrivKey.Sign(hash)

	ca := &ChannelAnnouncement{
		ChannelID:        someChannelID,
		FirstBitcoinSig:  firstBitcoinSig,
		SecondBitcoinSig: secondBitcoinSig,
		FirstNodeID:      firstNodePubKey,
		SecondNodeID:     secondNodePubKey,
		FirstBitcoinKey:  firstBitcoinPubKey,
		SecondBitcoinKey: secondBitcoinPubKey,
	}

	dataToSign, _ := ca.DataToSign()
	hash = chainhash.DoubleHashB(dataToSign)

	firstNodeSign, _ := firstNodePrivKey.Sign(hash)
	ca.FirstNodeSig = firstNodeSign

	secondNodeSign, _ := secondNodePrivKey.Sign(hash)
	ca.SecondNodeSig = secondNodeSign

	if err := ca.Validate(); err != nil {
		t.Fatal(err)
	}
}


text:
package com.arenas.droidfan.Util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.nfc.Tag;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.Toast;

import com.arenas.droidfan.AppContext;
import com.arenas.droidfan.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * Created by Arenas on 2016/7/14.
 */
public class ImageUtils {

    public static final String TAG = ImageUtils.class.getSimpleName();

    public static Bitmap scalePic(Context context , String path , int maxDp){
        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path , bfo);
        int maxPx = dip2px(context , maxDp);
        int sampleSize = getSampleSize(bfo.outWidth , bfo.outHeight , maxPx);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = sampleSize;
        Bitmap bitmap = BitmapFactory.decodeFile(path , options);
        return bitmap;
    }

    public static int getSampleSize(int width , int height , int px){
        int max = Math.max(width , height);
        if (max < px){
            return 1;
        }else {
            return max/px;
        }
    }
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static File getPhotoDir(){
        File photoDir = new File(Environment.getExternalStorageDirectory() + "/DCIM/DroidFan");
        if (!photoDir.exists()) {
            photoDir.mkdirs();
        }
        return photoDir;
    }

    public static String getPhotoName(String photoUrl){
        String ext = photoUrl.toLowerCase().endsWith(".gif") ? ".gif" : ".jpg";
        return getPhotoDir().getPath() + "/" + System.currentTimeMillis() + ext;
    }

    public static boolean copyFile(File src, File dest) {
        try {
            FileChannel srcChannel = new FileInputStream(src).getChannel();
            FileChannel destChannel = new FileOutputStream(dest).getChannel();
            srcChannel.transferTo(0, srcChannel.size(), destChannel);//(long position ,long size , WritableByteChannel target)
            srcChannel.close();
            destChannel.close();
            return true;
        } catch (Exception ex) {

        } finally {

        }
        return false;

    }

    public static void saveImage(Context context , Bitmap image , Fragment fragment){
        if (null == image){
            Log.d(TAG , "image == null");
            return;
        }
        File path = new File(Environment.getExternalStorageDirectory() + "/DCIM/DroidFan/" + Utils.getCurTimeStr() + ".png");
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(path);
            boolean success = image.compress(Bitmap.CompressFormat.PNG , 100 , fos);
            fos.flush();
            fos.close();
            if (success){
                Utils.showToast(context , "已保存");
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}


text:
require 'test_helper'

class RemoteMoipTest < Test::Unit::TestCase

  def setup
    @gateway = MoipGateway.new(fixtures(:moip))

    @amount = 100
    @credit_card = credit_card('4000100011112224')
    @declined_card = credit_card('6011000990139424', brand: 'discover')

    @options = {
      :order_id => generate_unique_id,
      :reason   => 'Moip active merchant remote test',
      :payer => {
        :name  => 'Guilherme Bernardino',
        :email => 'Guibernardino@me.com',
        :id    => 1
      },
      :billing_address => {
        :address1     => 'Av. Brigadeiro Faria Lima',
        :address2     => '8° Andar',
        :number       => '2927',
        :neighborhood => 'Jardim Paulistano',
        :city         => 'São Paulo',
        :state        => 'SP',
        :zip          => '01452-000',
        :country      => 'BRA',
        :phone        => '1131654020'
      },
      :creditcard => {
        :installments      => 1,
        :birthday          => '01/01/1990',
        :phone             => '1131654020',
        :identity_document => '52211670695',
      }
    }

    @payment_slip_options = {
      :payment_slip => {
        :expiration_days => 3,
        :instruction_line_1 => 'Instruction line 1',
        :instruction_line_2 => 'Instruction line 2',
        :instruction_line_3 => 'Instruction line 3'
      }
    }
  end

  def test_successful_authenticate
    omit("Skipping... because this test is broken")
    assert response = @gateway.send(:authenticate, @amount, @credit_card, @options)
    assert_success response
    assert_equal 'Sucesso', response.message
  end

  def test_authenticate_and_pay
    omit("Skipping... because this test is broken")
    assert auth = @gateway.send(:authenticate, @amount, @credit_card, @options)
    assert_success auth
    assert_equal 'Sucesso', auth.message
    assert auth.authorization

    payment = { :payment_method => @credit_card }
    my_options = @options.merge(payment)
    assert pay = @gateway.send(:pay, @amount, auth.authorization, my_options)
    assert_success pay
    assert_equal 'Requisição processada com sucesso', pay.message
  end

  def test_successful_purchase
    omit("Skipping... because this test is broken")
    assert response = @gateway.purchase(@amount, @credit_card, @options)
    assert_success response
    assert_equal 'Requisição processada com sucesso', response.message
  end

  def test_successful_purchase_with_payment_slip
    omit("Skipping... because this test is broken")
    assert response = @gateway.purchase(@amount, 'boleto_bancario', @options.merge(@payment_slip_options))
    assert_success response
    assert_equal 'Requisição processada com sucesso', response.message
  end

  def test_successful_purchase_with_bank_debit
    omit("Skipping... because this test is broken")
    assert response = @gateway.purchase(@amount, 'banco_do_brasil', @options)
    assert_success response
    assert_equal 'Requisição processada com sucesso', response.message
  end

  def test_unsuccessful_purchase
    omit("Skipping... because this test is broken")
    assert response = @gateway.purchase(@amount, @declined_card, @options)
    assert_failure response
    assert_equal 'Instituição de pagamento inválida', response.message
  end

  def test_unsuccessful_authenticate
    omit("Skipping... because this test is broken")
    assert response = @gateway.send(:authenticate, @amount, @credit_card, @options.merge(:order_id => 1))
    assert_failure response
    assert_equal 'Id Próprio já foi utilizado em outra Instrução', response.message
  end

  def test_failed_pay
    omit("Skipping... because this test is broken")
    payment = { :payment_method => @credit_card }
    my_options = @options.merge(payment)
    assert response = @gateway.send(:pay, @amount, 'error', my_options)
    response.message
    assert_equal 'Token inválido', response.message
  end

  def test_invalid_login
    omit("Skipping... because this test is broken")
    gateway = MoipGateway.new(:token => '', :api_key => '')
    assert_raise ActiveMerchant::ResponseError, 'Failed with 401 Unauthorized' do
      gateway.purchase(@amount, @credit_card, @options)
    end
  end

  def test_failed_create_plan
    params_plan = {
      days: 30,
      price: @amount,
      period: 'monthly',
      plan_code: '0011MONTLY'
    }

    response = @gateway.create_plan(params_plan)
    assert_failure response

    assert_equal "Erro na requisição", response.message
    assert_equal "Código do plano já utilizado. Escolha outro código", response.params['errors'][0]['description']
    assert_true response.test?

  end

  def test_failed_create_plan_no_period
    params_plan = {
      plan_code: '0011MONTLY',
      price: 100
    }

    response = @gateway.create_plan(params_plan)
    assert_failure response

    assert_equal "Erro na requisição", response.message
    assert_equal "Unidade do intervaldo deve ser DAY, MONTH ou YEAR", response.params['errors'][0]['description']
    assert_true response.test?

  end

  def test_failed_create_plan_no_amount
    params_plan = {
      plan_code: '0011MONTLY'
    }

    response = @gateway.create_plan(params_plan)
    assert_failure response

    assert_equal "Erro na requisição", response.message
    assert_equal "O valor deve ter apenas números", response.params['errors'][0]['description']
    assert_true response.test?

  end

  def test_failed_create_plan_no_params
    params_plan = {}

    response = @gateway.create_plan(params_plan)
    assert_failure response

    assert_equal "Erro na requisição", response.message
    assert_equal "Código do plano deve ser informado", response.params['errors'][0]['description']
    assert_true response.test?

  end

  def test_sucessful_create_plan
    params_plan = {
      days: 30,
      price: @amount,
      period: 'monthly',
      plan_code: "22141MONTLY#{rand(99999)}",
      hold_setup_fee: true,
      payment_method: 'ALL'
    }

    response = @gateway.create_plan(params_plan)
    assert_success response

    assert_equal "Plano criado com sucesso", response.message
    assert_not_nil response.plan_code
    assert_true response.test?

  end

  def test_sucessful_create_plan_with_alerts
    params_plan = {
      days: 30,
      price: @amount,
      period: 'monthly',
      plan_code: "13311MONTLY#{rand(99999)}",
    }

    response = @gateway.create_plan(params_plan)
    assert_not_nil response.plan_code
    assert_success response

    plan_response = response.params['plan']

    assert_equal "Plano criado com sucesso", response.message
    assert_equal 2, plan_response['alerts'].size

    assert_equal "Atributo hold_setup_fee não informado, por default ele será considerado true.", plan_response['alerts'][0]['description']
    assert_equal "MA102", plan_response['alerts'][0]['code']
    assert_equal "Método de pagamento não informado, portanto, o método padrão será CREDIT_CARD", plan_response['alerts'][1]['description']
    assert_equal "MA177", plan_response['alerts'][1]['code']

    assert_true response.test?
  end

  def test_successful_update_plan
    params_plan = {
      days: 30,
      price: @amount,
      period: 'monthly',
      plan_code: 'PLAN-CODE-22141MONTLY',
    }

    response = @gateway.update_plan(params_plan)
    assert_success response

    assert_equal "Plano atualizado com sucesso.", response.message
    assert_true response.params['success']
    assert_not_nil response.plan_code
    assert_true response.test?

  end

  def test_failed_update_plan
    params_plan = {
      days: 30,
      price: @amount,
      period: 'monthly',
    }

    response = @gateway.update_plan(params_plan)
    assert_failure response

    assert_equal "Erro ao atualizar plano.", response.message
    assert_equal "Ocorreu um erro no retorno do webservice.", response.params['message']
    assert_false response.params['success']
    assert_true response.test?

  end

  def test_successful_find_plan
    code = 'PLAN-CODE-22141MONTLY'
    response = @gateway.find_plan(code)
    assert_success response

    assert_equal "ONE INVOICE FOR 1 MONTH PLAN-CODE-22141MONTLY", response.params['plan']['name']
    assert_equal code, response.params['plan']['code']
    assert_true response.test?

  end

  def test_failed_find_plan
    response = @gateway.find_plan(nil)
    assert_failure response

    assert_equal "not found", response.message
    assert_equal "not found", response.params['message']
    assert_true response.test?

  end

end


text:
package net.java.cargotracker.interfaces.booking.rest;

import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import net.java.cargotracker.domain.model.cargo.Cargo;
import net.java.cargotracker.domain.model.cargo.CargoRepository;

@Stateless
@Path("/cargo")
public class CargoMonitoringService {

    public static final String ISO_8601_FORMAT = "yyyy-MM-dd HH:mm";
    @Inject
    private CargoRepository cargoRepository;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public JsonArray getAllCargo() {
        List<Cargo> cargos = cargoRepository.findAll();

        JsonArrayBuilder builder = Json.createArrayBuilder();

        for (Cargo cargo : cargos) {
            builder.add(Json.createObjectBuilder()
                    .add("trackingId", cargo.getTrackingId().getIdString())
                    .add("routingStatus", cargo.getDelivery()
                            .getRoutingStatus().toString())
                    .add("misdirected", cargo.getDelivery().isMisdirected())
                    .add("transportStatus", cargo.getDelivery()
                            .getTransportStatus().toString())
                    .add("atDestination", cargo.getDelivery()
                            .isUnloadedAtDestination())
                    .add("origin", cargo.getOrigin().getUnLocode().getIdString())
                    .add("lastKnownLocation",
                            cargo.getDelivery().getLastKnownLocation().getUnLocode().getIdString().equals("XXXXX")
                                    ? "Unknown"
                                    : cargo.getDelivery().getLastKnownLocation().getUnLocode().getIdString())
            );
        }

        return builder.build();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dbo;

namespace Interfaces
{
    public interface IObservation
    {
        List<Observation> CreateListObservation();
    }
}


text:
"use strict";

var util = require("./util");
var wrap = util.wrap;
var TrieAscoltatore = require("./trie_ascoltatore");
var AbstractAscoltatore = require('./abstract_ascoltatore');
var SubsCounter = require("./subs_counter");
var debug = require("debug")("ascoltatori:redis");

/**
 * RedisAscoltatore is a class that inherits from AbstractAscoltatore.
 * It is implemented through the `node_redis` package and it could be
 * backed up by any redis version greater than 2.2.
 *
 * The RedisAscoltatore defines two
 * properties _sub and _pub for handling
 * the two connections needed by redis.
 *
 * The options are:
 *  - `port`, the optional port to connect to;
 *  - `host`, the optional host to connect to;
 *  - `db`, the database to connect to (defaults to 0);
 *  - `password`, the optional password to use;
 *  - `sub_conn`, the optional redis connection to use for the sub and psub commands;
 *  - `pub_conn`, the optional redis connection to use for the pub command;
 *  - `redis`, the redis module (it will automatically be required if not present).
 *
 * @api public
 * @param {Object} opts The options object
 */
function RedisAscoltatore(opts) {
  AbstractAscoltatore.call(this, opts, {
    separator: '/',
    wildcardOne: '*',
    wildcardSome: '*'
  });

  this._ready_sub = false;
  this._ready_pub = false;
  this._opts = opts || {};
  this._opts.redis = this._opts.redis || require("redis");

  this._ascoltatores = {};

  this._domain = null;

  var that = this;
  this._ascoltatore = {
    registerDomain: function (domain) {
      that._domain = domain;
      for (var subTopic in that._ascoltatores) {
        that._ascoltatores[subTopic].registerDomain(domain);
      }
    }
  };

  this._startSub();
  this._startPub();

  this._subs_counter = new SubsCounter();
}

/**
 * Create a connection to redis using a default
 * from the opts if there is.
 *
 * @param {Object} opts The options object
 * @param {String} connName The name of the connection
 * @api private
 */
function createConn(opts, connName) {
  var conn = opts[connName];
  if (conn === undefined) {
    debug("connecting to " + opts.host + ":" + opts.port);
    conn = opts.redis.createClient(opts.port, opts.host, opts);
  }
  if (opts.password !== undefined) {
    debug("authenticating using password");
    conn.auth(opts.password);
  }
  debug("selected database " + opts.db);
  conn.select(opts.db || 0);
  conn.retry_backoff = 5;
  return conn;
}

/**
 * Inheriting
 *
 * @api private
 */
RedisAscoltatore.prototype = Object.create(AbstractAscoltatore.prototype);

/**
 * Start the pub connection
 *
 * @api private
 */
RedisAscoltatore.prototype._startPub = function() {
  var that = this;
  if (this._client === undefined) {
    this._client = createConn(this._opts, 'client_conn');
    this._client.on("ready", function() {
      debug("created pub connection");
      that._updateReady("_ready_pub");
    });
  }
  return this._client;
};

/**
 * Start the sub connection
 *
 * @api private
 */
RedisAscoltatore.prototype._startSub = function() {
  var that = this,
    handler = null;

  if (this._sub === undefined) {
    this._sub = createConn(this._opts, 'sub_conn');
    this._sub.on("ready", function() {
      debug("created sub connection");
      that._updateReady("_ready_sub");
    });

    handler = function(sub, topic, payload) {
      debug("new message received for topic " + topic);
      util.defer(function() {
        // we need to skip out this callback, so we do not
        // break the client when an exception occurs
        var ascoltatore = that._ascoltatores[sub];
        topic = topic.replace(new RegExp('/$'), '');
        topic = that._recvTopic(topic);

        payload = JSON.parse(payload);

        if (payload.binary) {
          payload.message = new Buffer(payload.message, 'hex');
        }

        if (ascoltatore) {
          ascoltatore.publish(topic, payload.message, payload.options);
        } else {
          debug("no ascoltatore for subscription: " + sub);
        }
      });
    };

    this._sub.on("message", function (topic, message) {
      handler(topic, topic, message);
    });
    this._sub.on("pmessage", function(sub, topic, message) {
      handler(sub, topic, message);
    });
  }

  return this._sub;
};

RedisAscoltatore.prototype._updateReady = function updateReady(key) {
  this[key] = true;
  if (this._ready_pub && this._ready_sub) {
    this.emit("ready");
  }
};

RedisAscoltatore.prototype._containsWildcard = function(topic) {
  return (topic.indexOf(this._wildcardOne) >= 0) ||
         (topic.indexOf(this._wildcardSome) >= 0);
};

RedisAscoltatore.prototype.subscribe = function subscribe(topic, callback, done) {
  this._raiseIfClosed();

  var newDone = function() {
    debug("registered new subscriber for topic " + topic);
    util.defer(done);
  };

  var subTopic = this._subTopic(topic);

  if (!subTopic.match(new RegExp('[/*]$'))) {
    subTopic += '/';
  }

  if (this._containsWildcard(topic)) {
    this._sub.psubscribe(subTopic, newDone);
  } else {
    this._sub.subscribe(subTopic, newDone);
  }

  debug("redis subscription topic is " + subTopic);
  this._subs_counter.add(subTopic);

  var ascoltatore = this._ascoltatores[subTopic];

  if (!ascoltatore) {
    ascoltatore = this._ascoltatores[subTopic] = new TrieAscoltatore(this._opts);

    if (this._domain) {
      ascoltatore.registerDomain(this._domain);
    }
  }

  ascoltatore.subscribe(topic, callback);
};

RedisAscoltatore.prototype.publish = function publish(topic, message, options, done) {
  this._raiseIfClosed();

  if (message === undefined || message === null) {
    message = false; // so we can convert it to JSON
  }

  var payload = {
    message: message,
    options: options
  };

  if (Buffer.isBuffer(message)) {
    payload.binary = true;
    payload.message = message.toString('hex');
  }

  topic = this._pubTopic(topic);

  if (!topic.match(new RegExp('/$'))) {
    topic += '/';
  }

  this._client.publish(topic, JSON.stringify(payload), function() {
    debug("new message published to " + topic);
    util.defer(done);
  });
};

RedisAscoltatore.prototype.unsubscribe = function unsubscribe(topic, callback, done) {
  this._raiseIfClosed();

  var isWildcard = this._containsWildcard(topic),
      subTopic = this._subTopic(topic);

  if (!subTopic.match(new RegExp('[/*]$'))) {
    subTopic += '/';
  }

  this._subs_counter.remove(subTopic);

  var ascoltatore = this._ascoltatores[subTopic];

  if (ascoltatore) {
    ascoltatore.unsubscribe(topic, callback);
  }

  var newDone = function() {
    debug("deregistered subscriber for topic " + topic);
    util.defer(done);
  };

  if (this._subs_counter.include(subTopic)) {
    newDone();
    return this;
  }

  if (ascoltatore) {
    ascoltatore.close();
    delete this._ascoltatores[subTopic];
  }

  if (isWildcard) {
    this._sub.punsubscribe(subTopic, newDone);
  } else {
    this._sub.unsubscribe(subTopic, newDone);
  }

  return this;
};

RedisAscoltatore.prototype.close = function close(done) {
  var that = this,
    newDone = null,
    closes = 2;

  newDone = function() {
    debug("closed");
    util.defer(done);
  };

  if (this._closed) {
    newDone();
    return;
  }

  this._subs_counter.clear();
  ["_sub", "_client"].forEach(function(c) {
    if (that[c] !== undefined) {
      that[c].on("end", function() {
        closes = closes - 1;
        if (closes === 0) {
          newDone();
        }
      });
      that[c].quit();
      delete that[c];
    } else {
      closes = closes - 1;
    }
  });

  for (var subTopic in this._ascoltatores) {
    this._ascoltatores[subTopic].close();
  }
  this._ascoltatores = {};

  this.emit("closed");
};

util.aliasAscoltatore(RedisAscoltatore.prototype);

/**
 * Exports the RedisAscoltatore
 *
 * @api public
 */
module.exports = RedisAscoltatore;


text:
//
//  CCBNodeTempBase.h
//  cpp
//
//  Created by Higgx on 11/4/13.
//
//

#ifndef __cpp__CCBNodeTempBase__
#define __cpp__CCBNodeTempBase__

#include "CUIBaseDelegate.h"

[[include]]

using namespace std;
USING_NS_CC;
USING_NS_CC_EXT;

class CCBNodeTempBase
:public CUIBaseDelegate
{
public:
    CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(CCBNodeTempBase, create);
    CCBNodeTempBase();
    virtual ~CCBNodeTempBase();

    void* userBag;

    virtual cocos2d::SEL_MenuHandler onResolveCCBCCMenuItemSelector(cocos2d::CCObject * pTarget, const char * pSelectorName);
    virtual cocos2d::extension::SEL_CCControlHandler onResolveCCBCCControlSelector(cocos2d::CCObject * pTarget, const char * pSelectorName);
    virtual bool onAssignCCBMemberVariable(cocos2d::CCObject * pTarget, const char * pMemberVariableName, cocos2d::CCNode * pNode);
    virtual cocos2d::SEL_CallFuncN onResolveCCBCCCallFuncSelector(CCObject * pTarget, const char* pSelectorName);

    virtual bool onAssignCCBCustomProperty(CCObject* pTarget, const char* pMemberVariableName, cocos2d::extension::CCBValue* pCCBValue);
    virtual void onNodeLoaded(cocos2d::CCNode * pNode, cocos2d::extension::CCNodeLoader * pNodeLoader);
    virtual void completedAnimationSequenceNamed(const char *name);

/*******************************************/

//    SEL_CCControlHandler
//    SEL_CallFuncN

/*******************************************/

public:

	[[value]]

    [[properties]]

	[[selector]]

    [[callback]]
};

#endif /* defined(__cpp__CCBNodeTempBase__) */


text:
<?php
class Enquetes_model extends CI_Model {
      public function __construct() {
        // Call the CI_Model constructor
        parent::__construct();
    }

    public function save($dados = null) {
        if ($dados != null) {
            $this->db->insert('enquetes', $dados);
        }
    }
     public function atualizar($dados = null) {
        if ($dados != null) {
            $this->db->update('enquetes', $dados, array('cliente_id' => $dados['cliente_id']));
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project

     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.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.stevengatto.android.wearable.pavlov" >

    <uses-sdk android:minSdkVersion="21"
        android:targetSdkVersion="21" />

    <uses-feature android:name="android.hardware.type.watch" />

    <!-- Required to act as a custom watch face. -->
    <uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <!-- Calendar permission used by CalendarWatchFaceService -->
    <uses-permission android:name="android.permission.READ_CALENDAR" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >

        <service
            android:name=".AnalogWatchFaceServiceUpdated"
            android:label="@string/analog_name_updated"
            android:allowEmbedded="true"
            android:taskAffinity=""
            android:permission="android.permission.BIND_WALLPAPER" >
            <meta-data
                android:name="android.service.wallpaper"
                android:resource="@xml/watch_face" />
            <meta-data
                android:name="com.google.android.wearable.watchface.preview"
                android:resource="@drawable/preview_analog" />
            <meta-data
                android:name="com.google.android.wearable.watchface.preview_circular"
                android:resource="@drawable/preview_analog_circular" />
            <meta-data
                android:name="com.google.android.wearable.watchface.companionConfigurationAction"
                android:value="com.example.android.wearable.watchface.CONFIG_ANALOG" />
            <intent-filter>
                <action android:name="android.service.wallpaper.WallpaperService" />
                <category android:name="com.google.android.wearable.watchface.category.WATCH_FACE" />
            </intent-filter>
        </service>

        <service android:name=".ListenerService">
            <intent-filter>
                <action android:name="com.google.android.gms.wearable.BIND_LISTENER"/>
            </intent-filter>
        </service>

        <activity android:name=".PromptActivity"
            android:label="PromptActivity"/>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

    </application>

</manifest>


text:
This PHP application automatically generates a responsive web app on top of your relational database. The app allows users to
* Create and edit records via web forms, taking into account foreign keys and other constraints
* View stored records along with related records from other tables
* Browse, search, and filter records in tables
* Query the database, visualize the results, and share the visualizations. Currenty the engine offers various visualizations like tables, bar charts, leaflet maps, sankeys, timelines, graphs/networks, social network analysis, geomaps and others

Developers may add custom functionality and extensions to the engine through hook functions in plugins, and admins may exploit an [extensive array of settings](settings.template.php) controlling the engine.

## Requirements
* Webserver running PHP (lowest tested version is 5.3)
* Database server (currently working only with PostgreSQL -- lowest tested version is 9.2; experimental support for MySQL)
* A database

## Get it Running
* Clone this repository into any folder that is served by your webserver.
* Run `npm install` in this folder.
* Since this repository contains the app engine only, you need to create another folder that will serve as the actual app folder
* In the app folder, create a PHP file that serves as the main entry point of the app (typically `index.php`). This file is very simple: it must include a definition of the constant `ENGINE_PATH`, which shall define the relative path to app engine folder. The other line in this file is the inclusion of `engine.php` from the app engine folder. You can also define the language by defining `DBWEBGEN_LANG` (currently English `en` and German `de` are available).

  Note: if required, you may use `ENGINE_PATH_LOCAL` to define the relative or absolute local file system path to the engine folder, which is used for including `.php` files; the `ENGINE_PATH` is used to point to files in `<script>` or `<link>` tags, so those must be resolveable by the web server.

  The typical index file would then look like this:

  ```php
  <?php
     define('ENGINE_PATH', '../dbWebGen/');
     define('DBWEBGEN_LANG', 'de');
     include ENGINE_PATH . 'engine.php';
  ?>
  ```
* Direct your web browser to the app folder. Upon first visit, a setup wizward will allow you to specify all app settings, which will be stored in a file called `settings.php`. If you encounter any issues or somehow misconfigure your app, you can also manually edit the `settings.php` file with explanations provided in [settings.template.php](settings.template.php)

## Example Database and App
An example app using this engine can be seen in the [dbWebGen-demo](https://github.com/eScienceCenter/dbWebGen-demo) repository

## Selected Features
* Fully localized in English and German; other languages can be added easily
* Access control via users table in database, custom authentication functions, or static user arrays
* Paginated, searchable, sortable viewing of table contents
* Viewing full details of single records
* Single-page or tabbed record editing forms
* Inline creation and editing of records referenced via foreign keys
* Conditional display and labeling of record fields in editing forms
* Grouped field display in editing forms (e.g. when date components are stored in separate columns)
* Hyperlinked display of records linked via foreign keys
* Record merging wizard
* Global and table-local search, allowing custom search transformations (e.g. removing diacritics, unaccenting, etc.)
* Custom menus, pages, and plugins with access to dbWebGen global objects, settings, and variables
* Input controls for most important field types, e.g. dropdown boxes, date pickers, geomap pickers, boolean toggles, text boxes, file uploads
* Custom JavaScript form validation

## Limitations
The major limitation currently is that the table settings for composite primary keys (e.g. in N:M-tables where each primary key part is a foreign key) currently only support a maximum of two primary key columns per table. If a composite primary key in some table in your DB consists of more than two columns, the remedy would be to create an artificial single-column primary key with auto-increment value for such tables.

## Screenshots
Below are some screenshots from a database app that uses dbWebGen to allow users to work with historic documents from 19th century Oman. Click any thumbnail to view at full resolution.

[![Data in a Table](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/list_documents_th.png)](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/list_documents.png)
[![Search Filter](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/filter_persons_th.png)](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/filter_persons.png)
[![View a Record](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/view_document_th.png)](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/view_document.png)
[![New Record Form](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/new_document_recipient_th.png)](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/new_document_recipient.png)
[![Edit Record Form](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/edit_document_th.png)](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/edit_document.png)
[![Query with Network Visualization](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/query_network_th.png)](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/query_network.png)
[![Query with Map Visualization](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/query_map_th.png)](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/query_map.png)
[![Responsive Edit](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/edit_responsive_th.png)](https://esciencecenter.github.io/assets/dbWebGen/screenshots/alhamra/edit_responsive.png)

## License
This code is licensed under the MIT license. See the [LICENSE](LICENSE) file.


text:
<?php

/**
 * PHP version 7.1
 *
 * @category Integration
 * @package  Intaro\RetailCrm\Component\Json\Strategy
 * @author   RetailCRM <integration@retailcrm.ru>
 * @license  MIT
 * @link     http://retailcrm.ru
 * @see      http://retailcrm.ru/docs
 */

namespace Intaro\RetailCrm\Component\Json\Strategy;

use Intaro\RetailCrm\Component\Json\Mapping\NoTransform;

/**
 * Class IsNoTransformTrait
 *
 * @package Intaro\RetailCrm\Component\Json\Strategy
 */
trait IsNoTransformTrait
{
    use AnnotationReaderTrait;

    /**
     * Returns true if NoTransform annotation was used
     *
     * @param \ReflectionProperty $property
     *
     * @return bool
     */
    protected static function isNoTransform(\ReflectionProperty $property): bool
    {
        $isNoTransform = static::annotationReader()->getPropertyAnnotation($property, NoTransform::class);

        return $isNoTransform instanceof NoTransform;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.mxgraph.layout.orthogonal.model Class Hierarchy (mxGraph 3.7.0.1 API Specification)</title>
<meta name="date" content="2017-01-29">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

mxGraph 3.7.0.1

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.mxgraph.layout.orthogonal.model

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.mxgraph.layout.orthogonal.model.mxOrthogonalModel

com.mxgraph.layout.orthogonal.model.mxPointPair

com.mxgraph.layout.orthogonal.model.mxPointSequence

com.mxgraph.layout.orthogonal.model.mxSegment

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

mxGraph 3.7.0.1

Prev

Next

Frames

No Frames

All Classes

Copyright (c) 2010 Gaudenz Alder, David Benson. All rights reserved.


text:
/**
 * Created by MingYin Lv on 2017/3/10 下午5:39.
 */

import path from 'path';
import config from './config';

export const createUrl = (url, prefix = config.publicDir) => {
  return path.join(prefix, url);
};

export const join = path.join;


text:
package org.apache.ivory.aspect;

import org.apache.ivory.monitors.Dimension;
import org.apache.ivory.monitors.Monitored;
import org.apache.ivory.monitors.TimeTaken;
import org.aspectj.lang.annotation.Aspect;

/**
 * Create a method with params you want to monitor via Aspect and log in metric
 * and iMon, invoke this method from code.
 */
@Aspect
public class GenericAlert {

	@Monitored(event = "retry-instance-failed")
	public static String alertRetryFailed(
			@Dimension(value = "entity-type") String entityType,
			@Dimension(value = "entity-name") String entityName,
			@Dimension(value = "nominal-name") String nominalTime,
			@Dimension(value = "wf-id") String wfId,
			@Dimension(value = "run-id") String runId,
			@Dimension(value = "error-message") String message) {
		return "IGNORE";
	}

	@Monitored(event = "late-rerun-failed")
	public static String alertLateRerunFailed(
			@Dimension(value = "entity-type") String entityType,
			@Dimension(value = "entity-name") String entityName,
			@Dimension(value = "nominal-name") String nominalTime,
			@Dimension(value = "wf-id") String wfId,
			@Dimension(value = "run-id") String runId,
			@Dimension(value = "error-message") String message) {
		return "IGNORE";

	}

	@Monitored(event = "wf-instance-failed")
	public static String instrumentFailedInstance(
			@Dimension(value = "cluster") String cluster,
			@Dimension(value = "entity-type") String entityType,
			@Dimension(value = "entity-name") String entityName,
			@Dimension(value = "nominal-time") String nominalTime,
			@Dimension(value = "wf-id") String workflowId,
			@Dimension(value = "run-id") String runId,
			@Dimension(value = "operation") String operation,
            @Dimension(value = "start-time") String startTime,
            @Dimension(value = "error-message") String errorMessage,
            @Dimension(value = "message") String message,
			@TimeTaken long timeTaken)
			throws Exception {
		return "IGNORE";
	}

	@Monitored(event = "wf-instance-succeeded")
	public static String instrumentSucceededInstance(
			@Dimension(value = "cluster") String cluster,
			@Dimension(value = "entity-type") String entityType,
			@Dimension(value = "entity-name") String entityName,
			@Dimension(value = "nominal-time") String nominalTime,
			@Dimension(value = "wf-id") String workflowId,
			@Dimension(value = "run-id") String runId,
			@Dimension(value = "operation") String operation,
            @Dimension(value = "start-time") String startTime,
			@TimeTaken long timeTaken)
			throws Exception {
		return "IGNORE";
	}

	@Monitored(event = "rerun-queue-failed")
	public static String alertRerunConsumerFailed(
			@Dimension(value = "message") String message,
			@Dimension(value = "exception") Exception exception) {
		return "IGNORE";

	}

	@Monitored(event = "sla-miss")
	public static String alertOnLikelySLAMiss(
            @Dimension(value = "cluster") String cluster,
            @Dimension(value = "entity-type") String entityType,
            @Dimension(value = "entity-name") String entityName,
            @Dimension(value = "nominal-time") String nominalTime) {
		return "IGNORE";
	}

	@Monitored(event = "log-cleanup-service-failed")
	public static String alertLogCleanupServiceFailed(
			@Dimension(value = "message") String message,
			@Dimension(value = "exception") Throwable throwable) {
		return "IGNORE";

	}
}


text:
#pragma once
#include <aws/wafv2/WAFV2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace WAFV2
{
namespace Model
{

  /**
   *
A single label name condition for a Condition in a logging
   * filter.

See Also:
   AWS
   * API Reference

   */
  class AWS_WAFV2_API LabelNameCondition
  {
  public:
    LabelNameCondition();
    LabelNameCondition(Aws::Utils::Json::JsonView jsonValue);
    LabelNameCondition& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The label name that a log record must contain in order to meet the condition.
     * This must be a fully qualified label name. Fully qualified labels have a prefix,
     * optional namespaces, and label name. The prefix identifies the rule group or web
     * ACL context of the rule that added the label.

     */
    inline const Aws::String& GetLabelName() const{ return m_labelName; }

    /**
     *
The label name that a log record must contain in order to meet the condition.
     * This must be a fully qualified label name. Fully qualified labels have a prefix,
     * optional namespaces, and label name. The prefix identifies the rule group or web
     * ACL context of the rule that added the label.

     */
    inline bool LabelNameHasBeenSet() const { return m_labelNameHasBeenSet; }

    /**
     *
The label name that a log record must contain in order to meet the condition.
     * This must be a fully qualified label name. Fully qualified labels have a prefix,
     * optional namespaces, and label name. The prefix identifies the rule group or web
     * ACL context of the rule that added the label.

     */
    inline void SetLabelName(const Aws::String& value) { m_labelNameHasBeenSet = true; m_labelName = value; }

    /**
     *
The label name that a log record must contain in order to meet the condition.
     * This must be a fully qualified label name. Fully qualified labels have a prefix,
     * optional namespaces, and label name. The prefix identifies the rule group or web
     * ACL context of the rule that added the label.

     */
    inline void SetLabelName(Aws::String&& value) { m_labelNameHasBeenSet = true; m_labelName = std::move(value); }

    /**
     *
The label name that a log record must contain in order to meet the condition.
     * This must be a fully qualified label name. Fully qualified labels have a prefix,
     * optional namespaces, and label name. The prefix identifies the rule group or web
     * ACL context of the rule that added the label.

     */
    inline void SetLabelName(const char* value) { m_labelNameHasBeenSet = true; m_labelName.assign(value); }

    /**
     *
The label name that a log record must contain in order to meet the condition.
     * This must be a fully qualified label name. Fully qualified labels have a prefix,
     * optional namespaces, and label name. The prefix identifies the rule group or web
     * ACL context of the rule that added the label.

     */
    inline LabelNameCondition& WithLabelName(const Aws::String& value) { SetLabelName(value); return *this;}

    /**
     *
The label name that a log record must contain in order to meet the condition.
     * This must be a fully qualified label name. Fully qualified labels have a prefix,
     * optional namespaces, and label name. The prefix identifies the rule group or web
     * ACL context of the rule that added the label.

     */
    inline LabelNameCondition& WithLabelName(Aws::String&& value) { SetLabelName(std::move(value)); return *this;}

    /**
     *
The label name that a log record must contain in order to meet the condition.
     * This must be a fully qualified label name. Fully qualified labels have a prefix,
     * optional namespaces, and label name. The prefix identifies the rule group or web
     * ACL context of the rule that added the label.

     */
    inline LabelNameCondition& WithLabelName(const char* value) { SetLabelName(value); return *this;}

  private:

    Aws::String m_labelName;
    bool m_labelNameHasBeenSet = false;
  };

} // namespace Model
} // namespace WAFV2
} // namespace Aws


text:
package engine

import (
	"sync"
	"time"

	"github.com/thrasher-corp/gocryptotrader/config"
	"github.com/thrasher-corp/gocryptotrader/currency"
	"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
)

// syncBase stores information
type syncBase struct {
	IsUsingWebsocket bool
	IsUsingREST      bool
	IsProcessing     bool
	LastUpdated      time.Time
	HaveData         bool
	NumErrors        int
}

// currencyPairSyncAgent stores the sync agent info
type currencyPairSyncAgent struct {
	Created   time.Time
	Exchange  string
	AssetType asset.Item
	Pair      currency.Pair
	Ticker    syncBase
	Orderbook syncBase
	Trade     syncBase
}

// SyncManagerConfig stores the currency pair synchronization manager config
type SyncManagerConfig struct {
	SynchronizeTicker       bool
	SynchronizeOrderbook    bool
	SynchronizeTrades       bool
	SynchronizeContinuously bool
	TimeoutREST             time.Duration
	TimeoutWebsocket        time.Duration
	NumWorkers              int
	FiatDisplayCurrency     currency.Code
	PairFormatDisplay       *currency.PairFormat
	Verbose                 bool
}

// syncManager stores the exchange currency pair syncer object
type syncManager struct {
	initSyncCompleted              int32
	initSyncStarted                int32
	started                        int32
	delimiter                      string
	uppercase                      bool
	initSyncStartTime              time.Time
	fiatDisplayCurrency            currency.Code
	websocketRoutineManagerEnabled bool
	mux                            sync.Mutex
	initSyncWG                     sync.WaitGroup
	inService                      sync.WaitGroup

	currencyPairs            []currencyPairSyncAgent
	tickerBatchLastRequested map[string]time.Time

	remoteConfig    *config.RemoteControlConfig
	config          SyncManagerConfig
	exchangeManager iExchangeManager
}


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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>MTB CAT1 Peripheral driver library: Transfer Errors</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen_style.css" rel="stylesheet" type="text/css" />

MTB CAT1 Peripheral driver library

Macros

Transfer Errors
USBFS        (USB Full-Speed Device) » Macros

General Description

Macros

#define 	CY_USBFS_DEV_ENDPOINT_TRANSFER_ERROR   (0x1U)

 	An error occurred during a USB transfer.  More...

#define 	CY_USBFS_DEV_ENDPOINT_SAME_DATA_TOGGLE   (0x2U)

 	The data toggle bit remains the same.  More...

Macro Definition Documentation

◆ CY_USBFS_DEV_ENDPOINT_TRANSFER_ERROR

          #define CY_USBFS_DEV_ENDPOINT_TRANSFER_ERROR   (0x1U)

An error occurred during a USB transfer.

For an IN transaction, this indicates a "no response" from the HOST scenario. For an OUT transaction, this represents a "PID or CRC error" or the bit-stuff error scenario.

◆ CY_USBFS_DEV_ENDPOINT_SAME_DATA_TOGGLE

          #define CY_USBFS_DEV_ENDPOINT_SAME_DATA_TOGGLE   (0x2U)

The data toggle bit remains the same.

The received OUT packet has the same data toggle bit that the previous packet had. This indicates that the Host retransmitted the packet.


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Sung, Hywel-Jones, Sung, Luangsa-ard, Shrestha & Spatafora, Stud. Mycol. 57: 37 (2007)

#### Original name
Cordyceps fracta Mains, 1957

### Remarks
null