text:
import bottle
import neo4jrestclient.client
import neo4jrestclient.query
import yaml

import argparse
import json
import logging
import sys
import urllib.parse

# This is needed to be able to add Relationships to a set()
neo4jrestclient.client.Relationship.__hash__ = lambda self: hash(self.id)

DEFAULT_NEO4J = 'http://neo4j:insecure@localhost:7474/db/data'

def argument_parser():
    parser = argparse.ArgumentParser("Software dependency visualiser - server "
                                     "component")
    parser.add_argument('--neo4j', '-n', metavar='URL',
                        default=DEFAULT_NEO4J,
                        help="Neo4J database (default: %s)" % DEFAULT_NEO4J)

    return parser

args = argument_parser().parse_args()

app = bottle.Bottle()

database = neo4jrestclient.client.GraphDatabase(args.neo4j)

@app.route('/')
@app.route('/group-force-layout')
@app.route('/group-force-layout/')
def browser_redirect():
    '''Convenience redirect URLs to the main browser content.'''
    bottle.redirect('/group-force-layout/force3.html')

@app.route('/group-force-layout/<path:path>')
def browser_content(path):
    '''Serve the browser content as static files.'''
    return bottle.static_file(path, root='group-force-layout/')

@app.route('/context.jsonld')
def jsonld_context():
    '''Serves the JSON-LD context that we use when describing resources.'''

    with open('data/context.jsonld.yaml') as f:
        context = yaml.load(f)
    bottle.response.content_type = 'application/ld+json'
    bottle.response.body = json.dumps(context, indent=4, sort_keys=True)
    return bottle.response

def lookup_node(identifier):
    '''Return a neo4jrestclient.Node instance, given a node identifier.

    This uses a neo4jrestclient filter, which boils down to a simple
    Cypher query underneath.

    '''
    try:
        node_number = int(identifier)
        return database.nodes.get(node_number)
    except ValueError:
        pass

    uri_lookup = neo4jrestclient.query.Q('uri', exact=identifier, limit=2)
    compact_uri_lookup = neo4jrestclient.query.Q('compact_uri',
                                                 exact=identifier, limit=2)

    nodes = database.nodes.filter(compact_uri_lookup)
    if len(nodes) > 0:
        return nodes[0]
    else:
        nodes = database.nodes.filter(uri_lookup)
        if len(nodes) > 0:
            return nodes[0]
    return None

@app.route('/graph/node-number/<node_uri>')
def graph_node_number(node_uri):
    '''Return the node number, given a node's URI or compact URI.'''
    node_uri = urllib.parse.unquote(node_uri)
    node = lookup_node(node_uri)
    if node:
        return node.id
    else:
        raise bottle.HTTPError(status=404)

def node_name(node):
    '''Get a human-readable name for a node.

    The 'name' property is used if set, but it may not be set.

    '''
    if 'name' in node.properties:
        return node.properties['name']
    elif 'compact_uri' in node.properties:
        return node.properties['compact_uri']
    else:
        print("Returning the node's URI");
        if type(node.uri) is not str:
            return "Unknown object"
        return node.uri

def encode_node(node, contents_graphjson=None):
    '''Represent as GraphJSON data, ready to send to client.'''

    return {
        '_id': node.id,
        'uri': node.properties['uri'],
        'caption': node_name(node),
        'contains': contents_graphjson or {},
    }

def encode_relationship(relationship):
    '''Represent a relationship as GraphJSON data, ready to send to client.'''

    return {
        '_source': relationship.start.id,
        '_target': relationship.end.id,
        'type': relationship.type,
    }

def traverse_paths(start_node, stop=None, direction=neo4jrestclient.client.All,
                   types=None):
    '''Run a Neo4j traversal through the REST API, to find paths.

    The result is a list of Path objects. Any relationships in 'types' are
    followed, according to 'direction'.

    '''
    return start_node.traverse(
        returnable=neo4jrestclient.client.RETURN_ALL_BUT_START_NODE,
        returns=neo4jrestclient.client.PATH,
        stop=stop,
        # This is some weird neo4jrestclient API, sorry.
        types=[getattr(direction, name) for name in types]
    )

def traverse_nodes(start_node, stop=None, direction=neo4jrestclient.client.All,
                   types=None):
    '''Run a Neo4j traversal through the REST API, to find nodes.

    The result is a list of Node objects.

    '''
    return start_node.traverse(
        returnable=neo4jrestclient.client.RETURN_ALL_BUT_START_NODE,
        returns=neo4jrestclient.client.NODE,
        stop=stop,
        # This is some weird neo4jrestclient API, sorry.
        types=[getattr(direction, name) for name in types]
    )

class Presentation():
    '''Describes how to present a given node.

    Presentation involves a 2-dimensional traverse. The 'width' relations
    are intended to be represented as different nodes at the same level, e.g:

        o  --  o
          \
           \
            o

    The 'depth' relations are intended to be represented as a parent-child
    heirarchy, e.g:
         ______       _____
        /      \     /     \
        | o    |     |   o |
        |  \   |-----|     |
        |   o  |     | o   |
        \______/     \_____/

    '''

    def __init__(self, root_node,
                 width_relationships=['sw:requires', 'sw:produces'],
                 max_width=2,
                 depth_relationships=['sw:contains'],
                 max_depth=2):
        self.root_node = root_node

        self.width_relationships = width_relationships
        self.max_width = max_width
        self.depth_relationships = depth_relationships
        self.max_depth = max_depth

    def encode(self):
        return {
            'root_node': self.root_node.id,
            'width_relationships': self.width_relationships,
            'max_width': self.max_width,
            'depth_relationships': self.depth_relationships,
            'max_depth': self.max_depth
        }

