text:
/*jshint browser:true */
/*global $ */(function()
{
 "use strict";
 /*
   hook up event handlers
 */
 function register_event_handlers()
 {

     /* button  #mapback */
    $(document).on("click", "#mapback", function(evt)
    {
         /*global activate_page */
         //activate_page("#mainpage");
        window.location.href='Det.html';
    });

        /* button  #rqdd */
    $(document).on("click", "#rqdd", function(evt)
    {
         /*global activate_page */
         //activate_page("#mainpage");
        window.location.href='dd.html';
    });

    }
 document.addEventListener("app.Ready", register_event_handlers, false);
})();
function crd_clk(){
        window.location.href='dist.html';

    }


text: <title>Implementation of plugin to Graylog to send stream via Syslog</title>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="shortcut icon" type="image/x-icon" href="/assets/images/favicon.png">

    <title>编译和安装Apache Http Server</title>
    <meta name="description"
          content="编译安装apr./configure –prefix=/usr/local/aprmake && make install">

    <link rel="canonical" href="http://127.0.0.1:4000/vps/2013/03/16/%E7%BC%96%E8%AF%91%E5%92%8C%E5%AE%89%E8%A3%85Apache-Http-Server-copy.html">
    <link rel="alternate" type="application/rss+xml" title="A place to write things" href="http://127.0.0.1:4000/feed.xml">

    <link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="/bower_components/octicons/octicons/octicons.css">
    <link rel="stylesheet" href="/bower_components/hover/css/hover-min.css">
    <link rel="stylesheet" href="/bower_components/primer-markdown/dist/user-content.min.css">
    <link rel="stylesheet" href="/assets/css/syntax.css">

    <link rel="stylesheet" href="/assets/css/common.css">

    <link rel="stylesheet" href="/assets/css/sidebar-post-nav.css">

             liuwei.co

                Home

                Open-Source

                Blog

                Bookmark

                About

编译和安装Apache Http Server

                 2013/03/16

编译安装apr

./configure –prefix=/usr/local/apr

make && make install

编译安装apr-util

./configure –prefix=/usr/local/apr-util

make && make install

编译安装pcre

./configure –prefix=/usr/local/pcre

出现 configure: error: You need a C++ compiler for C++ support

解决办法:sudo apt-get install g++

然后继续:

./configure –prefix=/usr/local/pcre

make && make install

最后编译安装Apache HTTP Server

./configure –prefix=/usr/local/apache \

–with-included-apr=/usr/local/apr \

–with-apr-util=/usr/local/apr-util \

–with-pcre=/usr/local/pcre

需要哪些模块功能可参考http://httpd.apache.org/docs/2.4/programs/configure.html

sudo gedit /usr/local/apache/conf/httpd.conf

在"#ServerName www.example.com:80"下面添加一行如下:

ServerName 127.0.0.1:80

/usr/local/apache/bin/apachectl -k start

打开浏览器输入:http://127.0.1.1/

出现 It works!

参考:

http://httpd.apache.org/docs/2.4/install.html

            Power by Yummy Jekyll

            TOP


text:
<?xml version="1.0" encoding="UTF-8"?>
<artifact name="Eventstore" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
    <file>org_wso2_sample_httpd_logs.xml</file>
</artifact>


text:
"""Provides a client to interact with Google Data API servers.

This module is used for version 2 of the Google Data APIs. The primary class
in this module is GDClient.

  GDClient: handles auth and CRUD operations when communicating with servers.
  GDataClient: deprecated client for version one services. Will be removed.
"""

__author__ = 'j.s@google.com (Jeff Scudder)'

import re
import atom.client
import atom.core
import atom.http_core
import gdata.gauth
import gdata.data

# Old imports
import gdata.service
import urllib
import urlparse
import gdata.auth
import atom

class Error(Exception):
  pass

class RequestError(Error):
  status = None
  reason = None
  body = None
  headers = None

class RedirectError(RequestError):
  pass

class CaptchaChallenge(RequestError):
  captcha_url = None
  captcha_token = None

class ClientLoginTokenMissing(Error):
  pass

class MissingOAuthParameters(Error):
  pass

class ClientLoginFailed(RequestError):
  pass

class UnableToUpgradeToken(RequestError):
  pass

class Unauthorized(Error):
  pass

class BadAuthenticationServiceURL(RedirectError):
  pass

class BadAuthentication(RequestError):
  pass

def error_from_response(message, http_response, error_class, response_body=None):
  """Creates a new exception and sets the HTTP information in the error.

  Args:
   message: str human readable message to be displayed if the exception is
            not caught.
   http_response: The response from the server, contains error information.
   error_class: The exception to be instantiated and populated with
                information from the http_response
   response_body: str (optional) specify if the response has already been read
                  from the http_response object.
  """
  if response_body is None:
    body = http_response.read()
  else:
    body = response_body
  error = error_class('%s: %i, %s' % (message, http_response.status, body))
  error.status = http_response.status
  error.reason = http_response.reason
  error.body = body
  error.headers = http_response.getheaders()
  return error

def get_xml_version(version):
  """Determines which XML schema to use based on the client API version.

  Args:
    version: string which is converted to an int. The version string is in
             the form 'Major.Minor.x.y.z' and only the major version number
             is considered. If None is provided assume version 1.
  """
  if version is None:
    return 1
  return int(version.split('.')[0])

