text:
'use strict';
/**
 * Required modules.
 */
var utilities = require('./utilities'),
  injector = require('./injector'),
  initializer = require('./initializer'),
  builder = require('./builder'),
  constants = require('./constants'),
  configurator = require('./configurator'),
  express = require('express'),
  http = require('http'),
  path = require('path');

/**
 * The umbrella object with public api.
 */
module.exports = function(parentModule) {
  // Define internal injectable components exposed as read only
  // All internals must be specified here before use to ensure public api exposure
  // All internals can be reached through the umbrella object or by injecting $[internalComponent]
  var internals = {
    umbrella: null,
    express: express,
    app: null,
    server: null,
    root: null,
    components: null,
    middlewares: null,
    routes: null,
    describe: utilities.describeInitializer
  };

  // Inject may be exposed through internals if required later on
  var inject = null; // The inject function will be created with the injector on bootstrap

  // Define the umbrella object
  var umbrella = {
    /**
     * Create an express app and set up umbrella.
     * Loads the umbrella initializer, router and components and sets up the internals.
     *
     * @param components The components to allow for injection.
     * @returns The umbrella object.
     */
    bootstrap: function(components) {
      if(internals.app !== null) throw new Error('umbrella bootstrap is being called multiple times which is not allowed.');

      // Expect the server module to be called server.js and be the bootstrapping parent of umbrella,
      // this is a precaution to avoid accidental bootstrapping from a sub-module which may cause issues.
      if(path.basename(parentModule.filename) !== constants.EXPECTED_SERVER_FILENAME) {
        console.warn('umbrella is being bootstrapped from a module other than server.js,' +
          ' this may cause unexpected behavior');
      }

      // Set internal components
      internals.umbrella = this;
      internals.app = express();
      internals.server = http.createServer(internals.app);
      internals.root = path.dirname(parentModule.filename);
      internals.components = components;

      // Create an injector function for this umbrella object with the app as context and injection components
      inject = injector.create(internals.app, utilities.createInjectionComponents(internals.components, internals));

      return this;
    },

    /**
     * Build the custom middlewares dependancy object and inject component dependencies
     *
     * @returns The umbrella object.
     */
    buildMiddlewares: function() {
      if(internals.app === null) throw new Error('umbrella has to be bootstrapped before buildMiddlewares() is called.');

      // Bulid dependancy object and inject with injector
      internals.middlewares = builder.buildAndProcess(internals.root + constants.MIDDLEWARES_PATH, inject);
      return this;
    },

    /**
     * Process each configuration for the current environment
     *
     * @returns The umbrella object.
     */
    configure: function() {
      if(internals.app === null) throw new Error('umbrella has to be bootstrapped before configure() is called.');

      // Require the umbrella environment modules
      var environmentsPath = internals.root + constants.ENVIRONMENTS_PATH;
      var config = {
        all: require(environmentsPath + 'all'),
        development: require(environmentsPath + 'development'),
        production: require(environmentsPath + 'production')
      };

      // Run the configurations
      configurator(internals.app, config, inject);

      return this;
    },

    /**
     * Initialize components specified by components object using each specific initializer
     * in the order specified in Umbrella initializer.
     * This is done asynchronously since some initializer may be run async.
     *
     * @param initCallback The callback for when initialization is done, is called according to convention with
     *                     (err,  umbrella)
     * @returns undefined, this function cannot be chained. Chain through callback.
     */
    init: function(initCallback) {
      if(internals.app === null) throw new Error('umbrella has to be bootstrapped before init() is called.');

      // Run the initializers
      initializer(internals.app.settings.env,
        require(internals.root + constants.UMBRELLA_INIT_PATH),
        internals.root + constants.INITIALIZERS_PATH,
        inject,
        function(err) {
          initCallback(err, internals.umbrella);
        }
      );

      // Do not return anything to prevent chaining for this async function
    },

    /**
     * Bootstrap all models present in model folder.
     * @returns The umbrella object.
     */
    bootstrapModels: function() {
      if(internals.app === null) throw new Error('umbrella has to be bootstrapped before bootstrapModels() is called.');

      var modelDirAbs = internals.root + constants.MODEL_DIR;

      // Only bootstrap if model folder present
      if(utilities.folderExists(modelDirAbs)) {
        utilities.mapAllFilesSync(modelDirAbs, function(file) {
          // Inject dependencies to model for bootstrapping
          // If the model bootstrapper function has more parameters than dependencies it cannot be invoked
          inject(require(modelDirAbs + file), true);
        });
      }

      return this;
    },

    /**
     * Map routes contained in routes directory using umbrella route config.
     * Also injects dependencies for routes.
     *
     * @returns The umbrella object.
     */
    route: function() {
      if(internals.app === null) throw new Error('umbrella has to be bootstrapped before route() is called.');

      // Map each route module to a routes object and inject dependencies accordingly
      internals.routes = builder.buildAndProcess(internals.root + constants.ROUTES_PATH, inject);

      // Call routes config with dependencies
      inject(require(internals.root + constants.UMBRELLA_ROUTES_PATH), true);

      return this;
    },

    /**
     * Start to listen on default port (3000) or port specified by environment.
     * @returns The umbrella object.
     */
    listen: function() {
      if(internals.app === null) throw new Error('umbrella has to be bootstrapped before listen() is called.');

      var port = process.env.PORT || 3000;
      internals.server.listen(port);
      console.log('Umbrella told express to listen on port %d in %s mode', port, internals.app.settings.env);

      return this;
    },

    /**
     * Combine bootstrapping and all initialization in a single function for convenience.
     * Will not throw errors, all errors are provided in callback.
     * Umbrella will silently fail if callback errors are ignored.
     *
     * @param components The components to allow for injection.
     * @param callback The callback for when initialization is done and express has started listening,
     *                 is called according to convention with (err,  umbrella)
     * @returns undefined, this function cannot be chained. Chain through callback.
     */
    all: function(components, callback) {
      try {
        // Bootstrap sync then init async
        this.bootstrap(components).buildMiddlewares().configure().init(function(err, umbrella) {
          if(err) return callback && callback(err, umbrella); // Pass on initializer errors
          try {
            // When init async is done, configure, route and listen sync then callback
            umbrella.bootstrapModels().route().listen();
            return callback && callback(null, umbrella);
          } catch (err) {
            return callback && callback(err, umbrella);
          }
        });
      } catch (err) {
        return callback && callback(err, this);
      }
    }
  };

  // Expose internal components through the umbrella api in a confined internals object
  // User may acquire internal components freely through this object. Don't put them directly
  // on the umbrella object to avoid clobbering.
  utilities.exposeInternals(umbrella, internals);

  return umbrella;
};


text:
#ifndef FileSystemCallback_h
#define FileSystemCallback_h

#if ENABLE(FILE_SYSTEM)

#include <wtf/RefCounted.h>

namespace WebCore {

class DOMFileSystem;

class FileSystemCallback : public RefCounted<FileSystemCallback> {
public:
    virtual ~FileSystemCallback() { }
    virtual bool handleEvent(DOMFileSystem*) = 0;
};

} // namespace

#endif // ENABLE(FILE_SYSTEM)

#endif // FileSystemCallback_h

redpajama_set_name: RedPajamaGithub


text:
/*!
 *  Copyright (c) 2018 by Contributors
 *  Optional module when build aocl is switched to off
 */
#include "../codegen_source_base.h"
#include "../../runtime/opencl/opencl_module.h"

namespace tvm {
namespace runtime {

Module AOCLModuleCreate(
    std::string data,
    std::string fmt,
    std::unordered_map<std::string, FunctionInfo> fmap,
    std::string source) {
  LOG(WARNING) << "AOCL runtime not enabled, return a source module...";
  return codegen::DeviceSourceModuleCreate(data, fmt, fmap, "aocl");
}

}  // namespace runtime
}  // namespace tvm


text:
package com.intellij.util.xml.ui;

import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomElementNavigationProvider;

import java.awt.*;
import java.util.List;

public class DomUINavigationProvider extends DomElementNavigationProvider {
  public static String DOM_UI_NAVIGATION_PROVIDER_NAME = "DOM_UI_NAVIGATION_PROVIDER_NAME";

  private final CompositeCommittable myComponent;

  public DomUINavigationProvider(final CompositeCommittable component) {
    myComponent = component;
  }

  @Override
  public String getProviderName() {
    return DOM_UI_NAVIGATION_PROVIDER_NAME;
  }

  @Override
  public void navigate(DomElement domElement, boolean requestFocus) {
    final DomUIControl domUIControl = findDomControl(myComponent, domElement);
    if(domUIControl != null) {
      domUIControl.navigate(domElement);
    }
  }

  @Override
  public boolean canNavigate(DomElement domElement) {
    return findDomControl(myComponent, domElement) != null;
  }

  public static DomElement findDomElement(final BasicDomElementComponent compositCommitable) {
    final Component component = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
    if (component != null) {
      final DomElement domElement = findDomElement(compositCommitable, component);
      if (domElement != null) {
        return domElement;
      }
    }
    return compositCommitable.getDomElement();
  }

  public static DomElement findDomElement(final CompositeCommittable compositCommitable, final Component component) {
    final List<Committable> list = compositCommitable.getChildren();
    for (Committable committable : list) {
      if (committable instanceof DomUIControl) {
        final DomUIControl uiControl = (DomUIControl)committable;
        if (uiControl.getComponent().isAncestorOf(component)) {
          return uiControl.getDomElement();
        }
      } else if (committable instanceof CompositeCommittable) {
        final DomElement element = findDomElement((CompositeCommittable)committable, component);
        if (element != null) return element;
      }
    }
    return null;
  }

