text:
"""URL downloading API.

Methods defined in this module:
   Fetch(): fetchs a given URL using an HTTP request using on of the methods
            GET, POST, HEAD, PUT, DELETE or PATCH request
"""

import httplib
import os
import StringIO
import threading
import UserDict
import urllib2
import urlparse

from google.appengine.api import apiproxy_stub_map
from google.appengine.api import urlfetch_service_pb
from google.appengine.api.urlfetch_errors import *
from google.appengine.runtime import apiproxy_errors

MAX_REDIRECTS = 5

GET = 1
POST = 2
HEAD = 3
PUT = 4
DELETE = 5
PATCH = 6

_URL_STRING_MAP = {
    'GET': GET,
    'POST': POST,
    'HEAD': HEAD,
    'PUT': PUT,
    'DELETE': DELETE,
    'PATCH': PATCH,
}

_VALID_METHODS = frozenset(_URL_STRING_MAP.values())

_thread_local_settings = threading.local()

class _CaselessDict(UserDict.IterableUserDict):
  """Case insensitive dictionary.

  This class was lifted from os.py and slightly modified.
  """

  def __init__(self, dict=None, **kwargs):
    self.caseless_keys = {}
    UserDict.IterableUserDict.__init__(self, dict, **kwargs)

  def __setitem__(self, key, item):
    """Set dictionary item.

    Args:
      key: Key of new item.  Key is case insensitive, so "d['Key'] = value "
        will replace previous values set by "d['key'] = old_value".
      item: Item to store.
    """
    caseless_key = key.lower()

    if caseless_key in self.caseless_keys:
      del self.data[self.caseless_keys[caseless_key]]
    self.caseless_keys[caseless_key] = key
    self.data[key] = item

  def __getitem__(self, key):
    """Get dictionary item.

    Args:
      key: Key of item to get.  Key is case insensitive, so "d['Key']" is the
        same as "d['key']".

    Returns:
      Item associated with key.
    """
    return self.data[self.caseless_keys[key.lower()]]

  def __delitem__(self, key):
    """Remove item from dictionary.

    Args:
      key: Key of item to remove.  Key is case insensitive, so "del d['Key']" is
        the same as "del d['key']"
    """
    caseless_key = key.lower()
    del self.data[self.caseless_keys[caseless_key]]
    del self.caseless_keys[caseless_key]

  def has_key(self, key):
    """Determine if dictionary has item with specific key.

    Args:
      key: Key to check for presence.  Key is case insensitive, so
        "d.has_key('Key')" evaluates to the same value as "d.has_key('key')".

    Returns:
      True if dictionary contains key, else False.
    """
    return key.lower() in self.caseless_keys

  def __contains__(self, key):
    """Same as 'has_key', but used for 'in' operator.'"""
    return self.has_key(key)

  def get(self, key, failobj=None):
    """Get dictionary item, defaulting to another value if it does not exist.

    Args:
      key: Key of item to get.  Key is case insensitive, so "d['Key']" is the
        same as "d['key']".
      failobj: Value to return if key not in dictionary.
    """
    try:
      cased_key = self.caseless_keys[key.lower()]
    except KeyError:
      return failobj
    return self.data[cased_key]

  def update(self, dict=None, **kwargs):
    """Update dictionary using values from another dictionary and keywords.

    Args:
      dict: Dictionary to update from.
      kwargs: Keyword arguments to update from.
    """
    if dict:
      try:
        keys = dict.keys()
      except AttributeError:

        for k, v in dict:
          self[k] = v
      else:

        for k in keys:
          self[k] = dict[k]
    if kwargs:
      self.update(kwargs)

  def copy(self):
    """Make a shallow, case sensitive copy of self."""
    return dict(self)

def _is_fetching_self(url, method):
  """Checks if the fetch is for the same URL from which it originated.

  Args:
    url: str, The URL being fetched.
    method: value from _VALID_METHODS.

  Returns:
    boolean indicating whether or not it seems that the app is trying to fetch
      itself.
  """
  if (method != GET or
      "HTTP_HOST" not in os.environ or
      "PATH_INFO" not in os.environ):
    return False

  _, host_port, path, _, _ = urlparse.urlsplit(url)

  if host_port == os.environ['HTTP_HOST']:
    current_path = urllib2.unquote(os.environ['PATH_INFO'])
    desired_path = urllib2.unquote(path)

    if (current_path == desired_path or
        (current_path in ('', '/') and desired_path in ('', '/'))):
      return True

  return False

def create_rpc(deadline=None, callback=None):
  """Creates an RPC object for use with the urlfetch API.

  Args:
    deadline: Optional deadline in seconds for the operation; the default
      is a system-specific deadline (typically 5 seconds).
    callback: Optional callable to invoke on completion.

  Returns:
    An apiproxy_stub_map.UserRPC object specialized for this service.
  """
  if deadline is None:
    deadline = get_default_fetch_deadline()
  return apiproxy_stub_map.UserRPC('urlfetch', deadline, callback)