class GDClient(atom.client.AtomPubClient):
  """Communicates with Google Data servers to perform CRUD operations.

  This class is currently experimental and may change in backwards
  incompatible ways.

  This class exists to simplify the following three areas involved in using
  the Google Data APIs.

  CRUD Operations:

  The client provides a generic 'request' method for making HTTP requests.
  There are a number of convenience methods which are built on top of
  request, which include get_feed, get_entry, get_next, post, update, and
  delete. These methods contact the Google Data servers.

  Auth:

  Reading user-specific private data requires authorization from the user as
  do any changes to user data. An auth_token object can be passed into any
  of the HTTP requests to set the Authorization header in the request.

  You may also want to set the auth_token member to a an object which can
  use modify_request to set the Authorization header in the HTTP request.

  If you are authenticating using the email address and password, you can
  use the client_login method to obtain an auth token and set the
  auth_token member.

  If you are using browser redirects, specifically AuthSub, you will want
  to use gdata.gauth.AuthSubToken.from_url to obtain the token after the
  redirect, and you will probably want to updgrade this since use token
  to a multiple use (session) token using the upgrade_token method.

  API Versions:

  This client is multi-version capable and can be used with Google Data API
  version 1 and version 2. The version should be specified by setting the
  api_version member to a string, either '1' or '2'.
  """

  # The gsessionid is used by Google Calendar to prevent redirects.
  __gsessionid = None
  api_version = None
  # Name of the Google Data service when making a ClientLogin request.
  auth_service = None
  # URL prefixes which should be requested for AuthSub and OAuth.
  auth_scopes = None

  def request(self, method=None, uri=None, auth_token=None,
              http_request=None, converter=None, desired_class=None,
              redirects_remaining=4, **kwargs):
    """Make an HTTP request to the server.

    See also documentation for atom.client.AtomPubClient.request.

    If a 302 redirect is sent from the server to the client, this client
    assumes that the redirect is in the form used by the Google Calendar API.
    The same request URI and method will be used as in the original request,
    but a gsessionid URL parameter will be added to the request URI with
    the value provided in the server's 302 redirect response. If the 302
    redirect is not in the format specified by the Google Calendar API, a
    RedirectError will be raised containing the body of the server's
    response.

    The method calls the client's modify_request method to make any changes
    required by the client before the request is made. For example, a
    version 2 client could add a GData-Version: 2 header to the request in
    its modify_request method.

    Args:
      method: str The HTTP verb for this request, usually 'GET', 'POST',
              'PUT', or 'DELETE'
      uri: atom.http_core.Uri, str, or unicode The URL being requested.
      auth_token: An object which sets the Authorization HTTP header in its
                  modify_request method. Recommended classes include
                  gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
                  among others.
      http_request: (optional) atom.http_core.HttpRequest
      converter: function which takes the body of the response as it's only
                 argument and returns the desired object.
      desired_class: class descended from atom.core.XmlElement to which a
                     successful response should be converted. If there is no
                     converter function specified (converter=None) then the
                     desired_class will be used in calling the
                     atom.core.parse function. If neither
                     the desired_class nor the converter is specified, an
                     HTTP reponse object will be returned.
      redirects_remaining: (optional) int, if this number is 0 and the
                           server sends a 302 redirect, the request method
                           will raise an exception. This parameter is used in
                           recursive request calls to avoid an infinite loop.

    Any additional arguments are passed through to
    atom.client.AtomPubClient.request.

    Returns:
      An HTTP response object (see atom.http_core.HttpResponse for a
      description of the object's interface) if no converter was
      specified and no desired_class was specified. If a converter function
      was provided, the results of calling the converter are returned. If no
      converter was specified but a desired_class was provided, the response
      body will be converted to the class using
      atom.core.parse.
    """
    if isinstance(uri, (str, unicode)):
      uri = atom.http_core.Uri.parse_uri(uri)

    # Add the gsession ID to the URL to prevent further redirects.
    # TODO: If different sessions are using the same client, there will be a
    # multitude of redirects and session ID shuffling.
    # If the gsession ID is in the URL, adopt it as the standard location.
    if uri is not None and uri.query is not None and 'gsessionid' in uri.query:
      self.__gsessionid = uri.query['gsessionid']
    # The gsession ID could also be in the HTTP request.
    elif (http_request is not None and http_request.uri is not None
          and http_request.uri.query is not None
          and 'gsessionid' in http_request.uri.query):
      self.__gsessionid = http_request.uri.query['gsessionid']
    # If the gsession ID is stored in the client, and was not present in the
    # URI then add it to the URI.
    elif self.__gsessionid is not None:
      uri.query['gsessionid'] = self.__gsessionid

    # The AtomPubClient should call this class' modify_request before
    # performing the HTTP request.
    #http_request = self.modify_request(http_request)

    response = atom.client.AtomPubClient.request(self, method=method,
        uri=uri, auth_token=auth_token, http_request=http_request, **kwargs)
    # On success, convert the response body using the desired converter
    # function if present.
    if response is None:
      return None
    if response.status == 200 or response.status == 201:
      if converter is not None:
        return converter(response)
      elif desired_class is not None:
        if self.api_version is not None:
          return atom.core.parse(response.read(), desired_class,
                                 version=get_xml_version(self.api_version))
        else:
          # No API version was specified, so allow parse to
          # use the default version.
          return atom.core.parse(response.read(), desired_class)
      else:
        return response
    # TODO: move the redirect logic into the Google Calendar client once it
    # exists since the redirects are only used in the calendar API.
    elif response.status == 302:
      if redirects_remaining > 0:
        location = response.getheader('Location')
        if location is not None:
          m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
          if m is not None:
            self.__gsessionid = m.group(1)
          # Make a recursive call with the gsession ID in the URI to follow
          # the redirect.
          return self.request(method=method, uri=uri, auth_token=auth_token,
                              http_request=http_request, converter=converter,
                              desired_class=desired_class,
                              redirects_remaining=redirects_remaining-1,
                              **kwargs)
        else:
          raise error_from_response('302 received without Location header',
                                    response, RedirectError)
      else:
        raise error_from_response('Too many redirects from server',
                                  response, RedirectError)
    elif response.status == 401:
      raise error_from_response('Unauthorized - Server responded with',
                                response, Unauthorized)
    # If the server's response was not a 200, 201, 302, or 401, raise an
    # exception.
    else:
      raise error_from_response('Server responded with', response,
                                RequestError)

  Request = request

  def request_client_login_token(self, email, password, source, service=None,
      account_type='HOSTED_OR_GOOGLE',
      auth_url=atom.http_core.Uri.parse_uri(
          'https://www.google.com/accounts/ClientLogin'),
      captcha_token=None, captcha_response=None):
    service = service or self.auth_service
    # Set the target URL.
    http_request = atom.http_core.HttpRequest(uri=auth_url, method='POST')
    http_request.add_body_part(
        gdata.gauth.generate_client_login_request_body(email=email,
            password=password, service=service, source=source,
            account_type=account_type, captcha_token=captcha_token,
            captcha_response=captcha_response),
        'application/x-www-form-urlencoded')

    # Use the underlying http_client to make the request.
    response = self.http_client.request(http_request)

    response_body = response.read()
    if response.status == 200:
      token_string = gdata.gauth.get_client_login_token_string(response_body)
      if token_string is not None:
        return gdata.gauth.ClientLoginToken(token_string)
      else:
        raise ClientLoginTokenMissing(
            'Recieved a 200 response to client login request,'
            ' but no token was present. %s' % (response_body,))
    elif response.status == 403:
      captcha_challenge = gdata.gauth.get_captcha_challenge(response_body)
      if captcha_challenge:
        challenge = CaptchaChallenge('CAPTCHA required')
        challenge.captcha_url = captcha_challenge['url']
        challenge.captcha_token = captcha_challenge['token']
        raise challenge
      elif response_body.splitlines()[0] == 'Error=BadAuthentication':
        raise BadAuthentication('Incorrect username or password')
      else:
        raise error_from_response('Server responded with a 403 code',
                                  response, RequestError, response_body)
    elif response.status == 302:
      # Google tries to redirect all bad URLs back to
      # http://www.google.<locale>. If a redirect
      # attempt is made, assume the user has supplied an incorrect
      # authentication URL
      raise error_from_response('Server responded with a redirect',
                                response, BadAuthenticationServiceURL,
                                response_body)
    else:
      raise error_from_response('Server responded to ClientLogin request',
                                response, ClientLoginFailed, response_body)

  RequestClientLoginToken = request_client_login_token

  def client_login(self, email, password, source, service=None,
                   account_type='HOSTED_OR_GOOGLE',
                   auth_url='https://www.google.com/accounts/ClientLogin',
                   captcha_token=None, captcha_response=None):
    service = service or self.auth_service
    self.auth_token = self.request_client_login_token(email, password,
        source, service=service, account_type=account_type, auth_url=auth_url,
        captcha_token=captcha_token, captcha_response=captcha_response)

  ClientLogin = client_login

  def upgrade_token(self, token=None, url=atom.http_core.Uri.parse_uri(
      'https://www.google.com/accounts/AuthSubSessionToken')):
    """Asks the Google auth server for a multi-use AuthSub token.

    For details on AuthSub, see:
    http://code.google.com/apis/accounts/docs/AuthSub.html

    Args:
      token: gdata.gauth.AuthSubToken or gdata.gauth.SecureAuthSubToken
          (optional) If no token is passed in, the client's auth_token member
          is used to request the new token. The token object will be modified
          to contain the new session token string.
      url: str or atom.http_core.Uri (optional) The URL to which the token
          upgrade request should be sent. Defaults to:
          https://www.google.com/accounts/AuthSubSessionToken

    Returns:
      The upgraded gdata.gauth.AuthSubToken object.
    """
    # Default to using the auth_token member if no token is provided.
    if token is None:
      token = self.auth_token
    # We cannot upgrade a None token.
    if token is None:
      raise UnableToUpgradeToken('No token was provided.')
    if not isinstance(token, gdata.gauth.AuthSubToken):
      raise UnableToUpgradeToken(
          'Cannot upgrade the token because it is not an AuthSubToken object.')
    http_request = atom.http_core.HttpRequest(uri=url, method='GET')
    token.modify_request(http_request)
    # Use the lower level HttpClient to make the request.
    response = self.http_client.request(http_request)
    if response.status == 200:
      token._upgrade_token(response.read())
      return token
    else:
      raise UnableToUpgradeToken(
          'Server responded to token upgrade request with %s: %s' % (
              response.status, response.read()))

  UpgradeToken = upgrade_token

  def get_oauth_token(self, scopes, next, consumer_key, consumer_secret=None,
                      rsa_private_key=None,
                      url=gdata.gauth.REQUEST_TOKEN_URL):
    """Obtains an OAuth request token to allow the user to authorize this app.

    Once this client has a request token, the user can authorize the request
    token by visiting the authorization URL in their browser. After being
    redirected back to this app at the 'next' URL, this app can then exchange
    the authorized request token for an access token.

    For more information see the documentation on Google Accounts with OAuth:
    http://code.google.com/apis/accounts/docs/OAuth.html#AuthProcess

    Args:
      scopes: list of strings or atom.http_core.Uri objects which specify the
          URL prefixes which this app will be accessing. For example, to access
          the Google Calendar API, you would want to use scopes:
          ['https://www.google.com/calendar/feeds/',
           'http://www.google.com/calendar/feeds/']
      next: str or atom.http_core.Uri object, The URL which the user's browser
          should be sent to after they authorize access to their data. This
          should be a URL in your application which will read the token
          information from the URL and upgrade the request token to an access
          token.
      consumer_key: str This is the identifier for this application which you
          should have received when you registered your application with Google
          to use OAuth.
      consumer_secret: str (optional) The shared secret between your app and
          Google which provides evidence that this request is coming from you
          application and not another app. If present, this libraries assumes
          you want to use an HMAC signature to verify requests. Keep this data
          a secret.
      rsa_private_key: str (optional) The RSA private key which is used to
          generate a digital signature which is checked by Google's server. If
          present, this library assumes that you want to use an RSA signature
          to verify requests. Keep this data a secret.
      url: The URL to which a request for a token should be made. The default
          is Google's OAuth request token provider.
    """
    http_request = None
    if rsa_private_key is not None:
      http_request = gdata.gauth.generate_request_for_request_token(
          consumer_key, gdata.gauth.RSA_SHA1, scopes,
          rsa_key=rsa_private_key, auth_server_url=url, next=next)
    elif consumer_secret is not None:
      http_request = gdata.gauth.generate_request_for_request_token(
          consumer_key, gdata.gauth.HMAC_SHA1, scopes,
          consumer_secret=consumer_secret, auth_server_url=url, next=next)
    else:
      raise MissingOAuthParameters(
          'To request an OAuth token, you must provide your consumer secret'
          ' or your private RSA key.')

    response = self.http_client.request(http_request)
    response_body = response.read()

    if response.status != 200:
      raise error_from_response('Unable to obtain OAuth request token',
                                response, RequestError, response_body)

    if rsa_private_key is not None:
      return gdata.gauth.rsa_token_from_body(response_body, consumer_key,
                                             rsa_private_key,
                                             gdata.gauth.REQUEST_TOKEN)
    elif consumer_secret is not None:
      return gdata.gauth.hmac_token_from_body(response_body, consumer_key,
                                              consumer_secret,
                                              gdata.gauth.REQUEST_TOKEN)

  GetOAuthToken = get_oauth_token

  def get_access_token(self, request_token,
                       url=gdata.gauth.ACCESS_TOKEN_URL):
    """Exchanges an authorized OAuth request token for an access token.

    Contacts the Google OAuth server to upgrade a previously authorized
    request token. Once the request token is upgraded to an access token,
    the access token may be used to access the user's data.

    For more details, see the Google Accounts OAuth documentation:
    http://code.google.com/apis/accounts/docs/OAuth.html#AccessToken

    Args:
      request_token: An OAuth token which has been authorized by the user.
      url: (optional) The URL to which the upgrade request should be sent.
          Defaults to: https://www.google.com/accounts/OAuthAuthorizeToken
    """
    http_request = gdata.gauth.generate_request_for_access_token(
        request_token, auth_server_url=url)
    response = self.http_client.request(http_request)
    response_body = response.read()
    if response.status != 200:
      raise error_from_response(
          'Unable to upgrade OAuth request token to access token',
          response, RequestError, response_body)

    return gdata.gauth.upgrade_to_access_token(request_token, response_body)

  GetAccessToken = get_access_token

  def modify_request(self, http_request):
    """Adds or changes request before making the HTTP request.

    This client will add the API version if it is specified.
    Subclasses may override this method to add their own request
    modifications before the request is made.
    """
    http_request = atom.client.AtomPubClient.modify_request(self,
                                                            http_request)
    if self.api_version is not None:
      http_request.headers['GData-Version'] = self.api_version
    return http_request

  ModifyRequest = modify_request

  def get_feed(self, uri, auth_token=None, converter=None,
               desired_class=gdata.data.GDFeed, **kwargs):
    return self.request(method='GET', uri=uri, auth_token=auth_token,
                        converter=converter, desired_class=desired_class,
                        **kwargs)

  GetFeed = get_feed

  def get_entry(self, uri, auth_token=None, converter=None,
                desired_class=gdata.data.GDEntry, **kwargs):
    return self.request(method='GET', uri=uri, auth_token=auth_token,
                        converter=converter, desired_class=desired_class,
                        **kwargs)

  GetEntry = get_entry

  def get_next(self, feed, auth_token=None, converter=None,
               desired_class=None, **kwargs):
    """Fetches the next set of results from the feed.

    When requesting a feed, the number of entries returned is capped at a
    service specific default limit (often 25 entries). You can specify your
    own entry-count cap using the max-results URL query parameter. If there
    are more results than could fit under max-results, the feed will contain
    a next link. This method performs a GET against this next results URL.

    Returns:
      A new feed object containing the next set of entries in this feed.
    """
    if converter is None and desired_class is None:
      desired_class = feed.__class__
    return self.get_feed(feed.get_next_url(), auth_token=auth_token,
                         converter=converter, desired_class=desired_class,
                         **kwargs)

  GetNext = get_next

  # TODO: add a refresh method to re-fetch the entry/feed from the server
  # if it has been updated.

  def post(self, entry, uri, auth_token=None, converter=None,
           desired_class=None, **kwargs):
    if converter is None and desired_class is None:
      desired_class = entry.__class__
    http_request = atom.http_core.HttpRequest()
    http_request.add_body_part(
        entry.to_string(get_xml_version(self.api_version)),
        'application/atom+xml')
    return self.request(method='POST', uri=uri, auth_token=auth_token,
                        http_request=http_request, converter=converter,
                        desired_class=desired_class, **kwargs)

  Post = post

  def update(self, entry, auth_token=None, force=False, **kwargs):
    """Edits the entry on the server by sending the XML for this entry.

    Performs a PUT and converts the response to a new entry object with a
    matching class to the entry passed in.

    Args:
      entry:
      auth_token:
      force: boolean stating whether an update should be forced. Defaults to
             False. Normally, if a change has been made since the passed in
             entry was obtained, the server will not overwrite the entry since
             the changes were based on an obsolete version of the entry.
             Setting force to True will cause the update to silently
             overwrite whatever version is present.

    Returns:
      A new Entry object of a matching type to the entry which was passed in.
    """
    http_request = atom.http_core.HttpRequest()
    http_request.add_body_part(
        entry.to_string(get_xml_version(self.api_version)),
        'application/atom+xml')
    # Include the ETag in the request if this is version 2 of the API.
    if self.api_version and self.api_version.startswith('2'):
      if force:
        http_request.headers['If-Match'] = '*'
      elif hasattr(entry, 'etag') and entry.etag:
        http_request.headers['If-Match'] = entry.etag
    return self.request(method='PUT', uri=entry.find_edit_link(),
                        auth_token=auth_token, http_request=http_request,
                        desired_class=entry.__class__, **kwargs)

  Update = update

  def delete(self, entry_or_uri, auth_token=None, force=False, **kwargs):
    # If the user passes in a URL, just delete directly, may not work as
    # the service might require an ETag.
    if isinstance(entry_or_uri, (str, unicode, atom.http_core.Uri)):
      return self.request(method='DELETE', uri=entry_or_uri,
                          auth_token=auth_token, **kwargs)
    http_request = atom.http_core.HttpRequest()
    # Include the ETag in the request if this is version 2 of the API.
    if self.api_version and self.api_version.startswith('2'):
      if force:
        http_request.headers['If-Match'] = '*'
      elif hasattr(entry_or_uri, 'etag') and entry_or_uri.etag:
        http_request.headers['If-Match'] = entry_or_uri.etag
    return self.request(method='DELETE', uri=entry_or_uri.find_edit_link(),
                        http_request=http_request, auth_token=auth_token,
                        **kwargs)

  Delete = delete

  #TODO: implement batch requests.
  #def batch(feed, uri, auth_token=None, converter=None, **kwargs):
  #  pass

  # TODO: add a refresh method to request a conditional update to an entry
  # or feed.