  public static DomUIControl findDomControl(final CompositeCommittable compositCommitable, final DomElement domElement) {
    final List<Committable> list = compositCommitable.getChildren();
    for (Committable committable : list) {
      if (committable instanceof DomUIControl) {
          if(((DomUIControl)committable).canNavigate(domElement)) {
            return (DomUIControl)committable;
          }
      } else if (committable instanceof CompositeCommittable) {
        final DomUIControl control = findDomControl((CompositeCommittable)committable, domElement);
        if(control != null) return control;
      }
    }
    return null;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebsitePanel.Providers.HostedSolution;
using System.Data;

namespace WebsitePanel.Portal.ExchangeServer.UserControls
{
	public partial class AccountsListWithPermissions : WebsitePanelControlBase
	{
		private enum SelectedState
		{
			All,
			Selected,
			Unselected
		}

	    public bool EnableMailboxOnly
	    {
            get {return ViewState["EnableMailboxOnly"] != null ? (bool)ViewState["EnableMailboxOnly"]: false; }
            set { ViewState["EnableMailboxOnly"] = value; }
	    }

        public bool MailboxesEnabled
		{
			get { return ViewState["MailboxesEnabled"] != null ? (bool)ViewState["MailboxesEnabled"] : false; }
			set { ViewState["MailboxesEnabled"] = value; }
		}

		public bool ContactsEnabled
		{
			get { return ViewState["ContactsEnabled"] != null ? (bool)ViewState["ContactsEnabled"] : false; }
			set { ViewState["ContactsEnabled"] = value; }
		}

		public bool DistributionListsEnabled
		{
			get { return ViewState["DistributionListsEnabled"] != null ? (bool)ViewState["DistributionListsEnabled"] : false; }
			set { ViewState["DistributionListsEnabled"] = value; }
		}

		public int ExcludeAccountId
		{
			get { return PanelRequest.AccountID; }
		}

		public void SetAccounts(ExchangeAccount[] accounts)
		{
			BindAccounts(accounts, false);
		}

		public ExchangeAccount[] GetAccounts()
		{
			// get selected accounts
			List<ExchangeAccount> selectedAccounts = GetGridViewAccounts(gvAccounts, SelectedState.All);

            List<ExchangeAccount> accountNames = new List<ExchangeAccount>();
            foreach (ExchangeAccount account in selectedAccounts)
            {
                accountNames.Add(account);
            }
            ExchangeAccount[] accounts = accountNames.ToArray();
            return accounts;
		}

		protected void Page_Load(object sender, EventArgs e)
		{

			// toggle controls
			if (!IsPostBack)
			{
				chkIncludeMailboxes.Visible = chkIncludeRooms.Visible = chkIncludeEquipment.Visible = MailboxesEnabled;
                chkIncludeMailboxes.Checked = chkIncludeRooms.Checked = chkIncludeEquipment.Checked = MailboxesEnabled;

                if (EnableMailboxOnly)
				{
				    chkIncludeRooms.Checked = false;
				    chkIncludeRooms.Visible = false;
				    chkIncludeEquipment.Checked = false;
				    chkIncludeEquipment.Visible = false;
				}

                chkIncludeContacts.Visible = ContactsEnabled;
				chkIncludeContacts.Checked = ContactsEnabled;
				chkIncludeLists.Visible = DistributionListsEnabled;
				chkIncludeLists.Checked = DistributionListsEnabled;
			}

			// register javascript
			if (!Page.ClientScript.IsClientScriptBlockRegistered("SelectAllCheckboxes"))
			{
				string script = @"    function SelectAllCheckboxes(box)
    {
		var state = box.checked;
        var elm = box.parentElement.parentElement.parentElement.parentElement.getElementsByTagName(""INPUT"");
        for(i = 0; i < elm.length; i++)
            if(elm[i].type == ""checkbox"" && elm[i].id != box.id && elm[i].checked != state && !elm[i].disabled)
		        elm[i].checked = state;
    }";
				Page.ClientScript.RegisterClientScriptBlock(typeof(AccountsList), "SelectAllCheckboxes",
					script, true);
			}
		}

		public string GetAccountImage(int accountTypeId)
		{
			ExchangeAccountType accountType = (ExchangeAccountType)accountTypeId;
			string imgName = "mailbox_16.gif";
			if (accountType == ExchangeAccountType.Contact)
				imgName = "contact_16.gif";
			else if (accountType == ExchangeAccountType.DistributionList)
				imgName = "dlist_16.gif";
            else if (accountType == ExchangeAccountType.Room)
                imgName = "room_16.gif";
            else if (accountType == ExchangeAccountType.Equipment)
                imgName = "equipment_16.gif";

			return GetThemedImage("Exchange/" + imgName);
		}

		protected void btnAdd_Click(object sender, EventArgs e)
		{
			// bind all accounts
			BindPopupAccounts();

			// show modal
			AddAccountsModal.Show();
		}

		protected void btnDelete_Click(object sender, EventArgs e)
		{
			// get selected accounts
			List<ExchangeAccount> selectedAccounts = GetGridViewAccounts(gvAccounts, SelectedState.Unselected);

			// add to the main list
			BindAccounts(selectedAccounts.ToArray(), false);
		}

		protected void btnAddSelected_Click(object sender, EventArgs e)
		{
			// get selected accounts
			List<ExchangeAccount> selectedAccounts = GetGridViewAccounts(gvPopupAccounts, SelectedState.Selected);
            List<ExchangeAccount> selectedAccountsWithPermissions = new List<ExchangeAccount>();
            foreach (ExchangeAccount account in selectedAccounts)
            {
                if (account.AccountId != ExcludeAccountId)
                    account.PublicFolderPermission = "Reviewer";
                selectedAccountsWithPermissions.Add(account);
            }
            // add to the main list
            BindAccounts(selectedAccountsWithPermissions.ToArray(), true);
		}

		private void BindPopupAccounts()
		{
			ExchangeAccount[] accounts = ES.Services.ExchangeServer.SearchAccounts(PanelRequest.ItemID,
				chkIncludeMailboxes.Checked, chkIncludeContacts.Checked, chkIncludeLists.Checked,
                chkIncludeRooms.Checked, chkIncludeEquipment.Checked, false,
				ddlSearchColumn.SelectedValue, txtSearchValue.Text + "%", "");

			if (ExcludeAccountId > 0)
			{
				List<ExchangeAccount> updatedAccounts = new List<ExchangeAccount>();
                foreach (ExchangeAccount account in accounts)
                {
                    if (account.AccountId != ExcludeAccountId)
                        account.PublicFolderPermission = "Reviewer";
                        updatedAccounts.Add(account);
                }
				accounts = updatedAccounts.ToArray();
			}

			gvPopupAccounts.DataSource = accounts;
			gvPopupAccounts.DataBind();
		}

		private void BindAccounts(ExchangeAccount[] newAccounts, bool preserveExisting)
		{
			// get binded addresses
			List<ExchangeAccount> accounts = new List<ExchangeAccount>();
			if(preserveExisting)
				accounts.AddRange(GetGridViewAccounts(gvAccounts, SelectedState.All));

			// add new accounts
			if (newAccounts != null)
			{
				foreach (ExchangeAccount newAccount in newAccounts)
				{
					// check if exists
					bool exists = false;
					foreach (ExchangeAccount account in accounts)
					{
						if (String.Compare(newAccount.AccountName, account.AccountName, true) == 0)
						{
							exists = true;
							break;
						}
					}

					if (exists)
						continue;

					accounts.Add(newAccount);
				}
			}

			gvAccounts.DataSource = accounts;
			gvAccounts.DataBind();

            btnDelete.Visible = gvAccounts.Rows.Count > 0;
		}

		private List<ExchangeAccount> GetGridViewAccounts(GridView gv, SelectedState state)
		{
			List<ExchangeAccount> accounts = new List<ExchangeAccount>();

			for (int i = 0; i < gv.Rows.Count; i++)
			{
				GridViewRow row = gv.Rows[i];
				CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect");
						if (chkSelect == null)
						continue;

				ExchangeAccount account = new ExchangeAccount();
				account.AccountType = (ExchangeAccountType)Enum.Parse(typeof(ExchangeAccountType), ((Literal)row.FindControl("litAccountType")).Text);
				account.AccountName = (string)gv.DataKeys[i][0];
				account.DisplayName = ((Literal)row.FindControl("litDisplayName")).Text;
				account.PrimaryEmailAddress = ((Literal)row.FindControl("litPrimaryEmailAddress")).Text;
                if (gv != gvPopupAccounts)
                {
                    DropDownList ddlPermissions = (DropDownList)row.FindControl("ddlPermissions");
                    //HiddenField PermissionLabel = (HiddenField)row.FindControl("PermissionLabel");
                    //account.PublicFolderPermission = PermissionLabel.Value;
                    account.PublicFolderPermission = ddlPermissions.SelectedValue;
                }
				if(state == SelectedState.All ||
					(state == SelectedState.Selected && chkSelect.Checked) ||
					(state == SelectedState.Unselected && !chkSelect.Checked))
					accounts.Add(account);
			}
			return accounts;
		}

		protected void chkIncludeMailboxes_CheckedChanged(object sender, EventArgs e)
		{
			BindPopupAccounts();
		}

		protected void cmdSearch_Click(object sender, ImageClickEventArgs e)
		{
			BindPopupAccounts();
		}

        protected void gvAccounts_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                DropDownList ddlPermissions = (DropDownList)e.Row.FindControl("ddlPermissions");
                HiddenField PermissionLabel = (HiddenField)e.Row.FindControl("PermissionLabel");

                ExchangeAccount dRow = (ExchangeAccount)e.Row.DataItem as ExchangeAccount;
                ListItem itm = new ListItem(dRow.PublicFolderPermission, dRow.PublicFolderPermission);

                if (ddlPermissions.Items.Contains(itm))
                {
                    PermissionLabel.Value = dRow.PublicFolderPermission;
                    ddlPermissions.SelectedValue = dRow.PublicFolderPermission;
                }
                else
                {
                    PermissionLabel.Value = dRow.PublicFolderPermission;
                    ddlPermissions.Items.Add(itm);
                    ddlPermissions.SelectedValue = dRow.PublicFolderPermission;
                    ddlPermissions.DataBind();
                }

            }
        }

        protected void ddlPermissions_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddlCurrentDropDownList = (DropDownList)sender;
            GridViewRow grdrDropDownRow = ((GridViewRow)ddlCurrentDropDownList.Parent.Parent);

            ExchangeAccount ex = (ExchangeAccount)grdrDropDownRow.DataItem as ExchangeAccount;
            if (ex != null)
                ex.PublicFolderPermission = ddlCurrentDropDownList.SelectedValue;
        }
	}
}


text:
<resources>
    <string name="app_name">SectionedRecyclerViewAdapter Demo</string>

    <string name="title_activity_home">HomeActivity</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>

    <string name="action_search">Search</string>

    <string name="nav_stateless">Stateless Section</string>
    <string name="nav_example1">Section with Header</string>
    <string name="nav_example2">Section with Header and Footer</string>
    <string name="nav_example4">Expandable Section</string>
    <string name="nav_example5">Grid Section with Header</string>
    <string name="nav_example6">Expandable Grid Section</string>
    <string name="nav_example7">SearchView with Sections</string>
    <string name="nav_stateful">Stateful Section</string>
    <string name="nav_example3">Section with Header and Footer</string>

    <string name="world_topic">World</string>
    <string name="biz_topic">Business</string>
    <string name="tech_topic">Technology</string>
    <string name="sports_topic">Sports</string>

    <string name="top_rated_movies_topic">Top Rated Movies</string>
    <string name="most_popular_movies_topic">Most Popular Movies</string>

    <string name="more">MORE</string>
    <string name="see_more">See more..</string>
    <string name="failed_load">Failed to load, tap to try again.</string>

</resources>


text:
@protocol ScanQRCodeVCDelegate <NSObject>
- (void) captureQRCode:(NSString*)code;
@optional
-(void)photoScan;
@end

@interface ScanQRCode_VC : UIViewController<AVCaptureMetadataOutputObjectsDelegate>
{
    int num;
    BOOL upOrdown;
    NSTimer * timer;
}
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;
@property (nonatomic, strong) UIImageView * line;
@property (nonatomic, weak) id<ScanQRCodeVCDelegate> delegate;
@end


text:
package com.yassergonzalez.pagerank;

import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.Writable;

public class FloatArrayWritable extends ArrayWritable {

	public FloatArrayWritable() {
		super(FloatWritable.class);
	}

	public FloatArrayWritable(Writable[] values) {
		super(FloatWritable.class, values);
	}

}


text:
class Hash
  def insert_before(key, kvpair)
    arr = to_a
    pos = arr.index(arr.assoc(key))
    if pos
      arr.insert(pos, kvpair)
    else
      arr << kvpair
    end
    replace Hash[arr]
  end
end


text:
import os
import shutil
import unicodedata
import webbrowser
import re

import requests
from wox import Wox,WoxAPI
from bs4 import BeautifulSoup

ROOT_URL = 'http://weekly.manong.io/'
ISSUE_URL = 'http://weekly.manong.io/issues/'

def full2half(uc):
    """Convert full-width characters to half-width characters.
    """
    return unicodedata.normalize('NFKC', uc)