def fetch(url, payload=None, method=GET, headers={},
          allow_truncated=False, follow_redirects=True,
          deadline=None, validate_certificate=None):
  """Fetches the given HTTP URL, blocking until the result is returned.

  Other optional parameters are:
     method: The constants GET, POST, HEAD, PUT, DELETE, or PATCH or the
       same HTTP methods as strings.
     payload: POST, PUT, or PATCH payload (implies method is not GET, HEAD,
       or DELETE). this is ignored if the method is not POST, PUT, or PATCH.
     headers: dictionary of HTTP headers to send with the request
     allow_truncated: if true, truncate large responses and return them without
       error. Otherwise, ResponseTooLargeError is raised when a response is
       truncated.
     follow_redirects: if true (the default), redirects are
       transparently followed and the response (if less than 5
       redirects) contains the final destination's payload and the
       response status is 200.  You lose, however, the redirect chain
       information.  If false, you see the HTTP response yourself,
       including the 'Location' header, and redirects are not
       followed.
     deadline: deadline in seconds for the operation.
     validate_certificate: if true, do not send request to server unless the
       certificate is valid, signed by a trusted CA and the hostname matches
       the certificate. A value of None indicates that the behaviour will be
       chosen by the underlying urlfetch implementation.

  We use a HTTP/1.1 compliant proxy to fetch the result.

  The returned data structure has the following fields:
     content: string containing the response from the server
     status_code: HTTP status code returned by the server
     headers: dictionary of headers returned by the server

  If the URL is an empty string or obviously invalid, we throw an
  urlfetch.InvalidURLError. If the server cannot be contacted, we throw a
  urlfetch.DownloadError.  Note that HTTP errors are returned as a part
  of the returned structure, so HTTP errors like 404 do not result in an
  exception.
  """

  rpc = create_rpc(deadline=deadline)
  make_fetch_call(rpc, url, payload, method, headers,
                  allow_truncated, follow_redirects, validate_certificate)
  return rpc.get_result()

def make_fetch_call(rpc, url, payload=None, method=GET, headers={},
                    allow_truncated=False, follow_redirects=True,
                    validate_certificate=None):
  """Executes the RPC call to fetch a given HTTP URL.

  The first argument is a UserRPC instance.  See urlfetch.fetch for a
  thorough description of remaining arguments.

  Raises:
    InvalidMethodError: if requested method is not in _VALID_METHODS
    ResponseTooLargeError: if the response payload is too large
    InvalidURLError: if there are issues with the content/size of the
      requested URL

  Returns:
    The rpc object passed into the function.

  """

  assert rpc.service == 'urlfetch', repr(rpc.service)
  if isinstance(method, basestring):
    method = method.upper()
  method = _URL_STRING_MAP.get(method, method)
  if method not in _VALID_METHODS:
    raise InvalidMethodError('Invalid method %s.' % str(method))

  if _is_fetching_self(url, method):
    raise InvalidURLError("App cannot fetch the same URL as the one used for "
                          "the request.")

  request = urlfetch_service_pb.URLFetchRequest()
  response = urlfetch_service_pb.URLFetchResponse()

  if isinstance(url, unicode):
    url = url.encode('UTF-8')
  request.set_url(url)

  if method == GET:
    request.set_method(urlfetch_service_pb.URLFetchRequest.GET)
  elif method == POST:
    request.set_method(urlfetch_service_pb.URLFetchRequest.POST)
  elif method == HEAD:
    request.set_method(urlfetch_service_pb.URLFetchRequest.HEAD)
  elif method == PUT:
    request.set_method(urlfetch_service_pb.URLFetchRequest.PUT)
  elif method == DELETE:
    request.set_method(urlfetch_service_pb.URLFetchRequest.DELETE)
  elif method == PATCH:
    request.set_method(urlfetch_service_pb.URLFetchRequest.PATCH)

  if payload and method in (POST, PUT, PATCH):
    request.set_payload(payload)

  for key, value in headers.iteritems():
    header_proto = request.add_header()
    header_proto.set_key(key)

    header_proto.set_value(str(value))

  request.set_followredirects(follow_redirects)
  if validate_certificate is not None:
    request.set_mustvalidateservercertificate(validate_certificate)

  if rpc.deadline is not None:
    request.set_deadline(rpc.deadline)

  rpc.make_call('Fetch', request, response, _get_fetch_result, allow_truncated)
  return rpc