@app.route('/graph/present/<root_node_identifier>')
def graph_present(root_node_identifier):
    '''Return siblings and children of a given graph node.

    This traverses the graph using the REST API of the Neo4j database.

    It's not possible to do this sort of traversal using the current version of
    the Cypher query language. You cannot define custom functions in Cypher
    2.3, and there are no other language features that would enable true
    recursion.

    It's actually not very convienient using the REST API either, because the
    existing traversals endpoint is designed for 1-dimensional traversal only.
    The ideal solution is probably to write a custom Neo4j plugin in Java: see
    <http://neo4j.com/docs/stable/server-plugins.html>. Or, it might work to
    write the queries we need in the Gremlin query language, and use this
    existing plugin: <https://github.com/neo4j-contrib/gremlin-plugin>.

    The return values are structed as GraphJSON data. This is slightly
    different to the format D3.js expects, but it seems better to me to use a
    standardised interchange format.

    GraphJSON is defined here: <https://github.com/GraphAlchemist/GraphJSON>
    (although it seems a little abandoned at time of writing). Note that
    the Node.js 'graph-json' package <https://www.npmjs.com/package/graph-json>
    is something else again.

    '''

    def traverse_widthwise(start_node, config, depth=0):
        logging.debug("Traversing widthwise from '%s'" % node_name(start_node))

        paths = traverse_paths(start_node, stop=config.max_width,
                               types=config.width_relationships)

        nodes = set([start_node])
        edges = set()
        children = {
            start_node: find_children(start_node, config, depth=depth)
        }

        for path in paths:
            end_node = path.nodes[-1]

            if end_node not in nodes:
                nodes.add(end_node)
                edges.add(path.last_relationship)

                contents = find_children(end_node, config, depth=depth)
                children[end_node] = contents

        return nodes, edges, children

    def find_children(parent_node, config, depth=0):
        if depth >= config.max_depth:
            return {}

        logging.debug("Finding children of %s" % node_name(parent_node))

        child_nodes = traverse_nodes(parent_node, stop=1,
                                     direction=neo4jrestclient.client.Outgoing,
                                     types=config.depth_relationships)

        # We now traverse from each child node in turn, to find all siblings
        # at this depth. This is pretty wasteful! It would be better to do
        # a single traverse operation that started from all child nodes at
        # once. That can't be done with the Neo4j REST API, though, we'd need
        # to write a Java plugin (or perhaps use the Gremlin query language).
        nodes = set()
        edges = set()
        children = {}
        for node in list(child_nodes):
            if node not in nodes:
                sibling_nodes, sibling_edges, sibling_children = \
                    traverse_widthwise(node, config, depth=depth+1)

                nodes.update(sibling_nodes)
                edges.update(sibling_edges)
                children.update(sibling_children)

        # We don't pass the config here, we only need to return it once per
        # query result.
        logging.debug("Presenting & returning %s, %s, %s", nodes, edges,
                      children)
        return encode_as_graphjson(nodes, edges, children)

    def encode_as_graphjson(node_list, edge_list, node_children, config=None):
        '''Structure traverse results as GraphJSON, suitable for clients.'''
        nodes_graphjson = []
        edges_graphjson = []

        for node in node_list:
            contents = node_children.get(node, {})
            info = encode_node(node, contents)
            if config and node == config.root_node:
                info['root'] = True
            nodes_graphjson.append(info)

        for edge in edge_list:
            edges_graphjson.append(encode_relationship(edge))

        result = {
            'nodes': nodes_graphjson,
            'edges': edges_graphjson,
        }

        if config:
            result['config'] = config.encode()

        return result

    root_node_identifier = urllib.parse.unquote(root_node_identifier)
    root_node = lookup_node(root_node_identifier)
    if not root_node:
        raise bottle.HTTPError(status=404)

    config = Presentation(root_node)

    nodes, edges, children = traverse_widthwise(root_node, config)
    return encode_as_graphjson(nodes, edges, children, config)

@app.route('/info/<node_identifier>')
def node_info(node_identifier):
    '''Return information about a resource, given its URI or compact URI.

    The info is returned as a Linked Data using the JSON-LD serialisation
    format.

    '''
    node_identifier = urllib.parse.unquote(node_identifier)
    node = lookup_node(node_identifier)

    # FIXME: this seems a bit of a dodgy way to get the URL for a route.
    scheme, netloc, path, query, _ = bottle.request.urlparts
    context_url = urllib.parse.urlunsplit(
        [scheme, netloc, app.get_url('/context.jsonld'), None, None])

    def node_link(node):
        query = {'focus':
                 urllib.parse.quote_plus(node.properties['compact_uri'])}
        query_string = urllib.parse.urlencode(query)
        return urllib.parse.urlunsplit([
            scheme, netloc, app.get_url('/group-force-layout/') + 'index.html',
            query_string, None])

    def relations_info(node, direction, relation_type):
        '''Return a little info on some direct relations of this node.'''
        assert direction in ['incoming', 'outgoing']

        if direction == 'incoming':
            relationships = node.relationships.incoming(types=[relation_type])
        else:
            relationships = node.relationships.outgoing(types=[relation_type])
        print("Found list of relationships for "+repr(node))
        infos = []
        for r in relationships:
            relation = r.end if direction=='outgoing' else r.start

            infos.append({
                '@id': relation.properties.get('uri'),
                'name': node_name(relation),
                'link': node_link(relation),
            })
        return infos or None

    return {
        '@context': context_url,

        # Note that this should be the URI of the *real* resource,
        # e.g. <https://git.gnome.org/browse/gtk+/tree/gtk/gtk.h?h=gtk-2-24>,
        # not a link to something in the software-dependency-visualiser
        # application.
        '@id': node.properties.get('uri'),

        'name': node_name(node),

        # FIXME: the *-by properties aren't defined anywhere. The main ontology
        # specifically avoids such 'unneeded' properties. I guess there or here
        # we should provide some 'supplemental' terms... or can it be done with
        # @reverse in the JSON-LD context??
        #
        # Also: we should be able to say 'requires' rather than 'sw:requires',
        # the import/neo4j script is getting that wrong right now.
        'requires': relations_info(node, 'outgoing', 'sw:requires'),
        'required_by': relations_info(node, 'incoming', 'sw:requires'),
        'produces': relations_info(node, 'outgoing', 'sw:produces'),
        'produced_by': relations_info(node, 'incoming', 'sw:produces'),
        'contains': relations_info(node, 'outgoing', 'sw:contains'),
        'contained_by': relations_info(node, 'incoming', 'sw:contains'),
        'calls': relations_info(node, 'incoming', 'sw:calls'),
    }

#logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

#node_number = graph_node_number("id:package/source/libgtk")
#print(graph_present(node_number))

app.run(host='0.0.0.0')


text:
/*  inline demuxer.
 *   probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
 */

import Event from '../events';
import { ErrorTypes, ErrorDetails } from '../errors';
import Decrypter from '../crypt/decrypter';
import AACDemuxer from '../demux/aacdemuxer';
import MP4Demuxer from '../demux/mp4demuxer';
import TSDemuxer from '../demux/tsdemuxer';
import MP3Demuxer from '../demux/mp3demuxer';
import MP4Remuxer from '../remux/mp4-remuxer';
import PassThroughRemuxer from '../remux/passthrough-remuxer';

class DemuxerInline {

  constructor(observer, typeSupported, config, vendor) {
    this.observer = observer;
    this.typeSupported = typeSupported;
    this.config = config;
    this.vendor = vendor;
  }

  destroy() {
    var demuxer = this.demuxer;
    if (demuxer) {
      demuxer.destroy();
    }
  }