def _add_query_param(param_string, value, http_request):
  if value:
    http_request.uri.query[param_string] = value

class Query(object):

  def __init__(self, text_query=None, categories=None, author=None, alt=None,
               updated_min=None, updated_max=None, pretty_print=False,
               published_min=None, published_max=None, start_index=None,
               max_results=None, strict=False):
    """Constructs a Google Data Query to filter feed contents serverside.

    Args:
      text_query: Full text search str (optional)
      categories: list of strings (optional). Each string is a required
          category. To include an 'or' query, put a | in the string between
          terms. For example, to find everything in the Fitz category and
          the Laurie or Jane category (Fitz and (Laurie or Jane)) you would
          set categories to ['Fitz', 'Laurie|Jane'].
      author: str (optional) The service returns entries where the author
          name and/or email address match your query string.
      alt: str (optional) for the Alternative representation type you'd like
          the feed in. If you don't specify an alt parameter, the service
          returns an Atom feed. This is equivalent to alt='atom'.
          alt='rss' returns an RSS 2.0 result feed.
          alt='json' returns a JSON representation of the feed.
          alt='json-in-script' Requests a response that wraps JSON in a script
          tag.
          alt='atom-in-script' Requests an Atom response that wraps an XML
          string in a script tag.
          alt='rss-in-script' Requests an RSS response that wraps an XML
          string in a script tag.
      updated_min: str (optional), RFC 3339 timestamp format, lower bounds.
          For example: 2005-08-09T10:57:00-08:00
      updated_max: str (optional) updated time must be earlier than timestamp.
      pretty_print: boolean (optional) If True the server's XML response will
          be indented to make it more human readable. Defaults to False.
      published_min: str (optional), Similar to updated_min but for published
          time.
      published_max: str (optional), Similar to updated_max but for published
          time.
      start_index: int or str (optional) 1-based index of the first result to
          be retrieved. Note that this isn't a general cursoring mechanism.
          If you first send a query with ?start-index=1&max-results=10 and
          then send another query with ?start-index=11&max-results=10, the
          service cannot guarantee that the results are equivalent to
          ?start-index=1&max-results=20, because insertions and deletions
          could have taken place in between the two queries.
      max_results: int or str (optional) Maximum number of results to be
          retrieved. Each service has a default max (usually 25) which can
          vary from service to service. There is also a service-specific
          limit to the max_results you can fetch in a request.
      strict: boolean (optional) If True, the server will return an error if
          the server does not recognize any of the parameters in the request
          URL. Defaults to False.
    """
    self.text_query = text_query
    self.categories = categories or []
    self.author = author
    self.alt = alt
    self.updated_min = updated_min
    self.updated_max = updated_max
    self.pretty_print = pretty_print
    self.published_min = published_min
    self.published_max = published_max
    self.start_index = start_index
    self.max_results = max_results
    self.strict = strict

  def modify_request(self, http_request):
    _add_query_param('q', self.text_query, http_request)
    if self.categories:
      http_request.uri.query['categories'] = ','.join(self.categories)
    _add_query_param('author', self.author, http_request)
    _add_query_param('alt', self.alt, http_request)
    _add_query_param('updated-min', self.updated_min, http_request)
    _add_query_param('updated-max', self.updated_max, http_request)
    if self.pretty_print:
      http_request.uri.query['prettyprint'] = 'true'
    _add_query_param('published-min', self.published_min, http_request)
    _add_query_param('published-max', self.published_max, http_request)
    if self.start_index is not None:
      http_request.uri.query['start-index'] = str(self.start_index)
    if self.max_results is not None:
      http_request.uri.query['max-results'] = str(self.max_results)
    if self.strict:
      http_request.uri.query['strict'] = 'true'

  ModifyRequest = modify_request

class GDQuery(atom.http_core.Uri):

  def _get_text_query(self):
    return self.query['q']

  def _set_text_query(self, value):
    self.query['q'] = value

  text_query = property(_get_text_query, _set_text_query,
      doc='The q parameter for searching for an exact text match on content')

# Version 1 code.
SCOPE_URL_PARAM_NAME = gdata.service.SCOPE_URL_PARAM_NAME
# Maps the service names used in ClientLogin to scope URLs.
CLIENT_LOGIN_SCOPES = gdata.service.CLIENT_LOGIN_SCOPES

class AuthorizationRequired(gdata.service.Error):
  pass

class GDataClient(gdata.service.GDataService):
  """This class is deprecated.

  All functionality has been migrated to gdata.service.GDataService.
  """
  @atom.deprecated('This class will be removed, use GDClient instead.')
  def __init__(self, application_name=None, tokens=None):
    gdata.service.GDataService.__init__(self, source=application_name,
        tokens=tokens)

  @atom.deprecated('The GDataClient class will be removed in a future release'
                   ', use GDClient.ClientLogin instead')
  def ClientLogin(self, username, password, service_name, source=None,
      account_type=None, auth_url=None, login_token=None, login_captcha=None):
    gdata.service.GDataService.ClientLogin(self, username=username,
        password=password, account_type=account_type, service=service_name,
        auth_service_url=auth_url, source=source, captcha_token=login_token,
        captcha_response=login_captcha)

  @atom.deprecated('The GDataClient class will be removed in a future release'
                   ', use GDClient.GetEntry or GDClient.GetFeed')
  def Get(self, url, parser):
    """Simplified interface for Get.

    Requires a parser function which takes the server response's body as
    the only argument.

    Args:
      url: A string or something that can be converted to a string using str.
          The URL of the requested resource.
      parser: A function which takes the HTTP body from the server as it's
          only result. Common values would include str,
          gdata.GDataEntryFromString, and gdata.GDataFeedFromString.

    Returns: The result of calling parser(http_response_body).
    """
    return gdata.service.GDataService.Get(self, uri=url, converter=parser)

  @atom.deprecated('The GDataClient class will be removed in a future release'
                   ', use GDClient.Post instead')
  def Post(self, data, url, parser, media_source=None):
    """Streamlined version of Post.

    Requires a parser function which takes the server response's body as
    the only argument.
    """
    return gdata.service.GDataService.Post(self, data=data, uri=url,
        media_source=media_source, converter=parser)

  @atom.deprecated('The GDataClient class will be removed in a future release'
                   ', use GDClient.Put instead')
  def Put(self, data, url, parser, media_source=None):
    """Streamlined version of Put.

    Requires a parser function which takes the server response's body as
    the only argument.
    """
    return gdata.service.GDataService.Put(self, data=data, uri=url,
        media_source=media_source, converter=parser)

  @atom.deprecated('The GDataClient class will be removed in a future release'
                   ', use GDClient.Delete instead')
  def Delete(self, url):
    return gdata.service.GDataService.Delete(self, uri=url)

ExtractToken = gdata.service.ExtractToken
GenerateAuthSubRequestUrl = gdata.service.GenerateAuthSubRequestUrl


text:
import { IProgress, IProgressService2, IProgressStep, IProgressOptions } from 'vs/platform/progress/common/progress';
import { MainThreadProgressShape, MainContext, IExtHostContext, ExtHostProgressShape, ExtHostContext } from '../node/extHost.protocol';
import { extHostNamedCustomer } from 'vs/workbench/api/electron-browser/extHostCustomers';

@extHostNamedCustomer(MainContext.MainThreadProgress)
export class MainThreadProgress implements MainThreadProgressShape {

	private _progressService: IProgressService2;
	private _progress = new Map<number, { resolve: Function, progress: IProgress<IProgressStep> }>();
	private _proxy: ExtHostProgressShape;

	constructor(
		extHostContext: IExtHostContext,
		@IProgressService2 progressService: IProgressService2
	) {
		this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostProgress);
		this._progressService = progressService;
	}

	dispose(): void {
		this._progress.forEach(handle => handle.resolve());
		this._progress.clear();
	}

	$startProgress(handle: number, options: IProgressOptions): void {
		const task = this._createTask(handle);

		this._progressService.withProgress(options, task, () => this._proxy.$acceptProgressCanceled(handle));
	}

	$progressReport(handle: number, message: IProgressStep): void {
		if (this._progress.has(handle)) {
			this._progress.get(handle).progress.report(message);
		}
	}

	$progressEnd(handle: number): void {
		if (this._progress.has(handle)) {
			this._progress.get(handle).resolve();
			this._progress.delete(handle);
		}
	}

	private _createTask(handle: number) {
		return (progress: IProgress<IProgressStep>) => {
			return new Promise<any>(resolve => {
				this._progress.set(handle, { resolve, progress });
			});
		};
	}
}


text:
'use strict';

var should = require('should'),
  request = require('supertest');
var requireHelper = require('../requireHelper');
var app = requireHelper('src/server');

describe('GET /api/awesomeThings', function () {
  it('should respond with JSON array', function (done) {
    request(app)
      .get('/api/awesomeThings')
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function (err, res) {
        if (err) return done(err);
        res.body.should.be.instanceof(Array);
        done();
      });
  });
});


text:
FactoryBot.define do
  factory :blockage do
    issue_id { Faker::Number.digit }
    blocked_issue_id { Faker::Number.digit }
  end
end


text:
package br.com.rdfreitas.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/*import br.com.rdfreitas.dao.JdbcConhecimentoDao;*/
import br.com.rdfreitas.dao.JdbcUsuarioDao;
import br.com.rdfreitas.modelo.Usuario;

@Controller
public class LoginController {

private final JdbcUsuarioDao dao;

	@Autowired
	public LoginController(JdbcUsuarioDao dao){
		this.dao = dao;
	}

	@RequestMapping("loginForm")
	public String loginForm(){
		return "site/form-login";
	}