def _get_fetch_result(rpc):
  """Check success, handle exceptions, and return converted RPC result.

  This method waits for the RPC if it has not yet finished, and calls the
  post-call hooks on the first invocation.

  Args:
    rpc: A UserRPC object.

  Raises:
    InvalidURLError: if the url was invalid.
    DownloadError: if there was a problem fetching the url.
    ResponseTooLargeError: if the response was either truncated (and
      allow_truncated=False was passed to make_fetch_call()), or if it
      was too big for us to download.

  Returns:
    A _URLFetchResult object.
  """
  assert rpc.service == 'urlfetch', repr(rpc.service)
  assert rpc.method == 'Fetch', repr(rpc.method)

  url = rpc.request.url()

  try:
    rpc.check_success()
  except apiproxy_errors.RequestTooLargeError, err:
    raise InvalidURLError(
        'Request body too large fetching URL: ' + url)
  except apiproxy_errors.ApplicationError, err:
    error_detail = ''
    if err.error_detail:
      error_detail = ' Error: ' + err.error_detail
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.INVALID_URL):
      raise InvalidURLError(
          'Invalid request URL: ' + url + error_detail)
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.CLOSED):
      raise ConnectionClosedError(
          'Connection closed unexpectedly by server at URL: ' + url)
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.TOO_MANY_REDIRECTS):
      raise TooManyRedirectsError(
          'Too many redirects at URL: ' + url + ' with redirect=true')
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.MALFORMED_REPLY):
      raise MalformedReplyError(
          'Malformed HTTP reply received from server at URL: '
          + url + error_detail)
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.INTERNAL_TRANSIENT_ERROR):
      raise InternalTransientError(
          'Temporary error in fetching URL: ' + url + ', please re-try')
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.DNS_ERROR):
      raise DNSLookupFailedError('DNS lookup failed for URL: ' + url)
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.UNSPECIFIED_ERROR):
      raise DownloadError('Unspecified error in fetching URL: '
                          + url + error_detail)
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.FETCH_ERROR):
      raise DownloadError("Unable to fetch URL: " + url + error_detail)
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.RESPONSE_TOO_LARGE):
      raise ResponseTooLargeError('HTTP response too large from URL: ' + url)
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.DEADLINE_EXCEEDED):
      raise DeadlineExceededError(
          'Deadline exceeded while waiting for HTTP response from URL: ' + url)
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.SSL_CERTIFICATE_ERROR):
      raise SSLCertificateError(
          'Invalid and/or missing SSL certificate for URL: ' + url)
    if (err.application_error ==
        urlfetch_service_pb.URLFetchServiceError.CONNECTION_ERROR):
      raise DownloadError('Unable to connect to server at URL: ' + url)

    raise err

  response = rpc.response
  allow_truncated = rpc.user_data
  result = _URLFetchResult(response)
  if response.contentwastruncated() and not allow_truncated:
    raise ResponseTooLargeError(result)
  return result

Fetch = fetch

class _URLFetchResult(object):
  """A Pythonic representation of our fetch response protocol buffer.
  """

  def __init__(self, response_proto):
    """Constructor.

    Args:
      response_proto: the URLFetchResponse proto buffer to wrap.
    """
    self.__pb = response_proto
    self.content = response_proto.content()
    self.status_code = response_proto.statuscode()
    self.content_was_truncated = response_proto.contentwastruncated()
    self.final_url = response_proto.finalurl() or None
    self.header_msg = httplib.HTTPMessage(
        StringIO.StringIO(''.join(['%s: %s\n' % (h.key(), h.value())
                          for h in response_proto.header_list()] + ['\n'])))
    self.headers = _CaselessDict(self.header_msg.items())

def get_default_fetch_deadline():
  """Get the default value for create_rpc()'s deadline parameter."""
  return getattr(_thread_local_settings, "default_fetch_deadline", None)

def set_default_fetch_deadline(value):
  """Set the default value for create_rpc()'s deadline parameter.

  This setting is thread-specific (i.e. it's stored in a thread local).
  This function doesn't do any range or type checking of the value.  The
  default is None.

  See also: create_rpc(), fetch()

  """
  _thread_local_settings.default_fetch_deadline = value


text:
{% extends 'content/gallery/p.classic.html' %}

{% load feincms_thumbnail %}

{% block caption %}{{ picture.translation.caption }}{% endblock %}

{% block image-original %}{{ picture.file.name|thumbnail:'960x650' }}{% endblock %}