  push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
    if ((data.byteLength > 0) && (decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'AES-128')) {
      let decrypter = this.decrypter;
      if (decrypter == null) {
        decrypter = this.decrypter = new Decrypter(this.observer, this.config);
      }
      var localthis = this;
      // performance.now() not available on WebWorker, at least on Safari Desktop
      var startTime;
      try {
        startTime = performance.now();
      } catch (error) {
        startTime = Date.now();
      }
      decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {
        var endTime;
        try {
          endTime = performance.now();
        } catch (error) {
          endTime = Date.now();
        }
        localthis.observer.trigger(Event.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });
        localthis.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
      });
    } else {
      this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
    }
  }

  pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
    var demuxer = this.demuxer;
    if (!demuxer ||
      // in case of continuity change, we might switch from content type (AAC container to TS container for example)
      // so let's check that current demuxer is still valid
      (discontinuity && !this.probe(data))) {
      const observer = this.observer;
      const typeSupported = this.typeSupported;
      const config = this.config;
      // probing order is AAC/MP3/TS/MP4
      const muxConfig = [{ demux: AACDemuxer, remux: MP4Remuxer },
      { demux: MP3Demuxer, remux: MP4Remuxer },
      { demux: TSDemuxer, remux: MP4Remuxer },
      { demux: MP4Demuxer, remux: PassThroughRemuxer }];

      // probe for content type
      for (let i = 0, len = muxConfig.length; i < len; i++) {
        const mux = muxConfig[i];
        const probe = mux.demux.probe;
        if (probe(data)) {
          const remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);
          demuxer = new mux.demux(observer, remuxer, config, typeSupported);
          this.probe = probe;
          break;
        }
      }
      if (!demuxer) {
        observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });
        return;
      }
      this.demuxer = demuxer;
    }
    const remuxer = this.remuxer;

    if (discontinuity || trackSwitch) {
      demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
      remuxer.resetInitSegment();
    }
    if (discontinuity) {
      demuxer.resetTimeStamp(defaultInitPTS);
      remuxer.resetTimeStamp(defaultInitPTS);
    }
    if (typeof demuxer.setDecryptData === 'function') {
      demuxer.setDecryptData(decryptdata);
    }
    demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);
  }
}

export default DemuxerInline;

redpajama_set_name: RedPajamaGithub


text:
package model

type Beam struct {
	Id       int
	SourceId int
}


text:
package course.labs.graphicslab.tests;

import course.labs.graphicslab.BubbleActivity;

import com.robotium.solo.*;
import android.test.ActivityInstrumentationTestCase2;

public class BubbleActivityPop extends
		ActivityInstrumentationTestCase2<BubbleActivity> {
	private Solo solo;

	public BubbleActivityPop() {
		super(BubbleActivity.class);
	}

	public void setUp() throws Exception {
		solo = new Solo(getInstrumentation(), getActivity());
	}

	@Override
	public void tearDown() throws Exception {
		solo.finishOpenedActivities();
	}

	public void testRun() {

		int delay = 2000;

		// Wait for activity: 'course.labs.TouchLab.BubbleActivity'
		solo.waitForActivity(course.labs.graphicslab.BubbleActivity.class,
				delay);

		// Set Still Mode
		solo.clickOnMenuItem("Still Mode");

		// Click on action bar item
		solo.clickOnMenuItem("Add a Bubble");

		solo.sleep(delay);

		// Assert that a bubble was displayed
		assertEquals(
				"Bubble hasn't appeared",
				1,
				solo.getCurrentViews(
						course.labs.graphicslab.BubbleActivity.BubbleView.class)
						.size());

		// Click on action bar item
		solo.clickOnMenuItem("Delete a Bubble");

		solo.sleep(delay);

		// Assert that there are no more bubbles
		assertEquals(
				"The bubble was not popped",
				0,
				solo.getCurrentViews(
						course.labs.graphicslab.BubbleActivity.BubbleView.class)
						.size());

	}
}


text:
"""Config flow for Samsung TV."""
from __future__ import annotations

from functools import partial
import socket
from types import MappingProxyType
from typing import Any
from urllib.parse import urlparse

import getmac
import voluptuous as vol

from homeassistant import config_entries, data_entry_flow
from homeassistant.components import dhcp, ssdp, zeroconf
from homeassistant.const import (
    CONF_HOST,
    CONF_MAC,
    CONF_METHOD,
    CONF_NAME,
    CONF_PORT,
    CONF_TOKEN,
)
from homeassistant.core import callback
from homeassistant.helpers.device_registry import format_mac

from .bridge import (
    SamsungTVBridge,
    SamsungTVLegacyBridge,
    SamsungTVWSBridge,
    async_get_device_info,
    mac_from_device_info,
)
from .const import (
    CONF_MANUFACTURER,
    CONF_MODEL,
    DEFAULT_MANUFACTURER,
    DOMAIN,
    LEGACY_PORT,
    LOGGER,
    METHOD_LEGACY,
    METHOD_WEBSOCKET,
    RESULT_AUTH_MISSING,
    RESULT_CANNOT_CONNECT,
    RESULT_NOT_SUPPORTED,
    RESULT_SUCCESS,
    RESULT_UNKNOWN_HOST,
    WEBSOCKET_PORTS,
)

DATA_SCHEMA = vol.Schema({vol.Required(CONF_HOST): str, vol.Required(CONF_NAME): str})
SUPPORTED_METHODS = [METHOD_LEGACY, METHOD_WEBSOCKET]

def _strip_uuid(udn: str) -> str:
    return udn[5:] if udn.startswith("uuid:") else udn

def _entry_is_complete(entry: config_entries.ConfigEntry) -> bool:
    """Return True if the config entry information is complete."""
    return bool(entry.unique_id and entry.data.get(CONF_MAC))

class SamsungTVConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle a Samsung TV config flow."""

    VERSION = 2

    def __init__(self) -> None:
        """Initialize flow."""
        self._reauth_entry: config_entries.ConfigEntry | None = None
        self._host: str = ""
        self._mac: str | None = None
        self._udn: str | None = None
        self._manufacturer: str | None = None
        self._model: str | None = None
        self._name: str | None = None
        self._title: str = ""
        self._id: int | None = None
        self._bridge: SamsungTVLegacyBridge | SamsungTVWSBridge | None = None
        self._device_info: dict[str, Any] | None = None

    def _get_entry_from_bridge(self) -> data_entry_flow.FlowResult:
        """Get device entry."""
        assert self._bridge

        data = {
            CONF_HOST: self._host,
            CONF_MAC: self._mac,
            CONF_MANUFACTURER: self._manufacturer or DEFAULT_MANUFACTURER,
            CONF_METHOD: self._bridge.method,
            CONF_MODEL: self._model,
            CONF_NAME: self._name,
            CONF_PORT: self._bridge.port,
        }
        if self._bridge.token:
            data[CONF_TOKEN] = self._bridge.token
        return self.async_create_entry(
            title=self._title,
            data=data,
        )

    async def _async_set_device_unique_id(self, raise_on_progress: bool = True) -> None:
        """Set device unique_id."""
        if not await self._async_get_and_check_device_info():
            raise data_entry_flow.AbortFlow(RESULT_NOT_SUPPORTED)
        await self._async_set_unique_id_from_udn(raise_on_progress)
        self._async_update_and_abort_for_matching_unique_id()

    async def _async_set_unique_id_from_udn(
        self, raise_on_progress: bool = True
    ) -> None:
        """Set the unique id from the udn."""
        assert self._host is not None
        await self.async_set_unique_id(self._udn, raise_on_progress=raise_on_progress)
        if (entry := self._async_update_existing_host_entry()) and _entry_is_complete(
            entry
        ):
            raise data_entry_flow.AbortFlow("already_configured")

    def _async_update_and_abort_for_matching_unique_id(self) -> None:
        """Abort and update host and mac if we have it."""
        updates = {CONF_HOST: self._host}
        if self._mac:
            updates[CONF_MAC] = self._mac
        self._abort_if_unique_id_configured(updates=updates)

    async def _try_connect(self) -> None:
        """Try to connect and check auth."""
        for method in SUPPORTED_METHODS:
            self._bridge = SamsungTVBridge.get_bridge(self.hass, method, self._host)
            result = await self._bridge.async_try_connect()
            if result == RESULT_SUCCESS:
                return
            if result != RESULT_CANNOT_CONNECT:
                raise data_entry_flow.AbortFlow(result)
        LOGGER.debug("No working config found")
        raise data_entry_flow.AbortFlow(RESULT_CANNOT_CONNECT)

    async def _async_get_and_check_device_info(self) -> bool:
        """Try to get the device info."""
        _port, _method, info = await async_get_device_info(
            self.hass, self._bridge, self._host
        )
        if not info:
            if not _method:
                LOGGER.debug(
                    "Samsung host %s is not supported by either %s or %s methods",
                    self._host,
                    METHOD_LEGACY,
                    METHOD_WEBSOCKET,
                )
                raise data_entry_flow.AbortFlow(RESULT_NOT_SUPPORTED)
            return False
        dev_info = info.get("device", {})
        if (device_type := dev_info.get("type")) != "Samsung SmartTV":
            raise data_entry_flow.AbortFlow(RESULT_NOT_SUPPORTED)
        self._model = dev_info.get("modelName")
        name = dev_info.get("name")
        self._name = name.replace("[TV] ", "") if name else device_type
        self._title = f"{self._name} ({self._model})"
        self._udn = _strip_uuid(dev_info.get("udn", info["id"]))
        if mac := mac_from_device_info(info):
            self._mac = mac
        elif mac := await self.hass.async_add_executor_job(
            partial(getmac.get_mac_address, ip=self._host)
        ):
            self._mac = mac
        self._device_info = info
        return True

    async def async_step_import(
        self, user_input: dict[str, Any]
    ) -> data_entry_flow.FlowResult:
        """Handle configuration by yaml file."""
        # We need to import even if we cannot validate
        # since the TV may be off at startup
        await self._async_set_name_host_from_input(user_input)
        self._async_abort_entries_match({CONF_HOST: self._host})
        port = user_input.get(CONF_PORT)
        if port in WEBSOCKET_PORTS:
            user_input[CONF_METHOD] = METHOD_WEBSOCKET
        elif port == LEGACY_PORT:
            user_input[CONF_METHOD] = METHOD_LEGACY
        user_input[CONF_MANUFACTURER] = DEFAULT_MANUFACTURER
        return self.async_create_entry(
            title=self._title,
            data=user_input,
        )

    async def _async_set_name_host_from_input(self, user_input: dict[str, Any]) -> None:
        try:
            self._host = await self.hass.async_add_executor_job(
                socket.gethostbyname, user_input[CONF_HOST]
            )
        except socket.gaierror as err:
            raise data_entry_flow.AbortFlow(RESULT_UNKNOWN_HOST) from err
        self._name = user_input.get(CONF_NAME, self._host) or ""
        self._title = self._name

    async def async_step_user(
        self, user_input: dict[str, Any] | None = None
    ) -> data_entry_flow.FlowResult:
        """Handle a flow initialized by the user."""
        if user_input is not None:
            await self._async_set_name_host_from_input(user_input)
            await self._try_connect()
            assert self._bridge
            self._async_abort_entries_match({CONF_HOST: self._host})
            if self._bridge.method != METHOD_LEGACY:
                # Legacy bridge does not provide device info
                await self._async_set_device_unique_id(raise_on_progress=False)
            return self._get_entry_from_bridge()

        return self.async_show_form(step_id="user", data_schema=DATA_SCHEMA)

    @callback
    def _async_update_existing_host_entry(self) -> config_entries.ConfigEntry | None:
        """Check existing entries and update them.

        Returns the existing entry if it was updated.
        """
        for entry in self._async_current_entries(include_ignore=False):
            if entry.data[CONF_HOST] != self._host:
                continue
            entry_kw_args: dict = {}
            if self.unique_id and entry.unique_id is None:
                entry_kw_args["unique_id"] = self.unique_id
            if self._mac and not entry.data.get(CONF_MAC):
                entry_kw_args["data"] = {**entry.data, CONF_MAC: self._mac}
            if entry_kw_args:
                self.hass.config_entries.async_update_entry(entry, **entry_kw_args)
                self.hass.async_create_task(
                    self.hass.config_entries.async_reload(entry.entry_id)
                )
                return entry
        return None

    async def _async_start_discovery_with_mac_address(self) -> None:
        """Start discovery."""
        assert self._host is not None
        if (entry := self._async_update_existing_host_entry()) and entry.unique_id:
            # If we have the unique id and the mac we abort
            # as we do not need anything else
            raise data_entry_flow.AbortFlow("already_configured")
        self._async_abort_if_host_already_in_progress()

    @callback
    def _async_abort_if_host_already_in_progress(self) -> None:
        self.context[CONF_HOST] = self._host
        for progress in self._async_in_progress():
            if progress.get("context", {}).get(CONF_HOST) == self._host:
                raise data_entry_flow.AbortFlow("already_in_progress")

    @callback
    def _abort_if_manufacturer_is_not_samsung(self) -> None:
        if not self._manufacturer or not self._manufacturer.lower().startswith(
            "samsung"
        ):
            raise data_entry_flow.AbortFlow(RESULT_NOT_SUPPORTED)

    async def async_step_ssdp(
        self, discovery_info: ssdp.SsdpServiceInfo
    ) -> data_entry_flow.FlowResult:
        """Handle a flow initialized by ssdp discovery."""
        LOGGER.debug("Samsung device found via SSDP: %s", discovery_info)
        model_name: str = discovery_info.upnp.get(ssdp.ATTR_UPNP_MODEL_NAME) or ""
        self._udn = _strip_uuid(discovery_info.upnp[ssdp.ATTR_UPNP_UDN])
        if hostname := urlparse(discovery_info.ssdp_location or "").hostname:
            self._host = hostname
        await self._async_set_unique_id_from_udn()
        self._manufacturer = discovery_info.upnp[ssdp.ATTR_UPNP_MANUFACTURER]
        self._abort_if_manufacturer_is_not_samsung()
        if not await self._async_get_and_check_device_info():
            # If we cannot get device info for an SSDP discovery
            # its likely a legacy tv.
            self._name = self._title = self._model = model_name
        self._async_update_and_abort_for_matching_unique_id()
        self._async_abort_if_host_already_in_progress()
        self.context["title_placeholders"] = {"device": self._title}
        return await self.async_step_confirm()

    async def async_step_dhcp(
        self, discovery_info: dhcp.DhcpServiceInfo
    ) -> data_entry_flow.FlowResult:
        """Handle a flow initialized by dhcp discovery."""
        LOGGER.debug("Samsung device found via DHCP: %s", discovery_info)
        self._mac = discovery_info.macaddress
        self._host = discovery_info.ip
        await self._async_start_discovery_with_mac_address()
        await self._async_set_device_unique_id()
        self.context["title_placeholders"] = {"device": self._title}
        return await self.async_step_confirm()

    async def async_step_zeroconf(
        self, discovery_info: zeroconf.ZeroconfServiceInfo
    ) -> data_entry_flow.FlowResult:
        """Handle a flow initialized by zeroconf discovery."""
        LOGGER.debug("Samsung device found via ZEROCONF: %s", discovery_info)
        self._mac = format_mac(discovery_info.properties["deviceid"])
        self._host = discovery_info.host
        await self._async_start_discovery_with_mac_address()
        await self._async_set_device_unique_id()
        self.context["title_placeholders"] = {"device": self._title}
        return await self.async_step_confirm()

    async def async_step_confirm(
        self, user_input: dict[str, Any] | None = None
    ) -> data_entry_flow.FlowResult:
        """Handle user-confirmation of discovered node."""
        if user_input is not None:

            await self._try_connect()
            assert self._bridge
            return self._get_entry_from_bridge()

        self._set_confirm_only()
        return self.async_show_form(
            step_id="confirm", description_placeholders={"device": self._title}
        )

    async def async_step_reauth(
        self, data: MappingProxyType[str, Any]
    ) -> data_entry_flow.FlowResult:
        """Handle configuration by re-auth."""
        self._reauth_entry = self.hass.config_entries.async_get_entry(
            self.context["entry_id"]
        )
        assert self._reauth_entry
        data = self._reauth_entry.data
        if data.get(CONF_MODEL) and data.get(CONF_NAME):
            self._title = f"{data[CONF_NAME]} ({data[CONF_MODEL]})"
        else:
            self._title = data.get(CONF_NAME) or data[CONF_HOST]
        return await self.async_step_reauth_confirm()

    async def async_step_reauth_confirm(
        self, user_input: dict[str, Any] | None = None
    ) -> data_entry_flow.FlowResult:
        """Confirm reauth."""
        errors = {}
        assert self._reauth_entry
        if user_input is not None:
            bridge = SamsungTVBridge.get_bridge(
                self.hass,
                self._reauth_entry.data[CONF_METHOD],
                self._reauth_entry.data[CONF_HOST],
            )
            result = await bridge.async_try_connect()
            if result == RESULT_SUCCESS:
                new_data = dict(self._reauth_entry.data)
                new_data[CONF_TOKEN] = bridge.token
                self.hass.config_entries.async_update_entry(
                    self._reauth_entry, data=new_data
                )
                await self.hass.config_entries.async_reload(self._reauth_entry.entry_id)
                return self.async_abort(reason="reauth_successful")
            if result not in (RESULT_AUTH_MISSING, RESULT_CANNOT_CONNECT):
                return self.async_abort(reason=result)

            # On websocket we will get RESULT_CANNOT_CONNECT when auth is missing
            errors = {"base": RESULT_AUTH_MISSING}

        self.context["title_placeholders"] = {"device": self._title}
        return self.async_show_form(
            step_id="reauth_confirm",
            errors=errors,
            description_placeholders={"device": self._title},
        )


text:
'''
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000
Answer: 1

Example 2:

11000
11000
00100
00011
Answer: 3
'''

class Solution:
    def adjacentPixel(self, pixel, grid):
        adjacent_pixel = set()
        pixel_row, pixel_col = pixel
        if pixel_row+1 < len(grid) and grid[pixel_row+1][pixel_col] == '1':
            adjacent_pixel.add( (pixel_row+1, pixel_col) )
        if pixel_col+1 < len(grid[0]) and grid[pixel_row][pixel_col+1] == '1':
            adjacent_pixel.add( (pixel_row, pixel_col+1) )
        if pixel_row-1 >=0  and grid[pixel_row-1][pixel_col] == '1':
            adjacent_pixel.add( (pixel_row-1, pixel_col) )
        if pixel_col-1 >= 0  and grid[pixel_row][pixel_col-1] == '1':
            adjacent_pixel.add( (pixel_row, pixel_col-1) )
        return adjacent_pixel

    # @param grid, a list of list of characters
    # @return an integer
    def numIslands(self, grid):
        if not grid:
            return 0
        row       = len(grid)
        col       = len(grid[0])
        count     = 0
        open_set  = set()
        close_set = set()
        for index_row in range(row):
            for index_col in range(col):
                if grid[index_row][index_col] == '0' or (index_row, index_col) in close_set:
                    continue
                open_set.add( (index_row, index_col) )
                count += 1
                # BFS
                while len(open_set) > 0:
                    pixel = open_set.pop()
                    (pixel_row, pixel_col) = pixel
                    close_set.add( (pixel_row, pixel_col) )
                    adjacent_pixel = self.adjacentPixel(pixel, grid)
                    open_set.update( adjacent_pixel - close_set )
        return count

if __name__ == '__main__':
    solution = Solution()
    grid1 = ['11110', '11010', '11000', '00000']
    grid2 = ['11000', '11000', '00100', '00011']
    grid3 = ["111","010","111"]
    print solution.numIslands(grid1)
    print solution.numIslands(grid2)
    print solution.numIslands(grid3)


text:
require 'rails_helper'

describe Twitter do
  describe '#create_access_token' do
    let(:user) {}
    let(:token) {Twitter.create_access_token(User.first)}
    it "generates an OAuth::Token object" do
      token.should be_kind_of(OAuth::Token)
    end
  end
end


text:
package com.nshmura.recyclertablayout.demo.imitationloop;

import com.nshmura.recyclertablayout.demo.R;

import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Shinichi Nishimura on 2015/07/24.
 */
public class DemoImitationLoopPagerAdapter extends PagerAdapter {

    private static final int NUMBER_OF_LOOPS = 10000;

    private List<String> mItems = new ArrayList<>();

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = LayoutInflater.from(container.getContext())
                .inflate(R.layout.layout_page, container, false);

        TextView textView = view.findViewById(R.id.title);
        textView.setText("Page: " + getValueAt(position));
        container.addView(view);

        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return mItems.size() * NUMBER_OF_LOOPS;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public String getPageTitle(int position) {
        return getValueAt(position);
    }

    public void addAll(List<String> items) {
        mItems = new ArrayList<>(items);
    }

    public int getCenterPosition(int position) {
        return mItems.size() * NUMBER_OF_LOOPS / 2 + position;
    }

    public String getValueAt(int position) {
        if (mItems.size() == 0) {
            return null;
        }
        return mItems.get(position % mItems.size());
    }
}


text:
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { ToastComponent } from '../shared/toast/toast.component';
import { AuthService } from '../services/auth.service';
import { UserService } from '../services/user.service';
import { AdminComponent } from './admin.component';
import { of, Observable } from 'rxjs';

class AuthServiceMock {
  currentUser = { _id: '1', username: 'test1@example.com', role: 'admin' };
}

class UserServiceMock {
  mockUsers = [
    { _id: '1', username: 'Test 1', email: 'test1@example.com', role: 'admin' },
    { _id: '2', username: 'Test 2', email: 'test2@example.com', role: 'user' },
  ];
  getUsers(): Observable<object[]> {
    return of(this.mockUsers);
  }
}

describe('Component: Admin', () => {
  let component: AdminComponent;
  let fixture: ComponentFixture<AdminComponent>;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [ AdminComponent ],
      providers: [
        ToastComponent,
        { provide: AuthService, useClass: AuthServiceMock },
        { provide: UserService, useClass: UserServiceMock },
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AdminComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should display the page header text', () => {
    const el = fixture.debugElement.query(By.css('h4')).nativeElement;
    expect(el.textContent).toContain('Registered users (2)');
  });

  it('should display the text for no users', () => {
    component.users = [];
    fixture.detectChanges();
    const headerEl = fixture.debugElement.query(By.css('h4')).nativeElement;
    expect(headerEl.textContent).toContain('Registered users (0)');
    const tdEl = fixture.debugElement.query(By.css('td')).nativeElement;
    expect(tdEl.textContent).toContain('There are no registered users');
  });

  it('should display registered users', () => {
    const tds = fixture.debugElement.queryAll(By.css('td'));
    expect(tds[0].nativeElement.textContent).toContain('Test 1');
    expect(tds[1].nativeElement.textContent).toContain('test1@example.com');
    expect(tds[2].nativeElement.textContent).toContain('admin');
    expect(tds[4].nativeElement.textContent).toContain('Test 2');
    expect(tds[5].nativeElement.textContent).toContain('test2@example.com');
    expect(tds[6].nativeElement.textContent).toContain('user');
  });

  it('should display the delete buttons', () => {
    const [btnDelete1, btnDelete2] = fixture.debugElement.queryAll(By.css('button'));
    expect(btnDelete1.nativeElement.disabled).toBeTruthy();
    expect(btnDelete1.nativeElement.textContent).toContain('Delete');
    expect(btnDelete2.nativeElement.disabled).toBeFalsy();
    expect(btnDelete2.nativeElement.textContent).toContain('Delete');
  });

});


text:
package ai.nxt.seqpred;

/**
 * Created by Jeppe Hallgren on 25/07/15.
 */
public class JsonModel {
}


text:
declare namespace java {
  namespace lang {

    class Character implements java.io.Serializable, java.lang.Comparable<java.lang.Character> {
      public static readonly MIN_RADIX: int
      public static readonly MAX_RADIX: int
      public static readonly MIN_VALUE: char
      public static readonly MAX_VALUE: char
      public static readonly TYPE: java.lang.Class<java.lang.Character>
      public static readonly UNASSIGNED: byte
      public static readonly UPPERCASE_LETTER: byte
      public static readonly LOWERCASE_LETTER: byte
      public static readonly TITLECASE_LETTER: byte
      public static readonly MODIFIER_LETTER: byte
      public static readonly OTHER_LETTER: byte
      public static readonly NON_SPACING_MARK: byte
      public static readonly ENCLOSING_MARK: byte
      public static readonly COMBINING_SPACING_MARK: byte
      public static readonly DECIMAL_DIGIT_NUMBER: byte
      public static readonly LETTER_NUMBER: byte
      public static readonly OTHER_NUMBER: byte
      public static readonly SPACE_SEPARATOR: byte
      public static readonly LINE_SEPARATOR: byte
      public static readonly PARAGRAPH_SEPARATOR: byte
      public static readonly CONTROL: byte
      public static readonly FORMAT: byte
      public static readonly PRIVATE_USE: byte
      public static readonly SURROGATE: byte
      public static readonly DASH_PUNCTUATION: byte
      public static readonly START_PUNCTUATION: byte
      public static readonly END_PUNCTUATION: byte
      public static readonly CONNECTOR_PUNCTUATION: byte
      public static readonly OTHER_PUNCTUATION: byte
      public static readonly MATH_SYMBOL: byte
      public static readonly CURRENCY_SYMBOL: byte
      public static readonly MODIFIER_SYMBOL: byte
      public static readonly OTHER_SYMBOL: byte
      public static readonly INITIAL_QUOTE_PUNCTUATION: byte
      public static readonly FINAL_QUOTE_PUNCTUATION: byte
      static readonly ERROR: int
      public static readonly DIRECTIONALITY_UNDEFINED: byte
      public static readonly DIRECTIONALITY_LEFT_TO_RIGHT: byte
      public static readonly DIRECTIONALITY_RIGHT_TO_LEFT: byte
      public static readonly DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC: byte
      public static readonly DIRECTIONALITY_EUROPEAN_NUMBER: byte
      public static readonly DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR: byte
      public static readonly DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR: byte
      public static readonly DIRECTIONALITY_ARABIC_NUMBER: byte
      public static readonly DIRECTIONALITY_COMMON_NUMBER_SEPARATOR: byte
      public static readonly DIRECTIONALITY_NONSPACING_MARK: byte
      public static readonly DIRECTIONALITY_BOUNDARY_NEUTRAL: byte
      public static readonly DIRECTIONALITY_PARAGRAPH_SEPARATOR: byte
      public static readonly DIRECTIONALITY_SEGMENT_SEPARATOR: byte
      public static readonly DIRECTIONALITY_WHITESPACE: byte
      public static readonly DIRECTIONALITY_OTHER_NEUTRALS: byte
      public static readonly DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING: byte
      public static readonly DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE: byte
      public static readonly DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING: byte
      public static readonly DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE: byte
      public static readonly DIRECTIONALITY_POP_DIRECTIONAL_FORMAT: byte
      public static readonly DIRECTIONALITY_LEFT_TO_RIGHT_ISOLATE: byte
      public static readonly DIRECTIONALITY_RIGHT_TO_LEFT_ISOLATE: byte
      public static readonly DIRECTIONALITY_FIRST_STRONG_ISOLATE: byte
      public static readonly DIRECTIONALITY_POP_DIRECTIONAL_ISOLATE: byte
      public static readonly MIN_HIGH_SURROGATE: char
      public static readonly MAX_HIGH_SURROGATE: char
      public static readonly MIN_LOW_SURROGATE: char
      public static readonly MAX_LOW_SURROGATE: char
      public static readonly MIN_SURROGATE: char
      public static readonly MAX_SURROGATE: char
      public static readonly MIN_SUPPLEMENTARY_CODE_POINT: int
      public static readonly MIN_CODE_POINT: int
      public static readonly MAX_CODE_POINT: int
      public static readonly SIZE: int
      public static readonly BYTES: int
      static readonly $assertionsDisabled: boolean
      public constructor(arg0: string | java.lang.Character)
      public static valueOf(arg0: string | java.lang.Character): string
      public charValue(): string
      public hashCode(): number
      public static hashCode(arg0: string | java.lang.Character): number
      public equals(arg0: java.lang.Object | any): boolean
      public toString(): java.lang.String
      public static toString(arg0: string | java.lang.Character): java.lang.String
      public static toString(arg0: number | java.lang.Integer): java.lang.String
      public static isValidCodePoint(arg0: number | java.lang.Integer): boolean
      public static isBmpCodePoint(arg0: number | java.lang.Integer): boolean
      public static isSupplementaryCodePoint(arg0: number | java.lang.Integer): boolean
      public static isHighSurrogate(arg0: string | java.lang.Character): boolean
      public static isLowSurrogate(arg0: string | java.lang.Character): boolean
      public static isSurrogate(arg0: string | java.lang.Character): boolean
      public static isSurrogatePair(arg0: string | java.lang.Character, arg1: string | java.lang.Character): boolean
      public static charCount(arg0: number | java.lang.Integer): number
      public static toCodePoint(arg0: string | java.lang.Character, arg1: string | java.lang.Character): number
      public static codePointAt(arg0: string | java.lang.CharSequence, arg1: number | java.lang.Integer): number
      public static codePointAt(arg0: string[] | java.lang.Character[], arg1: number | java.lang.Integer): number
      public static codePointAt(arg0: string[] | java.lang.Character[], arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): number
      static codePointAtImpl(arg0: string[] | java.lang.Character[], arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): number
      public static codePointBefore(arg0: string | java.lang.CharSequence, arg1: number | java.lang.Integer): number
      public static codePointBefore(arg0: string[] | java.lang.Character[], arg1: number | java.lang.Integer): number
      public static codePointBefore(arg0: string[] | java.lang.Character[], arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): number
      static codePointBeforeImpl(arg0: string[] | java.lang.Character[], arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): number
      public static highSurrogate(arg0: number | java.lang.Integer): string
      public static lowSurrogate(arg0: number | java.lang.Integer): string
      public static toChars(arg0: number | java.lang.Integer, arg1: string[] | java.lang.Character[], arg2: number | java.lang.Integer): number
      public static toChars(arg0: number | java.lang.Integer): string[]
      static toSurrogates(arg0: number | java.lang.Integer, arg1: string[] | java.lang.Character[], arg2: number | java.lang.Integer): void
      public static codePointCount(arg0: string | java.lang.CharSequence, arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): number
      public static codePointCount(arg0: string[] | java.lang.Character[], arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): number
      static codePointCountImpl(arg0: string[] | java.lang.Character[], arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): number
      public static offsetByCodePoints(arg0: string | java.lang.CharSequence, arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): number
      public static offsetByCodePoints(arg0: string[] | java.lang.Character[], arg1: number | java.lang.Integer, arg2: number | java.lang.Integer, arg3: number | java.lang.Integer, arg4: number | java.lang.Integer): number
      static offsetByCodePointsImpl(arg0: string[] | java.lang.Character[], arg1: number | java.lang.Integer, arg2: number | java.lang.Integer, arg3: number | java.lang.Integer, arg4: number | java.lang.Integer): number
      public static isLowerCase(arg0: string | java.lang.Character): boolean
      public static isLowerCase(arg0: number | java.lang.Integer): boolean
      public static isUpperCase(arg0: string | java.lang.Character): boolean
      public static isUpperCase(arg0: number | java.lang.Integer): boolean
      public static isTitleCase(arg0: string | java.lang.Character): boolean
      public static isTitleCase(arg0: number | java.lang.Integer): boolean
      public static isDigit(arg0: string | java.lang.Character): boolean
      public static isDigit(arg0: number | java.lang.Integer): boolean
      public static isDefined(arg0: string | java.lang.Character): boolean
      public static isDefined(arg0: number | java.lang.Integer): boolean
      public static isLetter(arg0: string | java.lang.Character): boolean
      public static isLetter(arg0: number | java.lang.Integer): boolean
      public static isLetterOrDigit(arg0: string | java.lang.Character): boolean
      public static isLetterOrDigit(arg0: number | java.lang.Integer): boolean
      public static isJavaLetter(arg0: string | java.lang.Character): boolean
      public static isJavaLetterOrDigit(arg0: string | java.lang.Character): boolean
      public static isAlphabetic(arg0: number | java.lang.Integer): boolean
      public static isIdeographic(arg0: number | java.lang.Integer): boolean
      public static isJavaIdentifierStart(arg0: string | java.lang.Character): boolean
      public static isJavaIdentifierStart(arg0: number | java.lang.Integer): boolean
      public static isJavaIdentifierPart(arg0: string | java.lang.Character): boolean
      public static isJavaIdentifierPart(arg0: number | java.lang.Integer): boolean
      public static isUnicodeIdentifierStart(arg0: string | java.lang.Character): boolean
      public static isUnicodeIdentifierStart(arg0: number | java.lang.Integer): boolean
      public static isUnicodeIdentifierPart(arg0: string | java.lang.Character): boolean
      public static isUnicodeIdentifierPart(arg0: number | java.lang.Integer): boolean
      public static isIdentifierIgnorable(arg0: string | java.lang.Character): boolean
      public static isIdentifierIgnorable(arg0: number | java.lang.Integer): boolean
      public static toLowerCase(arg0: string | java.lang.Character): string
      public static toLowerCase(arg0: number | java.lang.Integer): number
      public static toUpperCase(arg0: string | java.lang.Character): string
      public static toUpperCase(arg0: number | java.lang.Integer): number
      public static toTitleCase(arg0: string | java.lang.Character): string
      public static toTitleCase(arg0: number | java.lang.Integer): number
      public static digit(arg0: string | java.lang.Character, arg1: number | java.lang.Integer): number
      public static digit(arg0: number | java.lang.Integer, arg1: number | java.lang.Integer): number
      public static getNumericValue(arg0: string | java.lang.Character): number
      public static getNumericValue(arg0: number | java.lang.Integer): number
      public static isSpace(arg0: string | java.lang.Character): boolean
      public static isSpaceChar(arg0: string | java.lang.Character): boolean
      public static isSpaceChar(arg0: number | java.lang.Integer): boolean
      public static isWhitespace(arg0: string | java.lang.Character): boolean
      public static isWhitespace(arg0: number | java.lang.Integer): boolean
      public static isISOControl(arg0: string | java.lang.Character): boolean
      public static isISOControl(arg0: number | java.lang.Integer): boolean
      public static getType(arg0: string | java.lang.Character): number
      public static getType(arg0: number | java.lang.Integer): number
      public static forDigit(arg0: number | java.lang.Integer, arg1: number | java.lang.Integer): string
      public static getDirectionality(arg0: string | java.lang.Character): number
      public static getDirectionality(arg0: number | java.lang.Integer): number
      public static isMirrored(arg0: string | java.lang.Character): boolean
      public static isMirrored(arg0: number | java.lang.Integer): boolean
      public compareTo(arg0: string | java.lang.Character): number
      public static compare(arg0: string | java.lang.Character, arg1: string | java.lang.Character): number
      static toUpperCaseEx(arg0: number | java.lang.Integer): number
      static toUpperCaseCharArray(arg0: number | java.lang.Integer): string[]
      public static reverseBytes(arg0: string | java.lang.Character): string
      public static getName(arg0: number | java.lang.Integer): java.lang.String
      public static codePointOf(arg0: java.lang.String | string): number
      public compareTo(arg0: java.lang.Object | any): number
    }

  }
}


text:
Edge

### Version Introduced
4.6.2

### Version Reverted
4.7

### Source Analyzer Status
NotPlanned

### Change Description

<xref:System.Windows.Controls.DataGrid.ScrollIntoView(System.Object)>
will work asynchronously when column virtualization is enabled but the column
widths have not yet been determined.  If columns are removed before the
asynchronous work happens, an
<xref:System.ArgumentOutOfRangeException?displayProperty=name> can occur.

- [ ] Quirked
- [ ] Build-time break

### Recommended Action

Any one of the following:
1. Upgrade to .NET 4.7.
2. Install the latest servicing patch for .NET 4.6.2.
3. Avoid removing columns until the asynchronous response to <xref:System.Windows.Controls.DataGrid.ScrollIntoView(System.Object)> has completed.

### Affected APIs
- `M:System.Windows.Controls.DataGrid.ScrollIntoView(System.Object)`
- `M:System.Windows.Controls.DataGrid.ScrollIntoView(System.Object,System.Windows.Controls.DataGridColumn)`

### Category
Windows Presentation Foundation (WPF)

<!--
Original Bug: 272673
-->

<!-- breaking change id: 151 -->


text:
<form id="form">
    Yo000!
</form>


text:
import os
import jwt
import sqlalchemy as sa

from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug.security import check_password_hash, generate_password_hash

db = SQLAlchemy()

def init_models(app):
    db.init_app(app)

def decode_token(token):
    return jwt.decode(token, os.environ.get('JWT_SECRET'))

def encode_token(payload):
    return jwt.encode(payload, os.environ.get('JWT_SECRET'))

class Item(db.Model):

    __tablename__ = 'items'

    id = sa.Column('id', sa.Integer, primary_key=True)
    name = sa.Column('name', sa.String(255), nullable=False)
    is_bought = sa.Column('is_bought', sa.Boolean, default=False,
                          nullable=False)
    created = sa.Column('created', sa.DateTime, default=sa.func.now(),
                        nullable=False)
    modified = sa.Column('modified', sa.DateTime, default=sa.func.now(),
                         onupdate=sa.func.now(), nullable=False)

    def as_dict(self):
        return dict(id=self.id, name=self.name, is_bought=self.is_bought)

class User(db.Model):

    __tablename__ = 'users'

    id = sa.Column('id', sa.Integer, primary_key=True)
    username = sa.Column('username', sa.String(128), nullable=False,
                         unique=True)
    password = sa.Column('password', sa.String(128), nullable=False)

    def __init__(self, username, password):
        self.username = username
        self.password = generate_password_hash(password)

    @staticmethod
    def by_token(token):
        payload = decode_token(token)
        return User.query.filter(User.id == payload.get('id')).first()

    @staticmethod
    def by_username(username):
        return User.query.filter(User.username == username).first()

    def check_password(self, password):
        return check_password_hash(self.password, password)

    def token(self):
        return encode_token({'id': self.id})


text:
module Subscriber
  class UserMailer < ApplicationMailer

    # Subject can be set in your I18n file at config/locales/en.yml
    # with the following lookup:
    #
    #   en.user_mailer.password_reset.subject
    #
    default from: '"rankedHiRe Support" <support@rankedhire.com>'

    def sign_up_success(user)
      @user = user
      @inviter = User.find(user.organization.try(:owner_id)) if user.organization
      p "*******************************"
      p @user.password
      mail :to => user.email, :subject => "You've Been Invited To Join rankedHiRe"
    end

    def vendor_sign_up_success(user)
      @user = user
      @inviter = @user.member.account.owner
      @subdomain = @user.member.account.subdomain
      p "*******************************"
      p @user.password
      mail :to => user.email, :subject => "You've Been Invited To Join rankedHiRe"
    end

    def sign_up_agency_success(user)
      @user = user
      mail :to => user.email, :subject => "Placing More Talent with rankedHiRe"
    end

    def sign_up_client_success(user)
      @user = user
      mail :to => user.email, :subject => "Finding the Best Talent with rankedHiRe"
    end

    def approval_email(user)
      @user = user
      mail :to => "support@rankedhire.com", :subject => "A New User Has Signed Up"
    end

    def password_reset(user)
      @user = user
      mail :to => user.email, :subject => "Password Reset"
    end
  end
end


text:
ActiveRecord::Schema.define(version: 20170813190137) do

  create_table "allies", force: :cascade do |t|
    t.integer "value"
    t.integer "player_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["player_id"], name: "index_allies_on_player_id"
  end

  create_table "distractions", force: :cascade do |t|
    t.integer "value"
    t.integer "player_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["player_id"], name: "index_distractions_on_player_id"
  end

  create_table "encounters", force: :cascade do |t|
    t.integer "value"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "game_player", force: :cascade do |t|
    t.integer "game_id"
    t.integer "player_id"
    t.index ["game_id"], name: "index_game_player_on_game_id"
    t.index ["player_id"], name: "index_game_player_on_player_id"
  end

  create_table "games", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "name"
    t.integer "round", default: 1
    t.integer "turn"
  end

  create_table "players", force: :cascade do |t|
    t.string "name"
    t.string "color"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "game_id"
    t.integer "position", default: 0
  end

  create_table "resources", force: :cascade do |t|
    t.integer "value"
    t.integer "player_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["player_id"], name: "index_resources_on_player_id"
  end

  create_table "spaces", force: :cascade do |t|
    t.string "name"
    t.integer "position"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end