class Main(Wox):

    def request(self,url):
	#get system proxy if exists
        if self.proxy and self.proxy.get("enabled") and self.proxy.get("server"):
	    proxies = {
		"http":"http://{}:{}".format(self.proxy.get("server"),self.proxy.get("port")),
		"https":"http://{}:{}".format(self.proxy.get("server"),self.proxy.get("port"))
	    }
	    return requests.get(url,proxies = proxies)
	return requests.get(url)

    def getLastestIssue(self,url):

        r = self.request(url)
        r.encoding = 'utf-8'
        bs = BeautifulSoup(r.content, 'html.parser')

        return bs.find('div', class_='menu').find('a')['href']

    def query(self, param):
        url = self.getLastestIssue(ROOT_URL)
        if re.match('^\d+$', param.strip()):
            url = ISSUE_URL + param.strip()

	r = self.request(url)
	r.encoding = 'utf-8'
	bs = BeautifulSoup(r.content, 'html.parser')
	posts = bs.select('h4')

        if not param.strip() or int(param.strip()) > 110:
            posts.remove(posts[0])

	result = []
	for p in posts:
            ptitle = p.find('a').string
            plink = p.find('a')['href']
            user = p.find('small')
            psubtitle = p.next_sibling.next_sibling.string
            item = {
                'Title': u'{subject} by {user}'.format(subject=full2half(ptitle), user=user.string if user else ""),
                'SubTitle': psubtitle if psubtitle else "enter to open",
                'IcoPath': os.path.join('img', 'manong.png'),
                'JsonRPCAction': {
                    'method': 'open_url',
                    'parameters': [plink]
                }
            }
            result.append(item)

	return result

    def open_url(self, url):
	webbrowser.open(url)

if __name__ == '__main__':
    Main()


text:
module Pakyow
  module Fail
    class Handler
      def self.register(name, klass, required_config)
        Config.fail.available_handlers[name] = klass
        Config.fail.required_config[name] = required_config
      end

      def self.enable(name)
        return if Config.fail.enabled_handlers.include?(name)
        Config.fail.enabled_handlers << name
      end

      def self.disable(name)
        Config.fail.enabled_handlers.delete(name)
      end
    end
  end
end


text:
package swtch

import (
	"github.com/gotmc/ivi"
	"github.com/gotmc/query"
)

// Channel models the repeated capability of a generic channel.
type Channel struct {
	id   int
	name string
	inst ivi.Instrument
}

// NewChannel returns a Channel for a switch.
func NewChannel(id int, name string, inst ivi.Instrument) Channel {
	return Channel{id, name, inst}
}

// Set writes the format string, using the given paarameters to the channel.
func (ch *Channel) Set(format string, a ...interface{}) error {
	return ivi.Set(ch.inst, format, a...)
}

// QueryBool queries the channel and returns a bool.
func (ch *Channel) QueryBool(cmd string) (bool, error) {
	return query.Bool(ch.inst, cmd)
}

// QueryFloat64 queries the channel and returns a float64.
func (ch *Channel) QueryFloat64(cmd string) (float64, error) {
	return query.Float64(ch.inst, cmd)
}

// QueryInt queries the channel and returns an int.
func (ch *Channel) QueryInt(cmd string) (int, error) {
	return query.Int(ch.inst, cmd)
}

// QueryString queries the channel and returns a string.
func (ch *Channel) QueryString(cmd string) (string, error) {
	return query.String(ch.inst, cmd)
}


text:
package org.springframework.ejb.config;

import org.w3c.dom.Element;

import org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean;

/**
 * {@link org.springframework.beans.factory.xml.BeanDefinitionParser}
 * implementation for parsing 'local-slsb' tags and
 * creating {@link LocalStatelessSessionProxyFactoryBean} definitions.
 *
 * @author Rob Harrop
 * @author Juergen Hoeller
 * @since 2.0
 */
class LocalStatelessSessionBeanDefinitionParser extends AbstractJndiLocatingBeanDefinitionParser {