{% block image-remaining %}{{ picture.file.name|thumbnail:'960x650' }}{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
package breeze.stats
package distributions

import org.scalatest.junit.JUnitRunner
import org.scalatest.FunSuite
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Before
import org.scalatest.prop._
import org.scalacheck._
import java.util.zip.DeflaterInputStream

/**
 * @author dlwh
 */
trait MomentsTestBase[T] extends FunSuite with Checkers {
  implicit def arbDistr: Arbitrary[Measure[T] with Rand[T] with Moments[Double]];
  val numSamples = 10000;
  def asDouble(x: T):Double
  def fromDouble(x: Double):T

  test("mean") {
    check(Prop.forAll { (distr: Measure[T] with Rand[T] with Moments[Double])=>
       val sample = distr.sample(numSamples).map(asDouble _)
       val mean = DescriptiveStats.mean(sample)
       if ( (mean - distr.mean).abs/(mean.abs max 1) > 1E-1) {
         println("MExpected " + distr.mean + " but got " + mean)
         false
       } else {
         true
       }

    })
  }

  val VARIANCE_TOLERANCE = 5E-2
  test("variance") {
    check(Prop.forAll { (distr: Measure[T] with Rand[T] with Moments[Double])=>
    // try twice, and only fail if both fail.
    // just a little more robustness...
      Iterator.range(0,2).exists{ _ =>
        val sample = distr.sample(numSamples).map(asDouble _)
        val variance = DescriptiveStats.variance(sample)

        if((variance - distr.variance).abs/(variance max 1) > VARIANCE_TOLERANCE) {
          println("Expected " + distr.variance + " but got " + variance)
          false
        } else true
      }
    })
  }

  test("mode") {
    check(Prop.forAll { (distr: Rand[T] with Measure[T] with Moments[Double])=>
      val sample = distr.sample(40)
      val probMode = distr(fromDouble(distr.mode))
//      if(distr.isInstanceOf[Poisson])
//        println(distr,probMode,sample.map{ distr },sample)
      sample.forall(x => probMode >= distr(x) - 1E-4);
    })
  }

}


text:
package testclient

import (
	"fmt"

	"github.com/openshift/origin/pkg/client"
	imageapi "github.com/openshift/origin/pkg/image/api"
)

// FakeImageStreamTags implements ImageStreamTagInterface. Meant to be
// embedded into a struct to get a default implementation. This makes faking
// out just the methods you want to test easier.
type FakeImageStreamTags struct {
	Fake      *Fake
	Namespace string
}

var _ client.ImageStreamTagInterface = &FakeImageStreamTags{}

func (c *FakeImageStreamTags) Get(name, tag string) (result *imageapi.ImageStreamTag, err error) {
	c.Fake.Actions = append(c.Fake.Actions, FakeAction{Action: "get-imagestream-tag", Value: fmt.Sprintf("%s:%s", name, tag)})
	return &imageapi.ImageStreamTag{}, nil
}

func (c *FakeImageStreamTags) Delete(name, tag string) error {
	c.Fake.Actions = append(c.Fake.Actions, FakeAction{Action: "delete-imagestream-tag", Value: fmt.Sprintf("%s:%s", name, tag)})
	return nil
}


text:
package org.springframework.boot.web.embedded.jetty;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;

/**
 * Variation of Jetty's {@link ErrorPageErrorHandler} that supports all {@link HttpMethod
 * HttpMethods} rather than just {@code GET}, {@code POST} and {@code HEAD}. By default
 * Jetty intentionally only
 * supports a limited set of HTTP methods for error pages, however, Spring Boot
 * prefers Tomcat, Jetty and Undertow to all behave in the same way.
 *
 * @author Phillip Webb
 * @author Christoph Dreis
 */
class JettyEmbeddedErrorHandler extends ErrorPageErrorHandler {

	@Override
	public boolean errorPageForMethod(String method) {
		return true;
	}

	@Override
	public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		baseRequest.setMethod("GET");
		super.doError(target, baseRequest, request, response);
	}

}


text:
layout: post
date: 2017-10-18
title: "Moonlight Style MT9236"
category: Moonlight
tags: [Moonlight]
---
### Moonlight Style MT9236
Just **$219.99**
###

BRANDS	Moonlight