	@RequestMapping("efetuaLogin")
	public String efetuaLogin(Usuario usuario, HttpSession session){
		if(dao.existeUsuario(usuario)){
			session.setAttribute("usuarioLogado", usuario);
			return "menu";
		}
		return "redirect:loginForm";
	}

	@RequestMapping("logout")
	public String logout(HttpSession session){
		session.invalidate();
		return "redirect:loginForm";
	}
}


text:
package org.cactoos.collection;

import java.util.Collection;
import org.cactoos.list.ListOf;
import org.hamcrest.Description;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeMatcher;

/**
 * Matcher for collection.
 * @author Yegor Bugayenko (yegor256@gmail.com)
 * @version $Id$
 * @param <E> Type of source item
 * @since 0.23
 * @checkstyle JavadocMethodCheck (500 lines)
 */
public final class BehavesAsCollection<E> extends
    TypeSafeMatcher<Collection<E>>  {

    /**
     * Sample item.
     */
    private final E sample;

    /**
     * Ctor.
     * @param item Sample item
     */
    public BehavesAsCollection(final E item) {
        super();
        this.sample = item;
    }

    @Override
    @SuppressWarnings({ "unchecked", "PMD.ClassCastExceptionWithToArray" })
    public boolean matchesSafely(final Collection<E> col) {
        MatcherAssert.assertThat(col, Matchers.hasItem(this.sample));
        MatcherAssert.assertThat(col, Matchers.not(Matchers.emptyIterable()));
        MatcherAssert.assertThat(
            col, Matchers.hasSize(Matchers.greaterThan(0))
        );
        MatcherAssert.assertThat(
            new ListOf<>((E[]) col.toArray()),
            Matchers.hasItem(this.sample)
        );
        final E[] array = (E[]) new Object[col.size()];
        col.toArray(array);
        MatcherAssert.assertThat(
            new ListOf<>(array), Matchers.hasItem(this.sample)
        );
        MatcherAssert.assertThat(
            col.containsAll(new ListOf<>(this.sample)), Matchers.is(true)
        );
        return true;
    }

    @Override
    public void describeTo(final Description desc) {
        desc.appendText("not a valid collection");
    }
}


text:
import {Injectable} from "@angular/core";
import {Router} from "@angular/router";

export class UserAuth {
  constructor(public username: string,
              public password: string) {
  }
}

@Injectable()
export class AuthenticationService {

  constructor(private _router: Router) {
  }

  logout() {
    localStorage.removeItem("user");
    this._router.navigate(['/login']);
  }

  login(user, users) {
    var authenticatedUser = users.find(u => u.username === user.username);
    if (authenticatedUser && authenticatedUser.password === user.password) {
      localStorage.setItem("user", authenticatedUser);
      this._router.navigate(['/admin']);
      return true;
    }
    return false;
  }

  checkCredentials() {
    if (localStorage.getItem("user") === null) {
      this._router.navigate(['/login']);
    }
  }
}


text:
package org.jboss.aerogear.unifiedpush.rest;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

/**
 * The JAX-RS {@link Application} representing the base
 * entry point for all RESTful HTTP requests.
 */
@ApplicationPath("/rest")
public class RestApplication extends Application {
}


text:
#ifdef _MSC_VER
#pragma once
#endif

#ifndef ContactCache_H
#define ContactCache_H

#include "ContactListener.h"
#include "../../../bullet/LinearMath/btAlignedObjectArray.h"

#ifndef SWIG
struct ContactPair;
#endif //SWIG

/** @author Xoppa */
class ContactCache {
protected:
#ifndef SWIG
	bool filter;
	int events;
	btAlignedObjectArray<ContactPair> cache;
	//std::map<ContactPair, float> cache;
#endif
public:
	float cacheTime;

	ContactCache(bool dummy);
	virtual ~ContactCache();

#ifndef SWIG
	void setEvents(const int &events);
#endif //SWIG

	void enable();
	void disable();
	bool isEnabled();

	//virtual void onContactStarted(btPersistentManifold* manifold) = 0;
	//virtual void onContactStarted(const btCollisionObject* colObj0, const btCollisionObject* colObj1) = 0;
	//virtual void onContactStarted(const int &userValue0, const int &userValue1) = 0;

	virtual void onContactStarted(btPersistentManifold* manifold, const bool &match0, const bool &match1) = 0;
	//virtual void onContactStarted(const btCollisionObject* colObj0, const bool &match0, const btCollisionObject* colObj1, const bool &match1) = 0;
	//virtual void onContactStarted(const int &userValue0, const bool &match0, const int &userValue1, const bool &match1) = 0;

	//virtual void onContactEnded(btPersistentManifold* manifold) = 0;
	//virtual void onContactEnded(const btCollisionObject* colObj0, const btCollisionObject* colObj1) = 0;
	//virtual void onContactEnded(const int &userValue0, const int &userValue1) = 0;

	//virtual void onContactEnded(btPersistentManifold* manifold, const bool &match0, const bool &match1) = 0;
	virtual void onContactEnded(const btCollisionObject* colObj0, const bool &match0, const btCollisionObject* colObj1, const bool &match1) = 0;
	//virtual void onContactEnded(const int &userValue0, const bool &match0, const int &userValue1, const bool &match1) = 0;

	void clear();

	void update(float delta);

#ifndef SWIG
	int indexOf(const btCollisionObject* const &obj0, const btCollisionObject* const &obj1);

	void contactStarted(btPersistentManifold* manifold);

	void contactEnded(btPersistentManifold* manifold);
#endif //SWIG
};

#endif //ContactCache_H


text:
// 32feet.NET - Personal Area Networking for .NET
//
// InTheHand.Win32.Win32Error
//
// Copyright (c) 2011 Alan J McFarlane, All rights reserved.
// Copyright (c) 2011 In The Hand Ltd, All rights reserved.
// This source code is licensed under the MIT License

// Values from:
//   winerror.h --  error code definitions for the Win32 API functions   *
//   Copyright (c) Microsoft Corp.  All rights reserved.                 *

namespace InTheHand.Win32
{
    internal enum Win32Error
    {
        ERROR_SUCCESS = 0,
        ERROR_FILE_NOT_FOUND = 2,
        ERROR_INSUFFICIENT_BUFFER = 0x7A, //122
        ERROR_SERVICE_DOES_NOT_EXIST = 1060,
        ERROR_DEVICE_NOT_CONNECTED = 1167,
        ERROR_NOT_FOUND = 1168,
        ERROR_NOT_AUTHENTICATED = 1244,
    }
}


text:
package main

import (
	"time"
	"os"
	"net/http"
	"github.com/op/go-logging"
	"github.com/monoculum/formam"
)

var log = logging.MustGetLogger("cf")
var format = logging.MustStringFormatter(
	"%{color}%{time:15:04:05.000} %{shortfunc:20.20s} %{level:.4s} %{id:03x}%{color:reset} %{message}",
)

type Number struct {
	CallNumber string
	StartTime time.Time
	EndTime time.Time
}

type CallForwardService struct {
	Numbers []Number
	ActiveCalls map[string] *Call
}

func (cfs * CallForwardService) GetShiftNumbers () []Number {
	nums := make([]Number, 0, 100)

	log.Debug("Shift Numbers:")

	t := time.Now()
	for _, n := range cfs.Numbers {
		if t.After(n.StartTime) && t.Before(n.EndTime) {
			log.Debug(" %s", n.CallNumber)
			nums = append(nums, n)
		}
	}

	return nums
}

func (cfs * CallForwardService) GetCall (r * http.Request) *Call {

	sid := r.Header.Get("X-Twilio-CallSid")

	call, ok := cfs.ActiveCalls[sid]

	if !ok {
		call = cfs.NewCall(r)
	} else {
		var tcall TwimlCall

		r.ParseForm()
		if err := formam.Decode(r.Form, &tcall); err != nil {
			log.Error("%s", err)
		}
		call.CurrentInfo = tcall
	}

	return call
}

func (cfs * CallForwardService) NewCall (r * http.Request) *Call {

	var tcall TwimlCall

	r.ParseForm()
	if err := formam.Decode(r.Form, &tcall); err != nil {
		log.Error("%s", err)
	}

	c := new(Call)

	c.Numbers = cfs.GetShiftNumbers()
	c.NumberIndex = 0
	c.CallSid = tcall.CallSid
	c.Caller = tcall.Caller
	c.OriginalCall = tcall
	c.CurrentInfo = tcall

	cfs.ActiveCalls[c.CallSid] = c

	return c
}

func (cfs * CallForwardService) HandleCall(w http.ResponseWriter, r *http.Request) {
	call := cfs.GetCall(r)

	if call.NewCall() {
		log.Info("[%s] Incoming call from %s", call.CallSid, call.Caller)
	}

	// The connected call has ended
	if call.CallForwardEnded() == true {
		log.Info("Call Forward Ended")
		return;
	}

	// Caller has hungup
	if call.EndOfCall() {
		log.Info("[%s] Call ended", call.CallSid)

		hangup := NewHangup()
		hangup.Send(w)

		//call.End()
	} else {
		if !call.EndOfNumbers() {
			next_dial := call.GetNextNumber()
			log.Info("[%s] Dialing %s", call.CallSid, next_dial)

			dial := NewDial(next_dial)
			dial.Send(w)
		} else {
			log.Info("[%s] Out of Numbers", call.CallSid)

			hangup := NewNoNumbers()
			hangup.Send(w)
		}
	}
}

func (cfs CallForwardService) HandleScreen(w http.ResponseWriter, r *http.Request) {
	call := cfs.GetCall(r)

	log.Info("[%s] Attempting to connect %s with %s", call.CallSid, call.CurrentInfo.Caller, call.CurrentInfo.Called)

	screen := NewScreen()
	screen.Send(w)
}

func (cfs CallForwardService) HandleComplete(w http.ResponseWriter, r *http.Request) {
	call := cfs.GetCall(r)

	log.Info("[%s] Call connected %s to %s", call.CallSid, call.CurrentInfo.Caller, call.CurrentInfo.Called)

	complete := NewComplete()
	complete.Send(w)
}

func main () {

    backend := logging.NewLogBackend(os.Stderr, "", 0)

    backendFormatter := logging.NewBackendFormatter(backend, format)
	logging.SetBackend(backendFormatter)

	cfs := new(CallForwardService)
	cfs.Numbers = make([]Number, 0, 10)
	cfs.ActiveCalls = make(map[string]*Call)

	t := time.Now()

	nb := Number{"5095912174", t, t.Add(time.Hour)}
	cfs.Numbers = append(cfs.Numbers, nb)

	/*
	nb = Number{"5090000000", t.Add((-1) * time.Hour), t}
	cfs.Numbers = append(cfs.Numbers, nb)
	*/

	http.HandleFunc("/call", cfs.HandleCall)
	http.HandleFunc("/screen", cfs.HandleScreen)
	http.HandleFunc("/complete", cfs.HandleComplete)

	http.ListenAndServe(":8090", nil)

}


text:
// Copyright 2017, OpenCensus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <functional>
#include <memory>
#include <thread>

#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "gtest/gtest.h"
#include "opencensus/trace/exporter/status.h"
#include "opencensus/trace/sampler.h"
#include "opencensus/trace/span.h"

