text:
package com.accela.tetrixgame.gamelogic.uisupport;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.ImageObserver;

import com.accela.tetrixgame.gamelogic.gameData.GameData;

/**
 *
 * 绘制游戏区域的边界
 *
 */
public class GridPainter extends Painter
{
	/**
	 * 绘制游戏区域的边界
	 */
	@Override
	protected void paintImpl(Graphics g, Point orign, ImageObserver observer,
			GameData gameData, double scale)
	{
		final int GRID_WIDTH = gameData.getGridWidth();

		g.setColor(Color.WHITE);

		g.drawRect(orign.x,
				orign.y,
				(int) ((gameData.getColumnNum() * gameData.getBlockWidth() + 2 * GRID_WIDTH) * scale),
				(int) ((gameData.getRowNum() * gameData.getBlockHeight() + 2 * GRID_WIDTH) * scale));
		g.drawRect(orign.x + (int) (GRID_WIDTH * scale),
				orign.y + (int) (GRID_WIDTH * scale),
				(int) (gameData.getColumnNum() * gameData.getBlockWidth() * scale),
				(int) (gameData.getRowNum() * gameData.getBlockHeight() * scale));

	}

}


text:
"""Pre-defined predicates for nodes."""

from ..utils import part_has_modifier
from ...graph import BELGraph
from ....constants import (
    ACTIVITY,
    DEGRADATION,
    SOURCE_MODIFIER,
    TARGET_MODIFIER,
    TRANSLOCATION,
)
from ....dsl import BaseEntity

__all__ = [
    "has_edge_modifier",
    "has_activity",
    "is_degraded",
    "is_translocated",
]

def has_edge_modifier(graph: BELGraph, node: BaseEntity, modifier: str) -> bool:
    """Return true if over any of a nodes edges, it has a given modifier.

     Modifier can be one of:

     - :data:`pybel.constants.ACTIVITY`,
     - :data:`pybel.constants.DEGRADATION`
     - :data:`pybel.constants.TRANSLOCATION`.

    :param modifier: One of :data:`pybel.constants.ACTIVITY`, :data:`pybel.constants.DEGRADATION`, or
                        :data:`pybel.constants.TRANSLOCATION`
    """
    modifier_in_subject = any(
        part_has_modifier(d, SOURCE_MODIFIER, modifier) for _, _, d in graph.out_edges(node, data=True)
    )

    modifier_in_object = any(
        part_has_modifier(d, TARGET_MODIFIER, modifier) for _, _, d in graph.in_edges(node, data=True)
    )

    return modifier_in_subject or modifier_in_object

def has_activity(graph: BELGraph, node: BaseEntity) -> bool:
    """Return true if over any of the node's edges, it has a molecular activity."""
    return has_edge_modifier(graph, node, ACTIVITY)

def is_degraded(graph: BELGraph, node: BaseEntity) -> bool:
    """Return true if over any of the node's edges, it is degraded."""
    return has_edge_modifier(graph, node, DEGRADATION)

def is_translocated(graph: BELGraph, node: BaseEntity) -> bool:
    """Return true if over any of the node's edges, it is translocated."""
    return has_edge_modifier(graph, node, TRANSLOCATION)

redpajama_set_name: RedPajamaGithub


text:
from flask import Flask, render_template

# Define the WSGI application object
app = Flask(__name__)

########################################################################
# HTTP error handlers

@app.errorhandler(403)
def forbidden_403(exception):
    return render_template('403.html'), 403

@app.errorhandler(404)
def not_found_404(error):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_server_error_500(error):
#    db.session.rollback()
    return render_template('500.html'), 500

########################################################################

from . import controllers

# That's all!


text:
using System;
using NUnit.Framework;
using Palaso.UI.WindowsForms.ClearShare;

namespace PalasoUIWindowsForms.Tests.ClearShare
{
	[TestFixture]
	public class OlacSystemTests
	{
		private OlacSystem _system;

		[SetUp]
		public void TestSetup()
		{
			_system = new OlacSystem();
		}

		[Test]
		public void GetContributorElement_NullRoleCode_ThrowsException()
		{
			Assert.Throws<ArgumentNullException>(() => _system.GetContributorElement(null, "name"));
		}

		[Test]
		public void GetContributorElement_NullName_ThrowsException()
		{
			Assert.Throws<ArgumentNullException>(() => _system.GetContributorElement("code", null));
		}

		[Test]
		public void GetContributorElement_HasGoodRoleCodeAndName_ReturnsElement()
		{
			Assert.AreEqual("<dc:contributor xsi:type='olac:role' olac:code='secret' " +
				"view='Compiler'>willy</dc:contributor>", _system.GetContributorElement("secret", "willy"));
		}

		[Test]
		public void TryGetRoleByCode_TryInvalidCode_ReturnsFalse()
		{
			Role role;
			Assert.IsFalse(_system.TryGetRoleByCode("junk", out role));
		}

		[Test]
		public void TryGetRoleByCode_TryNullCode_ReturnsFalse()
		{
			Role role;
			Assert.IsFalse(_system.TryGetRoleByCode(null, out role));
		}

		[Test]
		public void TryGetRoleByCode_TryGoodCode_ReturnsTrueAndRole()
		{
			Role role;
			Assert.IsTrue(_system.TryGetRoleByCode("developer", out role));
			Assert.AreEqual("developer", role.Code);
		}

		[Test]
		public void TryGetRoleByName_TryInvalidName_ReturnsFalse()
		{
			Role role;
			Assert.IsFalse(_system.TryGetRoleByName("junk", out role));
		}

		[Test]
		public void TryGetRoleByName_TryNullName_ReturnsFalse()
		{
			Role role;
			Assert.IsFalse(_system.TryGetRoleByName(null, out role));
		}

		[Test]
		public void TryGetRoleByName_TryGoodName_ReturnsTrueAndRole()
		{
			Role role;
			Assert.IsTrue(_system.TryGetRoleByName("Developer", out role));
			Assert.AreEqual("Developer", role.Name);
		}

		[Test]
		public void GetRoleByCodeOrThrow_TryInvalidCode_ThrowsException()
		{
			Assert.Throws<ArgumentOutOfRangeException>(() => _system.GetRoleByCodeOrThrow("junk"));
		}

		[Test]
		public void GetRoleByCodeOrThrow_TryNullCode_ThrowsException()
		{
			Assert.Throws<ArgumentOutOfRangeException>(() => _system.GetRoleByCodeOrThrow(null));
		}

		[Test]
		public void GetRoleByCodeOrThrow_TryGoodCode_ReturnsRole()
		{
			Assert.AreEqual("developer", _system.GetRoleByCodeOrThrow("developer").Code);
		}
	}
}