Buy it: [https://www.readybrides.com/en/moonlight/48278-moonlight-style-mt9236.html](https://www.readybrides.com/en/moonlight/48278-moonlight-style-mt9236.html)


text:
package alien4cloud.it.application;

import static alien4cloud.it.Context.getRestClientInstance;
import static alien4cloud.it.utils.TestUtils.nullable;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;

import alien4cloud.dao.model.FacetedSearchResult;
import alien4cloud.it.Context;
import alien4cloud.it.common.CommonStepDefinitions;
import alien4cloud.model.application.Application;
import alien4cloud.model.application.ApplicationVersion;
import alien4cloud.rest.application.model.CreateApplicationVersionRequest;
import alien4cloud.rest.application.model.UpdateApplicationVersionRequest;
import alien4cloud.rest.model.FilteredSearchRequest;
import alien4cloud.rest.model.RestResponse;
import alien4cloud.rest.utils.JsonUtil;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class ApplicationVersionStepDefinitions {
    public static ApplicationVersion CURRENT_VERSION;

    @When("^I get the application version for application \"([^\"]*)\" with id \"([^\"]*)\"$")
    public void getApplicationVersion(String applicationId, String versionId) throws Throwable {
        Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/v1/applications/" + applicationId + "/versions/" + versionId));
        // Try to register the application version (this works only if the operations is successful)
        try {
            CURRENT_VERSION = null;
            CURRENT_VERSION = JsonUtil.read(Context.getInstance().getRestResponse(), ApplicationVersion.class).getData();
        } catch (IOException e) {
            // Registration is optional
        }
    }

    @And("^The application version should have an application topology version with version \"([^\"]*)\"$")
    public void checkApplicationTopologyVersion(String topologyVersion) throws Throwable {
        Assert.assertNotNull(CURRENT_VERSION);
        Assert.assertNotNull(CURRENT_VERSION.getTopologyVersions());
        Assert.assertNotNull(CURRENT_VERSION.getTopologyVersions().get(topologyVersion));
    }

    @And("^The application version should not have an application topology version with version \"([^\"]*)\"$")
    public void checkApplicationTopologyVersionNotExists(String topologyVersion) throws Throwable {
        Assert.assertNotNull(CURRENT_VERSION);
        Assert.assertNotNull(CURRENT_VERSION.getTopologyVersions());
        Assert.assertNull(CURRENT_VERSION.getTopologyVersions().get(topologyVersion));
    }

    @When("^I (successfully\\s)?create an application version for application \"([^\"]*)\" with version \"([^\"]*)\", description \"([^\"]*)\", topology template id \"([^\"]*)\" and previous version id \"([^\"]*)\"$")
    public void stepCreateApplicationVersion(String successfully, String applicationId, String version, String description, String topologyTemplateId,
            String fromVersionId) throws Throwable {
        createApplicationVersion(applicationId, nullable(version), nullable(description), nullable(topologyTemplateId), nullable(fromVersionId));
        CommonStepDefinitions.validateIfNeeded(StringUtils.isNotBlank(successfully));
    }

    private void createApplicationVersion(String applicationId, String version, String description, String topologyTemplateId, String fromVersionId)
            throws Throwable {
        CreateApplicationVersionRequest request = new CreateApplicationVersionRequest(version, description, topologyTemplateId, fromVersionId);
        Context.getInstance()
                .registerRestResponse(getRestClientInstance().postJSon("/rest/v1/applications/" + applicationId + "/versions", JsonUtil.toString(request)));
    }

    @When("^I delete an application version for application \"([^\"]*)\" with version id \"([^\"]*)\"$")
    public void deleteApplicationVersion(String applicationId, String versionId) throws Throwable {
        Context.getInstance().registerRestResponse(Context.getRestClientInstance().delete("/rest/v1/applications/" + applicationId + "/versions/" + versionId));
    }

    @When("^I search for application versions$")
    public void I_search_for_application_versions() throws Throwable {
        Application app = Context.getInstance().getApplication();
        FilteredSearchRequest request = new FilteredSearchRequest();
        request.setFrom(0);
        request.setSize(10);
        Context.getInstance().registerRestResponse(
                Context.getRestClientInstance().postJSon("/rest/v1/applications/" + app.getId() + "/versions/search", JsonUtil.toString(request)));
    }

    @Then("^I should receive (\\d+) application versions in the search result$")
    public void I_should_receive_application_versions_in_the_search_result(int nbAppVerions) throws Throwable {
        RestResponse<FacetedSearchResult> response = JsonUtil.read(Context.getInstance().getRestResponse(), FacetedSearchResult.class);
        Assert.assertNull(response.getError());
        Assert.assertNotNull(response.getData());
        Assert.assertTrue(response.getData().getTotalResults() == nbAppVerions);
    }

    @When("^I update the application version for application \"([^\"]*)\" version id \"([^\"]*)\" with new version \"([^\"]*)\" and description \"([^\"]*)\"$")
    public void updateApplicationVersionStep(String applicationId, String versionId, String newVersion, String description) throws Throwable {
        updateApplicationVersion(nullable(applicationId), nullable(versionId), nullable(newVersion), nullable(description));
    }

    private void updateApplicationVersion(String applicationId, String versionId, String newVersion, String description) throws Throwable {
        UpdateApplicationVersionRequest request = new UpdateApplicationVersionRequest();
        request.setVersion(newVersion);
        request.setDescription(description);
        Context.getInstance().registerRestResponse(
                Context.getRestClientInstance().putJSon("/rest/v1/applications/" + applicationId + "/versions/" + versionId, JsonUtil.toString(request)));

    }
}


text:
/* Sticky footer styles
-------------------------------------------------- */
html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}

/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */

body > .container {
  padding: 60px 15px 0;
}
.container .text-muted {
  margin: 20px 0;
}

.footer > .container {
  padding-right: 15px;
  padding-left: 15px;
}

code {
  font-size: 80%;
}

p.description > img {
    width: 300px;
    height: 200px;
}


text:
from django.core.urlresolvers import reverse_lazy
import os,sys
from os.path import dirname, join, exists
import logging.config

LOGFILE_BASE = 'wsgi'

#print os.environ

if 'django_mode' in os.environ:
    #if 'mod_wsgi.process_group' in os.environ:
    LOGFILE_BASE = 'wsgi'
else:
    print "running debug server"
    LOGFILE_BASE = 'dbg'