	protected String getBeanClassName(Element element) {
		return "org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean";
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cassandra
{
    /// <summary>
    /// Represents client-side, microsecond-precision query timestamps.
    /// <para>
    /// Given that Apache Cassandra uses those timestamps to resolve conflicts, implementations should generate
    /// monotonically increasing timestamps for successive invocations of <see cref="Next()"/>.
    /// </para>
    /// </summary>
    public interface ITimestampGenerator
    {
        /// <summary>
        /// Returns the next timestamp in microseconds since UNIX epoch.
        /// <para>
        /// Implementers should enforce increasing monotonic timestamps, that is,
        /// a timestamp returned should always be strictly greater that any previously returned
        /// timestamp.
        /// </para>
        /// <para>
        /// Implementers should strive to achieve microsecond precision in the best possible way,
        /// which is usually largely dependent on the underlying operating system's capabilities.
        /// </para>
        /// </summary>
        /// <returns>
        /// The next timestamp (in microseconds). When returning <see cref="long.MinValue"/>, the driver
        /// will not set the timestamp, letting Apache Cassandra generate a server-side timestamp.
        /// </returns>
        long Next();
    }
}


text:
function ncwhatsnew

% ncwhatsnew -- What's new in the NetCDF Toolbox.
%  ncwhatsnew emits a "what's new" message the first time
%   it is called.

% Copyright (C) 1998 Dr. Charles R. Denham, ZYDECO.
%  All Rights Reserved.
%   Disclosure without explicit written consent from the
%    copyright owner does not constitute publication.

% Version of 09-Dec-1998 10:47:04.
% Updated    19-Jul-1999 11:07:43.

global NC_WHATS_NEW_DISPLAYED

if isempty(NC_WHATS_NEW_DISPLAYED) & 0
	disp(' ')
	disp(' ## WHAT''S NEW in the NetCDF Toolbox')
	disp(' ')
	disp(' ##  Starting January 1, 1999, the "size" function for')
	disp(' ##  netcdf items will return at least two elements,')
	disp(' ##  following the Matlab convention.  To get the old')
	disp(' ##  style of size-vector, use "ncsize".')
	disp(' ')
	v = version;
	if isequal(v(1:3), '5.3')
		disp(' ##  Matlab v5.3 (Release 11) Alert -- Changes to the')
		disp(' ##  Matlab object-oriented scheme required that we patch')
		disp(' ##  the NetCDF Toolbox.  The present toolbox seems to be')
		disp(' ##  compatible with v5.3.  Please let us know if you notice')
		disp(' ##  otherwise: <cdenham@usgs.gov> (14Apr1999).')
		disp(' ')
	end
	NC_WHATS_NEW_DISPLAYED = 1;
end


text:
<?php

namespace lapistano\wsunit;

/**
 * @package    WsUnit
 * @subpackage Extensions_WebServiceListener
 * @author     Bastian Feder <php@bastian-feder.de>
 * @copyright  2011 Bastian Feder <php@bastian-feder.de>
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @link       http://www.phpunit.de/
 * @since      File available since Release 3.6.0
 */

class Extensions_Webservice_ListenerTest extends Wsunit_TestCase
{
    /**
     * Provides an instance of the WebServiceListener.
     *
     * @return \lapistano\wsunit\WebServiceListener
     */
    protected function getListener()
    {
        return new WebServiceListener(
            $this->getFactoryStub(),
            $this->getLoaderFake(),
            $this->getConfiguration()
        );
    }

    /**
     * @covers \lapistano\wsunit\WebServiceListener::__construct
     */
    public function testConstruct()
    {
        $this->assertAttributeInternalType(
            'array',
            'configuration',
            $this->getListener()
        );
    }

    /**
     * @dataProvider hasDataproviderDataprovider
     * @covers \lapistano\wsunit\WebServiceListener::hasDataprovider
     */
    public function testHasDataprovider($expected, $annotations)
    {
        $testCase = $this->getMockBuilder('wsTestCaseMock')
            ->disableOriginalConstructor()
            ->setMethods(array('getAnnotations'))
            ->getMock();
        $testCase
            ->expects($this->once())
            ->method('getAnnotations')
            ->will($this->returnValue($annotations));

        $wst = $this->getProxyBuilder('\lapistano\wsunit\WebServiceListener')
            ->disableOriginalConstructor()
            ->setMethods(array('hasDataprovider'))
            ->getProxy();
        $this->assertEquals($expected, $wst->hasDataprovider($testCase));
    }

    /**
     * @dataProvider loadMappingDataprovider
     * @covers \lapistano\wsunit\WebServiceListener::loadMapping
     */
    public function testLoadMapping($mapping)
    {
        $loader = $this->getLoaderFake(array('load'));
        $loader
            ->expects($this->any())
            ->method('load')
            ->will($this->returnValue($mapping));

        $wst = $this->getProxyBuilder('\lapistano\wsunit\WebServiceListener')
            ->disableOriginalConstructor()
            ->setMethods(array('loadMapping'))
            ->setProperties(array('mapping', 'loader', 'configuration'))
            ->getProxy();
        $wst->mapping = $mapping;
        $wst->loader = $loader;
        $wst->configuration = $this->getConfiguration();

        $this->assertEquals($mapping, $wst->loadMapping());
    }

    /**
     * @dataProvider getRunlevelDataprovider
     * @covers \lapistano\wsunit\WebServiceListener::getRunlevel
     * @covers \lapistano\wsunit\WebServiceListener::extractRunlevelFromTestName
     */
    public function testGetRunlevel($expected, $name)
    {
        $testCase = $this->getMockBuilder('wsTestCaseMock')
            ->disableOriginalConstructor()
            ->setMethods(array('getName'))
            ->getMock();
        $testCase
            ->expects($this->once())
            ->method('getName')
            ->will($this->returnValue($name));

        $wst = $this->getProxyBuilder('\lapistano\wsunit\WebServiceListener')
            ->disableOriginalConstructor()
            ->setMethods(array('getRunlevel'))
            ->getProxy();
        $this->assertEquals($expected, $wst->getRunlevel($testCase));
    }

    /**
     * @dataProvider sendRequestDataprovider
     * @covers \lapistano\wsunit\WebServiceListener::sendRequest
     */
    public function testSendRequest($runlevel, $url)
    {
        $config = array(
            'locations' => array(
                'expected' => array(
                    'url' => 'http://example.org/data.json',
                    'params' => array(
                        'mascott' => array(
                            'tux',
                            'RedHat' => 'beastie',
                         ),
                        'os' => 'Linux',
                    ),
                ),
                array(
                    'url' => 'http://example.org/data.xml',
                    'params' => array(),
                ),
                array(
                    'url' => 'http://example.org/data.txt',
                    'params' => array(),
                ),
            )
        );

        $client = $this->getHttpClientFake(array('get'));
        $client
            ->expects($this->once())
            ->method('get')
            ->with(
                $this->equalTo($url),
                $this->isType('array')
            )
            ->will($this->returnValue('Tux'));

        $wst = $this->getProxyBuilder('\\lapistano\\wsunit\\WebServiceListener')
            ->disableOriginalConstructor()
            ->setProperties(array('logger', 'httpClient'))
            ->setMethods(array('sendRequest'))
            ->getProxy();
        $wst->httpClient = $client;

        $this->assertEquals('Tux', $wst->sendRequest($config, $runlevel));
    }

    /*************************************************************************/
    /* Dataprovider                                                          */
    /*************************************************************************/

    public static function sendRequestDataprovider()
    {
        return array(
            'string identification' => array('expected', 'http://example.org/data.json'),
            'invalid string identification' => array('tux', 'http://example.org/data.txt'),
            'numeric identification' => array('0', 'http://example.org/data.xml'),
            'invalid numeric identification' => array('42', 'http://example.org/data.txt'),
        );
    }

    public static function getRunlevelDataprovider()
    {
        return array(
            'unnamed dataprovider in 1st iteration' => array(0, 'testCase::test with data set #0'),
            'unnamed dataprovider in 2nd iteration' => array(1, 'testCase::test with data set #1'),
            'named iteration of dataprovider'       => array('dataName', 'testCase::test with data set "dataName"'),
        );
    }

    public static function loadMappingDataprovider()
    {
        return array(
            'empty mapping' => array(array()),
            'set mapping'   => array(array('tux')),
        );
    }

    public static function hasDataproviderDataprovider()
    {
        return array(
            'with data provider' => array(
                true,
                array(
                   'method' => array(
                       'dataProvider' => array(
                           'translateTypeToPrefixDataprovider',
                        )
                    ),
                )
            ),
            'without data provider' => array(false, array('method' => array())),
            'without data provider ("method" not even set)' => array(false, array()),
        );
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ocellularia emersella Müll. Arg.

### Remarks
null


text:
from components.base.message.abst_bus_message import AbstractBusMessage
from components.base.message.abst_segment_bus_message import AbstractSegmentBusMessage
from tools.ecu_logging import ECULogger as L

class CANExtendedMessage(AbstractBusMessage):
    '''
    This class is an abstract implementation of a CAN Message
    '''

    MAX_DATAFIELD_SIZE = 8

    def __init__(self, sim_env, message_id, data, timestamp, sender_id):
        ''' Constructor

            Input:    sim_env        simpy.Environment        environment of this component
                      message_id     integer                  message identifier
                      data           object                   content of the message
                      timestamp      float                    time the message was generated
                      sender_id      string                   id of the sender
        '''
        AbstractBusMessage.__init__(self, sim_env, message_id, data, timestamp, sender_id)
        self.message_identifier = message_id  # 29 Bits
        self.ide = 1  # 1 Bit
        self.r0 = 0  # 1 Bit
        self.dlc = 4  # 4 Bits
        self.data = data  # 0 ... 64 Bits
        self.crc = 1  # 15 Bits
        self.crc_delimiter = 0  # 1 Bit
        self.ack_slot = 0  # 1 Bit IN can FD its 2 Bit
        self.ack_delimiter = 0  # 1 Bit
        self.eof = 0  # 7 Bits

        self._msg_length_in_bit = 60
        self.no_stuffing_bits = 0
        self.timestamp = timestamp

    @property

    def msg_length_in_bit(self):
        ''' this is the length that is used by the CAN Bus
            to determine the size of the packet

            Input:   -
            Output:  size     integer    Size of this message segment in Bit
        '''
        try:
            bit_rep = ""
            for i in self.data:
                hec = hex(ord(i))
                h_size = len(hec) * 2
                h = (bin(int(hec, 16))[2:]).zfill(h_size)
                bit_rep += h

            self._msg_length_in_bit = 60 + len(bit_rep) + self.no_stuffing_bits
            return self._msg_length_in_bit
        except:
            L().log_err(400)

class CANSegExtendedMessage(AbstractSegmentBusMessage):
    '''
    This class is an abstract implementation of a CAN Message with 29
    bit identifier
    '''

    MAX_DATAFIELD_SIZE = 8

    def __init__(self, sim_env, message_id, data, timestamp, sender_id):
        ''' Constructor

            Input:    sim_env        simpy.Environment        environment of this component
                      message_id     integer                  message identifier
                      data           object                   content of the message
                      timestamp      float                    time the message was generated
                      sender_id      string                   id of the sender
        '''
        AbstractSegmentBusMessage.__init__(self, sim_env, message_id, data, timestamp, sender_id)
        self.message_identifier = message_id  # 29 Bits
        self.ide = 1  # 1 Bit
        self.r0 = 0  # 1 Bit
        self.dlc = 4  # 4 Bits
        self.data = data  # 0 ... 64 Bits
        self.crc = 1  # 15 Bits
        self.crc_delimiter = 0  # 1 Bit
        self.ack_slot = 0  # 1 Bit IN can FD its 2 Bit
        self.ack_delimiter = 0  # 1 Bit
        self.eof = 0  # 7 Bits

        self._msg_length_in_bit = 60
        self.no_stuffing_bits = 0
        self.timestamp = timestamp

    @property

    def msg_length_in_bit(self):
        ''' this is the length that is used by the CAN Bus
            to determine the size of the packet

            Input:   -
            Output:  size     integer    Size of this message segment in Bit
        '''
        try:
            bit_rep = ""
            for i in self.data:
                hec = hex(ord(i))
                h_size = len(hec) * 2
                h = (bin(int(hec, 16))[2:]).zfill(h_size)
                bit_rep += h

            self._msg_length_in_bit = 60 + len(bit_rep) + self.no_stuffing_bits
            return self._msg_length_in_bit
        except TypeError:
            bit_rep = ""
            if self.seg_type == 0:  # single frame
                bit_rep = len(self.data) * 8

            if self.seg_type == 1:  # then this is a first frame
                bit_rep = 6 * 8

            if self.seg_type == 2:  # then this is a consecutive frame
                bit_rep = len(self.data) * 8

            self._msg_length_in_bit = 60 + bit_rep + self.no_stuffing_bits
            return self._msg_length_in_bit


text:
from __future__ import absolute_import, print_function

from sentry.auth.view import AuthView
from sentry.auth.providers.saml2.provider import SAML2Provider, Attributes
from sentry.auth.providers.saml2.views import make_simple_setup
from sentry.auth.providers.saml2.forms import URLMetadataForm

SelectIdP = make_simple_setup(URLMetadataForm, "sentry_auth_rippling/select-idp.html")

class WaitForCompletion(AuthView):
    """
    Rippling provides the Metadata URL during initial application setup, before
    configuration values have been saved, thus we cannot immediately attempt to
    create an identity for the setting up the SSO.

    This is simply an extra step to wait for them to complete that.
    """

    def handle(self, request, helper):
        if "continue_setup" in request.POST:
            return helper.next_step()

        return self.respond("sentry_auth_rippling/wait-for-completion.html")

class RipplingSAML2Provider(SAML2Provider):
    name = "Rippling"

    # Rippling is currently it's own feature
    required_feature = "organizations:sso-rippling"

    def get_saml_setup_pipeline(self):
        return [SelectIdP(), WaitForCompletion()]

    def attribute_mapping(self):
        return {
            Attributes.IDENTIFIER: "user_id",
            Attributes.USER_EMAIL: "urn:oid:1.2.840.113549.1.9.1.1",
            Attributes.FIRST_NAME: "first_name",
            Attributes.LAST_NAME: "last_name",
        }


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="robots" content="index, follow, all" />
    <title>Hayttp\Engines\CurlEngine | Hayttp API</title>

            <link rel="stylesheet" type="text/css" href="../../css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="../../css/bootstrap-theme.min.css">
        <link rel="stylesheet" type="text/css" href="../../css/sami.css">

        <meta name="MobileOptimized" content="width">
        <meta name="HandheldFriendly" content="true">
        <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">

                    <form action="#" method="GET">
                <select id="version-switcher" name="version">
                                            <option value="../../../1.0.0/index.html" data-version="1.0.0">1.0.0</option>
                                            <option value="../../../1.0.1/index.html" data-version="1.0.1">1.0.1</option>
                                            <option value="../../../master/index.html" data-version="master">master dev branch</option>
                                    </select>
            </form>

        <form id="search-form" action="../../search.html" method="GET">

            <input name="search"
                   class="typeahead form-control"
                   type="search"
                   placeholder="Search">
        </form>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements">
                    Toggle navigation

                </button>
                Hayttp API

Classes

Namespaces

Interfaces

Traits

Index

Search

class

Hayttp

\

Engines

\

CurlEngine

            CurlEngine

    class
    CurlEngine        implements
        Engine        (View source)

Methods

                    int

                    curlCryptoMethod(string $cryptoMethod)

No description

                    buildHandle(Request $request)

No description

                    Response

                    send(Request $request)

Send/execute the request.

Details

at         line 26

                    protected        int
    curlCryptoMethod(string $cryptoMethod)

Parameters

                string
                $cryptoMethod

Return Value

            int

at         line 52

                    protected
    buildHandle(Request $request)

Parameters

                Request
                $request

at         line 96

                            Response
    send(Request $request)

Send/execute the request.

Parameters

                Request
                $request

Return Value

            Response

Exceptions

                CouldNotConnectException
                if connection could not be established

        Generated by Sami, the API Documentation Generator.


text:
namespace __tsan {

#ifndef SANITIZER_GO
static void *SignalSafeGetOrAllocate(uptr *dst, uptr size) {
  atomic_uintptr_t *a = (atomic_uintptr_t *)dst;
  void *val = (void *)atomic_load_relaxed(a);
  atomic_signal_fence(memory_order_acquire);  // Turns the previous load into
                                              // acquire wrt signals.
  if (UNLIKELY(val == nullptr)) {
    val = (void *)internal_mmap(nullptr, size, PROT_READ | PROT_WRITE,
                                MAP_PRIVATE | MAP_ANON, -1, 0);
    CHECK(val);
    void *cmp = nullptr;
    if (!atomic_compare_exchange_strong(a, (uintptr_t *)&cmp, (uintptr_t)val,
                                        memory_order_acq_rel)) {
      internal_munmap(val, size);
      val = cmp;
    }
  }
  return val;
}

// On OS X, accessing TLVs via __thread or manually by using pthread_key_* is
// problematic, because there are several places where interceptors are called
// when TLVs are not accessible (early process startup, thread cleanup, ...).
// The following provides a "poor man's TLV" implementation, where we use the
// shadow memory of the pointer returned by pthread_self() to store a pointer to
// the ThreadState object. The main thread's ThreadState pointer is stored
// separately in a static variable, because we need to access it even before the
// shadow memory is set up.
static uptr main_thread_identity = 0;
static ThreadState *main_thread_state = nullptr;

ThreadState *cur_thread() {
  ThreadState **fake_tls;
  uptr thread_identity = (uptr)pthread_self();
  if (thread_identity == main_thread_identity || main_thread_identity == 0) {
    fake_tls = &main_thread_state;
  } else {
    fake_tls = (ThreadState **)MemToShadow(thread_identity);
  }
  ThreadState *thr = (ThreadState *)SignalSafeGetOrAllocate(
      (uptr *)fake_tls, sizeof(ThreadState));
  return thr;
}

// TODO(kuba.brecka): This is not async-signal-safe. In particular, we call
// munmap first and then clear `fake_tls`; if we receive a signal in between,
// handler will try to access the unmapped ThreadState.
void cur_thread_finalize() {
  uptr thread_identity = (uptr)pthread_self();
  CHECK_NE(thread_identity, main_thread_identity);
  ThreadState **fake_tls = (ThreadState **)MemToShadow(thread_identity);
  internal_munmap(*fake_tls, sizeof(ThreadState));
  *fake_tls = nullptr;
}
#endif

uptr GetShadowMemoryConsumption() {
  return 0;
}

void FlushShadowMemory() {
}

void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) {
}

#ifndef SANITIZER_GO
void InitializeShadowMemoryPlatform() { }

// On OS X, GCD worker threads are created without a call to pthread_create. We
// need to properly register these threads with ThreadCreate and ThreadStart.
// These threads don't have a parent thread, as they are created "spuriously".
// We're using a libpthread API that notifies us about a newly created thread.
// The `thread == pthread_self()` check indicates this is actually a worker
// thread. If it's just a regular thread, this hook is called on the parent
// thread.
typedef void (*pthread_introspection_hook_t)(unsigned int event,
                                             pthread_t thread, void *addr,
                                             size_t size);
extern "C" pthread_introspection_hook_t pthread_introspection_hook_install(
    pthread_introspection_hook_t hook);
static const uptr PTHREAD_INTROSPECTION_THREAD_CREATE = 1;
static const uptr PTHREAD_INTROSPECTION_THREAD_TERMINATE = 3;
static pthread_introspection_hook_t prev_pthread_introspection_hook;
static void my_pthread_introspection_hook(unsigned int event, pthread_t thread,
                                          void *addr, size_t size) {
  if (event == PTHREAD_INTROSPECTION_THREAD_CREATE) {
    if (thread == pthread_self()) {
      // The current thread is a newly created GCD worker thread.
      ThreadState *parent_thread_state = nullptr;  // No parent.
      int tid = ThreadCreate(parent_thread_state, 0, (uptr)thread, true);
      CHECK_NE(tid, 0);
      ThreadState *thr = cur_thread();
      ThreadStart(thr, tid, GetTid());
    }
  } else if (event == PTHREAD_INTROSPECTION_THREAD_TERMINATE) {
    if (thread == pthread_self()) {
      ThreadState *thr = cur_thread();
      if (thr->tctx) {
        DestroyThreadState();
      }
    }
  }

  if (prev_pthread_introspection_hook != nullptr)
    prev_pthread_introspection_hook(event, thread, addr, size);
}
#endif

void InitializePlatformEarly() {
}

void InitializePlatform() {
  DisableCoreDumperIfNecessary();
#ifndef SANITIZER_GO
  CheckAndProtect();

  CHECK_EQ(main_thread_identity, 0);
  main_thread_identity = (uptr)pthread_self();

  prev_pthread_introspection_hook =
      pthread_introspection_hook_install(&my_pthread_introspection_hook);
#endif
}

#ifndef SANITIZER_GO
// Note: this function runs with async signals enabled,
// so it must not touch any tsan state.
int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m,
    void *abstime), void *c, void *m, void *abstime,
    void(*cleanup)(void *arg), void *arg) {
  // pthread_cleanup_push/pop are hardcore macros mess.
  // We can't intercept nor call them w/o including pthread.h.
  int res;
  pthread_cleanup_push(cleanup, arg);
  res = fn(c, m, abstime);
  pthread_cleanup_pop(0);
  return res;
}
#endif

bool IsGlobalVar(uptr addr) {
  return false;
}

}  // namespace __tsan

#endif  // SANITIZER_MAC


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace MinimalDatabase
{
    public interface IRecordSerializer
    {
        void WriteEntry(object value, BinaryWriter writer);
        object ReadEntry(BinaryReader reader);
        uint BytesPerEntry { get; }
    }
}


text:
package co.cask.cdap.etl.realtime.kafka;

/**
 * This class is for configuring both Kafka broker and consumer information for {@link KafkaSimpleApiConsumer}.
 */
public interface KafkaConfigurer extends KafkaBrokerConfigurer, KafkaConsumerConfigurer {
  // No method define as it's just for gathering methods defined in super interfaces to one place
}


text:
<?php
if ( ! defined( 'ABSPATH' ) ) {
	die( '-1' );
}

/**
 * WPBakery WPBakery Page Builder shortcodes
 *
 * @package WPBakeryPageBuilder
 *
 */
class WPBakeryShortCode_VC_Button2 extends WPBakeryShortCode {
	protected function outputTitle( $title ) {
		$icon = $this->settings( 'icon' );

		return '

';
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ParallaxListView">
        <attr name="divider_color" format="color"/>
        <attr name="divider_height" format="dimension"/>
        <attr name="parallax_factor" format="float"/>
        <attr name="header_height" format="dimension"/>
    </declare-styleable>
</resources>


text:
SELECT
    tx_id,
    COUNT(txin_pos)
FROM txin_detail
GROUP BY tx_id;


text:
package client

// ContainerPort
type ContainerPort struct {
	Name          string `json:"name,omitempty"`
	HostPort      int    `json:"hostPort,omitempty"`
	ContainerPort int    `json:"containerPort"`
	Protocol      string `json:"protocol,omitempty"`
}

// EnvVar is environment variable
type EnvVar struct {
	Name      string        `json:"name"`
	Value     string        `json:"value,omitempty"`
	ValueFrom *EnvVarSource `json:"valueFrom,omitempty"`
}

// EnvVarSource represents a source for the value of an EnvVar.
type EnvVarSource struct {
	SecretKeyRef *SecretKeySelector `json:"secretKeyRef,omitempty"`
}

// SecretKeySelector selects a key of a Secret.
type SecretKeySelector struct {
	Key      string `json:"key"`
	Name     string `json:"name"`
	Optional bool   `json:"optional,omitempty"`
}

type Condition struct {
	Started string `json:"startedAt,omitempty"`
	Reason  string `json:"reason,omitempty"`
	Message string `json:"message,omitempty"`
}

// Container defined container runtime values
type Container struct {
	Name           string                `json:"name"`
	Image          string                `json:"image"`
	Env            []EnvVar              `json:"env,omitempty"`
	Command        []string              `json:"command,omitempty"`
	Args           []string              `json:"args,omitempty"`
	Ports          []ContainerPort       `json:"ports,omitempty"`
	ReadinessProbe *Probe                `json:"readinessProbe,omitempty"`
	Resources      *ResourceRequirements `json:"resources,omitempty"`
	VolumeMounts   []VolumeMount         `json:"volumeMounts,omitempty"`
}

// DeploymentSpec defines micro deployment spec
type DeploymentSpec struct {
	Replicas int            `json:"replicas,omitempty"`
	Selector *LabelSelector `json:"selector"`
	Template *Template      `json:"template,omitempty"`
}

// DeploymentCondition describes the state of deployment
type DeploymentCondition struct {
	LastUpdateTime string `json:"lastUpdateTime"`
	Type           string `json:"type"`
	Reason         string `json:"reason,omitempty"`
	Message        string `json:"message,omitempty"`
}

// DeploymentStatus is returned when querying deployment
type DeploymentStatus struct {
	Replicas            int                   `json:"replicas,omitempty"`
	UpdatedReplicas     int                   `json:"updatedReplicas,omitempty"`
	ReadyReplicas       int                   `json:"readyReplicas,omitempty"`
	AvailableReplicas   int                   `json:"availableReplicas,omitempty"`
	UnavailableReplicas int                   `json:"unavailableReplicas,omitempty"`
	Conditions          []DeploymentCondition `json:"conditions,omitempty"`
}

// Deployment is Kubernetes deployment
type Deployment struct {
	Metadata *Metadata         `json:"metadata"`
	Spec     *DeploymentSpec   `json:"spec,omitempty"`
	Status   *DeploymentStatus `json:"status,omitempty"`
}

// DeploymentList
type DeploymentList struct {
	Items []Deployment `json:"items"`
}

// LabelSelector is a label query over a set of resources
// NOTE: we do not support MatchExpressions at the moment
type LabelSelector struct {
	MatchLabels map[string]string `json:"matchLabels,omitempty"`
}

type LoadBalancerIngress struct {
	IP       string `json:"ip,omitempty"`
	Hostname string `json:"hostname,omitempty"`
}

type LoadBalancerStatus struct {
	Ingress []LoadBalancerIngress `json:"ingress,omitempty"`
}

// Metadata defines api object metadata
type Metadata struct {
	Name        string            `json:"name,omitempty"`
	Namespace   string            `json:"namespace,omitempty"`
	Version     string            `json:"version,omitempty"`
	Labels      map[string]string `json:"labels,omitempty"`
	Annotations map[string]string `json:"annotations,omitempty"`
}

// PodSpec is a pod
type PodSpec struct {
	Containers         []Container `json:"containers"`
	ServiceAccountName string      `json:"serviceAccountName"`
	Volumes            []Volume    `json:"volumes"`
}

// PodList
type PodList struct {
	Items []Pod `json:"items"`
}

// Pod is the top level item for a pod
type Pod struct {
	Metadata *Metadata  `json:"metadata"`
	Spec     *PodSpec   `json:"spec,omitempty"`
	Status   *PodStatus `json:"status"`
}

// PodStatus
type PodStatus struct {
	Conditions []PodCondition    `json:"conditions,omitempty"`
	Containers []ContainerStatus `json:"containerStatuses"`
	PodIP      string            `json:"podIP"`
	Phase      string            `json:"phase"`
	Reason     string            `json:"reason"`
}

// PodCondition describes the state of pod
type PodCondition struct {
	Type    string `json:"type"`
	Reason  string `json:"reason,omitempty"`
	Message string `json:"message,omitempty"`
}

type ContainerStatus struct {
	State ContainerState `json:"state"`
}

type ContainerState struct {
	Running    *Condition `json:"running"`
	Terminated *Condition `json:"terminated"`
	Waiting    *Condition `json:"waiting"`
}

// Resource is API resource
type Resource struct {
	Name  string
	Kind  string
	Value interface{}
}

// ServicePort configures service ports
type ServicePort struct {
	Name     string `json:"name,omitempty"`
	Port     int    `json:"port"`
	Protocol string `json:"protocol,omitempty"`
}

// ServiceSpec provides service configuration
type ServiceSpec struct {
	ClusterIP string            `json:"clusterIP"`
	Type      string            `json:"type,omitempty"`
	Selector  map[string]string `json:"selector,omitempty"`
	Ports     []ServicePort     `json:"ports,omitempty"`
}

// ServiceStatus
type ServiceStatus struct {
	LoadBalancer LoadBalancerStatus `json:"loadBalancer,omitempty"`
}

// Service is kubernetes service
type Service struct {
	Metadata *Metadata      `json:"metadata"`
	Spec     *ServiceSpec   `json:"spec,omitempty"`
	Status   *ServiceStatus `json:"status,omitempty"`
}

// ServiceList
type ServiceList struct {
	Items []Service `json:"items"`
}

// Template is micro deployment template
type Template struct {
	Metadata *Metadata `json:"metadata,omitempty"`
	PodSpec  *PodSpec  `json:"spec,omitempty"`
}

// Namespace is a Kubernetes Namespace
type Namespace struct {
	Metadata *Metadata `json:"metadata,omitempty"`
}

// NamespaceList
type NamespaceList struct {
	Items []Namespace `json:"items"`
}

// ImagePullSecret
type ImagePullSecret struct {
	Name string `json:"name"`
}

// Secret
type Secret struct {
	Type     string            `json:"type,omitempty"`
	Data     map[string]string `json:"data"`
	Metadata *Metadata         `json:"metadata,omitempty"`
}

// ServiceAccount
type ServiceAccount struct {
	Metadata         *Metadata         `json:"metadata,omitempty"`
	ImagePullSecrets []ImagePullSecret `json:"imagePullSecrets,omitempty"`
}

// Probe describes a health check to be performed against a container to determine whether it is alive or ready to receive traffic.
type Probe struct {
	TCPSocket           *TCPSocketAction `json:"tcpSocket,omitempty"`
	PeriodSeconds       int              `json:"periodSeconds"`
	InitialDelaySeconds int              `json:"initialDelaySeconds"`
}

// TCPSocketAction describes an action based on opening a socket
type TCPSocketAction struct {
	Host string      `json:"host,omitempty"`
	Port interface{} `json:"port,omitempty"`
}

// ResourceRequirements describes the compute resource requirements.
type ResourceRequirements struct {
	Limits   *ResourceLimits `json:"limits,omitempty"`
	Requests *ResourceLimits `json:"requests,omitempty"`
}

// ResourceLimits describes the limits for a service
type ResourceLimits struct {
	Memory           string `json:"memory,omitempty"`
	CPU              string `json:"cpu,omitempty"`
	EphemeralStorage string `json:"ephemeral-storage,omitempty"`
}

// Volume describes a volume which can be mounted to a pod
type Volume struct {
	Name                  string                            `json:"name"`
	PersistentVolumeClaim PersistentVolumeClaimVolumeSource `json:"persistentVolumeClaim,omitempty"`
}

// PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace
type PersistentVolumeClaimVolumeSource struct {
	ClaimName string `json:"claimName"`
}

// VolumeMount describes a mounting of a Volume within a container.
type VolumeMount struct {
	Name      string `json:"name"`
	MountPath string `json:"mountPath"`
}

// NetworkPolicy defines label-based filtering for network ingress
type NetworkPolicy struct {
	AllowedLabels map[string]string `json:"allowedLabels,omitempty"`
	Metadata      *Metadata         `json:"metadata,omitempty"`
}

// ResourceQuota defines resource limits for a namespace
type ResourceQuota struct {
	Requests *ResourceLimits `json:"requests,omitempty"`
	Limits   *ResourceLimits `json:"limits,omitempty"`
	Metadata *Metadata       `json:"metadata,omitempty"`
}


text:
#include <type_traits>
#include <functional>
#include <utility>
#include <boost/callable_traits/has_member_qualifiers.hpp>
#include "test.hpp"

struct foo {};

template<typename T>
void assert_qualified() {
    CT_ASSERT( has_member_qualifiers<T>::value);
}

template<typename T>
void assert_unqualified() {
    CT_ASSERT(! has_member_qualifiers<T>::value);
}

int main() {

    {
        using f   = void(foo::*)();
        using c   = void(foo::*)() const;
        using v   = void(foo::*)() volatile;
        using cv  = void(foo::*)() const volatile;

        assert_unqualified<f>();
        assert_qualified<c>();
        assert_qualified<v>();
        assert_qualified<cv>();
    }

    {
        struct f   { int operator()() { return 0; } };
        struct c   { int operator()() const { return 0; } };
        struct v   { int operator()() volatile { return 0; } };
        struct cv  { int operator()() const volatile { return 0; } };

        assert_unqualified<f>();
        assert_qualified<c>();
        assert_qualified<v>();
        assert_qualified<cv>();
    }

    using f_ptr = void(*)();
    assert_unqualified<f_ptr>();
    assert_unqualified<f_ptr foo::*>();
    assert_unqualified<int foo::*>();
    assert_unqualified<void(&)()>();
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<object name="PatientListItem"
        connection="EidssConnectionString"
        generator="ObjectGenerator.xslt"
        xmlns="urn:schemas-bv:objectmodel">

	<storage>
		<get name="fn_Patient_SelectList" type="fnlist" />
		<count name="spPatient_SelectCount"/>
	</storage>

	<tables>
		<table name="PatientListItem">
      <properties auditObject="daoPatient" auditTable="tlbHuman" permissionObject="Patient"/>
      <help web="HC_H03" win="HC_H03"/>
      <extfilters>
				<filter>
					<join>
						LEFT JOIN	tlbGeoLocationShared geo
						ON			geo.idfGeoLocationShared = fn_Patient_SelectList.idfCurrentResidenceAddress
					</join>
					<where>
						<expr param="idfsRegion" value="geo.idfsRegion {0} @idfsRegion"/>
						<expr param="idfsRayon" value="geo.idfsRayon {0} @idfsRayon"/>
					</where>
				</filter>
			</extfilters>
			<searchpanel>
        <item name="strLastName" editor="Text" labelId="strLastName" predicate="() => Customization.Instance.VisibilityFeatures.IsLastNameBeforeFirstName" />
        <item name="strFirstName" editor="Text" labelId="strFirstName" predicate="() => !EidssSiteContext.Instance.IsIraqCustomization"/>
        <item name="strLastName" editor="Text" labelId="strLastName" predicate="() => !Customization.Instance.VisibilityFeatures.IsLastNameBeforeFirstName" />
        <item name="strSecondName" editor="Text" labelId="strSecondName" predicate="() => !EidssSiteContext.Instance.IsIraqCustomization"/>
        <item name="datDateofBirth" editor="Date" labelId="datDateofBirth" range="true" />

				<item name="idfsRegion" editor="Lookup" labelId="idfsRegion" isParam="true" dependent="idfsRayon"
					  lookupName="RegionLookup" lookupType="RegionLookup" lookupText="c.strRegionName" lookupValue="c.idfsRegion"
					  defaultoper="=" />
        <!-- default="eidss.model.Core.EidssSiteContext.Instance.RegionID" -->
				<item name="idfsRayon" editor="Lookup" labelId="idfsRayon" isParam="true"
					  lookupName="RayonLookup" lookupType="RayonLookup" lookupText="c.strRayonName" lookupValue="c.idfsRayon"/>
        <item name="idfsPersonIDType" editor="Lookup" labelId="idfsPersonIDType"
					lookupName="PersonIDTypeLookup" lookupType="BaseReference" lookupText="c.name" lookupValue="c.idfsBaseReference"/>
				<item name="strPersonID" editor="Text" labelId="strPersonID" />
      </searchpanel>
			<grid>
				<item name="idfHumanActual" visible="false" key="true" />
				<item name="strLastName" action="ActionEditPerson" required="true" />
				<item name="strFirstName" predicate="() => !EidssSiteContext.Instance.IsIraqCustomization"/>
				<item name="strSecondName"  predicate="() => !EidssSiteContext.Instance.IsIraqCustomization"/>
				<item name="datDateofBirth" />
				<item name="AddressName" />
        <item name="strPersonIDType" />
        <item name="strPersonID" />
        <item name="datEnteredDate" />
        <item name="datModificationDate" />
			</grid>
      <labels>
        <item name="strPersonIDType" labelId="idfsPersonIDType"/>
        <item name="datEnteredDate" labelId="Patient.datEnteredDate"/>
        <item name="datModificationDate" labelId="Patient.datModificationDate"/>
      </labels>
			<fields>
				<storage name="idfsCountry" type="long?" />
				<storage name="idfsRegion" type="long?" />
				<storage name="idfsRayon" type="long?" />
			</fields>
			<readonly>
				<fields name="Region,idfsRegion" predicate="c => c.idfsCountry == null" />
				<fields name="Rayon,idfsRayon" predicate="c => c.idfsRegion == null" />
			</readonly>
			<lookups>
				<lookup name="Country" table="CountryLookup" source="idfsCountry" target="idfsCountry" />
				<lookup name="Region" table="RegionLookup" source="idfsRegion" target="idfsRegion">
					<params>
						<param name="CountryID" lambda="c => c.idfsCountry ?? 0" type="long" />
						<param name="ID" const="null" />
					</params>
				</lookup>
				<lookup name="Rayon" table="RayonLookup" source="idfsRayon" target="idfsRayon">
					<params>
						<param name="RegionID" lambda="c => c.idfsRegion ?? 0" type="long" />
						<param name="ID" const="null" />
					</params>
				</lookup>
        <lookup name="PersonIDType" table="BaseReference" section="rftPersonIDType" source="idfsPersonIDType" target="idfsBaseReference" />
      </lookups>
			<storage>
				<delete name="spPatientActual_Delete"/>
				<candelete name="spPatientActual_CanDelete"/>
			</storage>

			<extenders>
				<created>
					<!-- set default country as current country of database -->
					<lambda_extender target="Country" type="CountryLookup" lambda='c =>
                                     c.CountryLookup.Where(a => a.idfsCountry == eidss.model.Core.EidssSiteContext.Instance.CountryID)
                                     .SingleOrDefault()'/>
          <lambda_extender target="Region" type="RegionLookup" lambda='c =>
                                     EidssUserContext.User.Options.Prefs.DefaultRegion == true?
                                     c.RegionLookup.Where(a => a.idfsRegion == eidss.model.Core.EidssSiteContext.Instance.RegionID)
                                     .SingleOrDefault(): null'/>
        </created>
			</extenders>

			<handlers>
				<fieldhandler>
					<lambda_handler field="idfsCountry" target="Region" type="RegionLookup" lambda="c => null"/>
					<lambda_handler field="idfsRegion" target="Rayon" type="RayonLookup" lambda="c => null"/>
					<lookup_handler lookup="Region" field="idfsCountry" />
					<lookup_handler lookup="Rayon" field="idfsRegion" />
				</fieldhandler>
			</handlers>

			<actions child="Patient">
        <standard>
          <remove type="Report"/>
        </standard>
        <action name="ActionEditPerson" type="Action">
          <run>
            <preUI webType="JScript"/>
          </run>
        </action>
			</actions>
		</table>
	</tables>

</object>


text:
copyright:
  years: 2016, 2017
lastupdated: "2017-03-15"
---

<!-- Common attributes used in the template are defined as follows: -->
{:new_window: target="\_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# サービス状況
{: #service_status}

[IBM Watson IoT Service Health ダッシュボード ![外部リンクのアイコン](../../icons/launch-glyph.svg)](https://status.internetofthings.ibmcloud.com){: new_window} では、{{site.data.keyword.Bluemix_notm}} 上の {{site.data.keyword.iot_full}} やその他の Watson IoT サービスの現在の状況に関する情報を確認できます。
{:shortdesc}

## サービスの可用性と更新情報
{: #service_up}
{{site.data.keyword.Bluemix_notm}} の {{site.data.keyword.iotelectronics}} サービス API の状況や今後予定されているサービス・メンテナンス更新については、以下のサービス状況ページで**「Solutions」**をクリックしてください。

http://status.internetofthings.ibmcloud.com/

## Twitter での最新情報
{: #twitter_feed}

![Twitter フィード https://twitter.com/ibmiotf](images/twitter_logo.png "IBM Watson IoT Platform Twitter フィード")

[Twitter フィード](https://twitter.com/ibmiotf)をフォローすることによっても、{{site.data.keyword.iot_short_notm}} や関連するサービスに関する最新情報や更新情報を入手できます。


text:
'''Farmware Tools: Farmware API utilities used by `device` for FarmBot OS v8.'''

import sys
import json
import struct
import socket
import threading
from time import time, sleep
from uuid import uuid4
try:
    import paho.mqtt.client as mqtt
except ImportError:
    pass
from .env import Env

ENV = Env()
HEADER_FORMAT = '>HII'
TIMEOUT_SECONDS = 10

def _open_socket(address):
    opened_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    opened_socket.settimeout(TIMEOUT_SECONDS)
    try:
        opened_socket.connect(address)
    except FileNotFoundError:
        print('Could not connect to socket: address not found.')
        sys.exit(1)
    return opened_socket

class _ResponseBuffer():
    '''Collection of responses from FarmBot OS.'''

    def __init__(self):
        self.responses = {}
        self.response_socket = _open_socket(ENV.response_pipe)

    def listen(self):
        '''Collect responses from FarmBot OS.'''
        while True:
            try:
                header = self.response_socket.recv(10)
            except socket.timeout:
                continue
            if header == b'':
                continue
            (_, _, size) = struct.unpack(HEADER_FORMAT, header)
            response = json.loads(self.response_socket.recv(size).decode())
            self.responses[response['args']['label']] = response

    def pop(self, rpc_uuid):
        '''Pull a response off of the buffer by RPC UUID (label).'''
        wait_time = 0
        while wait_time < TIMEOUT_SECONDS:
            response = self.responses.pop(rpc_uuid, None)
            if response is None:
                wait_time += 0.5
                sleep(0.5)
            else:
                return response
        return 'no response'

# Listen for responses from FarmBot OS.
if ENV.use_v2() and ENV.farmware_api_available():
    RESPONSE_BUFFER = _ResponseBuffer()
    RESPONSES = threading.Thread(target=RESPONSE_BUFFER.listen, daemon=True)
    RESPONSES.start()
elif ENV.use_mqtt():
    RESPONSES = {}
    STATUS = {}
    client = mqtt.Client()

    def _on_message(_client, _userdata, msg):
        message = json.loads(msg.payload)
        if 'status' in msg.topic:
            for key, value in message.items():
                STATUS[key] = value
        elif message.get('kind') in ['rpc_ok', 'rpc_error']:
            rpc_id = message.get('args', {}).get('label')
            if rpc_id is not None:
                RESPONSES[rpc_id] = message
    client.on_message = _on_message
    client.username_pw_set(ENV.decoded_token['bot'], password=ENV.token)
    try:
        client.connect(ENV.decoded_token['mqtt'])
    except:
        MQTT_OK = False
    else:
        MQTT_OK = True

    if MQTT_OK:
        def _mqtt_channel(channel):
            return 'bot/{}/{}'.format(ENV.decoded_token['bot'], channel)
        client.subscribe(_mqtt_channel('from_device'))
        client.subscribe(_mqtt_channel('status'))

def _mqtt_request(payload, wait_for_status=False):
    'Make a request via MQTT.'
    if not MQTT_OK:
        return 'no MQTT'
    if wait_for_status:
        STATUS.clear()
    client.loop_start()
    print(f'sending MQTT message: {json.dumps(payload, indent=2)}')
    sleep(0.5)
    client.publish(_mqtt_channel('from_clients'), payload=json.dumps(payload))
    rpc_id = payload.get('args', {}).get('label', '')
    start = time()
    response = 'no response'
    while (time() - start) < TIMEOUT_SECONDS:
        sleep(0.5)
        if wait_for_status:
            if len(STATUS.keys()) > 0:
                return 'got status'
        elif rpc_id in RESPONSES.keys():
            response = RESPONSES[rpc_id]
    print(f'MQTT response: {json.dumps(response, indent=2)}')
    client.loop_stop()
    return response

def _mqtt_status():
    'Fetch bot state via MQTT.'
    _mqtt_request({
        'kind': 'rpc_request',
        'args': {'label': str(uuid4())},
        'body': [{'kind': 'read_status', 'args': {}}]}, wait_for_status=True)
    return STATUS

def _request_write(payload):
    'Make a request to FarmBot OS.'
    request_socket = _open_socket(ENV.request_pipe)
    message_bytes = bytes(json.dumps(payload), 'utf-8')
    header = struct.pack(HEADER_FORMAT, 0xFBFB, 0, len(message_bytes))
    request_socket.sendall(header + message_bytes)
    request_socket.close()

def _response_read(rpc_uuid):
    'Read a response from FarmBot OS for the provided request RPC UUID.'
    if rpc_uuid is not None:
        return RESPONSE_BUFFER.pop(rpc_uuid)
    return 'missing RPC label'


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Valentine</title>
  <link href="../../lib/jquery.uls/css/jquery.uls.css" rel="stylesheet"/>
  <link href="../../lib/jquery.uls/css/jquery.uls.grid.css" rel="stylesheet"/>
  <link href="../../lib/jquery.uls/css/jquery.uls.lcd.css" rel="stylesheet"/>
  <link href="https://fonts.googleapis.com/css?family=Sriracha&display=swap" rel="stylesheet" />
  <link rel="stylesheet" href="valentine.css" />

   Select language

     Q102231
     Q1075
     Q3142

     Q146095
     Q1075
     Q1088

     Q11002
     Q124794
     Q460453

     Q18618629
     Q316
     Q61768970

   Back to main page

   Background image source: Wikimedia Commons
     by Laitche

   Font: Sriracha
     by Cadson Demak

   Created by Denny Vrandečić,
   February 2020.


text:
<?php

namespace DesignPatterns\Behavioral\Command\Command;
use DesignPatterns\Behavioral\Command\Console;

/**
 * Class CommandBase
 * @package DesignPatterns\Behavioral\Command\Command
 */
abstract class CommandBase implements CommandInterface {
    /**
     * @var Console
     */
    protected $_console;

    /**
     * CommandBase constructor.
     * @param Console $console
     * @param array ...$args
     */
    final public function __construct(Console $console, ...$args) {
        $this->_console = $console;
        $this->_init(...$args);
    }

    /**
     * @param array ...$args
     */
    abstract protected function _init(...$args): void;
}


text:
package com.nostra13.example.universalimageloader;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.StrictMode;

import com.nostra13.example.universalimageloader.Constants.Config;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

/**
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 */
public class UILApplication extends Application {
	@SuppressWarnings("unused")
	@Override
	public void onCreate() {
		if (Config.DEVELOPER_MODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyDialog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyDeath().build());
		}

		super.onCreate();

		initImageLoader(getApplicationContext());
	}

	public static void initImageLoader(Context context) {
		int memoryCacheSize;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
			int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
			memoryCacheSize = (memClass / 8) * 1024 * 1024; // 1/8 of app memory limit
		} else {
			memoryCacheSize = 2 * 1024 * 1024;
		}

		// This configuration tuning is custom. You can tune every option, you may tune some of them,
		// or you can create default configuration by
		//  ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
			.threadPriority(Thread.NORM_PRIORITY - 2)
			.memoryCacheSize(memoryCacheSize)
			.denyCacheImageMultipleSizesInMemory()
			.discCacheFileNameGenerator(new Md5FileNameGenerator())
			.tasksProcessingOrder(QueueProcessingType.LIFO)
			.enableLogging() // Not necessary in common
			.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}
}


text:
/*
 * GCM Prototype - mapFilter
 *
 * TABLE OF CONTENTS
 *
 * Main
 *     Map
 *     GCM
 * Popups
 * Plugins
 *     tablesorter
 *     jScrollPane
 *     other
 */

/*
 *  Main
 */
body {
	margin: 0;
	padding: 0;
	font-size:80%;
}

/*
 *  Main | Map
 */
/*
 * Google colors
 * ocean blue: #99B3CC
 * icon blue: #307BC2
 * forrest green: #B5D29C
 * highway exit green: #41A774
 * orange highway: #FFC345
 * yellow road: #FFFD8B
 * grey city block: #EDEAE2
 * orange-brown buidling: #DED2AC
 */

#map_id {
	position:absolute;
	top:0;
	left:0;
	height:100%;
	width:100%;
    background:#99B3CC;
}

/* Info Window styles */
.IW { width: 340px;}
.IWContent {height: 120px; overflow:auto;}
.IWCaption {font-weight: bold; font-size: 12pt; color: #369; border-bottom: 2px solid #369;}
.IWFooter {margin-top: 5px; font-size: 8pt; }
.IWFooterZoom {}
.IWDirections{background-color:#FFF;}

/* want to save linebreaks but also wordwrap */
.preWrapped {
  white-space: pre;
  white-space: pre-wrap;       /* css-3 */
  white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
  white-space: -pre-wrap;      /* Opera 4-6 */
  white-space: -o-pre-wrap;    /* Opera 7 */
  word-wrap: break-word;       /* Internet Explorer 5.5+ */
  text-align:left;
  font: normal small verdana, arial, helvetica, sans-serif;
  font-size: 8pt;
  margin-bottom: 10px;
}

/*
 *  Main | GCM
 *
 *  GCM components that go on top of the map
 */

.transparent
{
	filter:alpha(opacity=90);
	-moz-opacity: 0.90;
	-khtml-opacity: 0.90;
	opacity: 0.90;
}

#rightTab {
    position:absolute;
    top:40px;
    right:0;
    display:block;
    height:30px;
    width:30px;
    cursor:pointer;
    z-index:10;
    background-color: #FFF;
    font-size:24px;
    font-weight:bold;
    padding-left:6px;
}
#rtSide {
	position:absolute;
	top:70px;
	right:0;
	margin-right:0;
	overflow:hidden;
	z-index:2;
}

#gcmMapLogo {
	position:absolute;
	bottom:20px;
	right:4px;
	background: url(https://chadnorwood.com/beermug.ico) no-repeat 0 0;
	height:17px;
	width:17px;
	overflow:hidden;
	z-index:25500;
}

.ui-slider .ui-slider-handle {
	width: 34px;
	height: 25px;
	padding: 2px;
	top: -10px;
	margin-left: 0;  /* reset horizontal handle offset */
	margin-bottom: 0; /* reset vertical handle offset */
	border: 1px solid #2E6E9E;
	color: #2E6E9E;
	text-align: center;
	font-size: 9px;
}
.ui-slider-horizontal {
	/* set dynamically - width: 300px; */
}
.ui-slider-range {
	background: #6699EE;
}

#titleDiv {
	overflow:auto;
	padding-right: 100px; /* match gcmLogo width */
	background-color: #B5D29C;

}
#titleDiv div {
}

#calendarTitle,
#resultsDataFilters {
	position: relative;
	float: left;
	padding: 0;
	/*background-color: #ECECE2;*/
	height: auto;
	font-size: 12px;
	text-align: left;
	width: 100%;
	background-color: #FFFFFF;

}
#calendarTitleContent {
	padding: 5px;
}
#calendarTitle h3 {
	font-size: 24px;
	margin: 5px 5px 2px 5px;
	margin: 0;
	text-align: left;
}
#calendarTitle h4 {
	font-size: 24px;
	margin: 5px 5px 2px 5px;
	margin: 0;
	text-align: left;
}
#calendarTitle span {
	font-size: 12px;
	margin: 1px 5px 5px 5px;
	margin: 0;
	text-align: left;
}
#gcmLogo,
#resultsDataStatus {
	position: relative;
	float:right;
	width: 100px;       /* match parent titleDiv's padding-right */
	margin-right: -100px;/* match parent titleDiv's padding-right */
	height: 60px;
	/*background-color: #AACCDD;*/
	/*color: #2E6E9E;*/
	text-align: center;
	background-color: #B5D29C;
}