namespace {

TEST(SpanExample, ParentAndChildSpans) {
  auto root_span = ::opencensus::trace::Span::StartSpan("MyRootSpan");
  root_span.AddAnnotation(
      "I'm the root span and I'm about to create a child span.");
  auto child_span = ::opencensus::trace::Span::StartSpan("MyChildSpan",
                                                         /*parent=*/&root_span);
  EXPECT_EQ(root_span.context().trace_id(), child_span.context().trace_id());
  child_span.AddAnnotation("Hello, I'm the child span.");
  child_span.AddAttribute("example.com/my_key", "my value");
  child_span.AddAttributes(
      {{"example.com/a_number", 123}, {"example.com/is_present", true}});
  child_span.SetStatus(::opencensus::trace::StatusCode::INVALID_ARGUMENT,
                       "Example error - pretend MyChildSpan had bad inputs.");
  child_span.End();
  root_span.AddAnnotation(
      "I'm the root span again and my child span has just ended.");
  root_span.End();  // Implies status is OK.
}

TEST(SpanExample, AlwaysSample) {
  opencensus::trace::AlwaysSampler sampler;
  auto span = ::opencensus::trace::Span::StartSpan(
      "MyRootSpan", /*parent=*/nullptr, {&sampler});
  span.End();
}

void PretendCallback(::opencensus::trace::Span&& s) {
  s.AddAnnotation("Performing work.");
  s.End();
}

TEST(SpanExample, MoveSpan) {
  auto span = ::opencensus::trace::Span::StartSpan("OperationSpan");
  span.AddAnnotation("About to defer work.");
  // This work could be scheduled on a thread pool or deferred until after an
  // async operation completes.
  std::function<void()> callback = [&span] {
    PretendCallback(std::move(span));
  };
  callback();
}

void ParallelWorker(::opencensus::trace::Span* span, int work_unit) {
  span->AddAnnotation(
      absl::StrCat("Doing work unit ", work_unit,
                   " on behalf of currently installed context."));
}

TEST(SpanExample, PointerToSpan) {
  auto op_span = ::opencensus::trace::Span::StartSpan("OperationSpan");
  {
    std::thread t1(ParallelWorker, &op_span, 123);
    std::thread t2(ParallelWorker, &op_span, 456);
    t1.join();
    t2.join();
  }
  op_span.End();
}

}  // namespace


text:
$(function () {

    //Datetimepicker plugin
    $('.datetimepicker').bootstrapMaterialDatePicker({
        format: 'dddd DD MMMM YYYY - HH:mm',
        clearButton: true,
        weekStart: 1
    });

    $('#datepicker').bootstrapMaterialDatePicker({
        format: 'YYYY-MM-DD',
        clearButton: true,
        weekStart: 1,
        time: false
    });

    $('.timepicker').bootstrapMaterialDatePicker({
        format: 'HH:mm',
        clearButton: true,
        date: false
    });
});


text:
#import "DConnectMessage.h"
#import "multipart_parser.h"

@interface DConnectMultipartParser : NSObject

+ (instancetype)multipartParserWithURL:(NSURLRequest *)url
                              userData:(id)userData;

- (void)parse;

@property NSURLRequest *url;
@property id userData;

@end

/**
 * DConnectMultipartParserに引き渡すユーザデータ
 */
@interface UserData : NSObject

+ (instancetype)userDataWithRequest:(DConnectMessage *)request;

/// dConnectリクエストメッセージ
@property DConnectMessage* request;
/// HTTPリクエストのヘッダ解析ステージにおいて、Content-Typeを解析中かどうか
@property BOOL isContentDisposition;
/// Content-Typeのnameパラメータの値
@property NSString *name;
/// ファイルが指定された際の、Content-Typeのfilenameパラメータの値
@property NSString *filename;
/// ファイルが指定された際の、ファイルを一時保管URL
@property NSURL *uri;
/**
 * パース中にコンテンツデータを溜め込むバッファ
 */
@property NSMutableData *bodyBuf;

@end


text:
'use strict';

/**
 * The parameters used to update a firewall rule.
 *
 */
class UpdateFirewallRuleParameters {
  /**
   * Create a UpdateFirewallRuleParameters.
   * @property {string} [startIpAddress] The start IP address for the firewall
   * rule. This can be either ipv4 or ipv6. Start and End should be in the same
   * protocol.
   * @property {string} [endIpAddress] The end IP address for the firewall
   * rule. This can be either ipv4 or ipv6. Start and End should be in the same
   * protocol.
   */
  constructor() {
  }

  /**
   * Defines the metadata of UpdateFirewallRuleParameters
   *
   * @returns {object} metadata of UpdateFirewallRuleParameters
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'UpdateFirewallRuleParameters',
      type: {
        name: 'Composite',
        className: 'UpdateFirewallRuleParameters',
        modelProperties: {
          startIpAddress: {
            required: false,
            serializedName: 'properties.startIpAddress',
            type: {
              name: 'String'
            }
          },
          endIpAddress: {
            required: false,
            serializedName: 'properties.endIpAddress',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = UpdateFirewallRuleParameters;


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)

## [1.0.0] - 2020-12-11

### Breaking changes
- `Maybe<T>` implements `IEquatable<Maybe<T>>` now
    - It already had non-interface `Equals` method before that
- Remove assembly signing
- Some utility methods are moved from `Try` instance to `TryExtensions` for better interop with nullable types

### Changed
- Add nullable annotations
- Target language version is C# 8.0
- Target platform is netstandard2.0
- Run tests and build under .NET Core 3.1


text:
/*
 * dfs-stack.c
 *
 *  Created on: May 7, 2009
 *  Author: laarman

 \brief a framestack build with two stacks
 */

#include <hre/config.h>

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <hre/user.h>
#include <util-lib/dfs-stack.h>

struct dfs_stack {
    isb_allocator_t states;
    isb_allocator_t frames;
    int frame_size; //size of current stack frame
    int frame_bottom;
    size_t nframes;
};

char *
dfs_stack_to_string (dfs_stack_t stack, char *r, ssize_t *sz_)
{
    ssize_t sz = *sz_;
    *sz_ = snprintf(r, sz, "FrameStack[%zu | %zu / %zu]",
                    isba_elt_size(stack->states),
                    isba_size_int(stack->states), isba_size_int(stack->frames));
    return r;
}

dfs_stack_t
dfs_stack_create (size_t element_size)
{
    dfs_stack_t result = RTmalloc(sizeof(struct dfs_stack));
    result->states = isba_create(element_size);
    result->frames = isba_create(2);
    result->frame_size = 0;
    result->frame_bottom = 0;
    result->nframes = 0;
    return result;
}

size_t
dfs_stack_nframes (const dfs_stack_t stack)
{
    return stack->nframes;
}

size_t
dfs_stack_frame_size (dfs_stack_t stack)
{
    return stack->frame_size - stack->frame_bottom;
}

size_t
dfs_stack_size (dfs_stack_t stack)
{
    return isba_size_int ( stack->states );
}

static void
clean_frame(dfs_stack_t stack)
{
    if (stack->frame_bottom){
        isba_discard_int(stack->states, stack->frame_bottom);
        stack->frame_bottom = 0;
        stack->frame_size = 0;
    }
}

void
dfs_stack_destroy (dfs_stack_t stack)
{
    isba_destroy(stack->states);
    isba_destroy(stack->frames);
    RTfree(stack);
}

void
dfs_stack_enter (dfs_stack_t stack)
{
    if (stack->frame_size == stack->frame_bottom) Abort("Enter on empty frame %d == %d ", stack->frame_size, stack->frame_bottom);
    int t[2] = {stack->frame_size, stack->frame_bottom};
    isba_push_int(stack->frames, t);
    stack->frame_size = 0;
    stack->frame_bottom = 0;
    stack->nframes++;
}

void
dfs_stack_leave (dfs_stack_t stack)
{
    if (stack->nframes == 0) Abort("Leave on empty stack");
    isba_discard_int(stack->states, stack->frame_size);
    int         *top = isba_top_int(stack->frames);
    stack->frame_size = top[0];
    stack->frame_bottom = top[1];
    isba_pop_int(stack->frames);
    stack->nframes--;
}

int *
dfs_stack_push (dfs_stack_t stack, const int *state)
{
    stack->frame_size++;
    return isba_push_int(stack->states, state);
}

int *
dfs_stack_pop (dfs_stack_t stack)
{
    if (stack->frame_size == stack->frame_bottom) {
        clean_frame(stack);
        return NULL;
    }
    stack->frame_size--;
    return isba_pop_int(stack->states);
}

int *
dfs_stack_top (dfs_stack_t stack)
{
    if (stack->frame_size == stack->frame_bottom) {
        clean_frame(stack);
        return NULL;
    }
    return isba_top_int(stack->states);
}

int *
dfs_stack_peek_top2 (dfs_stack_t stack, size_t frame_offset, size_t o)
{
    if (!frame_offset && stack->frame_size == stack->frame_bottom)
        Abort("Peek top on empty frame");
    size_t offset = frame_offset ? stack->frame_size : 0;
    size_t x;
    for (x = 1; x < frame_offset; x++) {
        offset += isba_peek_int(stack->frames, x-1)[0];
    }
    return isba_peek_int(stack->states, offset + o);
}

int *
dfs_stack_peek_top (dfs_stack_t stack, size_t frame_offset)
{
    return dfs_stack_peek_top2 (stack, frame_offset, 0);
}

int *
dfs_stack_peek (dfs_stack_t stack, size_t offset)
{
    return isba_peek_int(stack->states, offset);
}

int *
dfs_stack_index (dfs_stack_t stack, size_t index)
{
    return isba_index(stack->states, index);
}

void
dfs_stack_discard (dfs_stack_t stack, size_t num)
{
    size_t frame_size;
    while ( (frame_size = dfs_stack_frame_size (stack)) < num ) {
        dfs_stack_leave( stack );
        num -= frame_size;
    }
    isba_discard_int(stack->states, num);
    stack->frame_size -= num;
}

void
dfs_stack_clear (dfs_stack_t stack)
{
    isba_discard_int (stack->states, isba_size_int(stack->states));
    isba_discard_int (stack->frames, isba_size_int(stack->frames));
    stack->nframes = 0;
    stack->frame_size = 0;
    stack->frame_bottom = 0;
}

int *
dfs_stack_bottom (dfs_stack_t stack)
{
    if (stack->frame_size == stack->frame_bottom) {
        clean_frame(stack);
        return NULL;
    }
    return isba_peek_int(stack->states, stack->frame_size - stack->frame_bottom - 1);
}

int *
dfs_stack_pop_bottom (dfs_stack_t stack)
{
    if (stack->frame_size == stack->frame_bottom)
        Abort("pop bottom empty frame");
    stack->frame_bottom++;
    return isba_peek_int(stack->states, stack->frame_size - stack->frame_bottom);
}

/* stack:
 * [root] [frame 1  ..... ] [frame 2 .....  ]    .. [ last frame = stack->frame_size  .....
 * [ 0  ] [1 ] ...      [n] [ n+1 ] ..        [m-1] [ m + 1] ...... [l-1] [l]
 * result of walk up:
 * l, m-1, n, ... , root
 * down is the other way around..
 */
void
dfs_stack_walk_up(dfs_stack_t stack, int(*cb)(int*, void*), void* ctx)
{
    int offset = 0;
    int res = cb( isba_peek_int(stack->states, offset), ctx );
    if (res && stack->frame_size != 0) {
        offset += stack->frame_size;
        res = cb( isba_peek_int(stack->states, offset), ctx );
    }
    for(size_t i=0; i < stack->nframes-1 &&  res; i++) {
        offset += isba_peek_int(stack->frames, i)[0];
        res = cb( isba_peek_int(stack->states, offset), ctx );
    }
}

void
dfs_stack_walk_down(dfs_stack_t stack, int(*cb)(int*, void*), void* ctx)
{
    // set offset of the root node
    int offset = isba_size_int ( stack->states );
    int res = 1;

    for(size_t i=stack->nframes-1 ; i > 0 &&  res; i--) {
        offset -= isba_peek_int(stack->frames, i)[0];
        res = cb( isba_peek_int(stack->states, offset), ctx );
    }
    if (res && stack->frame_size != 0) {
        offset = stack->frame_size;
        res = cb( isba_peek_int(stack->states, offset), ctx );
    }
    if (res) res = cb( isba_peek_int(stack->states, 0), ctx );
}


text:
layout: post
title: Error Upgrading Boot2docker
author: joe_morgan
excerpt: ""
tags: [docker, devops, container, virtual container, upgrade, boot2docker, docker machine]
comments: true
---

I hadn't touched [Guapo](/guapo/ "Guapo") in awhile, and when I finally got a chance to start working on it again, low and behold there had been some major changes with Docker. Boot2docker has been largely supplanted by docker machine, which seems like a great move overall, but in trying to make the transition myself, I ran into a showstopper issue:

## Error getting IP address: Something went wrong running an SSH command! ##

Sufficiently vague for you? I mean, gotta love error messages that include the phrase "something went wrong".

I spent a couple of hours wading through issues on Github before finally hitting pay dirt. While this issue doesn't expressly call out my error message (which may have something to do with how long it took for me to find), the solution works just the same: delete the default VM in Virtual Box.

Now, I wasn't really being very judicious, so I also deleted several other VMs. Mostly just the ones you get from Microsoft Edge Dev (formerly modern.ie) for testing on old versions of Internet Explorer. So I can't say with 100% certainty which was the culprit. But I wanted to write this post in the event that it could save someone a couple hours of digging.

Happy upgrading!


text:
@interface RUViewController : UIViewController

@end


text:
\hypertarget{defines__1_8js}{}\section{/home/nrparikh/\+Desktop/acme\+\_\+robotics\+\_\+perception\+\_\+module/documentation/html/search/defines\+\_\+1.js File Reference}
\label{defines__1_8js}\index{/home/nrparikh/\+Desktop/acme\+\_\+robotics\+\_\+perception\+\_\+module/documentation/html/search/defines\+\_\+1.\+js@{/home/nrparikh/\+Desktop/acme\+\_\+robotics\+\_\+perception\+\_\+module/documentation/html/search/defines\+\_\+1.\+js}}
\subsection*{Variables}
\begin{DoxyCompactItemize}
\item
var \hyperlink{defines__1_8js_ad01a7523f103d6242ef9b0451861231e}{search\+Data}
\end{DoxyCompactItemize}

\subsection{Variable Documentation}
\index{defines\+\_\+1.\+js@{defines\+\_\+1.\+js}!search\+Data@{search\+Data}}
\index{search\+Data@{search\+Data}!defines\+\_\+1.\+js@{defines\+\_\+1.\+js}}
\subsubsection[{\texorpdfstring{search\+Data}{searchData}}]{\setlength{\rightskip}{0pt plus 5cm}var search\+Data}\hypertarget{defines__1_8js_ad01a7523f103d6242ef9b0451861231e}{}\label{defines__1_8js_ad01a7523f103d6242ef9b0451861231e}
{\bfseries Initial value\+:}
\begin{DoxyCode}
=
[
  [\textcolor{stringliteral}{'debug\_5fcamera'},[\textcolor{stringliteral}{'DEBUG\_CAMERA'},[\textcolor{stringliteral}{'../camera\_8cpp.html#ac0543811059575e953053b2d1820d482'},1,\textcolor{stringliteral}{'camera.cpp'}
      ]]]
]
\end{DoxyCode}

Definition at line 1 of file defines\+\_\+1.\+js.


text:
Dir.chdir File.join File.dirname(__FILE__), '../../../'
require './spec/env/iface.rb'
require './spec/lib/helpers.rb'
require './spec/lib/io_extensions.rb'
require './spec/lib/rspec_extensions.rb'

RSpec.describe "iface:kern:event" do
  module_dep "event"
  include_context "iface:kern"