# Build paths inside the project like this: join(BASE_DIR, "directory")
BASE_DIR = dirname(dirname(dirname(__file__)))
STATIC_ROOT = join(BASE_DIR, '..', 'site', 'static')
STATICFILES_DIRS = [
    join(BASE_DIR, 'static')
    ]
MEDIA_ROOT = join(BASE_DIR, 'media')
MEDIA_URL = "/media/"
STATIC_URL = '/static/'

MENU_SELECT_PARENTS=True
MENU_HIDE_EMPTY=False
# Log everything to the logs directory at the top
LOGFILE_ROOT = join(dirname(BASE_DIR), 'logs')

# Use Django templates using the new Django 1.8 TEMPLATES settings
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            join(BASE_DIR, 'templates'),
            # insert more TEMPLATE_DIRS here
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
                # list if you haven't customized them:
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# Use 12factor inspired environment variables or from a file
import environ
env = environ.Env()

# Ideally move env file should be outside the git repo
# i.e. BASE_DIR.parent.parent
env_file = join(dirname(__file__), 'local.env')
if exists(env_file):
    environ.Env.read_env(str(env_file))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# Raises ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')

ALLOWED_HOSTS = [
    u'127.0.0.1',
    u'localhost',
    'localhost',
    '*',
     ]

# Application definition

INSTALLED_APPS = (
    'django.contrib.auth',
    #'django_admin_bootstrapped',
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #'authtools',
    'menu',
    'crispy_forms',
    'easy_thumbnails',
    'django_tables2',
    'tinymce',
    'profiles',
    'accounts',
    'zs',
    'import_export',
    'track',
    'bootstrap3'
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'godiva_web.urls'

WSGI_APPLICATION = 'godiva_web.wsgi.application'

# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases

DATABASES_ORIG = {
    # Raises ImproperlyConfigured exception if DATABASE_URL not in
    # os.environ
    'default': env.db(),
}

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/

# Crispy Form Theme - Bootstrap 3
CRISPY_TEMPLATE_PACK = 'bootstrap3'

# For Bootstrap 3, change error alert to 'danger'
from django.contrib import messages

MESSAGE_TAGS = {
    messages.ERROR: 'danger'
}

# Authentication Settings
#AUTH_USER_MODEL = auth.User
LOGIN_REDIRECT_URL = reverse_lazy("profiles:show_self")
LOGIN_URL = reverse_lazy("accounts:login")

THUMBNAIL_EXTENSION = 'png'     # Or any extn for your thumbnails
# Reset logging
# (see http://www.caktusgroup.com/blog/2015/01/27/Django-Logging-Configuration-logging_config-default-settings-logger/)

LOGGING_CONFIG = None
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(pathname)s:%(lineno)s] %(message)s",
            'datefmt': "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'django_log_file': {
            'level': 'WARNING',
            'class': 'logging.FileHandler',
            'filename': join(LOGFILE_ROOT, LOGFILE_BASE+'.django.log'),
            'formatter': 'verbose'
        },
        'proj_log_file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': join(LOGFILE_ROOT, LOGFILE_BASE+'.project.log'),
            'formatter': 'verbose'
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        }
    },
    'loggers': {
        'django': {
            'handlers': ['django_log_file'],
            'propagate': True,
            'level': 'WARNING',
        },
        'project': {
            'handlers': ['proj_log_file'],
            'level': 'DEBUG',
        },
    }
}

logging.config.dictConfig(LOGGING)


text:
package org.isisaddons.module.settings.dom.jdo;

import org.apache.isis.applib.AbstractService;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.Contributed;
import org.apache.isis.applib.annotation.Mixin;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.apache.isis.applib.query.QueryDefault;

import org.isisaddons.module.settings.SettingsModule;
import org.isisaddons.module.settings.dom.ApplicationSetting;

@Mixin
public class ApplicationSetting_next extends AbstractService {

    //region > constructor
    private final ApplicationSetting current;

    public ApplicationSetting_next(final ApplicationSetting current) {
        this.current = current;
    }
    //endregion

    public static class ActionDomainEvent
            extends SettingsModule.ActionDomainEvent<ApplicationSetting_next> { }

    @Action(
            domainEvent = ActionDomainEvent.class,
            semantics = SemanticsOf.SAFE
    )
    @ActionLayout(
            contributed = Contributed.AS_ACTION,
            cssClassFa = "fa-step-forward",
            cssClassFaPosition = ActionLayout.CssClassFaPosition.RIGHT
    )
    public ApplicationSetting $$() {
        return firstMatch(
                new QueryDefault<>(ApplicationSettingJdo.class,
                        "findNext",
                        "key", current.getKey()));
    }

    public String disable$$() {
        return $$() == null? "No more settings": null;
    }

}


text:
		FINOPAY

@Copyright 2016

Company Address:

Hoxton Tech Limited

20-22 Wenlock Road

London N1 7GU

United Kingdom

Email:

		blabla@gmail.com

About Us:

We are team of finance and technology professionals? based in Swizeland and the UK. Cildren of the globalization, we`re always looking for ways to simplify our fast pased nomadic way of life. If you`ve read this far, you`ve probably just like us!

Subscribe to updates:

		<input type="email" placeholder="Your email">

		Terms&Conditions
		Privacy Policy
		Cookies


text:
foam.CLASS({
  package: 'foam.box',
  name: 'ReplyBox',
  extends: 'foam.box.ProxyBox',

  imports: [
    {
      name: 'registry',
      key: 'registry',
      javaType: 'foam.box.BoxRegistry'
    }
  ],

  properties: [
    {
      class: 'String',
      name: 'id',
      factory: function() {
        // TODO: Do these need to be long lived?
        // Someone could store a box for days and then use it
        // at that point the ID might no longer be valid.
        return foam.next$UID();
      }
    }
  ],

  methods: [
    {
      name: 'send',
      code: function send(msg) {
        this.registry.unregister(this.id);
        this.delegate.send(msg);
      },
      javaCode: `
getRegistry().unregister(getId());
getDelegate().send(message);
`
    }
  ]
});


text:
package org.databene.commons.converter;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.databene.commons.ConversionException;
import org.databene.commons.Converter;
import org.databene.commons.TimeUtil;

/**
 * Parses a {@link String} as a {@link Calendar}.
 * Created at 13.07.2009 18:49:00
 * @since 0.5.0
 * @author Volker Bergmann
 */

public class String2GregorianCalendarConverter extends ConverterWrapper<String, Date>
		implements Converter<String, GregorianCalendar> {

    public String2GregorianCalendarConverter() {
	    super(new String2DateConverter<Date>());
    }

    @Override
	public GregorianCalendar convert(String sourceValue) throws ConversionException {
	    Date date = realConverter.convert(sourceValue);
		return TimeUtil.gregorianCalendar(date);
    }

	@Override
	public Class<String> getSourceType() {
	    return String.class;
    }

	@Override
	public Class<GregorianCalendar> getTargetType() {
	    return GregorianCalendar.class;
    }

}


text:
package com.karasiq.bittorrent.announce

import java.net.InetSocketAddress

import akka.util.ByteString

import com.karasiq.bittorrent.dht.DHTMessages
import com.karasiq.bittorrent.format._
import com.karasiq.bittorrent.format.BEncodeImplicits._

case class TrackerPeer(peerId: Option[String], address: InetSocketAddress)

case class TrackerResponse(warning: Option[String], interval: Int, minInterval: Option[Int], trackerId: Option[String], complete: Option[Int], incomplete: Option[Int], peers: Seq[TrackerPeer])

case class TrackerError(reason: String)

object TrackerResponse {
  private def parsePeers: PartialFunction[BEncodedValue, Seq[TrackerPeer]] = {
    case BEncodedArray(peers) ⇒
      peers.collect {
        case BEncodedDictionary(values) ⇒
          val peer = values.toMap
          for {
            id <- Some(peer.string("peer id"))
            ip <- peer.string("ip")
            port <- peer.long("port")
          } yield TrackerPeer(id, InetSocketAddress.createUnresolved(ip, port.toInt))
      }.flatten

    case s: BEncodedString ⇒ // Compact
      DHTMessages.PeerAddress.parseList(s.asByteString)
        .map(pa ⇒ TrackerPeer(None, pa.address))
  }

  def fromBytes(str: ByteString): Either[TrackerError, TrackerResponse] = {
    val data = BEncode.parse(str.toArray[Byte])
    data match {
      case Seq(BEncodedDictionary(values)) ⇒
        val map = values.toMap
        map.string("failure reason") match {
          case Some(error) ⇒
            Left(TrackerError(s"Tracker error: $error"))

          case None ⇒
            val response = for {
              interval <- map.int("interval")
              peers <- map.get("peers").collect(parsePeers)
            } yield TrackerResponse(map.string("warning message"), interval, map.int("min interval"), map.string("tracker id"), map.int("complete"), map.int("incomplete"), peers)

            response.fold[Either[TrackerError, TrackerResponse]](Left(TrackerError("Invalid response")))(Right.apply)
        }

      case _ ⇒
        Left(TrackerError(s"Not a BEncoded value: ${str.utf8String}"))
    }
  }
}


text:
import os, sys

def execute(cmd, args):
    """
        Executes the right function
    """
    if args:
        if cmd == "cd":
            return cd(args)
        elif cmd == "cat":
            return cat(args)
    else:
        if cmd == "pwd":
            print(pwd())
        elif cmd == "ls":
            return ls()
        elif cmd == "exit":
            return exit()
        else:
            return "No such command"

def exit():
    """
        Exits the shell
    """
    sys.exit(0)

def cat(filename):
    """
        Displays the content of a file.
    """
    filename = filename[0]
    with open(filename) as f:
        for line in f:
            print(line, end="")

def ls():
    """
        Lists all files in the current directory.
    """
    list_of_files = [obj for obj in os.listdir(pwd())]
    for item in list_of_files:
        if os.path.isdir(pwd() + "/"  + item):
            index_of_item = list_of_files.index(item)
            list_of_files[index_of_item] = list_of_files[index_of_item] + "/"
            print(list_of_files[index_of_item])
            continue

        print(item)

def pwd():
    """
        Prints out the current working directory.
    """
    return os.getcwd()

def cd(path):
    if len(path) > 1:
        return "Command 'c' only takes in one argument!"

    path = path[0]
    try:
        os.chdir(path)
        pwd()
    except:
        return "No such directory!"

def main():
    """
        Main loop for program.
    """
    while True:
        cmd = input("command > ").split(" ")
        cmd, args = cmd[0], cmd[1:]
        execute(cmd, args)

if __name__ == "__main__":
    main()


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.ujorm.tools.xml.ApiElement (Ujorm 2.15 - ujo-web)</title>
<meta name="date" content="2021-04-05">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.ujorm.tools.xml.ApiElement

Packages that use ApiElement

Package
Description

org.ujorm.tools.web

org.ujorm.tools.web.table

org.ujorm.tools.xml

org.ujorm.tools.xml.builder

org.ujorm.tools.xml.config

org.ujorm.tools.xml.dom

A deprecated package

org.ujorm.tools.xml.model

Uses of ApiElement in org.ujorm.tools.web

Classes in org.ujorm.tools.web that implement ApiElement

Modifier and Type
Class and Description

class
Element

A HTML Element implements some methods for frequently used elements and attributes

 Usage

    MockServletResponse response = new MockServletResponse();
    try (HtmlElement html = HtmlElement.of(response)) {
        try (Element body = html.getBody()) {
            body.addHeading("Hello!")

class
HtmlElement

The root of HTML elements

 Usage

    MockServletResponse response = new MockServletResponse();
    try (HtmlElement html = HtmlElement.of(response)) {
        html.addBody().addHeading("Hello!")

Fields in org.ujorm.tools.web declared as ApiElement

Modifier and Type
Field and Description

protected ApiElement
Element.internalElement

An original XML element

Methods in org.ujorm.tools.web with parameters of type ApiElement

Modifier and Type
Method and Description

static Element
Element.of(ApiElement original)

New element for an API element

Constructors in org.ujorm.tools.web with parameters of type ApiElement

Constructor and Description

Element(ApiElement original)

New element for an API element

HtmlElement(ApiElement root,
           HtmlConfig config,
           Appendable writer)

Create new instance with empty html headers

Uses of ApiElement in org.ujorm.tools.web.table

Methods in org.ujorm.tools.web.table with parameters of type ApiElement

Modifier and Type
Method and Description

void
GridBuilder.build(ApiElement parent,
     ColumnModel sortedColumn,
     Function<GridBuilder<D>,Stream<D>> resource)

Build the HTML page including a table

void
GridBuilder.build(ApiElement parent,
     Function<GridBuilder<D>,Stream<D>> resource)

Build the HTML page including a table

Uses of ApiElement in org.ujorm.tools.xml

Classes in org.ujorm.tools.xml with type parameters of type ApiElement

Modifier and Type
Interface and Description

interface
ApiElement<E extends ApiElement<?>>

An element model API.

Classes in org.ujorm.tools.xml that implement ApiElement

Modifier and Type
Class and Description

class
AbstractElement<E extends AbstractElement<?>>

Deprecated.

Use the interface ApiElement rather.

Methods in org.ujorm.tools.xml with parameters of type ApiElement

Modifier and Type
Method and Description

void
AbstractWriter.writeRawValue(CharSequence rawValue,
             ApiElement element)

Write the content of an envelope

void
AbstractWriter.writeValue(Object value,
          ApiElement element,
          String attributeName)

Write escaped value to the output

Uses of ApiElement in org.ujorm.tools.xml.builder

Classes in org.ujorm.tools.xml.builder that implement ApiElement

Modifier and Type
Class and Description

class
XmlBuilder

A XML builder.

Uses of ApiElement in org.ujorm.tools.xml.config

Methods in org.ujorm.tools.xml.config with parameters of type ApiElement

Modifier and Type
Method and Description

CharSequence
Formatter.format(Object value,
      ApiElement element,
      String attributeName)

Format an objet value to a string ouptut, special characters will be escaped later.

void
ApiInjector.write(ApiElement element)

Performs an operation on the argument element.

Uses of ApiElement in org.ujorm.tools.xml.dom

Classes in org.ujorm.tools.xml.dom that implement ApiElement

Modifier and Type
Class and Description

class
XmlElement

Deprecated.

Use the XmlModel rather.

Uses of ApiElement in org.ujorm.tools.xml.model

Classes in org.ujorm.tools.xml.model that implement ApiElement

Modifier and Type
Class and Description

class
XmlModel

XML element model to rendering a XML file.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright 2019-2022, Pavel Ponec