#gcmLogo h1 {
	font-size: 36px;
	font-weight: bold;
	margin: 0;
}
#resultsData {
	overflow:hidden;
	padding-right: 100px; /* match gcmLogo width */
	background-color: #FFF;
}
#resultsDataFilters {
	/*background-color: #E6EEEE;*/
	position: relative;
	float: left;
}
#resultsDataStatus {
	height: auto;
	position: relative;
	float: left;
	text-align:center;
	/*background-color: #CCCCDD;*/
	background-color: #B5D29C;
}
#ResultsMapHdr {
	padding: 2px 5px;
	background: #99B3CC;
}
.jumpLink {
	color: #0085D0;
	color: #0045CC;
	text-decoration: none;
}
.actionable {
	color: #005599;
	text-decoration: none;
}
.actionable:hover,
.jumpLink:hover {
	text-decoration: underline;
}

.helpContainer {
	overflow: auto;
	background: #99B3CC;
}
.helpContainer h3 {
	padding-left: 5px;
}

#ResultsMapEventsTable tbody,
#ResultsMapEvents {
	overflow:auto;
}
.event_table {
	display:block;
}
.highlight2 {
	font: bold;
	background: #FFFD8B;
	color: #555555;
}

/*
 *  Popups
 */

#newDates {
	display:none;
	overflow: hidden;
	/* width set in dialogDates in js */
	text-align:left;
}