text:
package com.amazonaws.services.servicecatalog.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.servicecatalog.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * BatchDisassociateServiceActionFromProvisioningArtifactRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class BatchDisassociateServiceActionFromProvisioningArtifactRequestMarshaller {

    private static final MarshallingInfo<List> SERVICEACTIONASSOCIATIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ServiceActionAssociations").build();
    private static final MarshallingInfo<String> ACCEPTLANGUAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AcceptLanguage").build();

    private static final BatchDisassociateServiceActionFromProvisioningArtifactRequestMarshaller instance = new BatchDisassociateServiceActionFromProvisioningArtifactRequestMarshaller();

    public static BatchDisassociateServiceActionFromProvisioningArtifactRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(BatchDisassociateServiceActionFromProvisioningArtifactRequest batchDisassociateServiceActionFromProvisioningArtifactRequest,
            ProtocolMarshaller protocolMarshaller) {

        if (batchDisassociateServiceActionFromProvisioningArtifactRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(batchDisassociateServiceActionFromProvisioningArtifactRequest.getServiceActionAssociations(),
                    SERVICEACTIONASSOCIATIONS_BINDING);
            protocolMarshaller.marshall(batchDisassociateServiceActionFromProvisioningArtifactRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<?php

namespace CommerceGuys\Tax\Resolver\TaxRate;

use CommerceGuys\Tax\TaxableInterface;
use CommerceGuys\Tax\Model\TaxRateInterface;
use CommerceGuys\Tax\Model\TaxTypeInterface;
use CommerceGuys\Tax\Resolver\Context;

/**
 * Chain tax rate resolver interface.
 *
 * Sorts the provided tax rate resolvers by priority and invokes them
 * individually until one of them returns a result.
 */
interface ChainTaxRateResolverInterface
{
    /**
     * Adds a resolver.
     *
     * @param TaxRateResolverInterface $resolver The resolver.
     * @param int                      $priority The priority of the resolver.
     */
    public function addResolver(TaxRateResolverInterface $resolver, $priority = 0);

    /**
     * Gets all added resolvers, sorted by priority.
     *
     * @return TaxRateResolverInterface[] An array of tax rate resolvers.
     */
    public function getResolvers();

    /**
     * Resolves the tax rate by invoking the individual resolvers.
     *
     * @param TaxTypeInterface $taxTypes A previously resolved tax type.
     * @param TaxableInterface $taxable  The taxable object.
     * @param Context          $context  The context.
     *
     * @return TaxRateInterface|null The resolved tax rate, or null.
     */
    public function resolve(TaxTypeInterface $taxType, TaxableInterface $taxable, Context $context);
}


text:
package org.camunda.bpm.dmn.engine.impl.transform;

import org.camunda.bpm.dmn.engine.impl.DmnDecisionTableInputImpl;
import org.camunda.bpm.dmn.engine.impl.spi.transform.DmnElementTransformContext;
import org.camunda.bpm.dmn.engine.impl.spi.transform.DmnElementTransformHandler;
import org.camunda.bpm.model.dmn.instance.Input;

public class DmnDecisionTableInputTransformHandler implements DmnElementTransformHandler<Input, DmnDecisionTableInputImpl> {

  public DmnDecisionTableInputImpl handleElement(DmnElementTransformContext context, Input input) {
    return createFromInput(context, input);
  }

  protected DmnDecisionTableInputImpl createFromInput(DmnElementTransformContext context, Input input) {
    DmnDecisionTableInputImpl decisionTableInput = createDmnElement(context, input);

    decisionTableInput.setId(input.getId());
    decisionTableInput.setName(input.getLabel());
    decisionTableInput.setInputVariable(input.getCamundaInputVariable());

    return decisionTableInput;
  }

  protected DmnDecisionTableInputImpl createDmnElement(DmnElementTransformContext context, Input input) {
    return new DmnDecisionTableInputImpl();
  }

}


text:
package org.wso2.carbon.identity.user.endpoint.dto;

import io.swagger.annotations.ApiModel;
import java.util.ArrayList;
import java.util.List;

import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.*;

import javax.validation.constraints.NotNull;

/**
 * Challenge questions configured for the user.
 **/

@ApiModel(description = "Challenge questions configured for the user.")
public class ChallengeQuestionsDTO extends ArrayList<String> {

  @Override
  public String toString()  {
    StringBuilder sb = new StringBuilder();
    sb.append("class ChallengeQuestionsDTO {\n");
    sb.append("  " + super.toString()).append("\n");
    sb.append("}\n");
    return sb.toString();
  }
}


text:
using System.Net.Http;
using System.Threading.Tasks;

namespace NetHttp
{
    public partial class NetHttpClient
    {
        public async Task<IHttpResponse<TResponse>> GetAsync<TResponse>(string url)
        {
            var response = await ReadAsync<TResponse>(HttpMethod.Get, url).ConfigureAwait(false);
            return response;
        }
    }
}


text:
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""General functions which are useful throughout this project."""

import json
import logging
import os
import re
import time
import urllib

from apiclient import discovery
from apiclient import errors
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.api import urlfetch_errors
from google.appengine.api import users
from google.appengine.ext import ndb
import httplib2
from oauth2client import client

from dashboard.common import stored_object

SHERIFF_DOMAINS_KEY = 'sheriff_domains_key'
IP_WHITELIST_KEY = 'ip_whitelist'
SERVICE_ACCOUNT_KEY = 'service_account'
EMAIL_SCOPE = 'https://www.googleapis.com/auth/userinfo.email'
_PROJECT_ID_KEY = 'project_id'
_DEFAULT_CUSTOM_METRIC_VAL = 1

def _GetNowRfc3339():
  """Returns the current time formatted per RFC 3339."""
  return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())

def TickMonitoringCustomMetric(metric_name):
  """Increments the stackdriver custom metric with the given name.

  This is used for cron job monitoring; if these metrics stop being received
  an alert mail is sent. For more information on custom metrics, see
  https://cloud.google.com/monitoring/custom-metrics/using-custom-metrics

  Args:
    metric_name: The name of the metric being monitored.
  """
  credentials = client.GoogleCredentials.get_application_default()
  monitoring = discovery.build(
      'monitoring', 'v3', credentials=credentials)
  now = _GetNowRfc3339()
  project_id = stored_object.Get(_PROJECT_ID_KEY)
  points = [{
      'interval': {
          'startTime': now,
          'endTime': now,
      },
      'value': {
          'int64Value': _DEFAULT_CUSTOM_METRIC_VAL,
      },
  }]
  write_request = monitoring.projects().timeSeries().create(
      name='projects/%s' %project_id,
      body={'timeSeries': [{
          'metric': {
              'type': 'custom.googleapis.com/%s' % metric_name,
          },
          'points': points
      }]})
  write_request.execute()

def TestPath(key):
  """Returns the test path for a TestMetadata from an ndb.Key.

  A "test path" is just a convenient string representation of an ndb.Key.
  Each test path corresponds to one ndb.Key, which can be used to get an
  entity.

  Args:
    key: An ndb.Key where all IDs are string IDs.

  Returns:
    A test path string.
  """
  if key.kind() == 'Test':
    # The Test key looks like ('Master', 'name', 'Bot', 'name', 'Test' 'name'..)
    # Pull out every other entry and join with '/' to form the path.
    return '/'.join(key.flat()[1::2])
  assert key.kind() == 'TestMetadata' or key.kind() == 'TestContainer'
  return key.id()

def TestSuiteName(test_key):
  """Returns the test suite name for a given TestMetadata key."""
  assert test_key.kind() == 'TestMetadata'
  parts = test_key.id().split('/')
  return parts[2]

def TestKey(test_path):
  """Returns the ndb.Key that corresponds to a test path."""
  if test_path is None:
    return None
  path_parts = test_path.split('/')
  if path_parts is None:
    return None
  if len(path_parts) < 3:
    key_list = [('Master', path_parts[0])]
    if len(path_parts) > 1:
      key_list += [('Bot', path_parts[1])]
    return ndb.Key(pairs=key_list)
  return ndb.Key('TestMetadata', test_path)

def TestMetadataKey(key_or_string):
  """Convert the given (Test or TestMetadata) key or test_path string to a
     TestMetadata key.

  We are in the process of converting from Test entities to TestMetadata.
  Unfortunately, we haver trillions of Row entities which have a parent_test
  property set to a Test, and it's not possible to migrate them all. So we
  use the Test key in Row queries, and convert between the old and new format.

  Note that the Test entities which the keys refer to may be deleted; the
  queries over keys still work.
  """
  if key_or_string is None:
    return None
  if isinstance(key_or_string, basestring):
    return ndb.Key('TestMetadata', key_or_string)
  if key_or_string.kind() == 'TestMetadata':
    return key_or_string
  if key_or_string.kind() == 'Test':
    return ndb.Key('TestMetadata', TestPath(key_or_string))

def OldStyleTestKey(key_or_string):
  """Get the key for the old style Test entity corresponding to this key or
     test_path.

  We are in the process of converting from Test entities to TestMetadata.
  Unfortunately, we haver trillions of Row entities which have a parent_test
  property set to a Test, and it's not possible to migrate them all. So we
  use the Test key in Row queries, and convert between the old and new format.

  Note that the Test entities which the keys refer to may be deleted; the
  queries over keys still work.
  """
  if key_or_string is None:
    return None
  elif isinstance(key_or_string, ndb.Key) and key_or_string.kind() == 'Test':
    return key_or_string
  if (isinstance(key_or_string, ndb.Key) and
      key_or_string.kind() == 'TestMetadata'):
    key_or_string = key_or_string.id()
  assert isinstance(key_or_string, basestring)
  path_parts = key_or_string.split('/')
  key_parts = ['Master', path_parts[0], 'Bot', path_parts[1]]
  for part in path_parts[2:]:
    key_parts += ['Test', part]
  return ndb.Key(*key_parts)

def MostSpecificMatchingPattern(test, pattern_data_tuples):
  """Takes a test and a list of (pattern, data) tuples and returns the data
  for the pattern which most closely matches the test. It does this by
  ordering the matching patterns, and choosing the one with the most specific
  top level match.

  For example, if there was a test Master/Bot/Foo/Bar, then:

  */*/*/Bar would match more closely than */*/*/*
  */*/*/Bar would match more closely than */*/*/Bar.*
  */*/*/Bar.* would match more closely than */*/*/*
  """
  matching_patterns = []
  for p, v in pattern_data_tuples:
    if not TestMatchesPattern(test, p):
      continue
    matching_patterns.append([p, v])

  if not matching_patterns:
    return None

  if type(test) is ndb.Key:
    test_path = TestPath(test)
  else:
    test_path = test.test_path
  test_path_parts = test_path.split('/')

  # This ensures the ordering puts the closest match at index 0
  def CmpPatterns(a, b):
    a_parts = a[0].split('/')
    b_parts = b[0].split('/')
    for a_part, b_part, test_part in reversed(
        zip(a_parts, b_parts, test_path_parts)):
      # We favour a specific match over a partial match, and a partial
      # match over a catch-all * match.
      if a_part == b_part:
        continue
      if a_part == test_part:
        return -1
      if b_part == test_part:
        return 1
      if a_part != '*':
        return -1
      if b_part != '*':
        return 1
      return 0

  matching_patterns.sort(cmp=CmpPatterns)

  return matching_patterns[0][1]

def TestMatchesPattern(test, pattern):
  """Checks whether a test matches a test path pattern.

  Args:
    test: A TestMetadata entity or a TestMetadata key.
    pattern: A test path which can include wildcard characters (*).

  Returns:
    True if it matches, False otherwise.
  """
  if not test:
    return False
  if type(test) is ndb.Key:
    test_path = TestPath(test)
  else:
    test_path = test.test_path
  test_path_parts = test_path.split('/')
  pattern_parts = pattern.split('/')
  if len(test_path_parts) != len(pattern_parts):
    return False
  for test_path_part, pattern_part in zip(test_path_parts, pattern_parts):
    if not _MatchesPatternPart(pattern_part, test_path_part):
      return False
  return True

def _MatchesPatternPart(pattern_part, test_path_part):
  """Checks whether a pattern (possibly with a *) matches the given string.

  Args:
    pattern_part: A string which may contain a wildcard (*).
    test_path_part: Another string.

  Returns:
    True if it matches, False otherwise.
  """
  if pattern_part == '*' or pattern_part == test_path_part:
    return True
  if '*' not in pattern_part:
    return False
  # Escape any other special non-alphanumeric characters.
  pattern_part = re.escape(pattern_part)
  # There are not supposed to be any other asterisk characters, so all
  # occurrences of backslash-asterisk can now be replaced with dot-asterisk.
  re_pattern = re.compile('^' + pattern_part.replace('\\*', '.*') + '$')
  return re_pattern.match(test_path_part)

def TimestampMilliseconds(datetime):
  """Returns the number of milliseconds since the epoch."""
  return int(time.mktime(datetime.timetuple()) * 1000)

def GetTestContainerKey(test):
  """Gets the TestContainer key for the given TestMetadata.

  Args:
    test: Either a TestMetadata entity or its ndb.Key.

  Returns:
    ndb.Key('TestContainer', test path)
  """
  test_path = None
  if type(test) is ndb.Key:
    test_path = TestPath(test)
  else:
    test_path = test.test_path
  return ndb.Key('TestContainer', test_path)

def GetMulti(keys):
  """Gets a list of entities from a list of keys.

  If this user is logged in, this is the same as ndb.get_multi. However, if the
  user is logged out and any of the data is internal only, an AssertionError
  will be raised.

  Args:
    keys: A list of ndb entity keys.

  Returns:
    A list of entities, but no internal_only ones if the user is not logged in.
  """
  if IsInternalUser():
    return ndb.get_multi(keys)
  # Not logged in. Check each key individually.
  entities = []
  for key in keys:
    try:
      entities.append(key.get())
    except AssertionError:
      continue
  return entities

def MinimumAlertRange(alerts):
  """Returns the intersection of the revision ranges for a set of alerts.

  Args:
    alerts: An iterable of Alerts.

  Returns:
    A pair (start, end) if there is a valid minimum range,
    or None if the ranges are not overlapping.
  """
  ranges = [(a.start_revision, a.end_revision) for a in alerts if a]
  return MinimumRange(ranges)

def MinimumRange(ranges):
  """Returns the intersection of the given ranges, or None."""
  if not ranges:
    return None
  starts, ends = zip(*ranges)
  start, end = (max(starts), min(ends))
  if start > end:
    return None
  return start, end

def IsInternalUser():
  """Checks whether the user should be able to see internal-only data."""
  username = users.get_current_user()
  if not username:
    return False
  cached = GetCachedIsInternalUser(username)
  if cached is not None:
    return cached
  is_internal_user = IsGroupMember(identity=username, group='chromeperf-access')
  SetCachedIsInternalUser(username, is_internal_user)
  return is_internal_user

def GetCachedIsInternalUser(username):
  return memcache.get(_IsInternalUserCacheKey(username))

def SetCachedIsInternalUser(username, value):
  memcache.add(_IsInternalUserCacheKey(username), value, time=60*60*24)

def _IsInternalUserCacheKey(username):
  return 'is_internal_user_%s' % username

def IsGroupMember(identity, group):
  """Checks if a user is a group member of using chrome-infra-auth.appspot.com.

  Args:
    identity: User email address.
    group: Group name.

  Returns:
    True if confirmed to be a member, False otherwise.
  """
  cached = GetCachedIsGroupMember(identity, group)
  if cached is not None:
    return cached
  try:
    discovery_url = ('https://chrome-infra-auth.appspot.com'
                     '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest')
    service = discovery.build(
        'auth', 'v1', discoveryServiceUrl=discovery_url,
        http=ServiceAccountHttp())
    request = service.membership(identity=identity, group=group)
    response = request.execute()
    is_member = response['is_member']
    SetCachedIsGroupMember(identity, group, is_member)
    return is_member
  except (errors.HttpError, KeyError, AttributeError) as e:
    logging.error('Failed to check membership of %s: %s', identity, e)
    return False

def GetCachedIsGroupMember(identity, group):
  return memcache.get(_IsGroupMemberCacheKey(identity, group))

def SetCachedIsGroupMember(identity, group, value):
  memcache.add(_IsGroupMemberCacheKey(identity, group), value, time=60*60*24)

def _IsGroupMemberCacheKey(identity, group):
  return 'is_group_member_%s_%s' % (identity, group)

def ServiceAccountHttp(*args, **kwargs):
  """Returns the Credentials of the service account if available."""
  account_details = stored_object.Get(SERVICE_ACCOUNT_KEY)
  if not account_details:
    raise KeyError('Service account credentials not found.')

  client.logger.setLevel(logging.WARNING)
  credentials = client.SignedJwtAssertionCredentials(
      service_account_name=account_details['client_email'],
      private_key=account_details['private_key'],
      scope=EMAIL_SCOPE)

  http = httplib2.Http(*args, **kwargs)
  credentials.authorize(http)
  return http

def IsValidSheriffUser():
  """Checks whether the user should be allowed to triage alerts."""
  user = users.get_current_user()
  sheriff_domains = stored_object.Get(SHERIFF_DOMAINS_KEY)
  if user:
    domain_matched = sheriff_domains and any(
        user.email().endswith('@' + domain) for domain in sheriff_domains)
    return domain_matched or IsGroupMember(
        identity=user, group='project-chromium-tryjob-access')
  return False

def GetIpWhitelist():
  """Returns a list of IP address strings in the whitelist."""
  return stored_object.Get(IP_WHITELIST_KEY)

def BisectConfigPythonString(config):
  """Turns a bisect config dict into a properly formatted Python string.

  Args:
    config: A bisect config dict (see start_try_job.GetBisectConfig)

  Returns:
    A config string suitable to store in a TryJob entity.
  """
  return 'config = %s\n' % json.dumps(
      config, sort_keys=True, indent=2, separators=(',', ': '))

def GetRequestId():
  """Returns the request log ID which can be used to find a specific log."""
  return os.environ.get('REQUEST_LOG_ID')

def Validate(expected, actual):
  """Generic validator for expected keys, values, and types.

  Values are also considered equal if |actual| can be converted to |expected|'s
  type.  For instance:
    _Validate([3], '3')  # Returns True.

  See utils_test.py for more examples.

  Args:
    expected: Either a list of expected values or a dictionary of expected
        keys and type.  A dictionary can contain a list of expected values.
    actual: A value.
  """
  def IsValidType(expected, actual):
    if type(expected) is type and type(actual) is not expected:
      try:
        expected(actual)
      except ValueError:
        return False
    return True

  def IsInList(expected, actual):
    for value in expected:
      try:
        if type(value)(actual) == value:
          return True
      except ValueError:
        pass
    return False

  if not expected:
    return
  expected_type = type(expected)
  actual_type = type(actual)
  if expected_type is list:
    if not IsInList(expected, actual):
      raise ValueError('Invalid value. Expected one of the following: '
                       '%s. Actual: %s.' % (','.join(expected), actual))
  elif expected_type is dict:
    if actual_type is not dict:
      raise ValueError('Invalid type. Expected: %s. Actual: %s.'
                       % (expected_type, actual_type))
    missing = set(expected.keys()) - set(actual.keys())
    if missing:
      raise ValueError('Missing the following properties: %s'
                       % ','.join(missing))
    for key in expected:
      Validate(expected[key], actual[key])
  elif not IsValidType(expected, actual):
    raise ValueError('Invalid type. Expected: %s. Actual: %s.' %
                     (expected, actual_type))

def FetchURL(request_url, skip_status_code=False):
  """Wrapper around URL fetch service to make request.

  Args:
    request_url: URL of request.
    skip_status_code: Skips return code check when True, default is False.

  Returns:
    Response object return by URL fetch, otherwise None when there's an error.
  """
  logging.info('URL being fetched: ' + request_url)
  try:
    response = urlfetch.fetch(request_url)
  except urlfetch_errors.DeadlineExceededError:
    logging.error('Deadline exceeded error checking %s', request_url)
    return None
  except urlfetch_errors.DownloadError as err:
    # DownloadError is raised to indicate a non-specific failure when there
    # was not a 4xx or 5xx status code.
    logging.error(err)
    return None
  if skip_status_code:
    return response
  elif response.status_code != 200:
    logging.error(
        'ERROR %s checking %s', response.status_code, request_url)
    return None
  return response

def GetBuildDetailsFromStdioLink(stdio_link):
  no_details = (None, None, None, None, None)
  m = re.match(r'\[(.+?)\]\((.+?)\)', stdio_link)
  if not m:
    # This wasn't the markdown-style link we were expecting.
    return no_details
  _, link = m.groups()
  m = re.match(
      r'(https{0,1}://.*/([^\/]*)/builders/)'
      r'([^\/]+)/builds/(\d+)/steps/([^\/]+)', link)
  if not m:
    # This wasn't a buildbot formatted link.
    return no_details
  base_url, master, bot, buildnumber, step = m.groups()
  bot = urllib.unquote(bot)
  return base_url, master, bot, buildnumber, step

def GetStdioLinkFromRow(row):
  """Returns the markdown-style buildbot stdio link.

  Due to crbug.com/690630, many row entities have this set to "a_a_stdio_uri"
  instead of "a_stdio_uri".
  """
  return(getattr(row, 'a_stdio_uri', None) or
         getattr(row, 'a_a_stdio_uri', None))

def GetBuildbotStatusPageUriFromStdioLink(stdio_link):
  base_url, _, bot, buildnumber, _ = GetBuildDetailsFromStdioLink(
      stdio_link)
  if not base_url:
    # Can't parse status page
    return None
  return '%s%s/builds/%s' % (base_url, urllib.quote(bot), buildnumber)

def GetLogdogLogUriFromStdioLink(stdio_link):
  base_url, master, bot, buildnumber, step = GetBuildDetailsFromStdioLink(
      stdio_link)
  if not base_url:
    # Can't parse status page
    return None
  bot = re.sub(r'[ \(\)]', '_', bot)
  s_param = urllib.quote('chrome/bb/%s/%s/%s/+/recipes/steps/%s/0/stdout' % (
      master, bot, buildnumber, step), safe='')
  return 'https://luci-logdog.appspot.com/v/?s=%s' % s_param

def GetRowKey(testmetadata_key, revision):
  test_container_key = GetTestContainerKey(testmetadata_key)
  return ndb.Key('Row', revision, parent=test_container_key)


text:
{{lyceum.name}}

{{kpi.name}}

2010-2012

2013-present


text:
/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('userlanding', {
    title: 'Session Demo',
    username: req.session.username
  });
  console.log(req.session.username);
};


text:
@dir src/key_handlers
@brief Key handlers provide the implementation for keycodes.


text:
package cn.hybris.demo.ex10;

import javax.accessibility.Accessible;
import javax.swing.JComponent;

/**
 * This class extends the JComponent GUI control but does not implement the
 * Accessibility interface. This makes this control unable to be processed by
 * screen readers, etc, for people with reading/vision difficulties.
 */
public class MyComponent extends JComponent implements Accessible {
	/**
	 *
	 */
	private static final long serialVersionUID = -257327773162674189L;

}


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;

exports.__esModule = true;
exports.default = void 0;

var React = _interopRequireWildcard(require("react"));

var _View = _interopRequireDefault(require("../View"));

var _createElement = _interopRequireDefault(require("../createElement"));

var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));

var _UIManager = _interopRequireDefault(require("../UIManager"));

var _canUseDom = _interopRequireDefault(require("../../modules/canUseDom"));

/**
 * This Component is used to "wrap" the modal we're opening
 * so that changing focus via tab will never leave the document.
 *
 * This allows us to properly trap the focus within a modal
 * even if the modal is at the start or end of a document.
 */
var FocusBracket = () => {
  return (0, _createElement.default)('div', {
    accessibilityRole: 'none',
    tabIndex: 0,
    style: styles.focusBracket
  });
};

function attemptFocus(element) {
  if (!_canUseDom.default) {
    return false;
  }

  try {
    element.focus();
  } catch (e) {// Do nothing
  }

  return document.activeElement === element;
}

function focusFirstDescendant(element) {
  for (var i = 0; i < element.childNodes.length; i++) {
    var child = element.childNodes[i];

    if (attemptFocus(child) || focusFirstDescendant(child)) {
      return true;
    }
  }

  return false;
}

function focusLastDescendant(element) {
  for (var i = element.childNodes.length - 1; i >= 0; i--) {
    var child = element.childNodes[i];

    if (attemptFocus(child) || focusLastDescendant(child)) {
      return true;
    }
  }

  return false;
}

var ModalFocusTrap = _ref => {
  var active = _ref.active,
      children = _ref.children;
  var trapElementRef = React.useRef();
  var focusRef = React.useRef({
    trapFocusInProgress: false,
    lastFocusedElement: null
  });
  React.useEffect(() => {
    if (_canUseDom.default) {
      var trapFocus = () => {
        // We should not trap focus if:
        // - The modal hasn't fully initialized with an HTMLElement ref
        // - Focus is already in the process of being trapped (e.g., we're refocusing)
        // - isTrapActive prop being falsey tells us to do nothing
        if (trapElementRef.current == null || focusRef.current.trapFocusInProgress || !active) {
          return;
        }

        try {
          focusRef.current.trapFocusInProgress = true;

          if (document.activeElement instanceof Node && !trapElementRef.current.contains(document.activeElement)) {
            // To handle keyboard focusing we can make an assumption here.
            // If you're tabbing through the focusable elements, the previously
            // active element will either be the first or the last.
            // If the previously selected element is the "first" descendant
            // and we're leaving it - this means that we should be looping
            // around to the other side of the modal.
            var hasFocused = focusFirstDescendant(trapElementRef.current);

            if (focusRef.current.lastFocusedElement === document.activeElement) {
              hasFocused = focusLastDescendant(trapElementRef.current);
            } // If we couldn't focus a new element then we need to focus onto the trap target

            if (!hasFocused && trapElementRef.current != null && document.activeElement) {
              _UIManager.default.focus(trapElementRef.current);
            }
          }
        } finally {
          focusRef.current.trapFocusInProgress = false;
        }

        focusRef.current.lastFocusedElement = document.activeElement;
      }; // Call the trapFocus callback at least once when this modal has been activated.

      trapFocus();
      document.addEventListener('focus', trapFocus, true);
      return () => document.removeEventListener('focus', trapFocus, true);
    }
  }, [active]); // To be fully compliant with WCAG we need to refocus element that triggered opening modal
  // after closing it

  React.useEffect(function () {
    if (_canUseDom.default) {
      var lastFocusedElementOutsideTrap = document.activeElement;
      return function () {
        if (lastFocusedElementOutsideTrap && document.contains(lastFocusedElementOutsideTrap)) {
          _UIManager.default.focus(lastFocusedElementOutsideTrap);
        }
      };
    }
  }, []);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(FocusBracket, null), /*#__PURE__*/React.createElement(_View.default, {
    ref: trapElementRef
  }, children), /*#__PURE__*/React.createElement(FocusBracket, null));
};

var _default = ModalFocusTrap;
exports.default = _default;

var styles = _StyleSheet.default.create({
  focusBracket: {
    outlineStyle: 'none'
  }
});

module.exports = exports.default;


text:
var modules =
[
    [ "Initialize/finalize", "group__magma__init.html", "group__magma__init" ],
    [ "Utilities", "group__group__util.html", "group__group__util" ],
    [ "Internal routines", "group__magma__internal.html", "group__magma__internal" ],
    [ "Dense linear algebra", "group__dense.html", "group__dense" ],
    [ "Batched", "group__batched.html", "group__batched" ],
    [ "Sparse", "group__sparse.html", "group__sparse" ],
    [ "Unused", "group__group__unused.html", "group__group__unused" ]
];


text:
using System;
using System.Collections.Generic;
using Era.Text;
using Xunit;

namespace Era.Facts
{
    public sealed class DurationFacts
    {
        static readonly DateTime Reference = new DateTime(2015, 9, 10, 14, 30, 10); // Sunday

        [Theory]
        [MemberData(nameof(SuccessTheoryValues))]
        public void Parse_Success(string text, TimeSpan expected)
        {
            // arrange
            var parser = new DurationParser(new TokenEnumerator(new StringTokenReader(text)));

            // act
            var builder = new DurationBuilder(Reference);
            var result = parser.TryMake(builder);

            // assert
            Assert.True(result);
            Assert.Equal(expected, builder.Build());
        }

        [Theory]
        [MemberData(nameof(FailureTheoryValues))]
        public void Parse_Failure(string text)
        {
            // arrange
            var parser = new DurationParser(new TokenEnumerator(new StringTokenReader(text)));

            // act
            var builder = new DurationBuilder(Reference);
            var result = parser.TryMake(builder);

            // assert
            Assert.False(result);
        }

        public static IEnumerable<object[]> SuccessTheoryValues
        {
            get
            {
                return new List<object[]>
                {
                    new object[] { "2y", TimeSpan.FromDays(731) }, // reference time is a leap year
                    new object[] { "2h", TimeSpan.FromHours(2) },
                };
            }
        }

        public static IEnumerable<object[]> FailureTheoryValues
        {
            get
            {
                return new List<object[]>
                {
                    new object[] { "1s 2h" },
                    new object[] { "12.33.4m" },
                };
            }
        }
    }
}


text:
import { IBuiltinExtensionsScannerService, ExtensionType, IExtensionManifest, IExtension } from 'vs/platform/extensions/common/extensions';
import { isWeb } from 'vs/base/common/platform';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { URI } from 'vs/base/common/uri';
import { getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { FileAccess } from 'vs/base/common/network';
import { localizeManifest } from 'vs/platform/extensionManagement/common/extensionNls';

interface IBundledExtension {
	extensionPath: string;
	packageJSON: IExtensionManifest;
	packageNLS?: any;
	readmePath?: string;
	changelogPath?: string;
}

export class BuiltinExtensionsScannerService implements IBuiltinExtensionsScannerService {

	declare readonly _serviceBrand: undefined;

	private readonly builtinExtensions: IExtension[] = [];

	constructor(
		@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
		@IUriIdentityService uriIdentityService: IUriIdentityService,
	) {
		if (isWeb) {
			const builtinExtensionsServiceUrl = this._getBuiltinExtensionsUrl(environmentService);
			if (builtinExtensionsServiceUrl) {
				let bundledExtensions: IBundledExtension[] = [];

				if (environmentService.isBuilt) {
					// Built time configuration (do NOT modify)
					bundledExtensions = [/*BUILD->INSERT_BUILTIN_EXTENSIONS*/];
				} else {
					// Find builtin extensions by checking for DOM
					const builtinExtensionsElement = document.getElementById('vscode-workbench-builtin-extensions');
					const builtinExtensionsElementAttribute = builtinExtensionsElement ? builtinExtensionsElement.getAttribute('data-settings') : undefined;
					if (builtinExtensionsElementAttribute) {
						try {
							bundledExtensions = JSON.parse(builtinExtensionsElementAttribute);
						} catch (error) { /* ignore error*/ }
					}
				}

				this.builtinExtensions = bundledExtensions.map(e => ({
					identifier: { id: getGalleryExtensionId(e.packageJSON.publisher, e.packageJSON.name) },
					location: uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl!, e.extensionPath),
					type: ExtensionType.System,
					isBuiltin: true,
					manifest: e.packageNLS ? localizeManifest(e.packageJSON, e.packageNLS) : e.packageJSON,
					readmeUrl: e.readmePath ? uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl!, e.readmePath) : undefined,
					changelogUrl: e.changelogPath ? uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl!, e.changelogPath) : undefined,
				}));
			}
		}
	}

	private _getBuiltinExtensionsUrl(environmentService: IWorkbenchEnvironmentService): URI | undefined {
		let enableBuiltinExtensions: boolean;
		if (environmentService.options && typeof environmentService.options._enableBuiltinExtensions !== 'undefined') {
			enableBuiltinExtensions = environmentService.options._enableBuiltinExtensions;
		} else {
			enableBuiltinExtensions = true;
		}
		if (enableBuiltinExtensions) {
			return FileAccess.asBrowserUri('../../../../../../extensions', require);
		}
		return undefined;
	}

	async scanBuiltinExtensions(): Promise<IExtension[]> {
		if (isWeb) {
			return this.builtinExtensions;
		}
		throw new Error('not supported');
	}
}

registerSingleton(IBuiltinExtensionsScannerService, BuiltinExtensionsScannerService);


text: require 'newrelic-excon/instrumentation'


text:
<?php
/**
 * @package    Internals
 * @since      1.8.0
 * @version    1.8.0
 */

// Avoid direct calls to this file
if ( ! class_exists( 'WPSEO_Video_Sitemap' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit();
}

/*******************************************************************
 * Add support for the YouTube Embed plugin
 *
 * @see http://wordpress.org/extend/plugins/youtube-embed/
 *
 * @internal Last update: July 2014 based upon v 3.2.1
 *******************************************************************/
if ( ! class_exists( 'WPSEO_Video_Plugin_Youtube_Embed' ) ) {

	/**
	 * Class WPSEO_Video_Plugin_Youtube_Embed
	 */
	class WPSEO_Video_Plugin_Youtube_Embed extends WPSEO_Video_Supported_Plugin {

		/**
		 * Conditionally add plugin features to analyse for video content
		 */
		public function __construct() {
			if ( defined( 'youtube_embed_version' ) ) {
				$this->shortcodes = array(
					'youtube',
					'youtube_playlist', // old, deprecated, but ought to still be recognized
					'youtube_video', // default for 'youtube_embed_shortcode' option[1]
				);

				$xtra_shortcodes = get_option( 'youtube_embed_shortcode' );
				if ( is_array( $xtra_shortcodes ) && $xtra_shortcodes !== array() ) {
					foreach ( $xtra_shortcodes as $sc ) {
						if ( is_string( $sc ) && $sc !== '' ) {
							$this->shortcodes[] = $sc;
						}
					}
				}
				unset( $xtra_shortcodes, $sc );

				// @todo - check in which version which protocol was added and adjust for that ?
				$this->alt_protocols = array(
					'httpv://',
					'httpvh://',
					//'httpvp://', = playlist, not (yet) supported
					'httpa://',
					'youtube::',
				);

				// @todo figure out what to do (if anything) about the 'bracket' and 'alt' syntax
				// @see info from the plugin below
				// [http://www.youtube.com/watch?v=Z_sCoHGIpU0]
				// get_option( 'youtube_embed_general' ); //'bracket' == '1', 'alt' == '1'
			}
		}

		/**
		 * Analyse a video shortcode from the plugin for usable video information
		 *
		 * @param  string  $full_shortcode Full shortcode as found in the post content
		 * @param  string  $sc             Shortcode found
		 * @param  array   $atts           Shortcode attributes - already decoded if needed
		 * @param  string  $content        The shortcode content, i.e. the bit between [sc]content[/sc]
		 *
		 * @return array   An array with the usable information found or else an empty array
		 */
		public function get_info_from_shortcode( $full_shortcode, $sc, $atts = array(), $content = '' ) {
			$vid = array();

			if ( isset( $content ) ) {
				// ignore audio = yes
				// ignore list -> value doesn't matter (=playlist)
				// ignore if has search (=playlist)
				// ignore if has user (=playlist)
				if ( ( ! isset( $atts['list'] ) && ( ! isset( $atts['search'] ) && ! isset( $atts['user'] ) ) ) && ( ! isset( $atts['audio'] ) || $atts['audio'] != 'yes' ) ) {

					// Is it a url or an id ?
					if ( strpos( $content, 'http' ) === 0 || strpos( $content, '//' ) === 0 ) {
						$vid['url'] = $content;
					}
					elseif ( $this->is_youtube_id( $content ) ) {
						$vid['id'] = $content;
					}

					if ( $vid !== array() ) {
						$vid['type'] = 'youtube';
						$vid         = $this->maybe_get_dimensions( $vid, $atts, true );
					}
				}
			}

			return $vid;
		}

		/*
		Alternative Shortcodes

		Within your WordPress administration page, select Options from the YouTube menu to see a list of general options:

		One section is named Alternative Shortcodes and allows you to specify two additional shortcodes - these will work exactly the same as the standard shortcode of [youtube].

		There are two reasons why you might want to do this...

		    If migrating from another plug-in, it may use a different shortcode - more details can be found in the section named "Migration".
		    If another plug-in uses the same shortcode (e.g. Jetpack) this will allow you to specify and use an alternative.

		Each of the new shortcodes can also have their own default profile assigned to them (see Profiles for more details).

		Automatically Generated Playlists

		Vixy YouTube Embed includes the ability to automatically generate playlists based upon a user name or a search name. Simply use the user or search parameter to switch the appropriate option on. Instead of a video ID or URL, specify either the user name or search word(s), like this:

		[youtube search=yes]Blake Griffin[/youtube]
		[youtube user=yes]NBA[/youtube]

		Migrating from Other Plug-ins

		Within your WordPress administration page, select Options from the YouTube menu, then scroll to the Migration section. There are two boxes that can be checked to activate two different types of alternative embedding - these have been provided to allow easy migration from other similar plug-ins. You can also assign a specific profile to these migrated options.

		The Bracket Embedding option allows YouTube URLs to be assigned within brackets - similar to shortcodes but without the actual shortcode name. Example:

		[http://www.youtube.com/watch?v=Z_sCoHGIpU0]

		The Alternative Embedding option activates a shortcode of other alternative embedding methods.

		Deploying these will impact performance, so they should only be used if absolutely necessary.
		*/

	} /* End of class */

} /* End of class-exists wrapper */


text:
/**
 * Arguments for EmbeddedMetadata class.
 */
export interface EmbeddedMetadataArgs {

    /**
     * Class to which this column is applied.
     */
    readonly target: Function;

    /**
     * Class's property name to which this column is applied.
     */
    readonly propertyName: string;

    /**
     * Type of the class to be embedded.
     */
    readonly type: ((type?: any) => Function);

}


text:
package gov.samhsa.consent2share.domain.patient;

import gov.samhsa.consent2share.domain.reference.LegalRepresentativeTypeCodeDataOnDemand;
import gov.samhsa.consent2share.service.patient.PatientLegalRepresentativeAssociationService;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;

@Configurable
@Component
public class PatientLegalRepresentativeAssociationDataOnDemand {

	private Random rnd = new SecureRandom();

	private List<PatientLegalRepresentativeAssociation> data;

	@Autowired
    LegalRepresentativeTypeCodeDataOnDemand legalRepresentativeTypeCodeDataOnDemand;

	@Autowired
    PatientLegalRepresentativeAssociationService patientLegalRepresentativeAssociationService;

	@Autowired
    PatientLegalRepresentativeAssociationRepository patientLegalRepresentativeAssociationRepository;

	public PatientLegalRepresentativeAssociation getNewTransientPatientLegalRepresentativeAssociation(int index) {
        PatientLegalRepresentativeAssociation obj = new PatientLegalRepresentativeAssociation();
        setPatientLegalRepresentativeAssociationPk(obj, index);
        setRelationshipEndDate(obj, index);
        setRelationshipStartDate(obj, index);
        return obj;
    }

	public void setPatientLegalRepresentativeAssociationPk(PatientLegalRepresentativeAssociation obj, int index) {
        PatientLegalRepresentativeAssociationPk embeddedClass = new PatientLegalRepresentativeAssociationPk();
        setPatientLegalRepresentativeAssociationPkPatient(embeddedClass, index);
        setPatientLegalRepresentativeAssociationPkLegalRepresentative(embeddedClass, index);
        obj.setPatientLegalRepresentativeAssociationPk(embeddedClass);
    }

	public void setPatientLegalRepresentativeAssociationPkPatient(PatientLegalRepresentativeAssociationPk obj, int index) {
        Patient patient = null;
        obj.setPatient(patient);
    }

	public void setPatientLegalRepresentativeAssociationPkLegalRepresentative(PatientLegalRepresentativeAssociationPk obj, int index) {
        Patient legalRepresentative = null;
        obj.setLegalRepresentative(legalRepresentative);
    }

	public void setRelationshipEndDate(PatientLegalRepresentativeAssociation obj, int index) {
        Date relationshipEndDate = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH), Calendar.getInstance().get(Calendar.HOUR_OF_DAY), Calendar.getInstance().get(Calendar.MINUTE), Calendar.getInstance().get(Calendar.SECOND) + new Double(Math.random() * 1000).intValue()).getTime();
        obj.setRelationshipEndDate(relationshipEndDate);
    }

	public void setRelationshipStartDate(PatientLegalRepresentativeAssociation obj, int index) {
        Date relationshipStartDate = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH), Calendar.getInstance().get(Calendar.HOUR_OF_DAY), Calendar.getInstance().get(Calendar.MINUTE), Calendar.getInstance().get(Calendar.SECOND) + new Double(Math.random() * 1000).intValue()).getTime();
        obj.setRelationshipStartDate(relationshipStartDate);
    }

	public PatientLegalRepresentativeAssociation getSpecificPatientLegalRepresentativeAssociation(int index) {
        init();
        if (index < 0) {
            index = 0;
        }
        if (index > (data.size() - 1)) {
            index = data.size() - 1;
        }
        PatientLegalRepresentativeAssociation obj = data.get(index);
        Long id = obj.getId();
        return patientLegalRepresentativeAssociationService.findPatientLegalRepresentativeAssociation(id);
    }

	public PatientLegalRepresentativeAssociation getRandomPatientLegalRepresentativeAssociation() {
        init();
        PatientLegalRepresentativeAssociation obj = data.get(rnd.nextInt(data.size()));
        Long id = obj.getId();
        return patientLegalRepresentativeAssociationService.findPatientLegalRepresentativeAssociation(id);
    }

	public boolean modifyPatientLegalRepresentativeAssociation(PatientLegalRepresentativeAssociation obj) {
        return false;
    }

	public void init() {
        int from = 0;
        int to = 10;
        data = patientLegalRepresentativeAssociationService.findPatientLegalRepresentativeAssociationEntries(from, to);
        if (data == null) {
            throw new IllegalStateException("Find entries implementation for 'PatientLegalRepresentativeAssociation' illegally returned null");
        }
        if (!data.isEmpty()) {
            return;
        }

        data = new ArrayList<PatientLegalRepresentativeAssociation>();
        for (int i = 0; i < 10; i++) {
            PatientLegalRepresentativeAssociation obj = getNewTransientPatientLegalRepresentativeAssociation(i);
            try {
                patientLegalRepresentativeAssociationService.savePatientLegalRepresentativeAssociation(obj);
            } catch (ConstraintViolationException e) {
                StringBuilder msg = new StringBuilder();
                for (Iterator<ConstraintViolation<?>> iter = e.getConstraintViolations().iterator(); iter.hasNext();) {
                    ConstraintViolation<?> cv = iter.next();
                    msg.append("[").append(cv.getConstraintDescriptor()).append(":").append(cv.getMessage()).append("=").append(cv.getInvalidValue()).append("]");
                }
                throw new RuntimeException(msg.toString(), e);
            }
            patientLegalRepresentativeAssociationRepository.flush();
            data.add(obj);
        }
    }
}


text:
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
from mpl_toolkits.axes_grid1 import make_axes_locatable

def plot(title, labx, laby, xdata, ydata, fname):

	del xdata[0]
	del ydata[0]

	xdata = map(float, xdata)
	ydata = map(float, ydata)

	fnam = fname + ".png"
	fig = plt.figure(figsize=(20, 10))
	plt.subplot(1, 2, 1)
	plt.scatter(xdata, ydata, s=80, facecolors='none', edgecolors='k')

	plt.subplot(1, 2, 2)
	plt.hist(ydata, bins='auto', histtype="bar", color="k", orientation="horizontal")

	plt.savefig(fnam)
	plt.close()

def bonds(lfin):

	for ent in lfin:
		print "Current file being analysed {} .....".format(ent)
		title = ent.split(".")[0].strip() + "Bond Length"
		labx = "Time Steps (1000's)"
		laby = "Bond Length (A)"
		xdata = [elt.split(",")[3].strip() for elt in open(ent, "r")]
		ydata = [elt.split(",")[-1].strip() for elt in open(ent, "r")]
		plot(title, labx, laby, xdata, ydata, ent.split(".")[0].strip())

def angles(lfin):

	for ent in lfin:
		print "Current file being analysed {} .....".format(ent)
		title = ent.split(".")[0].strip() + "Bond Angle"
		labx = "Time Steps (1000's)"
		laby = "Bond Angle (Degrees)"
		xdata = [elt.split(",")[4].strip() for elt in open(ent, "r")]
		ydata = [elt.split(",")[-1].strip() for elt in open(ent, "r")]
		plot(title, labx, laby, xdata, ydata, ent.split(".")[0].strip())

def dihedrals(lfin):

	for ent in lfin:
		print "Current file being analysed {} .....".format(ent)
		title = ent.split(".")[0].strip() + "Dihedral Angle"
		labx = "Time Steps (1000's)"
		laby = "Dihedral Angle (degrees)"
		xdata = [elt.split(",")[5].strip() for elt in open(ent, "r")]
		ydata = [elt.split(",")[-1].strip() for elt in open(ent, "r")]
		plot(title, labx, laby, xdata, ydata, ent.split(".")[0].strip())

def main():
	count = 1

	path = raw_input(str("Please enter the path to running directory of HERMES "))
	for index in range(1, 4, 1):
		if index == 1:
			pathbonds = os.path.join(path, "BONDS_plot")
			print "\nPath to bonds analysis; {}".format(pathbonds)
			os.chdir(pathbonds)
			files = [f for f in os.listdir('.') if os.path.isfile(f) and os.path.splitext(f)[1] == ".csv"]
			bonds(files)
		elif index == 2:
			pathangles = os.path.join(path, "ANGLES_plot")
			print "Path to angles analysis; {}".format(pathangles)
			os.chdir(pathangles)
			files = [f for f in os.listdir('.') if os.path.isfile(f) and os.path.splitext(f)[1] == ".csv"]
			angles(files)
		elif index == 3:
			pathd = os.path.join(path, "DIHEDRAL_plot")
			print "Path to the dihedrals analysis; {}".format(pathd)
			os.chdir(pathd)
			files = [f for f in os.listdir('.') if os.path.isfile(f) and os.path.splitext(f)[1] == ".csv"]
			dihedrals(files)

	print "FINISHED"

if __name__ == "__main__":
	main()


text:
A pdf / image to text converter that helps students learn

When a professor uploads an image of text, whether it's a page of a book or their handwritten
notes, it is not immediately accessible to those who are visually impaired.

Currently, at the University of Washington, students with visual and learning disabilities have to wait for staff
to get inaccessible materials that can't be used with screen readers or text-to-speech tools into an accessible format for the students.
This process adds extra time and is a cost to the campus.

With A11y Text, these students can upload all of their academic materials as PDFs, JPGs, or PNGs
and download versions they can use in a simple text file. Minimal wait time and no travel required.


text:
// @filename: /a/node_modules/@types/node/index.d.ts
interface Error {
    stack2: string;
}

// @filename: /a/app.ts
/// <reference types="node"/>
function foo(): Error {
    return undefined;
}


text:
				<img src="<?php echo base_url() ?>assets/front/img/icons/chart.png" alt="" />

Dashboard Penerimaan

					 Data Penerimaan Pajak Seluruh KPP di Wilayah Jakarta Utara.

				Klik Disini

				<img src="<?php echo base_url() ?>assets/front/img/icons/box-3-white.png" alt="" />

Data
Potensi

					 Data dan Potensi Penggalian Pajak di Lingkup Kanwil DJP Jakarta Utara

				Klik Disini

				<img src="<?php echo base_url() ?>assets/front/img/icons/mail.png" alt="" />

Sistem Surat Kanwil (SISUKA)

					 Sistem adminstrasi Surat Masuk dan Surat Keluar Kanwil DJP Jakarta Utara

				Klik Disini

				<img src="<?php echo base_url() ?>assets/front/img/icons/globe.png" alt="" />

Geo
Spasial

					 Pemetaan Potensi Pajak di Wilayah Jakarta Utara

				Klik Disini

  Today's Motivation

							<img src="<?php echo base_url() ?>assets/front/img/quotes/pele.jpg" alt="" />

									 "Success is no accident. It is hard work, perseverance, learning, studying, sacrifice and most of all, love of what you are doing or learning to do."

								Pele,
								Football Legend

							<img src="<?php echo base_url() ?>assets/front/img/quotes/sherlock.jpg" alt="" />

									 "…when you have eliminated all which is impossible, then whatever remains, however improbable, must be the truth"

								Sherlock Holmes,
								at, The Blanched Soldier

				‹
				›

  Useful Links

						1. Berita dan Pengumuman

							<img src="<?php echo base_url() ?>assets/front/img/icons/responsive-icon.png" class="alignright" alt="" />

Pengumuman Baru

							<?php
							$i = 1;
							foreach($pengumuman->result_array() as $p)
							{

							?>
								 <?php echo $i;?>. <?php echo $p['judul_pengumuman'];?>

								<a class="btn btn-group" href="#info<?php echo $i;?>" data-toggle="modal"> Baca Selengkapnya

								<div class="modal fade" id="info<?php echo $i;?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

												<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
												 <?php echo $p['judul_pengumuman']; ?>

												<?php echo $p['isi_pengumuman'];?>

												<a href="<?php echo $p['link_file'];?>">DISINI

												<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>

								<?php
								$i++;
							}
							?>

						2. Link Aplikasi Direkorat Jenderal Pajak

						<img src="<?php echo base_url() ?>assets/front/img/icons/check.png" class="alignright" alt="" />
								<?php
								foreach($link->result_array() as $l){

								?>
								<a class="according-toggle" data-toggle="collapse" data-parent"#accordion2" href="<?php echo $l['url']; ?>" >
								<?php echo $l['nama']; ?>  ||
								<?php
								}
								?>

						3. Download

							<img src="<?php echo base_url() ?>assets/front/img/icons/app.png" class="alignleft" alt="" />

Aplikasi

								 Aplikasi eSPT, eFaktur, dan aplikasi lainnya bisa didownload di pajak.go.id.

							Learn more

  Disc KUSUT - Discussion Khusus Utara

                     Chat

                        <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">

                        </button>

                            Refresh

                            Available

                            Busy

                                Away

                                Sign Out

                                    Jack Sparrow
                                        12 mins ago

                                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur bibendum ornare
                                    dolor, quis ullamcorper ligula sodales.

                                    13 mins ago
                                    Bhaumik Patel

                                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur bibendum ornare
                                    dolor, quis ullamcorper ligula sodales.

                                    Jack Sparrow
                                        14 mins ago

                                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur bibendum ornare
                                    dolor, quis ullamcorper ligula sodales.

                                    15 mins ago
                                    Bhaumik Patel

                                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur bibendum ornare
                                    dolor, quis ullamcorper ligula sodales.

                        <input id="btn-input" type="text" class="form-control input-sm" placeholder="Type your message here..." />

                            <button class="btn btn-warning btn-sm" id="btn-chat">
                                Send</button>

 Dashboard KPP di Lingkungan Kanwil DJP Jakarta Utara

								<img src="<?php echo base_url() ?>assets/front/img/kpp/penjaringan.jpg" alt="Portfolio name" title="" />

								<img src="<?php echo base_url() ?>assets/front/img/icons/link_post_icon.png" alt="" />
								<a class="zoom" data-pretty="prettyPhoto" href="<?php echo base_url() ?>assets/front/img/dummies/big1.jpg"><img src="<?php echo base_url() ?>assets/front/img/icons/zoom_icon.png" alt="Portfolio name" title="Portfolio name" />

KPP Pratama Jakarta Penjaringan

								<img src="<?php echo base_url() ?>assets/front/img/kpp/priok.jpg" alt="Portfolio name" title="" />

								<img src="<?php echo base_url() ?>assets/front/img/icons/link_post_icon.png" alt="" />
								<a class="zoom" data-pretty="prettyPhoto" href="<?php echo base_url() ?>assets/front/img/dummies/big1.jpg"><img src="<?php echo base_url() ?>assets/front/img/icons/zoom_icon.png" alt="Portfolio name" title="Portfolio name" />

KPP Pratama Jakarta Tanjung Priok

								<img src="<?php echo base_url() ?>assets/front/img/kpp/gading.jpg" alt="Portfolio name" title="" />

								<img src="<?php echo base_url() ?>assets/front/img/icons/link_post_icon.png" alt="" />
								<a class="zoom" data-pretty="prettyPhoto" href="<?php echo base_url() ?>assets/front/img/dummies/big1.jpg"><img src="<?php echo base_url() ?>assets/front/img/icons/zoom_icon.png" alt="Portfolio name" title="Portfolio name" />

KPP Pratama Jakarta Kelapa Gading

								<img src="<?php echo base_url() ?>assets/front/img/kpp/pademangan.jpg" alt="Portfolio name" title="" />

								<img src="<?php echo base_url() ?>assets/front/img/icons/link_post_icon.png" alt="" />
								<a class="zoom" data-pretty="prettyPhoto" href="<?php echo base_url() ?>assets/front/img/dummies/big1.jpg"><img src="<?php echo base_url() ?>assets/front/img/icons/zoom_icon.png" alt="Portfolio name" title="Portfolio name" />

KPP Pratama Jakarta Pademangan

								<img src="<?php echo base_url() ?>assets/front/img/kpp/koja.jpg" alt="Portfolio name" title="" />

								<img src="<?php echo base_url() ?>assets/front/img/icons/link_post_icon.png" alt="" />
								<a class="zoom" data-pretty="prettyPhoto" href="<?php echo base_url() ?>assets/front/img/dummies/big1.jpg"><img src="<?php echo base_url() ?>assets/front/img/icons/zoom_icon.png" alt="Portfolio name" title="Portfolio name" />

KPP Pratama Jakarta Koja

								<img src="<?php echo base_url() ?>assets/front/img/kpp/pluit.jpg" alt="Portfolio name" title="" />

								<img src="<?php echo base_url() ?>assets/front/img/icons/link_post_icon.png" alt="" />
								<a class="zoom" data-pretty="prettyPhoto" href="<?php echo base_url() ?>assets/front/img/dummies/big1.jpg"><img src="<?php echo base_url() ?>assets/front/img/icons/zoom_icon.png" alt="Portfolio name" title="Portfolio name" />

KPP Pratama Jakarta Pluit

								<img src="<?php echo base_url() ?>assets/front/img/kpp/madya.jpg" alt="Portfolio name" title="" />

								<img src="<?php echo base_url() ?>assets/front/img/icons/link_post_icon.png" alt="" />
								<a class="zoom" data-pretty="prettyPhoto" href="<?php echo base_url() ?>assets/front/img/dummies/big1.jpg"><img src="<?php echo base_url() ?>assets/front/img/icons/zoom_icon.png" alt="Portfolio name" title="Portfolio name" />

KPP Madya Jakarta Utara

								<img src="<?php echo base_url() ?>assets/front/img/kpp/sunter.jpg" alt="Portfolio name" title="" />

								<img src="<?php echo base_url() ?>assets/front/img/icons/link_post_icon.png" alt="" />
								<a class="zoom" data-pretty="prettyPhoto" href="<?php echo base_url() ?>assets/front/img/dummies/big1.jpg"><img src="<?php echo base_url() ?>assets/front/img/icons/zoom_icon.png" alt="Portfolio name" title="Portfolio name" />

KPP Pratama Jakarta Sunter


text:
package net.minidev.ovh.api.docker.slave.framework.app;

/**
 * Application volumes
 */
public class OvhVolume {
	/**
	 * Volume mode
	 *
	 * canBeNull && readOnly
	 */
	public String mode;

	/**
	 * Container path
	 *
	 * canBeNull && readOnly
	 */
	public Long containerPath;

	/**
	 * Host path
	 *
	 * canBeNull && readOnly
	 */
	public Long hostPath;
}


text:
package org.jkiss.dbeaver.ext.mysql.tools;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IExportWizard;
import org.eclipse.ui.IWorkbench;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.ext.mysql.MySQLConstants;
import org.jkiss.dbeaver.ext.mysql.MySQLDataSourceProvider;
import org.jkiss.dbeaver.ext.mysql.MySQLMessages;
import org.jkiss.dbeaver.ext.mysql.MySQLServerHome;
import org.jkiss.dbeaver.ext.mysql.model.MySQLTableBase;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.dialogs.DialogUtils;
import org.jkiss.dbeaver.ui.dialogs.tools.AbstractImportExportWizard;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;

import java.io.*;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class MySQLExportWizard extends AbstractImportExportWizard<MySQLDatabaseExportInfo> implements IExportWizard {

    public enum DumpMethod {
        ONLINE,
        LOCK_ALL_TABLES,
        NORMAL
    }

    DumpMethod method;
    boolean noCreateStatements;
    boolean addDropStatements = true;
    boolean disableKeys = true;
    boolean extendedInserts = true;
    boolean dumpEvents;
    boolean comments;
    boolean removeDefiner;
    boolean binariesInHex;
    boolean showViews;
    private String extraCommandArgs;

    public List<MySQLDatabaseExportInfo> objects = new ArrayList<>();

    private MySQLExportWizardPageObjects objectsPage;
    private MySQLExportWizardPageSettings settingsPage;

    public MySQLExportWizard(Collection<DBSObject> objects) {
        super(objects, MySQLMessages.tools_db_export_wizard_task_name);
        this.method = DumpMethod.NORMAL;
        this.outputFolder = new File(DialogUtils.getCurDialogFolder()); //$NON-NLS-1$ //$NON-NLS-2$

        final DBPPreferenceStore store = DBeaverCore.getGlobalPreferenceStore();
        this.outputFilePattern = store.getString("MySQL.export.outputFilePattern");
        if (CommonUtils.isEmpty(this.outputFilePattern)) {
            this.outputFilePattern = "dump-${database}-${timestamp}.sql";
        }
        noCreateStatements = CommonUtils.getBoolean(store.getString("MySQL.export.noCreateStatements"), false);
        addDropStatements = CommonUtils.getBoolean(store.getString("MySQL.export.addDropStatements"), true);
        disableKeys = CommonUtils.getBoolean(store.getString("MySQL.export.disableKeys"), true);
        extendedInserts = CommonUtils.getBoolean(store.getString("MySQL.export.extendedInserts"), true);
        dumpEvents = CommonUtils.getBoolean(store.getString("MySQL.export.dumpEvents"), false);
        comments = CommonUtils.getBoolean(store.getString("MySQL.export.comments"), false);
        removeDefiner = CommonUtils.getBoolean(store.getString("MySQL.export.removeDefiner"), false);
        binariesInHex = CommonUtils.getBoolean(store.getString("MySQL.export.binariesInHex"), false);
        showViews = CommonUtils.getBoolean(store.getString("MySQL.export.showViews"), false);
        extraCommandArgs = store.getString("MySQL.export.extraArgs");
    }

    @Override
    public void init(IWorkbench workbench, IStructuredSelection selection) {
        super.init(workbench, selection);
        objectsPage = new MySQLExportWizardPageObjects(this);
        settingsPage = new MySQLExportWizardPageSettings(this);
    }

    @Override
    public void addPages() {
        addPage(objectsPage);
        addPage(settingsPage);
        super.addPages();
    }

    @Override
    public IWizardPage getNextPage(IWizardPage page) {
        if (page == settingsPage) {
            return null;
        }
        return super.getNextPage(page);
    }

    @Override
    public IWizardPage getPreviousPage(IWizardPage page) {
        if (page == logPage) {
            return settingsPage;
        }
        return super.getPreviousPage(page);
    }

    @Override
	public void onSuccess(long workTime) {
        UIUtils.showMessageBox(
            getShell(),
            MySQLMessages.tools_db_export_wizard_title,
            CommonUtils.truncateString(NLS.bind(MySQLMessages.tools_db_export_wizard_message_export_completed, getObjectsName()), 255),
            SWT.ICON_INFORMATION);
        UIUtils.launchProgram(outputFolder.getAbsolutePath());
	}

    public String getExtraCommandArgs() {
        return extraCommandArgs;
    }

    public void setExtraCommandArgs(String extraCommandArgs) {
        this.extraCommandArgs = extraCommandArgs;
    }

    @Override
    public void fillProcessParameters(List<String> cmd, MySQLDatabaseExportInfo arg) throws IOException
    {
        File dumpBinary = RuntimeUtils.getHomeBinary(getClientHome(), MySQLConstants.BIN_FOLDER, "mysqldump"); //$NON-NLS-1$
        String dumpPath = dumpBinary.getAbsolutePath();
        cmd.add(dumpPath);
        switch (method) {
            case LOCK_ALL_TABLES:
                cmd.add("--lock-all-tables"); //$NON-NLS-1$
                break;
            case ONLINE:
                cmd.add("--single-transaction"); //$NON-NLS-1$
                break;
        }

        if (noCreateStatements) {
            cmd.add("--no-create-info"); //$NON-NLS-1$
        } else {
            if (CommonUtils.isEmpty(arg.getTables())) {
                cmd.add("--routines"); //$NON-NLS-1$
            }
        }
        if (addDropStatements) cmd.add("--add-drop-table"); //$NON-NLS-1$
        if (disableKeys) cmd.add("--disable-keys"); //$NON-NLS-1$
        if (extendedInserts) {
            cmd.add("--extended-insert"); //$NON-NLS-1$
        } else {
            cmd.add("--skip-extended-insert"); //$NON-NLS-1$
        }
        if (binariesInHex) {
            cmd.add("--hex-blob"); //$NON-NLS-1$
        }
        if (dumpEvents) cmd.add("--events"); //$NON-NLS-1$
        if (comments) cmd.add("--comments"); //$NON-NLS-1$

        if (!CommonUtils.isEmptyTrimmed(extraCommandArgs)) {
            cmd.add(extraCommandArgs);
        }
    }

    @Override
    protected void setupProcessParameters(ProcessBuilder process) {
        if (!CommonUtils.isEmpty(getToolUserPassword())) {
            process.environment().put(MySQLConstants.ENV_VARIABLE_MYSQL_PWD, getToolUserPassword());
        }
    }

    @Override
    public boolean performFinish() {
        objectsPage.saveState();

        final DBPPreferenceStore store = DBeaverCore.getGlobalPreferenceStore();
        store.setValue("MySQL.export.outputFilePattern", this.outputFilePattern);
        store.setValue("MySQL.export.noCreateStatements", noCreateStatements);
        store.setValue("MySQL.export.addDropStatements", addDropStatements);
        store.setValue("MySQL.export.disableKeys", disableKeys);
        store.setValue("MySQL.export.extendedInserts", extendedInserts);
        store.setValue("MySQL.export.dumpEvents", dumpEvents);
        store.setValue("MySQL.export.comments", comments);
        store.setValue("MySQL.export.removeDefiner", removeDefiner);
        store.setValue("MySQL.export.binariesInHex", binariesInHex);
        store.setValue("MySQL.export.showViews", showViews);
        store.setValue("MySQL.export.extraArgs", extraCommandArgs);

        return super.performFinish();
    }

    @Override
    public MySQLServerHome findServerHome(String clientHomeId)
    {
        return MySQLDataSourceProvider.getServerHome(clientHomeId);
    }

    @Override
    public Collection<MySQLDatabaseExportInfo> getRunInfo() {
        return objects;
    }

    @Override
    protected List<String> getCommandLine(MySQLDatabaseExportInfo arg) throws IOException
    {
        List<String> cmd = MySQLToolScript.getMySQLToolCommandLine(this, arg);
        if (objects.isEmpty()) {
            // no dump
        } else if (!CommonUtils.isEmpty(arg.getTables())) {
            cmd.add(arg.getDatabase().getName());
            for (MySQLTableBase table : arg.getTables()) {
                cmd.add(table.getName());
            }
        } else {
            cmd.add(arg.getDatabase().getName());
        }

        return cmd;
    }

    @Override
    public boolean isVerbose()
    {
        return true;
    }

    @Override
    protected void startProcessHandler(DBRProgressMonitor monitor, final MySQLDatabaseExportInfo arg, ProcessBuilder processBuilder, Process process)
    {
        super.startProcessHandler(monitor, arg, processBuilder, process);

        String outFileName = GeneralUtils.replaceVariables(outputFilePattern, new GeneralUtils.IVariableResolver() {
            @Override
            public String get(String name) {
                switch (name) {
                    case VARIABLE_DATABASE:
                        return arg.getDatabase().getName();
                    case VARIABLE_HOST:
                        return arg.getDatabase().getDataSource().getContainer().getConnectionConfiguration().getHostName();
                    case VARIABLE_TABLE:
                        final Iterator<MySQLTableBase> iterator = arg.getTables() == null ? null : arg.getTables().iterator();
                        if (iterator != null && iterator.hasNext()) {
                            return iterator.next().getName();
                        } else {
                            return "null";
                        }
                    case VARIABLE_TIMESTAMP:
                        return RuntimeUtils.getCurrentTimeStamp();
                    default:
                        System.getProperty(name);
                }
                return null;
            }
        });

        File outFile = new File(outputFolder, outFileName);
        boolean isFiltering = removeDefiner;
        Thread job = isFiltering ?
            new DumpFilterJob(monitor, process.getInputStream(), outFile) :
            new DumpCopierJob(monitor, MySQLMessages.tools_db_export_wizard_monitor_export_db, process.getInputStream(), outFile);
        job.start();
    }

    private static Pattern DEFINER_PATTER = Pattern.compile("DEFINER\\s*=\\s*`[^*]*`@`[0-9a-z\\-_\\.%]*`", Pattern.CASE_INSENSITIVE);

    class DumpFilterJob extends DumpJob {
        protected DumpFilterJob(DBRProgressMonitor monitor, InputStream stream, File outFile)
        {
            super(MySQLMessages.tools_db_export_wizard_job_dump_log_reader, monitor, stream, outFile);
        }

        @Override
        public void runDump() throws IOException {
            monitor.beginTask(MySQLMessages.tools_db_export_wizard_monitor_export_db, 100);
            long prevStatusUpdateTime = 0;
            try {
                NumberFormat numberFormat = NumberFormat.getInstance();

                LineNumberReader reader = new LineNumberReader(new InputStreamReader(input, GeneralUtils.DEFAULT_ENCODING));
                try (OutputStream output = new FileOutputStream(outFile)) {
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, GeneralUtils.DEFAULT_ENCODING));
                    for (;;) {
                        String line = reader.readLine();
                        if (line == null) {
                            break;
                        }
                        final Matcher matcher = DEFINER_PATTER.matcher(line);
                        if (matcher.find()) {
                            line = matcher.replaceFirst("");
                        }
                        long currentTime = System.currentTimeMillis();
                        if (currentTime - prevStatusUpdateTime > 300) {
                            monitor.subTask("Saved " + numberFormat.format(reader.getLineNumber()) + " lines");
                            prevStatusUpdateTime = currentTime;
                        }
                        line = filterLine(line);
                        writer.write(line);
                        writer.newLine();
                    }
                    writer.flush();
                }
            }
            finally {
                monitor.done();
            }
        }

        @NotNull
        private String filterLine(@NotNull String line) {
            return line;
        }
    }

}


text:
/**
 */
package org.afplib.afplib;

import org.afplib.base.Triplet;

/**
 *
 * A representation of the model object 'Set Bi Level Image Color'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link org.afplib.afplib.SetBiLevelImageColor#getAREA AREA}

 *
{@link org.afplib.afplib.SetBiLevelImageColor#getReserved Reserved}

 *
{@link org.afplib.afplib.SetBiLevelImageColor#getNAMECOLR NAMECOLR}

 *

 *
 * @see org.afplib.afplib.AfplibPackage#getSetBiLevelImageColor()
 * @model
 * @generated
 */
public interface SetBiLevelImageColor extends Triplet {
	/**
	 * Returns the value of the 'AREA' attribute.
	 *
	 *
	 *
	 *
mandatory
fixed length

	 *
	 * @return the value of the 'AREA' attribute.
	 * @see #setAREA(Integer)
	 * @see org.afplib.afplib.AfplibPackage#getSetBiLevelImageColor_AREA()
	 * @model required="true"
	 * @generated
	 */
	Integer getAREA();

	/**
	 * Sets the value of the '{@link org.afplib.afplib.SetBiLevelImageColor#getAREA AREA}' attribute.
	 *
	 *
	 * @param value the new value of the 'AREA' attribute.
	 * @see #getAREA()
	 * @generated
	 */
	void setAREA(Integer value);

	/**
	 * Returns the value of the 'Reserved' attribute.
	 *
	 *
	 *
	 *
mandatory
variable length

	 *
	 * @return the value of the 'Reserved' attribute.
	 * @see #setReserved(byte[])
	 * @see org.afplib.afplib.AfplibPackage#getSetBiLevelImageColor_Reserved()
	 * @model required="true"
	 * @generated
	 */
	byte[] getReserved();

	/**
	 * Sets the value of the '{@link org.afplib.afplib.SetBiLevelImageColor#getReserved Reserved}' attribute.
	 *
	 *
	 * @param value the new value of the 'Reserved' attribute.
	 * @see #getReserved()
	 * @generated
	 */
	void setReserved(byte[] value);

	/**
	 * Returns the value of the 'NAMECOLR' attribute.
	 *
	 *
	 *
	 *
mandatory
fixed length

	 *
	 * @return the value of the 'NAMECOLR' attribute.
	 * @see #setNAMECOLR(Integer)
	 * @see org.afplib.afplib.AfplibPackage#getSetBiLevelImageColor_NAMECOLR()
	 * @model required="true"
	 * @generated
	 */
	Integer getNAMECOLR();

	/**
	 * Sets the value of the '{@link org.afplib.afplib.SetBiLevelImageColor#getNAMECOLR NAMECOLR}' attribute.
	 *
	 *
	 * @param value the new value of the 'NAMECOLR' attribute.
	 * @see #getNAMECOLR()
	 * @generated
	 */
	void setNAMECOLR(Integer value);

} // SetBiLevelImageColor


text:
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkConcaveToTriangles.h"

#define SIZE    SkIntToScalar(150)

typedef void (*PathProc)(SkPath*);

static void make_path0(SkPath* path) {
    SkRect r;
    r.set(0, 0, SIZE, SIZE);
    path->addRect(r);
}

static void make_path1(SkPath* path) {
    SkRect r;
    r.set(0, 0, SIZE, SIZE);
    path->addRoundRect(r, SIZE/4, SIZE/4);
}

static void make_path2(SkPath* path) {
    SkRect r;
    r.set(0, 0, SIZE, SIZE);
    path->addOval(r);
}

static const PathProc gProcs[] = {
    make_path0,
    make_path1,
    make_path2,
};

#define COUNT_PROCS SK_ARRAY_COUNT(gProcs)

class TriangleView : public SkView {
public:
    SkPath fPaths[COUNT_PROCS];

	TriangleView() {
        for (size_t i = 0; i < COUNT_PROCS; i++) {
            gProcs[i](&fPaths[i]);
        }
    }

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt) {
        if (SampleCode::TitleQ(*evt)) {
            SampleCode::TitleR(evt, "Triangles");
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    void drawBG(SkCanvas* canvas) {
        canvas->drawColor(SK_ColorGRAY);
    }

    static void draw_path(SkCanvas* canvas, const SkPaint& pathPaint,
                          const SkPath& path, const SkPaint& triPaint) {
        canvas->drawPath(path, pathPaint);

        int n = path.getPoints(NULL, 0);
        SkPoint* pts = new SkPoint[n];
        path.getPoints(pts, n);

        SkTDArray<SkPoint> triangles;
        if (SkConcaveToTriangles(n, pts, &triangles)) {
            canvas->drawVertices(SkCanvas::kTriangles_VertexMode,
                                 triangles.count(), triangles.begin(), NULL,
                                 NULL, NULL, NULL, 0, triPaint);
        }

        SkPaint paint;
        paint.setColor(SK_ColorGREEN);
        paint.setStrokeWidth(SkIntToScalar(4));
        canvas->drawPoints(SkCanvas::kPoints_PointMode, n, pts, paint);
        delete[] pts;
    }

    virtual void onDraw(SkCanvas* canvas) {
        this->drawBG(canvas);

        canvas->translate(SIZE/2, SIZE/2);

        SkPaint pathPaint, triPaint;

        pathPaint.setColor(SK_ColorBLUE);
        pathPaint.setStrokeWidth(SIZE / 12);

        triPaint.setColor(SK_ColorRED);
        triPaint.setStyle(SkPaint::kStroke_Style);

        for (size_t i = 0; i < COUNT_PROCS; i++) {
            pathPaint.setStyle(SkPaint::kFill_Style);
            draw_path(canvas, pathPaint, fPaths[i], triPaint);

            canvas->save();
            canvas->translate(0, SIZE * 6 / 5);

            pathPaint.setStyle(SkPaint::kStroke_Style);
            draw_path(canvas, pathPaint, fPaths[i], triPaint);

            canvas->restore();
            canvas->translate(SIZE * 6 / 5, 0);
        }
    }

private:
    typedef SkView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new TriangleView; }
static SkViewRegister reg(MyFactory);


text:
<?php

namespace Box\Spout\Reader\XLSX\Helper;

/**
 * Class CellValueFormatter
 * This class provides helper functions to format cell values
 *
 * @package Box\Spout\Reader\XLSX\Helper
 */
class CellValueFormatter
{
    /** Definition of all possible cell types */
    const CELL_TYPE_INLINE_STRING = 'inlineStr';
    const CELL_TYPE_STR = 'str';
    const CELL_TYPE_SHARED_STRING = 's';
    const CELL_TYPE_BOOLEAN = 'b';
    const CELL_TYPE_NUMERIC = 'n';
    const CELL_TYPE_DATE = 'd';
    const CELL_TYPE_ERROR = 'e';

    /** Definition of XML nodes names used to parse data */
    const XML_NODE_VALUE = 'v';
    const XML_NODE_INLINE_STRING_VALUE = 't';

    /** Definition of XML attributes used to parse data */
    const XML_ATTRIBUTE_TYPE = 't';
    const XML_ATTRIBUTE_STYLE_ID = 's';

    /** Constants used for date formatting */
    const NUM_SECONDS_IN_ONE_DAY = 86400;
    const NUM_SECONDS_IN_ONE_HOUR = 3600;
    const NUM_SECONDS_IN_ONE_MINUTE = 60;

    /**
     * February 29th, 1900 is NOT a leap year but Excel thinks it is...
     * @see https://en.wikipedia.org/wiki/Year_1900_problem#Microsoft_Excel
     */
    const ERRONEOUS_EXCEL_LEAP_YEAR_DAY = 60;

    /** @var SharedStringsHelper Helper to work with shared strings */
    protected $sharedStringsHelper;

    /** @var StyleHelper Helper to work with styles */
    protected $styleHelper;

    /** @var bool Whether date/time values should be returned as PHP objects or be formatted as strings */
    protected $shouldFormatDates;

    /** @var \Box\Spout\Common\Escaper\XLSX Used to unescape XML data */
    protected $escaper;

    /**
     * @param SharedStringsHelper $sharedStringsHelper Helper to work with shared strings
     * @param StyleHelper $styleHelper Helper to work with styles
     * @param bool $shouldFormatDates Whether date/time values should be returned as PHP objects or be formatted as strings
     */
    public function __construct($sharedStringsHelper, $styleHelper, $shouldFormatDates)
    {
        $this->sharedStringsHelper = $sharedStringsHelper;
        $this->styleHelper = $styleHelper;
        $this->shouldFormatDates = $shouldFormatDates;

        /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
        $this->escaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
    }

    /**
     * Returns the (unescaped) correctly marshalled, cell value associated to the given XML node.
     *
     * @param \DOMNode $node
     * @return string|int|float|bool|\DateTime|null The value associated with the cell (null when the cell has an error)
     */
    public function extractAndFormatNodeValue($node)
    {
        // Default cell type is "n"
        $cellType = $node->getAttribute(self::XML_ATTRIBUTE_TYPE) ?: self::CELL_TYPE_NUMERIC;
        $cellStyleId = intval($node->getAttribute(self::XML_ATTRIBUTE_STYLE_ID));
        $vNodeValue = $this->getVNodeValue($node);

        if (($vNodeValue === '') && ($cellType !== self::CELL_TYPE_INLINE_STRING)) {
            return $vNodeValue;
        }

        switch ($cellType) {
            case self::CELL_TYPE_INLINE_STRING:
                return $this->formatInlineStringCellValue($node);
            case self::CELL_TYPE_SHARED_STRING:
                return $this->formatSharedStringCellValue($vNodeValue);
            case self::CELL_TYPE_STR:
                return $this->formatStrCellValue($vNodeValue);
            case self::CELL_TYPE_BOOLEAN:
                return $this->formatBooleanCellValue($vNodeValue);
            case self::CELL_TYPE_NUMERIC:
                return $this->formatNumericCellValue($vNodeValue, $cellStyleId);
            case self::CELL_TYPE_DATE:
                return $this->formatDateCellValue($vNodeValue);
            default:
                return null;
        }
    }

    /**
     * Returns the cell's string value from a node's nested value node
     *
     * @param \DOMNode $node
     * @return string The value associated with the cell
     */
    protected function getVNodeValue($node)
    {
        // for cell types having a "v" tag containing the value.
        // if not, the returned value should be empty string.
        $vNode = $node->getElementsByTagName(self::XML_NODE_VALUE)->item(0);
        return ($vNode !== null) ? $vNode->nodeValue : '';
    }

    /**
     * Returns the cell String value where string is inline.
     *
     * @param \DOMNode $node
     * @return string The value associated with the cell (null when the cell has an error)
     */
    protected function formatInlineStringCellValue($node)
    {
        // inline strings are formatted this way:
        // <c r="A1" t="inlineStr"><is><t>[INLINE_STRING]</t></is></c>
        $tNode = $node->getElementsByTagName(self::XML_NODE_INLINE_STRING_VALUE)->item(0);
        $cellValue = $this->escaper->unescape($tNode->nodeValue);
        return $cellValue;
    }

    /**
     * Returns the cell String value from shared-strings file using nodeValue index.
     *
     * @param string $nodeValue
     * @return string The value associated with the cell (null when the cell has an error)
     */
    protected function formatSharedStringCellValue($nodeValue)
    {
        // shared strings are formatted this way:
        // <c r="A1" t="s"><v>[SHARED_STRING_INDEX]</v></c>
        $sharedStringIndex = intval($nodeValue);
        $escapedCellValue = $this->sharedStringsHelper->getStringAtIndex($sharedStringIndex);
        $cellValue = $this->escaper->unescape($escapedCellValue);
        return $cellValue;
    }

    /**
     * Returns the cell String value, where string is stored in value node.
     *
     * @param string $nodeValue
     * @return string The value associated with the cell (null when the cell has an error)
     */
    protected function formatStrCellValue($nodeValue)
    {
        $escapedCellValue = trim($nodeValue);
        $cellValue = $this->escaper->unescape($escapedCellValue);
        return $cellValue;
    }

    /**
     * Returns the cell Numeric value from string of nodeValue.
     * The value can also represent a timestamp and a DateTime will be returned.
     *
     * @param string $nodeValue
     * @param int $cellStyleId 0 being the default style
     * @return int|float|\DateTime|null The value associated with the cell
     */
    protected function formatNumericCellValue($nodeValue, $cellStyleId)
    {
        // Numeric values can represent numbers as well as timestamps.
        // We need to look at the style of the cell to determine whether it is one or the other.
        $shouldFormatAsDate = $this->styleHelper->shouldFormatNumericValueAsDate($cellStyleId);

        if ($shouldFormatAsDate) {
            return $this->formatExcelTimestampValue(floatval($nodeValue), $cellStyleId);
        } else {
            $nodeIntValue = intval($nodeValue);
            return ($nodeIntValue == $nodeValue) ? $nodeIntValue : floatval($nodeValue);
        }
    }

    /**
     * Returns a cell's PHP Date value, associated to the given timestamp.
     * NOTE: The timestamp is a float representing the number of days since January 1st, 1900.
     * NOTE: The timestamp can also represent a time, if it is a value between 0 and 1.
     *
     * @param float $nodeValue
     * @param int $cellStyleId 0 being the default style
     * @return \DateTime|null The value associated with the cell or NULL if invalid date value
     */
    protected function formatExcelTimestampValue($nodeValue, $cellStyleId)
    {
        // Fix for the erroneous leap year in Excel
        if (ceil($nodeValue) > self::ERRONEOUS_EXCEL_LEAP_YEAR_DAY) {
            --$nodeValue;
        }

        if ($nodeValue >= 1) {
            // Values greater than 1 represent "dates". The value 1.0 representing the "base" date: 1900-01-01.
            return $this->formatExcelTimestampValueAsDateValue($nodeValue, $cellStyleId);
        } else if ($nodeValue >= 0) {
            // Values between 0 and 1 represent "times".
            return $this->formatExcelTimestampValueAsTimeValue($nodeValue, $cellStyleId);
        } else {
            // invalid date
            return null;
        }
    }

    /**
     * Returns a cell's PHP DateTime value, associated to the given timestamp.
     * Only the time value matters. The date part is set to Jan 1st, 1900 (base Excel date).
     *
     * @param float $nodeValue
     * @param int $cellStyleId 0 being the default style
     * @return \DateTime|string The value associated with the cell
     */
    protected function formatExcelTimestampValueAsTimeValue($nodeValue, $cellStyleId)
    {
        $time = round($nodeValue * self::NUM_SECONDS_IN_ONE_DAY);
        $hours = floor($time / self::NUM_SECONDS_IN_ONE_HOUR);
        $minutes = floor($time / self::NUM_SECONDS_IN_ONE_MINUTE) - ($hours * self::NUM_SECONDS_IN_ONE_MINUTE);
        $seconds = $time - ($hours * self::NUM_SECONDS_IN_ONE_HOUR) - ($minutes * self::NUM_SECONDS_IN_ONE_MINUTE);

        // using the base Excel date (Jan 1st, 1900) - not relevant here
        $dateObj = new \DateTime('1900-01-01');
        $dateObj->setTime($hours, $minutes, $seconds);

        if ($this->shouldFormatDates) {
            $styleNumberFormat = $this->styleHelper->getNumberFormat($cellStyleId);
            $phpDateFormat = DateFormatHelper::toPHPDateFormat($styleNumberFormat);
            return $dateObj->format($phpDateFormat);
        } else {
            return $dateObj;
        }
    }

    /**
     * Returns a cell's PHP Date value, associated to the given timestamp.
     * NOTE: The timestamp is a float representing the number of days since January 1st, 1900.
     *
     * @param float $nodeValue
     * @param int $cellStyleId 0 being the default style
     * @return \DateTime|string|null The value associated with the cell or NULL if invalid date value
     */
    protected function formatExcelTimestampValueAsDateValue($nodeValue, $cellStyleId)
    {
        // Do not use any unix timestamps for calculation to prevent
        // issues with numbers exceeding 2^31.
        $secondsRemainder = fmod($nodeValue, 1) * self::NUM_SECONDS_IN_ONE_DAY;
        $secondsRemainder = round($secondsRemainder, 0);

        try {
            $dateObj = \DateTime::createFromFormat('|Y-m-d', '1899-12-31');
            $dateObj->modify('+' . intval($nodeValue) . 'days');
            $dateObj->modify('+' . $secondsRemainder . 'seconds');

            if ($this->shouldFormatDates) {
                $styleNumberFormat = $this->styleHelper->getNumberFormat($cellStyleId);
                $phpDateFormat = DateFormatHelper::toPHPDateFormat($styleNumberFormat);
                return $dateObj->format($phpDateFormat);
            } else {
                return $dateObj;
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Returns the cell Boolean value from a specific node's Value.
     *
     * @param string $nodeValue
     * @return bool The value associated with the cell
     */
    protected function formatBooleanCellValue($nodeValue)
    {
        // !! is similar to boolval()
        $cellValue = !!$nodeValue;
        return $cellValue;
    }

    /**
     * Returns a cell's PHP Date value, associated to the given stored nodeValue.
     *
     * @param string $nodeValue
     * @return \DateTime|null The value associated with the cell or NULL if invalid date value
     */
    protected function formatDateCellValue($nodeValue)
    {
        // Mitigate thrown Exception on invalid date-time format (http://php.net/manual/en/datetime.construct.php)
        try {
            $cellValue = new \DateTime($nodeValue);
            return $cellValue;
        } catch (\Exception $e) {
            return null;
        }
    }
}


text:
package com.gatebuzz.rapidapi.rx.internal;

import com.google.gson.Gson;
import com.google.gson.JsonElement;

/**
 * Process the payload part of the response envelope and return it as some kind of object.
 */
public interface ResponseProcessor {
    Object process(Gson gson, JsonElement payloadElement);
}


text:
module Typescript
  module Sprockets
    # just to define the module Typescript::Sprockets
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <title>BeMob</title>

    <link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon">
    <link rel="icon" href="img/favicon.ico" type="image/x-icon">

    <link href="css/bootstrap.css" rel="stylesheet" media="screen">
    <link href="css/style.css" rel="stylesheet" media="screen">
    <link href="css/animate.min.css" rel="stylesheet" media="screen">
    <link href="css/font-awesome.css" rel="stylesheet" media="screen">
    <link href="css/owl.carousel.css" rel="stylesheet" media="screen">
    <link href="css/flexslider.css" rel="stylesheet" media="screen">
    <link href="css/fancySelect.css" rel="stylesheet" media="screen">
    <link href="css/responsive.css" rel="stylesheet" media="screen">

    <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,700" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Belgrano" rel="stylesheet" type="text/css">

                                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                                    Toggle navigation

                                </button>

Home

A Empresa

Serviços

Contato

                            © BMob Softwares 2015