  #A callback was registered in the kernel for testing purposes
  it "An event sent to the kernel will dispatch the `spec_event_handler` function and send the same info `int_event` received." do
    @secret = SecureRandom.hex

    #Wait for response
    @pipe.puts [0, "ping"].to_json; @pipe.readline_timeout

    #Send the event, we should get something back
    @pipe.puts [3, "int_event", 3848392, "my_event", {"secret" => @secret}].to_json

    res = [
      [0, 3, "if_event", 3848392, "my_event", {"secret"=>@secret}]
    ]

    expect(@pipe).to readline_and_equal_json_x_within_y_seconds(res, 5.seconds)
  end

  it "An event sent to the kernel will NOT dispatch the `spec_event_handler` if it has been de-registered" do
    @secret = SecureRandom.hex

    #Wait for response
    @pipe.puts [0, "ping"].to_json; @pipe.readline_timeout

    #De-register event function
    @pipe.puts [0, "int_spec_event_dereg"].to_json

    #Send the event, we should get something back
    @pipe.puts [3, "int_event", 3848392, "my_event", {"secret" => @secret}].to_json

    res = [
      [0, 3, "if_event", 3848392, "my_event", {"secret"=>@secret}]
    ]

    expect(@pipe).not_to readline_and_equal_json_x_within_y_seconds(res, 5.seconds)
  end
end


text:
package resolve

import (
	"path"
	"path/filepath"

	"github.com/bazelbuild/rules_go/go/tools/gazelle/config"
)

// Labeler generates Bazel labels for rules, based on their locations
// within the repository.
type Labeler interface {
	LibraryLabel(rel string) Label
	TestLabel(rel string, isXTest bool) Label
	BinaryLabel(rel string) Label
}

func NewLabeler(c *config.Config) Labeler {
	if c.StructureMode == config.FlatMode {
		return &flatLabeler{c}
	}
	return &hierarchicalLabeler{c}
}

type hierarchicalLabeler struct {
	c *config.Config
}

func (l *hierarchicalLabeler) LibraryLabel(rel string) Label {
	return Label{Pkg: rel, Name: config.DefaultLibName}
}

func (l *hierarchicalLabeler) TestLabel(rel string, isXTest bool) Label {
	var name string
	if isXTest {
		name = config.DefaultXTestName
	} else {
		name = config.DefaultTestName
	}
	return Label{Pkg: rel, Name: name}
}

func (l *hierarchicalLabeler) BinaryLabel(rel string) Label {
	name := relBaseName(l.c, rel)
	return Label{Pkg: rel, Name: name}
}

type flatLabeler struct {
	c *config.Config
}

func (l *flatLabeler) LibraryLabel(rel string) Label {
	if rel == "" {
		return Label{Name: relBaseName(l.c, rel)}
	}
	return Label{Name: rel}
}

func (l *flatLabeler) TestLabel(rel string, isXTest bool) Label {
	var suffix string
	if isXTest {
		suffix = "_xtest"
	} else {
		suffix = "_test"
	}
	if rel == "" {
		return Label{Name: relBaseName(l.c, rel) + suffix}
	}
	return Label{Name: rel + suffix}
}

func (l *flatLabeler) BinaryLabel(rel string) Label {
	suffix := "_cmd"
	if rel == "" {
		return Label{Name: relBaseName(l.c, rel) + suffix}
	}
	return Label{Name: rel + suffix}
}

func relBaseName(c *config.Config, rel string) string {
	base := path.Base(rel)
	if base == "." || base == "/" {
		base = path.Base(c.GoPrefix)
	}
	if base == "." || base == "/" {
		base = filepath.Base(c.RepoRoot)
	}
	if base == "." || base == "/" {
		base = "root"
	}
	return base
}


text:
package com.google.appengine.api.datastore;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A {@link List} implementation that pulls query results from the server lazily.
 *
 * <p>Although {@link AbstractList} only requires us to implement {@link #get(int)}, {@link
 * #size()}, {@link #set(int, Entity)}, and {@link #remove(int)}, we provide our own implementations
 * for many other methods. The reason is that many of the implementations in {@link AbstractList}
 * invoke {@link #size()}, which requires us to pull the entire result set back from the server. We
 * provide more efficient implementations wherever possible (which is most places).
 *
 */
class LazyList extends AbstractList<Entity> implements QueryResultList<Entity>, Serializable {
  static final long serialVersionUID = -288529194506134706L;

  // The iterator from which we'll pull results lazily.  Will be null if this
  // object is instantiated via deserialization.
  @Nullable private final transient QueryResultIteratorImpl resultIterator;
  final List<Entity> results = new ArrayList<Entity>();
  // True if the entire result set has been fetched from the server.
  private boolean endOfData = false;
  // True if the user has called clear().  We require a separate flag for this
  // because if a user requests a Cursor we need to fetch the entire result set
  // from the server even if clear() has been called (which in all other cases
  // prevents us from fetching additional results).
  private boolean cleared = false;

  // Null until the user asks for it.  Used to support serialization.
  /* @Nullabe */ private Cursor cursor = null;

  LazyList(QueryResultIteratorImpl resultIterator) {
    this.resultIterator = resultIterator;
  }

  /** Resolves the entire result set. */
  private void resolveAllData() {
    resolveToIndex(-1, true);
  }

  /**
   * Resolves enough of the result set to return the {@link Entity} at the specified {@code index}.
   * There is no guarantee that the result set actually has an {@link Entity} at this index, but
   * it's up to the caller to recognize this and respond appropriately.
   *
   * @param index The index to which we need to resolve.
   */
  private void resolveToIndex(int index) {
    resolveToIndex(index, false);
  }

  /**
   * Resolves enough of the result set to return the {@link Entity} at the specified {@code index}.
   * There is no guarantee that the result set actually has an {@link Entity} at this index, but
   * it's up to the caller to recognize this and respond appropriately.
   *
   * @param index The index to which we need to resolve.
   * @param fetchAll If {@code true}, ignores the provided index and fetches all data.
   */
  private void resolveToIndex(int index, boolean fetchAll) {
    if (cleared) {
      // user called clear() so don't bother trying to fetch any more data
      return;
    }
    forceResolveToIndex(index, fetchAll);
  }

  /**
   * @see #resolveToIndex(int, boolean) The only difference here is that we ignore the short-circuit
   *     that may have been set by a call to {@link #clear()}.
   */
  private void forceResolveToIndex(int index, boolean fetchAll) {
    if (endOfData) {
      // No more data so don't bother trying to fetch.
      return;
    }
    if (fetchAll || results.size() <= index) {
      // There might be more data available and we haven't resolved enough of
      // the result set to return the Entity at the index specified by the
      // user, so fetch more data.
      int numToFetch;
      if (fetchAll) {
        numToFetch = Integer.MAX_VALUE;
      } else {
        numToFetch = (index - results.size()) + 1;
      }

      if (resultIterator == null) {
        endOfData = true;
      } else {
        List<Entity> nextBatch = resultIterator.nextList(numToFetch);
        results.addAll(nextBatch);
        if (nextBatch.size() < numToFetch) {
          // If we got fewer results than we asked for then we know there is no
          // more data.
          endOfData = true;
        }
      }
    }
  }

  /** Implementation required for concrete implementations of {@link AbstractList}. */
  @Override
  public Entity get(int i) {
    resolveToIndex(i);
    // Will throw IndexOutOfBounds if the result set isn't large enough, which
    // is what we want.
    return results.get(i);
  }

  /** Implementation required for concrete implementations of {@link AbstractList}. */
  @Override
  public int size() {
    resolveAllData();
    return results.size();
  }

  /** Implementation required for concrete, modifiable implementations of {@link AbstractList}. */
  @Override
  public Entity set(int i, Entity entity) {
    resolveToIndex(i);
    return results.set(i, entity);
  }

  /**
   * Implementation required for concrete, modifiable, variable-length implementations of {@link
   * AbstractList}.
   */
  @Override
  public void add(int i, Entity entity) {
    resolveToIndex(i);
    // Will throw IndexOutOfBounds if the result set isn't large enough, which
    // is what we want.
    results.add(i, entity);
  }

  /**
   * Implementation required for concrete, modifiable, variable-length implementations of {@link
   * AbstractList}.
   */
  @Override
  public Entity remove(int i) {
    resolveToIndex(i);
    // Will throw IndexOutOfBounds if the result set isn't large enough, which
    // is what we want.
    return results.remove(i);
  }

  /** We provide our own implementation that does not invoke {@link #size()}. */
  @Override
  public Iterator<Entity> iterator() {
    return listIterator();
  }

  /**
   * We provide our own implementation that does not invoke {@link #size()}.
   *
   * @see ListIterator for the spec.
   */
  @Override
  public ListIterator<Entity> listIterator() {
    return new ListIterator<Entity>() {
      // Index into the List over which we're iterating.
      // Must be >= 0 and < size.  When next() is invoked, the element at this
      // index will be returned.  When previous() is invoked, the element at
      // this index - 1 will be returned.
      int currentIndex = 0;
      int indexOfLastElementReturned = -1;
      // The ListIterator spec has all sorts of rules about when you can call
      // different methods.  We use these members for book keeping so we can
      // enforce these rules.
      boolean elementReturned = false;
      boolean addOrRemoveCalledSinceElementReturned = false;

      @Override
      public boolean hasNext() {
        resolveToIndex(currentIndex);
        return currentIndex < results.size();
      }

      @Override
      public Entity next() {
        if (hasNext()) {
          elementReturned = true;
          addOrRemoveCalledSinceElementReturned = false;
          indexOfLastElementReturned = currentIndex++;
          return results.get(indexOfLastElementReturned);
        }
        throw new NoSuchElementException();
      }

      @Override
      public boolean hasPrevious() {
        return currentIndex > 0;
      }

      @Override
      public Entity previous() {
        if (hasPrevious()) {
          elementReturned = true;
          addOrRemoveCalledSinceElementReturned = false;
          indexOfLastElementReturned = --currentIndex;
          return results.get(indexOfLastElementReturned);
        }
        throw new NoSuchElementException();
      }

      @Override
      public int nextIndex() {
        return currentIndex;
      }

      @Override
      public int previousIndex() {
        return currentIndex - 1;
      }

      @Override
      public void remove() {
        if (!elementReturned || addOrRemoveCalledSinceElementReturned) {
          // ListIterator returned by ArrayList throws an exception with no
          // message for all these conditions.
          throw new IllegalStateException();
        }
        addOrRemoveCalledSinceElementReturned = true;
        if (indexOfLastElementReturned < currentIndex) {
          // the item we're removing is earlier than the current pointer so
          // move the current pointer down by one
          currentIndex--;
        }
        LazyList.this.remove(indexOfLastElementReturned);
      }

      @Override
      public void set(Entity entity) {
        if (!elementReturned || addOrRemoveCalledSinceElementReturned) {
          // ListIterator returned by ArrayList throws an exception with no
          // message.
          throw new IllegalStateException();
        }
        LazyList.this.set(indexOfLastElementReturned, entity);
      }

      @Override
      public void add(Entity entity) {
        addOrRemoveCalledSinceElementReturned = true;
        LazyList.this.add(currentIndex++, entity);
      }
    };
  }

  /**
   * The spec for this method says we need to throw {@link IndexOutOfBoundsException} if {@code
   * index} is < 0 or > size(). Since we need to know size up front, there's no way to service this
   * method without resolving the entire result set. The only reason for the override is to provide
   * a good location for this comment.
   */
  @Override
  public ListIterator<Entity> listIterator(int index) {
    return super.listIterator(index);
  }

  /** We provide our own implementation that does not invoke {@link #size()}. */
  @Override
  public boolean isEmpty() {
    resolveToIndex(0);
    return results.isEmpty();
  }

  /** We provide our own implementation that does not invoke {@link #size()}. */
  @Override
  public List<Entity> subList(int from, int to) {
    resolveToIndex(to - 1);
    return results.subList(from, to);
  }

  /** We provide our own implementation that does not invoke {@link #size()}. */
  @Override
  public void clear() {
    // clear out whatever we've paged in thus far
    results.clear();
    // make sure nothing else gets paged in
    cleared = true;
  }

  /** We provide our own implementation that does not invoke {@link #size()}. */
  @Override
  public int indexOf(Object o) {
    int index = 0;
    // for loop invokes iterator(), which will only pull back data as needed
    for (Entity e : this) {
      if (o == null) {
        if (e == null) {
          return index;
        }
      } else if (o.equals(e)) {
        return index;
      }
      index++;
    }
    return -1;
  }

  @Override
  public List<Index> getIndexList() {
    List<Index> indexList = null;
    if (resultIterator != null) {
      indexList = resultIterator.getIndexList();
    }
    return indexList;
  }

  @Override
  public Cursor getCursor() {
    if (cursor == null && resultIterator != null) {
      // The cursor needs to point to the end of the result set, so make sure we
      // resolve the entire result set before we actually ask for the cursor.
      forceResolveToIndex(-1, true); // Fetch all data.
      cursor = resultIterator.getCursor();
    }
    return cursor;
  }

  /**
   * Custom serialization logic to ensure that we read the entire result set before we serialize.
   */
  private void writeObject(ObjectOutputStream out) throws IOException {
    // Resolve all data before we serialize.
    resolveAllData();
    // Get ahold of the cursor before we serialize.
    cursor = getCursor();
    out.defaultWriteObject();
  }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.cost;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class PlanNodeStatsAndCostSummary
{
    private final double outputRowCount;
    private final double outputSizeInBytes;
    private final double cpuCost;
    private final double memoryCost;
    private final double networkCost;

    @JsonCreator
    public PlanNodeStatsAndCostSummary(
            @JsonProperty("outputRowCount") double outputRowCount,
            @JsonProperty("outputSizeInBytes") double outputSizeInBytes,
            @JsonProperty("cpuCost") double cpuCost,
            @JsonProperty("memoryCost") double memoryCost,
            @JsonProperty("networkCost") double networkCost)
    {
        this.outputRowCount = outputRowCount;
        this.outputSizeInBytes = outputSizeInBytes;
        this.cpuCost = cpuCost;
        this.memoryCost = memoryCost;
        this.networkCost = networkCost;
    }

    @JsonProperty("outputRowCount")
    public double getOutputRowCount()
    {
        return outputRowCount;
    }

    @JsonProperty("outputSizeInBytes")
    public double getOutputSizeInBytes()
    {
        return outputSizeInBytes;
    }

    @JsonProperty("cpuCost")
    public double getCpuCost()
    {
        return cpuCost;
    }

    @JsonProperty("memoryCost")
    public double getMemoryCost()
    {
        return memoryCost;
    }

    @JsonProperty("networkCost")
    public double getNetworkCost()
    {
        return networkCost;
    }
}


text:
package main

import "github.com/madyanov/gotcp"

type request struct {
	Name string `json:"name"`
	gotcp.RequestStruct
}

func main() {
	server := gotcp.NewServer(&gotcp.ServerConfig{
		Listen:     ":8088",
		NewRequest: func() gotcp.Request { return &request{} },
		Workers:    10,
		Buffer:     10,
	})

	// register commands
	server.Command("hello", func(req gotcp.Request) interface{} {
		if req, ok := req.(*request); ok {
			return map[string]string{
				"hello": "Hello, " + req.Name,
			}
		}

		return nil
	})

	// run server
	server.Listen()
}


text:
<?php

use Dbdg\Utils\StreamReaders\StreamReaderString;

class StreamReaderStringTest extends PHPUnit_Framework_TestCase
{

    public function setUp()
    {

    }

    /**
     * @test
     */
    public function basicUsage()
    {
        $expectedText = 'abcdefg';
        $streamReader = new StreamReaderString($expectedText);

        $result = $streamReader->read();
        $this->assertEquals($expectedText, $result);

        $this->assertTrue($streamReader->isEof());
    }

    /**
     * @test
     */
    public function beSureResultIsSplitWhenBufferLengthSpecified()
    {
        $baseText = 'abcdefg';
        $streamReader = new StreamReaderString($baseText);

        $result = $streamReader->read(3);
        $this->assertEquals('abc', $result);
        $this->assertFalse($streamReader->isEof());

        $result = $streamReader->read(3);
        $this->assertEquals('def', $result);
        $this->assertFalse($streamReader->isEof());

        $result = $streamReader->read(3);
        $this->assertEquals('g', $result);
        $this->assertTrue($streamReader->isEof());
    }

    /**
     * @test
     */
    public function beSureIsEofMethodCorrectlyWorks()
    {
        $baseText = 'abcdefg';
        $streamReader = new StreamReaderString($baseText);

        $streamReader->read(6);
        $this->assertFalse($streamReader->isEof());

        $streamReader->read(1);
        $this->assertTrue($streamReader->isEof());

    }

}


text:
"use strict"

module.exports = [
  [
    { route: 'form', text: 'Form', handler: require('./pages/form.jsx') },
    { route: 'formControl', text: 'FormControl', handler: require('./pages/formControl.jsx') },
    { route: 'formSubmit', text: 'FormSubmit', handler: require('./pages/formSubmit.jsx') },
    { route: 'checkbox', text: 'Checkbox', handler: require('./pages/checkbox.jsx') },
    { route: 'checkboxGroup', text: 'CheckboxGroup', handler: require('./pages/checkboxGroup.jsx') },
    { route: 'datetime', text: 'Datetime', handler: require('./pages/datetime.jsx') },
    { route: 'input', text: 'Input', handler: require('./pages/input.jsx') },
    { route: 'radioGroup', text: 'RadioGroup', handler: require('./pages/radioGroup.jsx') },
    { route: 'rating', text: 'Rating', handler: require('./pages/rating.jsx') },
    { route: 'select', text: 'Select', handler: require('./pages/select.jsx') },
    { route: 'tree', text: 'Tree', handler: require('./pages/tree.jsx') }
  ],
  [
    { route: 'table', text: 'Table', handler: require('./pages/table.jsx') },
    { route: 'filter', text: 'Filter', handler: require('./pages/filter.jsx') },
    { route: 'button', text: 'Button', handler: require('./pages/button.jsx') },
    { route: 'icon', text: 'Icon', handler: require('./pages/icon.jsx') },
    { route: 'lang', text: 'Lang', handler: require('./pages/lang.jsx') },
    { route: 'pagination', text: 'Pagination', handler: require('./pages/pagination.jsx') },
    { route: 'message', text: 'Message', handler: require('./pages/message.jsx') },
    { route: 'modal', text: 'Modal', handler: require('./pages/modal.jsx') },
    { route: 'dataSource', text: 'DataSource', handler: require('./pages/dataSource.jsx') }
  ]
]


text:
package id3v2

import (
	"bufio"
	"bytes"
	"io"
	"sync"
)

// bsPool is a pool of byte slices.
var bsPool = sync.Pool{
	New: func() interface{} { return nil },
}

// getByteSlice returns []byte with len >= minSize.
func getByteSlice(minSize int) []byte {
	fromPool := bsPool.Get()
	if fromPool == nil {
		return make([]byte, minSize)
	}
	bs := fromPool.([]byte)
	if len(bs) < minSize {
		bs = make([]byte, minSize)
	}
	return bs
}

// putByteSlice puts b to pool.
func putByteSlice(b []byte) {
	bsPool.Put(b)
}

// bwPool is a pool of *bufio.Writer.
var bwPool = sync.Pool{
	New: func() interface{} { return bufio.NewWriter(nil) },
}

// getBufioWriter returns *bufio.Writer with specified w.
func getBufioWriter(w io.Writer) *bufio.Writer {
	bw := bwPool.Get().(*bufio.Writer)
	bw.Reset(w)
	return bw
}

// putBufioWriter puts bw back to pool.
func putBufioWriter(bw *bufio.Writer) {
	bwPool.Put(bw)
}

// lrPool is a pool of *io.LimitedReader.
var lrPool = sync.Pool{
	New: func() interface{} { return new(io.LimitedReader) },
}

// getLimitedReader returns *io.LimitedReader with specified rd and n from pool.
func getLimitedReader(rd io.Reader, n int64) *io.LimitedReader {
	r := lrPool.Get().(*io.LimitedReader)
	r.R = rd
	r.N = n
	return r
}

// putLimitedReader puts r back to pool.
func putLimitedReader(r *io.LimitedReader) {
	r.N = 0
	r.R = nil
	lrPool.Put(r)
}

// rdPool is a pool of *reader.
var rdPool = sync.Pool{
	New: func() interface{} { return newReader(nil) },
}

// getUtilReader returns *reader with specified rd.
func getUtilReader(rd io.Reader) *reader {
	reader := rdPool.Get().(*reader)
	reader.Reset(rd)
	return reader
}

// putUtilReader puts rd back to pool.
func putUtilReader(rd *reader) {
	rdPool.Put(rd)
}

// bbPool is a pool of *bytes.Buffer.
var bbPool = sync.Pool{
	New: func() interface{} { return new(bytes.Buffer) },
}

// getBytesBuffer returns empty *bytes.Buffer.
func getBytesBuffer() *bytes.Buffer {
	return bbPool.Get().(*bytes.Buffer)
}

// putBytesBuffer resets buf and puts to pool.
func putBytesBuffer(buf *bytes.Buffer) {
	buf.Reset()
	bbPool.Put(buf)
}


text:
Sista föreläsningen lp3 (oopython, linux kmom10)
=================================

Digital Ocean
---------------------------------

1. (pi som hemmaserver)
(eget domännamn)

1. Create a droplet

1. Startmiljö som repo
https://github.com/mosbth/env

1. Visa install-biten

1. Visa aliases och fecr

Tmux och servrar
---------------------------------

1. Grunden med tmux

alias tmux_basic_start='tmux new-session -s basic'
alias tmux_basic='tmux attach -t basic'

alias tbs='tmux_basic_start'
alias tb='tmux_basic'
tb -d

1. Tmux med olika servrar

servrar, ssh.student, seekers, sweet
visa irc, logga in/ut och reconnecta

1. Komma åt egen hemmaserver

Logga in hemmaservern
Visa irc
Logga in på desktop

1. Infrastruktur mellan servrar

ssh
ssh keys

ssh-keygen -t rsa
ssh-copy-id -i $HOME/.ssh/id_rsa.pub mos@linux.dbwebb.se -p 2222

rsync
(git / github)
(tmux)

dbwebb-cli
---------------------------------

1. Repot
* https://github.com/mosbth/dbwebb-cli/graphs/contributors
* https://github.com/mosbth/dbwebb-cli/issues

1. Varför?
* Varför behövdes dbwebb-cli?
* Samband med första python kursen (och javascript1)
* Behov av validering
* Behov av att hjälpa på distans, upload/download
* Minifiering och skydd
* Förenkla rättning

1. Hur är det uppbyggt?
* v1 del av kursrepot, v2 som eget program
* dbwebb2, dbwebb2-validate, dbwebb2-inspect
* install.bash (https://dbwebb.se/dbwebb-cli/installera)
* Makefile slår samman delarna från \*.bash
* Funktioner, bootstrap, usage, script

1. Erfarenheter 3 år senare?
* Koll på bash-programmering
* Många små berg att kliva över...
* Skriptet, kursrepot, användarens konfig
* Kompabilitet mellan linux, Mac, Cygwin
* Struktur som fungerar att underhålla/vidarutveckla
* (delvis omskrivet 2 gånger)
* Mycket kod för att underhålla själva koden (selfupdate, check, etc)
* Passerar koden shellcheck?
* Värsta mardrömmen?

* 10-30% död kod, delvis bunden till äldre versioner
* Bakåtkompabilitet...
* Kod som skrivs kan "alltid" skrivas bättre
* (https://github.com/mosbth/dbwebb-cli/blob/master/dbwebb2#L371)

1. Kika på hur det fungerar
* dbwebb-init
* dbwebb-sshkey
* dbwebb-validate

1. Kärnan i dbwebb-validate
* validate()
* publish()
* publishChmod()

1. Kärnan i dbwebb-inspect
* Tex linuxkmom05()

1. Lokal testmiljö av kursrepo
* make test
* make dbwebb-validate
* make dbwebb-inspect

1. Summering
* Är det värt insatsen?

Node.js
------------------------------------------------

1. Moduler, exempel med guessmynumber
* (https://dbwebb.se/kunskap/gor-en-kommandoradsklient-i-node-js)

1. Promise
* (https://dbwebb.se/kunskap/nodejs-mysql-och-promise)

Python och venv med ooadv
------------------------------------------------

1. Var hamnar moduler som installeras?
* Globalt kontra lokalt?

- system packages
>>> import sys
>>> sys.prefix

- pip packages
>>> import site
>>> site.getsitepackages()

1. Virtual environments
https://docs.python.org/3/library/venv.html

1. Skapa, aktivera/deaktivera en venv
python3 -m venv .venv
.venv/bin/activate
deactivate

1. Exempel med python/example/image
wget https://raw.githubusercontent.com/dbwebb-se/python/master/example/image/image.py
wget https://github.com/dbwebb-se/python/raw/master/example/image/mos.jpg
python3 image.py
activate
pip install pillow
pip list
pip freeze

1. Miljö
```
# Python
alias activate=". .venv/bin/activate"
PIP_DOWNLOAD_CACHE="$HOME/.pip_download_cache"
[ -d "$PIP_DOWNLOAD_CACHE" ] || mkdir "$PIP_DOWNLOAD_CACHE"
```

1. ooadv med virtualenv
Skapa en virtualenv
Aktivera den
Installera alla moduler
Kolla med make check
Deaktivera
Kolla med make check


text:
package net.grinder.plugin.http.tcpproxyfilter;

import static net.grinder.util.NoOp.noOp;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.fail;
import net.grinder.tools.tcpproxy.ConnectionDetails;
import net.grinder.tools.tcpproxy.EndPoint;

import org.junit.Test;

/**
 * @author JunHo Yoon
 *
 */
public class ConnectionFilterTest {
	/**
	 * Test Connection Filter.
	 */
	@Test
	public void testConnectionFilter() {
		ConnectionFilter connectionFilter = new ConnectionFilterImpl();
		connectionFilter.addConnectionDetails(new ConnectionDetails(new EndPoint("hello", 80),
						new EndPoint("world", 80), false), true);
		assertThat(connectionFilter.isFiltered(new EndPoint("world", 80))).isFalse();

		connectionFilter.setFilter(new EndPoint("world", 80), true);
		assertThat(connectionFilter.isFiltered(new EndPoint("world", 80))).isTrue();

		connectionFilter.addConnectionDetails(new ConnectionDetails(new EndPoint("hello", 80),
						new EndPoint("world", 80), true), true);
		assertThat(connectionFilter.isFiltered(new EndPoint("world", 80))).isTrue();
		assertThat(connectionFilter.isChanged()).isTrue();
		assertThat(connectionFilter.getConnectionEndPoints()).hasSize(1);

		assertThat(connectionFilter.isFiltered(new EndPoint("world", 90))).isFalse();
		assertThat(connectionFilter.getConnectionEndPoints()).hasSize(1);
		assertThat(connectionFilter.getConnectionEndPoints()).contains(new EndPoint("world", 80));
		try {
			assertThat(connectionFilter.getConnectionEndPoint(2));
			fail("Error");
		} catch (Exception d) {
			noOp();
		}

	}
}


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { AppLoaderComponent } from './app-loader.component';

describe('AppLoaderComponent', () => {
  let component: AppLoaderComponent;
  let fixture: ComponentFixture<AppLoaderComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AppLoaderComponent ]
    })
    .compileComponents();
  }));

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

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


text:
namespace Limitless
{

UTILITIES_EXPORT glm::mat3 calibToRotation(std::vector<float> &params);
UTILITIES_EXPORT void rotationToCalib(glm::mat3 &mat, std::vector<float> &params);

UTILITIES_EXPORT glm::vec3 calibToTranslation(std::vector<float> &params);
UTILITIES_EXPORT void translationToCalib(glm::vec3 &vec, std::vector<float> &params);

UTILITIES_EXPORT glm::mat4 calibToTransformation(std::vector<float> &params);
UTILITIES_EXPORT void transformationToCalib(glm::mat4 &transform, std::vector<float> &params);

}//namespace Limitless

#endif //_utilities_glmHelper_h_


text:
"""Rules that check email body."""

import oa.regex
import oa.rules.base

class BodyRule(oa.rules.base.BaseRule):
    """Match a regular expression against the extracted text of the message.

    The text is:
        - decoded and stripped of any headers
        - all line break replaced with ' '
        - all HTML parts removed.
        - subject headers prepended
    """
    _rule_type = "BODY: "
    rule_type = "body"

    def __init__(self, name, pattern, score=None, desc=None, priority=0,
                 tflags=None):
        super(BodyRule, self).__init__(name, score=score, desc=desc,
                                       priority=priority, tflags=tflags)
        self._pattern = pattern

    def match(self, msg):
        return bool(self._pattern.match(msg.text))

    @staticmethod
    def get_rule_kwargs(data):
        kwargs = oa.rules.base.BaseRule.get_rule_kwargs(data)
        kwargs["pattern"] = oa.regex.perl2re(data["value"])
        return kwargs

class RawBodyRule(BodyRule):
    """Like the BodyRule but matches against the raw body.

    The text is:
        - decoded and stripped of any headers
    """
    _rule_type = "RAW: "
    rule_type = "rawbody"

    def match(self, msg):
        return bool(self._pattern.match(msg.raw_text))