/*
 *  Plugins | tablesorter
 *
 * originally from tablesorter.style.css
 */
table.tablesorter {
	font-family:arial;
	margin:10px 0pt 15px;
	font-size: 8pt;
	width: 100%;
	text-align: left;
}
table.tablesorter thead tr th, table.tablesorter tfoot tr th {
	background-color: #e6EEEE;
	border: 1px solid #FFF;
	font-size: 8pt;
	padding: 4px;
}
table.tablesorter thead tr .header {
	background-image: url(../img/bg.gif);
	background-repeat: no-repeat;
	background-position: center right;
	cursor: pointer;
}
table.tablesorter tbody td {
	color: #3D3D3D;
	padding: 4px;
	background-color: #FFF;
	vertical-align: top;
	filter:alpha(opacity=90);
	-moz-opacity: 0.90;
	-khtml-opacity: 0.90;
	opacity: 0.90;
}
table.tablesorter tbody tr.odd td {
	background-color:#F0F0F6;
}
table.tablesorter thead tr .headerSortUp {
	background-image: url(../img/asc.gif);
}
table.tablesorter thead tr .headerSortDown {
	background-image: url(../img/desc.gif);
}
table.tablesorter thead tr .headerSortDown, table.tablesorter thead tr .headerSortUp {
    background-color: #8dbdd8;
}
table.tablesorter {margin: 0 0 0 0;}

 /*
  *  Plugins | jScrollPane
  *
  *  http://www.kelvinluck.com/assets/jquery/jScrollPane/examples.html
  *  note - if winxp is used, must pass options like this
  *  	$('#pane1').jScrollPane({showArrows:true, scrollbarWidth: 17});
  *  note - if osX is used, like this
  *		$('#pane2').jScrollPane({showArrows:true, scrollbarWidth: 15, arrowSize: 16});
  */

.scrollPane {
  height: auto;
  overflow: visible;
  background: #EEEEEE;
  float: left;
  text-align:left;
  position:absolute;
}

.jScrollPaneContainer {
	/*border: 5px solid #9999CC;*/
}

.winXP .jScrollPaneTrack {
	background: url(../img/windows_track.gif) repeat-y;
}
.winXP .jScrollPaneDrag {
	background: url(../img/windows_drag_middle.gif) no-repeat 0 50%;
}
.winXP .jScrollPaneDragTop {
	background: url(../img/windows_drag_top.gif) no-repeat;
	height: 4px;
}
.winXP .jScrollPaneDragBottom {
	background: url(../img/windows_drag_bottom.gif) no-repeat;
	height: 4px;
}
.winXP a.jScrollArrowUp {
	height: 17px;
	background: url(../img/windows_arrow_up.gif) no-repeat 0 0;
}
.winXP a.jScrollArrowUp:hover {
	background-position: 0 -20px;
}
.winXP a.jScrollArrowDown {
	height: 17px;
	background: url(../img/windows_arrow_down.gif) no-repeat 0 0;
}
.winXP a.jScrollArrowDown:hover {
	background-position: 0 -20px;
}
.winXP a.jScrollActiveArrowButton, .winXP a.jScrollActiveArrowButton:hover {
	background-position: 0 -40px;
}

.osX .jScrollPaneTrack {
	background: url(../img/osx_track.gif) repeat-y;
}
.osX .jScrollPaneDrag {
	background: url(../img/osx_drag_middle.gif) repeat-y;
}
.osX .jScrollPaneDragTop {
	background: url(../img/osx_drag_top.gif) no-repeat;
	height: 6px;
}
.osX .jScrollPaneDragBottom {
	background: url(../img/osx_drag_bottom.gif) no-repeat;
	height: 7px;
}
.osX a.jScrollArrowUp {
	height: 24px;
	background: url(../img/osx_arrow_up.png) no-repeat 0 -30px;
}
.osX a.jScrollArrowUp:hover {
	background-position: 0 0;
}
.osX a.jScrollArrowDown {
	height: 24px;
	background: url(../img/osx_arrow_down.png) no-repeat 0 -30px;
}
.osX a.jScrollArrowDown:hover {
	background-position: 0 0;
}

/*
 *  Plugins | other
 */

.ui-state-active { background: white; }


text:
<?php
include_once("conexion.php");
include_once("cabecera.php");
$menu = "reportes";
include_once("menu.php");
$men2 = "";
include_once("pagos.php");
?>

<?php
if ($_POST['cod_desde']<>'') {
	$dsd = $_POST['cod_desde'];
} else {
	$dsd = 'Primero';
}
if ($_POST['cod_hasta']<>'') {
	$hst = $_POST['cod_hasta'];
} else {
	$hst = 'Último';
}

echo '
';
	echo '
';
		echo '
BONOS DE REEMBOLSO POR CONSUMO
';
		echo 'Desde el código: '.trim($dsd).' hasta el código: '.trim($hst).'
';
	echo '
';

if ($dsd<>'Primero') {
	if ($hst<>'Último') {
		$query = "SELECT reembolso.*,transacciones.tipo,transacciones.monto as monto_original FROM reembolso left outer join transacciones on reembolso.trans_id=transacciones.id WHERE reembolso.afiliado>='".trim($dsd)."' AND reembolso.afiliado<='".trim($hst)."' AND reembolso.status_comision='Pendiente' order by reembolso.afiliado,reembolso.fecha,transacciones.tipo";
	} else {
		$query = "SELECT reembolso.*,transacciones.tipo,transacciones.monto as monto_original FROM reembolso left outer join transacciones on reembolso.trans_id=transacciones.id WHERE reembolso.afiliado>='".trim($dsd)."' AND reembolso.status_comision='Pendiente' order by reembolso.afiliado,reembolso.fecha,transacciones.tipo";
	}
} else {
	if ($hst<>'Último') {
		$query = "SELECT reembolso.*,transacciones.tipo,transacciones.monto as monto_original FROM reembolso left outer join transacciones on reembolso.trans_id=transacciones.id WHERE reembolso.afiliado<='".trim($hst)."' AND reembolso.status_comision='Pendiente' order by reembolso.afiliado,reembolso.fecha,transacciones.tipo";
	} else {
		$query = "SELECT reembolso.*,transacciones.tipo,transacciones.monto as monto_original FROM reembolso left outer join transacciones on reembolso.trans_id=transacciones.id WHERE reembolso.status_comision='Pendiente' order by reembolso.afiliado,reembolso.fecha,transacciones.tipo";
	}
}

$result = mysql_query($query,$link);
$grupo = 1;
echo "";
echo '

';
echo '

';
echo "FECHA";

echo '

';
echo '

';
echo "# TRANSACCIÓN";

echo '

';
echo "TIPO DE OPERACIÓN";

echo '

';
echo '

';
echo '

';
echo '

';
echo '

';
echo '

';
echo "MONTO";

echo '

';
echo '

';
echo '

';
echo '

';
echo '

';
echo "COMISION";
echo "
";

$first = true;
echo '<form name="gestion" method="post" action="totreembolsoindividual.php">';
while($row = mysql_fetch_array($result)) {
	if ($first) {
		$afiliado = $row['afiliado'];
		$quer2 = "SELECT tit_nombres,tit_apellidos FROM afiliados WHERE tit_codigo='".$afiliado."'";
		$resul2 = mysql_query($quer2,$link);
		$ro2 = mysql_fetch_array($resul2);
		$nombre = trim($ro2['tit_nombres']).' '.trim($ro2['tit_apellidos']);
		echo 'Afiliado: '.$afiliado.' - '.$nombre.'
';
		$first = false;
	}
	if ($afiliado<>$row['afiliado']) {
		echo '
';
		$afiliado = $row['afiliado'];
		$quer2 = "SELECT tit_nombres,tit_apellidos FROM afiliados WHERE tit_codigo='".$afiliado."'";
		$resul2 = mysql_query($quer2,$link);
		$ro2 = mysql_fetch_array($resul2);
		$nombre = trim($ro2['tit_nombres']).' '.trim($ro2['tit_apellidos']);
		echo 'Afiliado: '.$afiliado.' - '.$nombre.'
';
	}
	$fecha = $row['fecha'];
	$monto = $row['monto'];
	$monto_original = $row['monto_original'];
	$trans_id= $row['trans_id'];
	$tipo = $row['tipo'];
	$id = $row['id'];

	echo '

';
	echo '
'.substr($fecha,8,2).'/'.substr($fecha,5,2).'/'.substr($fecha,0,4).'
';

	echo '

';
	echo '
'.number_format($trans_id,0,',','.').'
';

	echo '

';
	echo '

';
	switch ($tipo) {
		case '04':
			$nombre_trans = 'Consumo aliados';
			break;
		case '14':
			$nombre_trans = 'Consumo cliente';
			break;
		case '24':
			$nombre_trans = 'Consumo cliente preferencial';
			break;
		default:
			$nombre_trans = 'No identificada';
			break;
	}
	echo '
'.$nombre_trans.'
';

	echo '

';
	echo '
'.number_format($monto_original,2,',','.').'
';

	echo '

';
	echo '
'.number_format($monto,2,',','.').'
';

	echo '

';
	echo '
'.'<input type="checkbox" name="'.trim($id).'"/> Pagar
'."
";
}
echo '
';
	echo '
';
	echo '<input type="submit" value="Totalizar">';
echo '
';
?>


text:
define('URL', function() {

	/**
	 * Return default port for `protocol`.
	 *
	 * @param  {String} protocol
	 * @return {String}
	 * @api private
	 */
	function port(protocol) {
		switch (protocol) {
			case 'http:':
				return 80;
			case 'https:':
				return 443;
			default:
				return location.port;
		}
	}

	function parse(url) {
		var a = document.createElement("a");
		a.href = url;
		var query = a.search.slice(1);
		var queryArr = [];
		if(!!query) {
			queryArr = query.split("&");
		}
		var queryObj = {};
		for(var i = 0; i < queryArr.length; i++) {
			queryObj[queryArr[i].split("=")[0]] = queryArr[i].split("=")[1];
		}

		return {
			href : a.href,
			host : a.host || location.host,
			port : ('0' === a.port || '' === a.port) ? port(a.protocol) : a.port,
			hash : a.hash,
			hostname : a.hostname || location.hostname,
			pathname : a.pathname.charAt(0) != '/' ? '/' + a.pathname : a.pathname,
			protocol : !a.protocol || ':' == a.protocol ? location.protocol : a.protocol,
			search : a.search,
			query : query,
			queryObj : queryObj
		};
	}

	/**
	 * Check if `url` is absolute.
	 *
	 * @param {String} url
	 * @return {Boolean}
	 * @api public
	 */
	function isAbsolute(url) {
		return 0 == url.indexOf('//') || !!~url.indexOf('://');
	}

	/**
	 * Check if `url` is relative.
	 *
	 * @param {String} url
	 * @return {Boolean}
	 * @api public
	 */
	function isRelative(url) {
		return !isAbsolute(url);
	}

	/**
	 * Check if `url` is cross domain.
	 *
	 * @param {String} url
	 * @return {Boolean}
	 * @api public
	 */
	function isCrossDomain(url) {
		url = parse(url);
		var location = parse(window.location.href);
		return url.hostname !== location.hostname || url.port !== location.port || url.protocol !== location.protocol;
	}

	return {
		parse : parse,
		isAbsolute : isAbsolute,
		isRelative : isRelative,
		isCrossDomain : isCrossDomain
	};

});


text:
require 'rails_helper'

describe CarriersController do
  login_user

  describe 'GET index' do
    let(:carriers) { [create(:carrier)] }
    before { get :index }

    it 'finds and assign carriers for view' do
      expect(assigns(:carriers)).to eq carriers
    end

    it 'renders the index view' do
      expect(response).to render_template :index
    end
  end

  describe 'GET show' do
    let(:carrier) { create :carrier }
    before { get :show, id: carrier.id }

    it 'finds and assign carrier for view' do
      expect(assigns(:carrier)).to eq carrier
    end

    it 'renders the show view' do
      expect(response).to render_template :show
    end
  end
end


text:
using System;

namespace VirtFunc
{
    public class CDerived19
    {
        public override int GetHashCode() { return 19; }
    }
}