text:
import zlib
import time
import os
import sys
from aquests.protocols.http import http_date, http_util
from rs4.reraise import reraise
from rs4 import producers, compressors
from aquests.protocols.http import respcodes
from ..wastuff import selective_logger
from ..utility import catch
import skitai
from rs4 import asyncore
import json
from skitai import exceptions
from ..wastuff.api import API, catch

try:
    from urllib.parse import urljoin
except ImportError:
    from urlparse import urljoin

UNCOMPRESS_MAX = 2048
ONETIME_COMPRESS_MAX = 1048576

# Default error message
DEFAULT_ERROR_MESSAGE = """<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>%(code)d %(message)s</title>

%(code)d %(message)s

%(detail)s

%(traceback)s

%(software)s

"""

class http_response:
    log_or_not = selective_logger.SelectiveLogger ()
    reply_code = 200
    reply_message = "OK"
    _is_async_streaming = False

    def __init__ (self, request):
        self.request = request
        self.reply_headers = [
            ('Server', skitai.NAME),
            ('Date', http_date.build_http_date (time.time()))
        ]
        altsvc = self.request.channel.server.altsvc
        if altsvc:
            self.reply_headers.append (("Alt-Svc", altsvc.ALTSVC_HEADER))
        self.outgoing = producers.fifo ()
        self._is_done = False
        self.stime = time.time ()
        self.htime = 0
        self.content_type = None
        self.current_app = None
        self.current_env = None

    def is_async_streaming (self):
        return self._is_async_streaming

    def set_streaming (self):
        self._is_async_streaming = True

    def is_responsable (self):
        return not self._is_done

    def is_done (self):
        return self._is_done

    def __len__ (self):
        return len (self.outgoing)

    def __setitem__ (self, key, value):
        self.set (key, value)

    def __getitem__ (self, key):
        return self.get (key)

    def __delitem__ (self, k):
        self.delete (k)

    def has_key (self, key):
        key = key.lower ()
        return key in [x [0].lower () for x in self.reply_headers]

    def set (self, key, value):
        self.reply_headers.append ((key, value))

    def get (self, key):
        key = key.lower ()
        for k, v in self.reply_headers:
            if k.lower () == key:
                return v

    def delete (self, key):
        index = 0
        found = 0
        key = key.lower ()
        for hk, hv in self.reply_headers:
            if key == hk.lower ():
                found = 1
                break
            index += 1

        if found:
            del self.reply_headers [index]
            self.delete (key)

    def update (self, key, value):
        self.delete (key)
        self.set (key, value)

    def append_header (self, key, value):
        val = self.get (key)
        if not val:
            self.set (key, value)
        else:
            self.set (key, val + ", " + value)

    set_header = set
    get_header = get
    del_header = delete

    def set_cache (self, max_age = 0):
        if self.request.version == "1.0":
            self.set_header ('Expires', http_date.build_http_date (time.time() + max_age))
        else:
            self.set_header ('Cache-Control', "max-age=%d" % max_age)

    def set_headers (self, headers):
        for k, v in headers:
            self.set (k, v)

    def append_headers (self, headers):
        for k, v in headers:
            self.set (k, v)

    def get_hedaers (self):
        return self.reply_headers

    def set_reply (self, status):
        # for atila.Atila App
        self.reply_code, self.reply_message = self.parse_ststus (status)
    set_status = set_reply

    def get_status (self):
        return "%d %s" % self.get_reply ()

    def build_reply_header (self, with_header = 1):
        h = [self.response (self.reply_code, self.reply_message)]
        if with_header:
            h.extend (['%s: %s' % x for x in self.reply_headers])
        h = '\r\n'.join (h) + '\r\n\r\n'
        return h

    def get_status_msg (self, code):
        return respcodes.get (code, "Undefined Error")

    def response (self, code, status):
        return 'HTTP/%s %d %s' % (self.request.version, code, status)

    def parse_ststus (self, status):
        try:
            code, status = status.split (" ", 1)
            code = int (code)
        except:
            raise AssertionError ("Can't understand given status code")
        return code, status

    def get_reply (self):
        # for atila.Atila App
        return self.reply_code, self.reply_message

    def instant (self, status = "", headers = None):
        # instance messaging
        if self.request.channel is None:
            return
        code, msg = self.parse_ststus (status)
        reply = [self.response (code, msg)]
        if headers:
            for header in headers:
                reply.append ("%s: %s" % header)
        self.request.channel.push (("\r\n".join (reply) + "\r\n\r\n").encode ("utf8"))

    # for WSGI App -------------------------------------------------------
    def start_response (self, status, headers = None, exc_info = None):
        if not self.is_responsable ():
            if exc_info:
                try:
                    reraise (*exc_info)
                finally:
                    exc_info = None
            else:
                raise AssertionError ("Response already sent!")
            return

        code, status = self.parse_ststus (status)
        self.start (code, status, headers)

        if exc_info:
            # expect plain/text, send exception info to developers
            content = catch (0, exc_info)
            self.push (content)

        return self.push #by WSGI Spec.

    # Internal Response Methods ------------------------------------------
    def abort (self, code, status = "", why = ""):
        self.request.channel.reject ()
        self.error (code, status, why, force_close = True)

    def start (self, code, status = "", headers = None):
        if not self.is_responsable ():
            return
        self.reply_code = code
        if status:
            self.reply_message = status
        else:
            self.reply_message = self.get_status_msg (code)
        if headers:
            if isinstance (headers, dict):
                headers = headers.items ()
            for k, v in headers:
                self.set (k, v)
    reply = start

    def catch (self, exc_info = None):
        if self.request.get_header ('accept').find ("application/json") != -1:
            return catch (2, exc_info)
        return catch (1, exc_info)

    def build_error_template (self, why = '', errno = 0, was = None):
        global DEFAULT_ERROR_MESSAGE

        exc_info = None
        if type (why) is tuple: # sys.exc_info ()
            if self.current_app and not self.current_app.debug:
                why = None
            exc_info, why  = why, ''

        is_html_response = self.request.get_header ('accept', '').find ("text/html") != -1
        error = {
            'code': self.reply_code,
            'errno': errno,
            'message': self.reply_message,
            'detail': why,
            'mode': exc_info and 'debug' or 'normal',
            'time': http_date.build_http_date (time.time ()),
            'url': urljoin ("%s://%s/" % (self.request.get_scheme (), self.request.get_header ("host")), self.request.uri),
            'software': skitai.NAME,
            'debug': None,
            "traceback": exc_info and catch (is_html_response and 1 or 2, exc_info) or None,
        }
        if self.current_app and hasattr (self.current_app, 'render_error'):
            content = None
            try:
                content = self.current_app.render_error (error, was)
            except:
                self.request.logger.trace ()
                if self.current_app.debug:
                    if is_html_response:
                        error ["traceback"] += "
Exception Occured During Building Error Template
" + catch (1)
                    else:
                        error ["traceback"] += ["Exception Occured During Building Error Template"] + catch (2)
            if content:
                return content

        if is_html_response:
            self.update ('content-type', 'text/html')
            return DEFAULT_ERROR_MESSAGE % {k: v or '' for k, v in error.items ()}
        else:
            return self.fault (
                error ["message"].lower (), errno,
                None,
                error ["detail"],
                exc_info = error ["traceback"]
            )

    def error (self, code, status = "", why = "", force_close = False, push_only = False):
        if not self.is_responsable (): return
        self.outgoing.clear ()
        self.reply_code = code
        if status: self.reply_message = status
        else:    self.reply_message = self.get_status_msg (code)

        body = self.build_error_template (why).encode ("utf8")
        self.update ('Content-Length', len(body))
        self.update ('Cache-Control', 'max-age=0')
        self.push (body)
        if not push_only:
            self.done (force_close)

    # Send Response -------------------------------------------------------
    def die_with (self, thing):
        if self.request.channel:
            self.request.channel.attend_to (thing)

    def push_promise (self, *args, **kargs):
        # ignore in version 1.x
        pass
    hint_promise = push_promise

    def push_and_done (self, thing, *args, **kargs):
        self.push (thing)
        self.done (*args, **kargs)

    def push (self, thing):
        if not self.is_responsable ():
            return
        if type(thing) is bytes:
            self.outgoing.push (producers.simple_producer (thing))
        else:
            self.outgoing.push (thing)

    def __call__ (self, status = "200 OK", body = None, headers = None, exc_info = None):
        self.start_response (status, headers)
        if body is None:
            return self.build_error_template (exc_info)
        return body

    def done (self, force_close = False, upgrade_to = None, with_header = 1):
        self.content_type = self.get ('content-type')

        if not self.is_responsable (): return
        self._is_done = True
        if self.request.channel is None: return

        self.htime = (time.time () - self.stime) * 1000
        self.stime = time.time () #for delivery time

        # compress payload and globbing production
        do_optimize = True
        if upgrade_to or self.is_async_streaming ():
            do_optimize = False

        connection = http_util.get_header (http_util.CONNECTION, self.request.header).lower()
        close_it = False
        way_to_compress = ""
        wrap_in_chunking = False

        if force_close:
            close_it = True
            if self.request.version == '1.1':
                self.update ('Connection', 'close')
            else:
                self.delete ('Connection')

        else:
            if self.request.version == '1.0':
                if connection == 'keep-alive':
                    if not self.has_key ('content-length'):
                        close_it = True
                        self.update ('Connection', 'close')
                    else:
                        self.update ('Connection', 'keep-alive')
                else:
                    close_it = True

            elif self.request.version == '1.1':
                if connection == 'close':
                    close_it = True
                    self.update ('Connection', 'close')
                if not self.has_key ('transfer-encoding') and not self.has_key ('content-length') and self.has_key ('content-type'):
                    wrap_in_chunking = True

            else:
                # unknown close
                self.update ('Connection', 'close')
                close_it = True

        if len (self.outgoing) == 0:
            self.update ('Content-Length', "0")
            self.delete ('transfer-encoding')
            self.delete ('content-type')
            outgoing_producer = producers.simple_producer (self.build_reply_header(with_header).encode ("utf8"))
            do_optimize = False

        elif len (self.outgoing) == 1 and hasattr (self.outgoing.first (), "ready"):
            outgoing_producer = producers.composite_producer (self.outgoing)
            if wrap_in_chunking:
                self.update ('Transfer-Encoding', 'chunked')
                outgoing_producer = producers.chunked_producer (outgoing_producer)
            outgoing_header = producers.simple_producer (self.build_reply_header(with_header).encode ("utf8"))
            self.request.channel.push_with_producer (outgoing_header)
            do_optimize = False

        elif do_optimize and not self.has_key ('Content-Encoding'):
            maybe_compress = self.request.get_header ("Accept-Encoding")
            if maybe_compress:
                cl = self.has_key ("content-length") and int (self.get ("Content-Length")) or -1
                if cl == -1:
                    cl = self.outgoing.get_estimate_content_length ()

                if 0 < cl  <= UNCOMPRESS_MAX:
                    maybe_compress = ""
                elif not wrap_in_chunking and cl > ONETIME_COMPRESS_MAX:
                    # too big for memory, do not compress
                    maybe_compress = ""

            if maybe_compress:
                content_type = self.get ("Content-Type")
                if content_type and (content_type.startswith ("text/") or content_type.startswith ("application/json")):
                    accept_encoding = [x.strip () for x in maybe_compress.split (",")]
                    if "gzip" in accept_encoding:
                        way_to_compress = "gzip"
                    elif "deflate" in accept_encoding:
                        way_to_compress = "deflate"

            if way_to_compress:
                if self.has_key ('Content-Length'):
                    self.delete ("content-length") # rebuild
                self.update ('Content-Encoding', way_to_compress)

            if wrap_in_chunking:
                outgoing_producer = producers.composite_producer (self.outgoing)
                self.delete ('content-length')
                self.update ('Transfer-Encoding', 'chunked')
                if way_to_compress:
                    if way_to_compress == "gzip":
                        compressing_producer = producers.gzipped_producer
                    else: # deflate
                        compressing_producer = producers.compressed_producer
                    outgoing_producer = compressing_producer (outgoing_producer)
                outgoing_producer = producers.chunked_producer (outgoing_producer)
                outgoing_header = producers.simple_producer (self.build_reply_header(with_header).encode ("utf8"))

            else:
                self.delete ('transfer-encoding')
                if way_to_compress:
                    if way_to_compress == "gzip":
                        compressor = compressors.GZipCompressor ()
                    else: # deflate
                        compressor = zlib.compressobj (6, zlib.DEFLATED)
                    cdata = b""
                    has_producer = 1
                    while 1:
                        has_producer, producer = self.outgoing.pop ()
                        if not has_producer: break
                        while 1:
                            data = producer.more ()
                            if not data:
                                break
                            cdata += compressor.compress (data)
                    cdata += compressor.flush ()
                    self.update ("Content-Length", len (cdata))
                    outgoing_producer = producers.simple_producer (cdata)
                else:
                    outgoing_producer = producers.composite_producer (self.outgoing)

                outgoing_header = producers.simple_producer (self.build_reply_header(with_header).encode ("utf8"))

            outgoing_producer = producers.composite_producer (
                producers.fifo([outgoing_header, outgoing_producer])
            )

        outgoing_producer = self.log_or_not (self.request.uri, outgoing_producer, self.log)
        if do_optimize:
            outgoing_producer = producers.globbing_producer (outgoing_producer)

        # IMP: second testing after push_with_producer()->init_send ()
        if self.request.channel is None: return

        if upgrade_to:
            request, terminator = upgrade_to
            self.request.channel.current_request = request
            self.request.channel.set_terminator (terminator)
        else:
            # preapre to receice new request for channel
            self.request.channel.current_request = None
            self.request.channel.set_terminator (b"\r\n\r\n")

        # proxy collector and producer is related to asynconnect
        # and relay data with channel
        # then if request is suddenly stopped, make sure close them
        self.die_with (self.request.collector)
        self.die_with (self.request.producer)

        logger = self.request.logger #IMP: for  disconnect with request
        try:
            if outgoing_producer:
                self.request.channel.push_with_producer (outgoing_producer)
            if close_it:
                self.request.channel.close_when_done ()
        except:
            logger.trace ()

    def maybe_log (self, bytes):
        if self.log_or_not.loggable (self.request.uri):
            self.log (bytes)

    def log (self, bytes):
        server = self.request.channel.server
        referer = self.request.get_header ('referer')
        real_ip = self.request.get_real_ip ()
        worker = server.worker_ident [0] == "m" and "M" or ("W" + server.worker_ident [1:])
        host = self.request.host
        server.log_request (
            '%s %s %s %s %d %d %d %s %d %s %s %s %s %s %s %s %s %d %d'
            % (
            self.request.channel.addr [0],
            self.request.is_promise () and "PUSH" or self.request.method,
            self.request.uri,
            self.request.version,
            self.request.rbytes, # recv body size

            self.reply_code,
            bytes, # send body size
            worker,
            self.htime, # due time to request handling

            self.request.user_agent and '"' + self.request.user_agent + '"' or "-",
            host and host [0].isalpha () and host or "-",
            referer and '"' + referer + '"' or "-",
            real_ip != self.request.channel.addr [0] and real_ip or '-',

            # debugging
            self.request.gtxid or "-",
            self.request.ltxid or "-",
            self.request.user and '"' + str (self.request.user) + '"' or "-",
            self.request.token or "-",

            len (asyncore.socket_map),
            (time.time () - self.stime) * 1000, # due time to sending data
            )
        )
        # clearing resources, back refs
        self.request.response_finished ()

    # Sugar syntaxes ----------------------------------------------------------------
    def set_timeout (self, timeout):
        self.request.channel.set_timeout (timeout)

    def adaptive_error (self, status, message, code, more_info):
        ac = self.request.get_header ('accept', '')
        if ac.find ("text/html") != -1:
            return self.with_explain (status, "{} (code: {}): {}".format (message, code, more_info))
        return self.Fault (status, message, code, None, more_info)

    def fault (self, message = "", code = 0, debug = None, more_info = None, exc_info = None, traceback = False):
        api = self.API ()
        if not code:
            code = int (self.reply_code) * 100 + (traceback and 90 or 0)
        if traceback:
            api.traceback (message, code, debug or "see traceback", more_info)
        else:
            api.error (message, code, debug, more_info, exc_info)
        return api
    eapi = fault # will be derecating

    def throw (self, status, why = ""):
        raise exceptions.HTTPError (status, why)

    def with_explain (self, status = "200 OK", why = "", errcode = None, headers = None):
        self.start_response (status, headers)
        return self.build_error_template (why, errcode)

    def API (self, __status__ = None, __data_dict__ = None, **kargs):
        if isinstance (__status__, str):
            self.set_status (__status__)
        elif isinstance (__status__, dict):
            __data_dict__ = __status__
        elif __status__ is not None:
            raise TypeError ("first arg for was.API should be status string or dict data only")
        if __data_dict__ and kargs:
            __data_dict__.update (kargs)
        api = API (self.request, __data_dict__ or kargs)
        self.update ("Content-Type", api.get_content_type ())
        return api
    api = API

    def Fault (self, status = "200 OK", *args, **kargs):
        self.set_status (status)
        r = self.fault (*args, **kargs)
        return self (status, r)
    for_api = Fault

    def File (self, path, mimetype = 'application/octet-stream', filename = None):
        self.set_header ('Content-Type',  mimetype)
        if filename:
            self.set_header ('Content-Disposition', 'attachment; filename="{}"'.format (filename))

        if isinstance (path, str):
            self.set_header ('Content-Length', str (os.path.getsize (path)))
            fp = open (path, "rb")
        else:
            fp = path
            fp.seek (0)
        return producers.file_producer (fp)

    file = File


text:
var library = require("./index");

var supportedLocales = library.getSupportedLanguages()

for (var i = 0; i < supportedLocales.length; i++) {
  var locale = require("./langs/" + supportedLocales[i] + ".json")
  library.registerLocale(locale);
}

module.exports = library;

redpajama_set_name: RedPajamaGithub


text:
/*

    Test the i18n helper functions in isolation.

*/
/* eslint-env node */
"use strict";
var fluid = require("infusion");
var gpii  = fluid.registerNamespace("gpii");
var jqUnit = require("node-jqunit");

fluid.require("%gpii-handlebars");

jqUnit.module("Unit tests for i18n functions.");

jqUnit.test("Testing message loading.", function () {
    var messageBundle = gpii.handlebars.i18n.loadMessageBundles(
        {
            primary: "%gpii-handlebars/tests/messages/primary",
            secondary: "%gpii-handlebars/tests/messages/secondary"
        },
        "en_us");

    jqUnit.assertEquals("Locale content should have been loaded as expected (from a map).", "Things are fine.", fluid.get(messageBundle, "en_us.how-are-things"));

    jqUnit.assertEquals("Content with no language/locale should be stored in the default locale.", "Yes, this works.", fluid.get(messageBundle, "en_us.files-without-suffixes-stored-in-default-locale"));

    jqUnit.assertEquals("Locale content from the primary directory should have been added to the language data.", "Things are fine.", fluid.get(messageBundle, "en.how-are-things"));

    jqUnit.assertEquals("Content should have been added from a secondary directory.", "Works just fine.", fluid.get(messageBundle, "en_us.unique-to-secondary-dir"));
    jqUnit.assertEquals("Content should have been merged from a secondary directory.", "Young.  I feel young.", fluid.get(messageBundle, "en_us.merged-key"));
    jqUnit.assertEquals("Unique locale content from a secondary directory should have been added to the language data.", "Works just fine.", fluid.get(messageBundle, "en.unique-to-secondary-dir"));

    var messageBundleFromArray = gpii.handlebars.i18n.loadMessageBundles(["%gpii-handlebars/tests/messages/primary","%gpii-handlebars/tests/messages/secondary"],"en_us");
    jqUnit.assertEquals("Locale content should have been loaded as expected (from an array).", "Things are fine.", fluid.get(messageBundleFromArray, "en_us.how-are-things"));

});

jqUnit.test("Testing message loading error handling.", function () {
    var messageBundle = gpii.handlebars.i18n.loadMessageBundles(["%non-existing-package/messages", "/bad/path/messages"]);
    jqUnit.assertDeepEq("An empty message bundle should be returned if no valid message directories are provided.", {}, messageBundle);
});

/*
{
  "en_gb": {
    "four-oh-four": "Oh dear.  Nothing here.",
    "how-are-things": "Things are tolerable.",
    "noQuotes": "Quote 'works' unquote.",
    "hasComment": "No comment at this time.",
    "message-key-from-uppercase": "IT WORKS!"
  },
  "en": {
    "four-oh-four": "Page not found.",
    "message-key-language-only": "Works.",
    "unique-to-secondary-dir": "Works just fine.",
    "merged-key": "Young.  I feel young.",
    "files-without-suffixes-stored-in-default-locale": "Yes, this works.",
    "how-are-things": "This is fine.",
    "shallow-variable": "This is %condition.",
    "deep-variable": "This is even %deep.value.",
    "noQuotes": "Quote 'works' unquote.",
    "hasComment": "No comment at this time.",
    "message-key-from-uppercase": "IT WORKS!"
  },
  "nl_be": {
    "keyboard": "klavier",
    "four-oh-four": "Hier is er geen kat."
  },
  "nl": {
    "how-are-things": "Het gaat goed.",
    "wave": "golf",
    "four-oh-four": "Hier is er geen hond.",
    "keyboard": "toetesenbord",
    "microwave": "magnetron"
  },
  "nl_nl": {
    "four-oh-four": "Hier is er geen hond.",
    "keyboard": "toetesenbord",
    "microwave": "magnetron"
  },
  "en_us": {
    "unique-to-secondary-dir": "Works just fine.",
    "merged-key": "Young.  I feel young.",
    "files-without-suffixes-stored-in-default-locale": "Yes, this works.",
    "four-oh-four": "Nothing to see here.",
    "how-are-things": "This is fine.",
    "shallow-variable": "This is %condition.",
    "deep-variable": "This is even %deep.value."
  }
}
*/

jqUnit.test("Testing deriving messages from message bundle by language/locale.", function () {
    var messageBundles = gpii.handlebars.i18n.loadMessageBundles(["%gpii-handlebars/tests/messages/primary", "%gpii-handlebars/tests/messages/secondary"], "en_us");

    var nlNlMessages =  gpii.handlebars.i18n.deriveMessageBundleFromHeader("nl_nl", messageBundles);
    jqUnit.assertEquals("Locale specific data should be included in a bundle derived from a locale.", "Hier is er geen hond.", fluid.get(nlNlMessages, "four-oh-four"));
    jqUnit.assertEquals("Language data should be included in a bundle derived from a locale.", "Het gaat goed.", fluid.get(nlNlMessages, "how-are-things"));
    jqUnit.assertEquals("Unique data from the default locale should be included in a bundle derived from a locale.", "This is %condition.", fluid.get(nlNlMessages, "shallow-variable"));

    var nlBeMessages =  gpii.handlebars.i18n.deriveMessageBundleFromHeader("nl_be", messageBundles);
    jqUnit.assertEquals("Locale specific data should be included in a bundle derived from a locale.", "Hier is er geen kat.", fluid.get(nlBeMessages, "four-oh-four"));
    jqUnit.assertEquals("Language data should be included in a bundle derived from a locale.", "Het gaat goed.", fluid.get(nlBeMessages, "how-are-things"));
    jqUnit.assertEquals("Unique from a locale with the same language should be included in a bundle derived from a locale.", "golf", fluid.get(nlBeMessages, "wave"));

    var enInMessages = gpii.handlebars.i18n.deriveMessageBundleFromHeader("en_in", messageBundles);
    jqUnit.assertEquals("A locale for which we have no messages should fail over to the language.", "Things are fine.", fluid.get(enInMessages, "how-are-things"));

    var zhTwMessages = gpii.handlebars.i18n.deriveMessageBundleFromHeader("zh_tw", messageBundles);
    jqUnit.assertEquals("A language for which we have no messages should fail over to the default.", "Things are fine.", fluid.get(zhTwMessages, "how-are-things"));

    jqUnit.assertDeepEq("Missing headers should be handled correctly in deriveMessageBundleFromHeader.", { "this": "works"}, gpii.handlebars.i18n.deriveMessageBundleFromHeader(undefined, { "my-default": { "this": "works"} }, "my-default"));

    jqUnit.assertDeepEq("Missing headers should be handled correctly in getAllLocalesFromHeader.", ["*"],  gpii.handlebars.i18n.getAllLocalesFromHeader());

    jqUnit.assertDeepEq("Garbled headers should be handled correctly in getAllLocalesFromHeader.", ["*"],  gpii.handlebars.i18n.getAllLocalesFromHeader(Math.PI));
});

jqUnit.test("Testing language detection from locale.", function () {
    jqUnit.assertEquals("A valid locale should return a language.", "en", gpii.handlebars.i18n.languageFromLocale("en_us"));
    jqUnit.assertEquals("Upper-case locale data should result in a lower case language.", "en", gpii.handlebars.i18n.languageFromLocale("EN_US"));
    jqUnit.assertEquals("A nonsensical locale should by handled correctly.", undefined, gpii.handlebars.i18n.languageFromLocale("Narnia"));
    jqUnit.assertEquals("An undefined locale should by handled correctly.", undefined, gpii.handlebars.i18n.languageFromLocale(undefined));
    jqUnit.assertEquals("A null locale should by handled correctly.", undefined, gpii.handlebars.i18n.languageFromLocale(null));
});


text:
package gojsonschema

import (
	"errors"
	"fmt"
	"strings"
)

type jsonSchemaType struct {
	types []string
}

// Is the schema typed ? that is containing at least one type
// When not typed, the schema does not need any type validation
func (t *jsonSchemaType) IsTyped() bool {
	return len(t.types) > 0
}

func (t *jsonSchemaType) Add(etype string) error {

	if !isStringInSlice(JSONTypes, etype) {
		return errors.New(formatErrorDescription(Locale.NotAValidType(), ErrorDetails{"given": "/" + etype + "/", "expected": JSONTypes}))
	}

	if t.Contains(etype) {
		return errors.New(formatErrorDescription(Locale.Duplicated(), ErrorDetails{"type": etype}))
	}

	t.types = append(t.types, etype)

	return nil
}

func (t *jsonSchemaType) Contains(etype string) bool {

	for _, v := range t.types {
		if v == etype {
			return true
		}
	}

	return false
}

func (t *jsonSchemaType) String() string {

	if len(t.types) == 0 {
		return StringUndefined // should never happen
	}

	// Displayed as a list [type1,type2,...]
	if len(t.types) > 1 {
		return fmt.Sprintf("[%s]", strings.Join(t.types, ","))
	}

	// Only one type: name only
	return t.types[0]
}


text:
import React, { PropTypes } from 'react';
import classNames from 'classnames';

/**
 * Contenedor principal de la aplicación.
 */
export default function Main (props) {

  const { className, children, ...rest } = props;
  const cls = classNames('main', className);

  return (
    <div className={cls} {...rest}>
      {children}
    </div>
  );
}

Main.propTypes = {
  children: PropTypes.any
};


text:
package org.apache.spark.sql.execution.ui

import org.apache.spark.sql.execution.SparkPlanInfo
import org.apache.spark.sql.test.SharedSparkSession

class SparkPlanInfoSuite extends SharedSparkSession{

  import testImplicits._

  def vaidateSparkPlanInfo(sparkPlanInfo: SparkPlanInfo): Unit = {
    sparkPlanInfo.nodeName match {
      case "InMemoryTableScan" => assert(sparkPlanInfo.children.length == 1)
      case _ => sparkPlanInfo.children.foreach(vaidateSparkPlanInfo)
    }
  }

  test("SparkPlanInfo creation from SparkPlan with InMemoryTableScan node") {
    val dfWithCache = Seq(
      (1, 1),
      (2, 2)
    ).toDF().filter("_1 > 1").cache().repartition(10)

    val planInfoResult = SparkPlanInfo.fromSparkPlan(dfWithCache.queryExecution.executedPlan)

    vaidateSparkPlanInfo(planInfoResult)
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="edu.byu.cs456.journall.social_journal.activities.note.AddNote"
    tools:showIn="@layout/activity_add_note">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <EditText
                android:id="@+id/note_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/note_title_hint"
                android:inputType="textCapWords"
                android:maxLines="1" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <EditText
                android:id="@+id/new_note"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="top|start"
                android:hint="@string/note_hint"
                android:inputType="textMultiLine|textCapSentences|textLongMessage"
                android:minLines="15"
                android:scrollbars="vertical" />
        </android.support.design.widget.TextInputLayout>
    </LinearLayout>

</android.support.constraint.ConstraintLayout>


text:
typedef NS_ENUM(NSInteger, AopubsUploaderMethod) {

    AopubsUploaderGetMethod = 1,

    AopubsUploaderPostMethod = 2,
};

typedef void(^AopubsUploaderCompletedBlock)(id _Nullable completedBlock);

@interface AopubsUploader : NSObject

+ (_Nonnull instancetype)shareInstance;

- (void)uploadUbsWithMethod:(AopubsUploaderMethod)method
                        URL:(NSString *_Nullable)urlString
                  parameter:(id _Nullable )parameter
             completedBlock:(AopubsUploaderCompletedBlock _Nullable )completedBlock;

@end


text:
"""Compute the bleu score on generated text and the ground truth."""

import math
import os
import pickle

from absl import app
from absl import flags
from absl import logging

import numpy as np

import utils

flags.DEFINE_string('checkpoint_dir', '/tmp/transformerXL',
                    'Checkpoint directory to load saved samples.')
flags.DEFINE_string('dataset', 'freebase2wikitext', 'Which dataset to the model'
                    ' is trained on, one of "wikitext", "freebase2wikitext".')

FLAGS = flags.FLAGS

def group_samples(samples, tokenizer):
  """Groups generated and ground truth texts."""
  groups = {}
  for i, row in enumerate(samples):
    gt = tokenizer.decode(row['ground_truth_text'])
    sample = tokenizer.decode(row['sample_tokens'])
    if gt not in groups:
      groups[gt] = (gt.split(), [sample.split()])
    else:
      groups[gt][-1].append(sample.split())
    if (i + 1) % 100 == 0:
      logging.info('Processed %d samples', i + 1)
  return groups

def eval_samples(raw_samples, tokenizer):
  """Evaluates generated samples."""
  gt_refs = []
  samples = []

  groups = group_samples(raw_samples, tokenizer)
  groups = list(groups.values())
  avg_group_size = np.mean([len(g[-1]) for g in groups])
  logging.info('Average samples per example: %.2f', avg_group_size)
  avg_group_size = int(math.ceil(avg_group_size))
  for i, (gt, s) in enumerate(groups):
    gt_refs.append(gt)
    idx = i % len(groups)
    samples.append(groups[idx][-1])

  gt_bleu, gt_n_grams = utils.compute_bleu(samples, gt_refs)

  logging.info('Processed %d samples in total.', sum([len(s) for s in samples]))
  flat_samples = []
  for s in samples:
    flat_samples.extend(s)
  logging.info('Average sample len: %.2f',
               np.mean([len(s) for s in flat_samples]))
  logging.info('Average ground-truth len: %.2f',
               np.mean([len(gt) for gt in gt_refs]))

  logging.info('Ground-truth BLEU: %6.2f, n-gram precision: (%s)',
               gt_bleu * 100,
               ', '.join(['%6.2f%%' % (s * 100) for s in gt_n_grams]))

def main(_):
  tokenizer = utils.init_tokenizer(FLAGS.dataset)
  checkpoint_dir = os.path.join(FLAGS.checkpoint_dir, 'samples.pkl')
  logging.info('Loading samples from %s', checkpoint_dir)
  with open(checkpoint_dir, 'rb') as f:
    samples = pickle.load(f)['samples']
  eval_samples(samples, tokenizer)

if __name__ == '__main__':
  app.run(main)


text:
using ZKWeb.Plugins.Shopping.Product.src.Components.ProductStates.Interfaces;
using ZKWebStandard.Ioc;

namespace ZKWeb.Plugins.Shopping.Product.src.Components.ProductStates {
	/// <summary>
	/// 准备上架
	/// </summary>
	[ExportMany]
	public class WaitForSales : IAmVisibleToThePublic {
		/// <summary>
		/// 商品状态
		/// </summary>
		public string State { get { return "WaitForSales"; } }
	}
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.commons.collections4.bag (Apache Commons Collections 4.0 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.apache.commons.collections4.bag

Classes

AbstractBagDecorator

AbstractMapBag

AbstractMapBag.MutableInteger

AbstractSortedBagDecorator

CollectionBag

CollectionSortedBag

HashBag

PredicatedBag

PredicatedSortedBag

SynchronizedBag

SynchronizedSortedBag

TransformedBag

TransformedSortedBag

TreeBag

UnmodifiableBag

UnmodifiableSortedBag


text:
module CRM
  class CustomerRating
    UNRATED = "Unrated"
  end
end


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>remove_if</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../../index.html" title="Chapter 1. Range 2.0">
<link rel="up" href="../mutating.html" title="Mutating algorithms">
<link rel="prev" href="remove_copy_if.html" title="remove_copy_if">
<link rel="next" href="replace.html" title="replace">

Home
Libraries
People
FAQ
More

remove_if

            Prototype

template<
    class ForwardRange,
    class UnaryPredicate
    >
typename range_iterator<ForwardRange>::type
remove(ForwardRange& rng, UnaryPredicate pred);

template<
    class ForwardRange,
    class UnaryPredicate
    >
typename range_iterator<const ForwardRange>::type
remove(const ForwardRange& rng, UnaryPredicate pred);

template<
    range_return_value re,
    class ForwardRange,
    class UnaryPredicate
    >
typename range_return<ForwardRange,re>::type
remove(ForwardRange& rng, UnaryPredicate pred);

template<
    range_return_value re,
    class ForwardRange,
    class UnaryPredicate
    >
typename range_return<const ForwardRange,re>::type
remove(const ForwardRange& rng, UnaryPredicate pred);

            Description

            remove_if removes from
            rng all of the elements
            x for which pred(x)
            is true. The versions of
            remove_if that return
            an iterator, return an iterator new_last
            such that the range [begin(rng), new_last) contains no elements where pred(x)
            is true. The iterators in
            the range [new_last, end(rng)) are dereferenceable, but the elements
            are unspecified.

            Definition

            Defined in the header file boost/range/algorithm/remove_if.hpp

            Requirements

                ForwardRange is a
                model of the Forward
                Range Concept.

                ForwardRange is mutable.

                UnaryPredicate is
                a model of the PredicateConcept.

                ForwardRange's value
                type is convertible to UnaryPredicate's
                argument type.

            Complexity

            Linear. remove_if performs
            exactly distance(rng)
            applications of pred.

Copyright © 2003-2010 Thorsten Ottosen,
      Neil Groves

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
for i in $(seq 0 10); do
    python3 ../src/pvcheck.py example.test ./program $i
    echo -----------------------------------------------
done


text:
module ConfigVolumizer
  VERSION = "0.3.1"
end


text:
package com.sheepdog.mashmesh.servlets;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class IndexServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.sendRedirect("/view/profile/");
    }
}


text:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>

#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>

#include <glib.h>

#include <gdbus.h>

#include "plugin.h"
#include "adapter.h"
#include "log.h"

static gboolean session_event(GIOChannel *chan,
					GIOCondition cond, gpointer data)
{
	unsigned char buf[672];
	gsize len, written;
	GIOError err;

	if (cond & (G_IO_HUP | G_IO_ERR | G_IO_NVAL))
		return FALSE;

	err = g_io_channel_read(chan, (gchar *) buf, sizeof(buf), &len);
	if (err == G_IO_ERROR_AGAIN)
		return TRUE;

	g_io_channel_write(chan, (const gchar *) buf, len, &written);

	return TRUE;
}

static gboolean connect_event(GIOChannel *chan,
					GIOCondition cond, gpointer data)
{
	GIOChannel *io;
	struct sockaddr_rc addr;
	socklen_t optlen;
	char address[18];
	int sk, nsk;

	sk = g_io_channel_unix_get_fd(chan);

	memset(&addr, 0, sizeof(addr));
	optlen = sizeof(addr);

	nsk = accept(sk, (struct sockaddr *) &addr, &optlen);
	if (nsk < 0)
		return TRUE;

	io = g_io_channel_unix_new(nsk);
	g_io_channel_set_close_on_unref(io, TRUE);

	ba2str(&addr.rc_bdaddr, address);

	g_io_add_watch(io, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
							session_event, NULL);

	return TRUE;
}

static GIOChannel *setup_rfcomm(uint8_t channel)
{
	GIOChannel *io;
	struct sockaddr_rc addr;
	int sk;

	sk = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
	if (sk < 0)
		return NULL;

	memset(&addr, 0, sizeof(addr));
	addr.rc_family = AF_BLUETOOTH;
	bacpy(&addr.rc_bdaddr, BDADDR_ANY);
	addr.rc_channel = channel;

	if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
		close(sk);
		return NULL;
	}

	if (listen(sk, 10) < 0) {
		close(sk);
		return NULL;
	}

	io = g_io_channel_unix_new(sk);
	g_io_channel_set_close_on_unref(io, TRUE);

	g_io_add_watch(io, G_IO_IN, connect_event, NULL);

	return io;
}

static GIOChannel *chan = NULL;

static int echo_probe(struct btd_adapter *adapter)
{
	const char *path = adapter_get_path(adapter);

	DBG("path %s", path);

	chan = setup_rfcomm(23);

	return 0;
}

static void echo_remove(struct btd_adapter *adapter)
{
	const char *path = adapter_get_path(adapter);

	DBG("path %s", path);

	g_io_channel_unref(chan);
}

static struct btd_adapter_driver echo_server = {
	.name	= "echo-server",
	.probe	= echo_probe,
	.remove	= echo_remove,
};

static int echo_init(void)
{
	DBG("Setup echo plugin");

	return btd_register_adapter_driver(&echo_server);
}

static void echo_exit(void)
{
	DBG("Cleanup echo plugin");

	btd_unregister_adapter_driver(&echo_server);
}

BLUETOOTH_PLUGIN_DEFINE(echo, VERSION,
		BLUETOOTH_PLUGIN_PRIORITY_DEFAULT, echo_init, echo_exit)


text:
<?php
namespace Vidal\DrugBundle\Command;

use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class DropNonRusCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('vidal:drop_non_rus');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        ini_set('memory_limit', -1);
        $output->writeln('--- vidal:drop_non_rus');

        /** @var EntityManager $em */
        $em = $this->getContainer()->get('doctrine')->getManager('drug');
        $pdo = $em->getConnection();

        $stmt = $pdo->prepare('SET FOREIGN_KEY_CHECKS=0');
        $stmt->execute();

        $this->changeYear($em);

        $pdo->prepare("DELETE FROM document WHERE IsApproved = 0")->execute();
        $pdo->prepare("DELETE FROM product WHERE IsNotForSite = 1")->execute();
        $pdo->prepare("DELETE FROM infopage WHERE CountryEditionCode != 'RUS'")->execute();
        $pdo->prepare("DELETE FROM company WHERE CountryEditionCode != 'RUS'")->execute();
        $pdo->prepare("DELETE FROM product WHERE CountryEditionCode != 'RUS'")->execute();
        $pdo->prepare("UPDATE document SET CountryEditionCode = 'RUS' WHERE CountryEditionCode IS NULL OR CountryEditionCode = ''")->execute();
        $pdo->prepare("DELETE FROM document WHERE CountryEditionCode != 'RUS'")->execute();

        $output->writeln("+++ vidal:drop_non_rus completed!");
    }

    private function changeYear(EntityManager $em)
    {
        // теперь, если у продукта есть документ 17 - го года(или, чтобы алгоритм был универсален, – скорее,
        // ПОСЛЕДУЮЩЕГО за текущим), и НЕТ НИКАКИХ ДРУГИХ(типы 1 и 4 не считаем – т . е . нет других документов
        // типов 2 и 5), выводим его под продуктом и пишем "2017" .

        $year = date('Y');

        $productDocuments = $em->createQuery("
			SELECT pd.ProductID, pd.DocumentID, d.ArticleID, d.YearEdition, d.IsNotForSite
			FROM VidalDrugBundle:ProductDocument pd
			JOIN VidalDrugBundle:Product p WITH p.ProductID = pd.ProductID
			JOIN VidalDrugBundle:Document d WITH d.DocumentID = pd.DocumentID
			WHERE d.ArticleID IN (2,5)
				AND d.YearEdition > $year
			ORDER BY pd.ProductID ASC
		")->getResult();

        $docIds = array();

        foreach ($productDocuments as $pd) {
            if (!empty($pd['DocumentID'])) {
                $pd2016 = $em->createQuery("
                    SELECT pd.ProductID, pd.DocumentID, d.ArticleID, d.YearEdition, d.IsNotForSite
                    FROM VidalDrugBundle:ProductDocument pd
                    JOIN VidalDrugBundle:Product p WITH p.ProductID = pd.ProductID
                    JOIN VidalDrugBundle:Document d WITH d.DocumentID = pd.DocumentID
                    WHERE d.ArticleID IN (2,5)
                        AND d.YearEdition <= $year
                        AND d.DocumentID = :documentID
                    ORDER BY pd.ProductID ASC
                ")->setParameter('documentID', $pd['DocumentID'])
                        ->getResult();

                if (empty($pd2016)) {
                    $docIds[] = $pd['DocumentID'];
                }
            }
        }

        if (!empty($docIds)) {
            $docIds = array_unique($docIds);

            $em->createQuery("
                UPDATE VidalDrugBundle:Document d
                SET d.YearEdition = $year
                WHERE d.DocumentID IN (:docIds)
            ")->setParameter('docIds', $docIds)
                ->execute();
        }
    }
}


text:
define(["Tone/core/Tone", "Tone/signal/Signal", "Tone/core/Timeline"], function (Tone) {

	"use strict";

	/**
	 *  @class A signal which adds the method getValueAtTime.
	 *         Code and inspiration from https://github.com/jsantell/web-audio-automation-timeline
	 *  @extends {Tone.Param}
	 *  @param {Number=} value The initial value of the signal
	 *  @param {String=} units The conversion units of the signal.
	 */
	Tone.TimelineSignal = function(){

		var options = this.optionsObject(arguments, ["value", "units"], Tone.Signal.defaults);

		//constructors
		Tone.Signal.apply(this, options);
		options.param = this._param;
		Tone.Param.call(this, options);

		/**
		 *  The scheduled events
		 *  @type {Tone.Timeline}
		 *  @private
		 */
		this._events = new Tone.Timeline(10);

		/**
		 *  The initial scheduled value
		 *  @type {Number}
		 *  @private
		 */
		this._initial = this._fromUnits(this._param.value);
	};

	Tone.extend(Tone.TimelineSignal, Tone.Param);

	/**
	 *  The event types of a schedulable signal.
	 *  @enum {String}
	 */
	Tone.TimelineSignal.Type = {
		Linear : "linear",
		Exponential : "exponential",
		Target : "target",
		Set : "set"
	};

	/**
	 * The current value of the signal.
	 * @memberOf Tone.TimelineSignal#
	 * @type {Number}
	 * @name value
	 */
	Object.defineProperty(Tone.TimelineSignal.prototype, "value", {
		get : function(){
			return this._toUnits(this._param.value);
		},
		set : function(value){
			var convertedVal = this._fromUnits(value);
			this._initial = convertedVal;
			this._param.value = convertedVal;
		}
	});

	///////////////////////////////////////////////////////////////////////////
	//	SCHEDULING
	///////////////////////////////////////////////////////////////////////////

	/**
	 *  Schedules a parameter value change at the given time.
	 *  @param {*}	value The value to set the signal.
	 *  @param {Time}  time The time when the change should occur.
	 *  @returns {Tone.TimelineSignal} this
	 *  @example
	 * //set the frequency to "G4" in exactly 1 second from now.
	 * freq.setValueAtTime("G4", "+1");
	 */
	Tone.TimelineSignal.prototype.setValueAtTime = function (value, startTime) {
		value = this._fromUnits(value);
		startTime = this.toSeconds(startTime);
		this._events.addEvent({
			"type" : Tone.TimelineSignal.Type.Set,
			"value" : value,
			"time" : startTime
		});
		//invoke the original event
		this._param.setValueAtTime(value, startTime);
		return this;
	};

	/**
	 *  Schedules a linear continuous change in parameter value from the
	 *  previous scheduled parameter value to the given value.
	 *
	 *  @param  {number} value
	 *  @param  {Time} endTime
	 *  @returns {Tone.TimelineSignal} this
	 */
	Tone.TimelineSignal.prototype.linearRampToValueAtTime = function (value, endTime) {
		value = this._fromUnits(value);
		endTime = this.toSeconds(endTime);
		this._events.addEvent({
			"type" : Tone.TimelineSignal.Type.Linear,
			"value" : value,
			"time" : endTime
		});
		this._param.linearRampToValueAtTime(value, endTime);
		return this;
	};

	/**
	 *  Schedules an exponential continuous change in parameter value from
	 *  the previous scheduled parameter value to the given value.
	 *
	 *  @param  {number} value
	 *  @param  {Time} endTime
	 *  @returns {Tone.TimelineSignal} this
	 */
	Tone.TimelineSignal.prototype.exponentialRampToValueAtTime = function (value, endTime) {
		value = this._fromUnits(value);
		value = Math.max(this._minOutput, value);
		endTime = this.toSeconds(endTime);
		this._events.addEvent({
			"type" : Tone.TimelineSignal.Type.Exponential,
			"value" : value,
			"time" : endTime
		});
		this._param.exponentialRampToValueAtTime(value, endTime);
		return this;
	};

	/**
	 *  Start exponentially approaching the target value at the given time with
	 *  a rate having the given time constant.
	 *  @param {number} value
	 *  @param {Time} startTime
	 *  @param {number} timeConstant
	 *  @returns {Tone.TimelineSignal} this
	 */
	Tone.TimelineSignal.prototype.setTargetAtTime = function (value, startTime, timeConstant) {
		value = this._fromUnits(value);
		value = Math.max(this._minOutput, value);
		timeConstant = Math.max(this._minOutput, timeConstant);
		startTime = this.toSeconds(startTime);
		this._events.addEvent({
			"type" : Tone.TimelineSignal.Type.Target,
			"value" : value,
			"time" : startTime,
			"constant" : timeConstant
		});
		this._param.setTargetAtTime(value, startTime, timeConstant);
		return this;
	};

	/**
	 *  Cancels all scheduled parameter changes with times greater than or
	 *  equal to startTime.
	 *
	 *  @param  {Time} startTime
	 *  @returns {Tone.TimelineSignal} this
	 */
	Tone.TimelineSignal.prototype.cancelScheduledValues = function (after) {
		this._events.cancel(after);
		this._param.cancelScheduledValues(this.toSeconds(after));
		return this;
	};

	/**
	 *  Sets the computed value at the given time. This provides
	 *  a point from which a linear or exponential curve
	 *  can be scheduled after. Will cancel events after
	 *  the given time and shorten the currently scheduled
	 *  linear or exponential ramp so that it ends at `time` .
	 *  This is to avoid discontinuities and clicks in envelopes.
	 *  @param {Time} time When to set the ramp point
	 *  @returns {Tone.TimelineSignal} this
	 */
	Tone.TimelineSignal.prototype.setRampPoint = function (time) {
		time = this.toSeconds(time);
		//get the value at the given time
		var val = this.getValueAtTime(time);
		//reschedule the next event to end at the given time
		var after = this._searchAfter(time);
		if (after){
			//cancel the next event(s)
			this.cancelScheduledValues(time);
			if (after.type === Tone.TimelineSignal.Type.Linear){
				this.linearRampToValueAtTime(val, time);
			} else if (after.type === Tone.TimelineSignal.Type.Exponential){
				this.exponentialRampToValueAtTime(val, time);
			}
		}
		this.setValueAtTime(val, time);
		return this;
	};

	/**
	 *  Do a linear ramp to the given value between the start and finish times.
	 *  @param {Number} value The value to ramp to.
	 *  @param {Time} start The beginning anchor point to do the linear ramp
	 *  @param {Time} finish The ending anchor point by which the value of
	 *                       the signal will equal the given value.
	 *  @returns {Tone.TimelineSignal} this
	 */
	Tone.TimelineSignal.prototype.linearRampToValueBetween = function (value, start, finish) {
		this.setRampPoint(start);
		this.linearRampToValueAtTime(value, finish);
		return this;
	};

	/**
	 *  Do a exponential ramp to the given value between the start and finish times.
	 *  @param {Number} value The value to ramp to.
	 *  @param {Time} start The beginning anchor point to do the exponential ramp
	 *  @param {Time} finish The ending anchor point by which the value of
	 *                       the signal will equal the given value.
	 *  @returns {Tone.TimelineSignal} this
	 */
	Tone.TimelineSignal.prototype.exponentialRampToValueBetween = function (value, start, finish) {
		this.setRampPoint(start);
		this.exponentialRampToValueAtTime(value, finish);
		return this;
	};

	///////////////////////////////////////////////////////////////////////////
	//	GETTING SCHEDULED VALUES
	///////////////////////////////////////////////////////////////////////////

	/**
	 *  Returns the value before or equal to the given time
	 *  @param  {Number}  time  The time to query
	 *  @return  {Object}  The event at or before the given time.
	 *  @private
	 */
	Tone.TimelineSignal.prototype._searchBefore = function(time){
		return this._events.getEvent(time);
	};

	/**
	 *  The event after the given time
	 *  @param  {Number}  time  The time to query.
	 *  @return  {Object}  The next event after the given time
	 *  @private
	 */
	Tone.TimelineSignal.prototype._searchAfter = function(time){
		return this._events.getEventAfter(time);
	};

	/**
	 *  Get the scheduled value at the given time. This will
	 *  return the unconverted (raw) value.
	 *  @param  {Number}  time  The time in seconds.
	 *  @return  {Number}  The scheduled value at the given time.
	 */
	Tone.TimelineSignal.prototype.getValueAtTime = function(time){
		var after = this._searchAfter(time);
		var before = this._searchBefore(time);
		var value = this._initial;
		//if it was set by
		if (before === null){
			value = this._initial;
		} else if (before.type === Tone.TimelineSignal.Type.Target){
			var previous = this._events.getEventBefore(before.time);
			var previouVal;
			if (previous === null){
				previouVal = this._initial;
			} else {
				previouVal = previous.value;
			}
			value = this._exponentialApproach(before.time, previouVal, before.value, before.constant, time);
		} else if (after === null){
			value = before.value;
		} else if (after.type === Tone.TimelineSignal.Type.Linear){
			value = this._linearInterpolate(before.time, before.value, after.time, after.value, time);
		} else if (after.type === Tone.TimelineSignal.Type.Exponential){
			value = this._exponentialInterpolate(before.time, before.value, after.time, after.value, time);
		} else {
			value = before.value;
		}
		return value;
	};

	/**
	 *  When signals connect to other signals or AudioParams,
	 *  they take over the output value of that signal or AudioParam.
	 *  For all other nodes, the behavior is the same as a default connect.
	 *
	 *  @override
	 *  @param {AudioParam|AudioNode|Tone.Signal|Tone} node
	 *  @param {number} [outputNumber=0] The output number to connect from.
	 *  @param {number} [inputNumber=0] The input number to connect to.
	 *  @returns {Tone.TimelineSignal} this
	 *  @method
	 */
	Tone.TimelineSignal.prototype.connect = Tone.SignalBase.prototype.connect;

	///////////////////////////////////////////////////////////////////////////
	//	AUTOMATION CURVE CALCULATIONS
	//	MIT License, copyright (c) 2014 Jordan Santell
	///////////////////////////////////////////////////////////////////////////

	/**
	 *  Calculates the the value along the curve produced by setTargetAtTime
	 *  @private
	 */
	Tone.TimelineSignal.prototype._exponentialApproach = function (t0, v0, v1, timeConstant, t) {
		return v1 + (v0 - v1) * Math.exp(-(t - t0) / timeConstant);
	};

	/**
	 *  Calculates the the value along the curve produced by linearRampToValueAtTime
	 *  @private
	 */
	Tone.TimelineSignal.prototype._linearInterpolate = function (t0, v0, t1, v1, t) {
		return v0 + (v1 - v0) * ((t - t0) / (t1 - t0));
	};

	/**
	 *  Calculates the the value along the curve produced by exponentialRampToValueAtTime
	 *  @private
	 */
	Tone.TimelineSignal.prototype._exponentialInterpolate = function (t0, v0, t1, v1, t) {
		v0 = Math.max(this._minOutput, v0);
		return v0 * Math.pow(v1 / v0, (t - t0) / (t1 - t0));
	};

	/**
	 *  Clean up.
	 *  @return {Tone.TimelineSignal} this
	 */
	Tone.TimelineSignal.prototype.dispose = function(){
		Tone.Signal.prototype.dispose.call(this);
		Tone.Param.prototype.dispose.call(this);
		this._events.dispose();
		this._events = null;
	};

	return Tone.TimelineSignal;
});


text:
use core::sync::atomic::AtomicU16;
use core::sync::atomic::Ordering;

extern crate x86;

use self::x86::io;

/// One Mhz is that many Hz.
const MHZ_TO_HZ: u64 = 1000 * 1000;

/// One Khz is that many Hz.
const KHZ_TO_HZ: u64 = 1000;

/// One sec has that many ns.
const _NS_PER_SEC: u64 = 1_000_000_000u64;

pub static SERIAL_PRINT_PORT: AtomicU16 = AtomicU16::new(0x3f8); /* default COM1 */

/// Write a string to the output channel.
pub unsafe fn puts(s: &str) {
    let port = SERIAL_PRINT_PORT.load(Ordering::Relaxed);
    for b in s.bytes() {
        putb(port, b);
    }
}

pub unsafe fn putc(c: char) {
    let port = SERIAL_PRINT_PORT.load(Ordering::Relaxed);
    putb(port, c as u8);
}

/// Write a single byte to the output channel.
unsafe fn putb(port: u16, b: u8) {
    // Wait for the serial FIFO to be ready
    while (io::inb(port + 5) & 0x20) == 0 {}
    io::outb(port, b);
}

pub fn set_output(port: u16) {
    SERIAL_PRINT_PORT.store(port, Ordering::Relaxed);
}

pub fn get_timestamp() -> u64 {
    unsafe { x86::time::rdtsc() }
}

pub fn has_tsc() -> bool {
    let cpuid = x86::cpuid::CpuId::new();
    cpuid
        .get_feature_info()
        .map_or(false, |finfo| finfo.has_tsc())
}

pub fn has_invariant_tsc() -> bool {
    let cpuid = x86::cpuid::CpuId::new();
    cpuid
        .get_advanced_power_mgmt_info()
        .map_or(false, |efinfo| efinfo.has_invariant_tsc())
}

pub fn get_tsc_frequency_hz() -> Option<u64> {
    let cpuid = x86::cpuid::CpuId::new();
    cpuid.get_tsc_info().and_then(|tinfo| {
        if tinfo.nominal_frequency() != 0 {
            // If we have a crystal clock we can calculate the tsc frequency directly
            tinfo.tsc_frequency()
        } else if tinfo.numerator() != 0 && tinfo.denominator() != 0 {
            // Skylake and Kabylake don't report the crystal clock frequency,
            // so we approximate with CPU base frequency:
            cpuid.get_processor_frequency_info().map(|pinfo| {
                let cpu_base_freq_hz = pinfo.processor_base_frequency() as u64 * MHZ_TO_HZ;
                let crystal_hz =
                    cpu_base_freq_hz * tinfo.denominator() as u64 / tinfo.numerator() as u64;
                crystal_hz * tinfo.numerator() as u64 / tinfo.denominator() as u64
            })
        } else {
            // We couldn't figure out the TSC frequency
            None
        }
    })
}

pub fn get_vmm_tsc_frequency_hz() -> Option<u64> {
    let cpuid = x86::cpuid::CpuId::new();
    cpuid
        .get_hypervisor_info()
        .and_then(|hv| hv.tsc_frequency().map(|tsc_khz| tsc_khz as u64 * KHZ_TO_HZ))
}


text:
'use strict';

describe('ServerStorageStrategy', function(){
  var storageConfig = require('app/config/storage');
  var ServerStorageStrategy = require('./server-storage-strategy');
  var Task = require('./task');

  var httpBackend, storage;

  beforeEach(function(){
    angular.mock.module(function($provide){
      $provide.constant('storageConfig', storageConfig);
      $provide.value('Task', Task);
      $provide.factory('ServerStorageStrategy', ServerStorageStrategy);
    });

    inject(function($httpBackend, ServerStorageStrategy){
      httpBackend = $httpBackend;
      storage = ServerStorageStrategy;
    });
  });

  afterEach(function(){
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
  });

  describe('Creating a task', function(){
    it('should add task to `tasks` array', function(){
      var task = {title: 'test'};

      httpBackend.whenPOST(storageConfig.TASKS_URL).respond(200, task);
      storage.tasks = [];
      storage.createTask(task.title);
      httpBackend.flush();

      expect(storage.tasks[0]).toEqual(task);
    });

    it('should POST new task to server', function(){
      var task = {completed: false, title: 'test'};
      httpBackend.expectPOST(storageConfig.TASKS_URL, task).respond(200);
      storage.createTask(task.title);
      httpBackend.flush();
    });

    it('should fulfill promise with the newly created task', function(){
      var task = {title: 'test'};

      httpBackend.whenPOST(storageConfig.TASKS_URL).respond(200, task);

      storage.createTask(task.title)
        .then(function(_task){
          expect(_task).toEqual(task);
        });

      httpBackend.flush();
    });
  });

  describe('Deleting a task', function(){
    it('should remove task from `tasks` array', function(){
      var task = new Task('test');
      task.links = {self: '/tasks/123'};

      httpBackend.whenDELETE(storageConfig.BASE_URL + task.links.self).respond(204);
      storage.tasks = [task];
      storage.deleteTask(task);
      httpBackend.flush();

      expect(storage.tasks.length).toBe(0);
    });

    it('should DELETE task from server', function(){
      var task = new Task('test');
      task.links = {self: '/tasks/123'};

      httpBackend.expectDELETE(storageConfig.BASE_URL + task.links.self).respond(204);
      storage.deleteTask(task);
      httpBackend.flush();
    });

    it('should fulfill promise with the deleted task', function(){
      var task = new Task('test');
      task.links = {self: '/tasks/123'};

      httpBackend.whenDELETE(storageConfig.BASE_URL + task.links.self).respond(204);

      storage.deleteTask(task)
        .then(function(_task){
          expect(_task).toBe(task);
        });

      httpBackend.flush();
    });
  });

  describe('Updating a task', function(){
    it('should PUT task to server', function(){
      var task = new Task('test');
      task.links = {self: '/tasks/123'};

      httpBackend.expectPUT(storageConfig.BASE_URL + task.links.self, task).respond(200);
      storage.updateTask(task);
      httpBackend.flush();
    });

    it('should fulfill promise with the updated task', function(){
      var task = new Task('test');
      task.links = {self: '/tasks/123'};

      httpBackend.whenPUT(storageConfig.BASE_URL + task.links.self).respond(200);

      storage.updateTask(task)
        .then(function(_task){
          expect(_task).toBe(task);
        });

      httpBackend.flush();
    });
  });

  describe('Getting tasks', function(){
    it('should GET tasks from server', function(){
      httpBackend.expectGET(storageConfig.TASKS_URL).respond(200, []);
      storage.getTasks();
      httpBackend.flush();
    });

    it('should set `tasks` with an array of tasks from server', function(){
      httpBackend.whenGET(storageConfig.TASKS_URL).respond(200, [{}, {}]);
      storage.tasks = [];
      storage.getTasks();
      httpBackend.flush();

      expect(storage.tasks.length).toBe(2);
    });

    it('should set `tasks` with an empty array if there are no tasks', function(){
      httpBackend.whenGET(storageConfig.TASKS_URL).respond(200, []);
      storage.tasks = [];
      storage.getTasks();
      httpBackend.flush();

      expect(storage.tasks.length).toBe(0);
    });

    it('should fulfill promise with the tasks array', function(){
      httpBackend.whenGET(storageConfig.TASKS_URL).respond(200, [{}, {}]);
      storage.tasks = [];

      storage.getTasks()
        .then(function(tasks){
          expect(tasks).toBe(storage.tasks);
        });

      httpBackend.flush();
    });
  });

});


text:
#ifdef HAVE_CONFIG_H
#include "../../ext_config.h"
#endif

#include <php.h>
#include "../../php_ext.h"
#include "../../ext.h"

#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>

#include "kernel/main.h"
#include "kernel/object.h"

ZEPHIR_INIT_CLASS(Test_Properties_PrivateProperties) {

	ZEPHIR_REGISTER_CLASS(Test\\Properties, PrivateProperties, test, properties_privateproperties, test_properties_privateproperties_method_entry, 0);

	/**
	 * This is a private property with no initial value
	 */
	zend_declare_property_null(test_properties_privateproperties_ce, SL("someNull"), ZEND_ACC_PRIVATE);

	/**
	 * This is a private property with initial null value
	 */
	zend_declare_property_null(test_properties_privateproperties_ce, SL("someNullInitial"), ZEND_ACC_PRIVATE);

	/**
	 * This is a private property with initial boolean false
	 */
	zend_declare_property_bool(test_properties_privateproperties_ce, SL("someFalse"), 0, ZEND_ACC_PRIVATE);

	/**
	 * This is a private property with initial boolean true
	 */
	zend_declare_property_bool(test_properties_privateproperties_ce, SL("someTrue"), 1, ZEND_ACC_PRIVATE);

	/**
	 * This is a private property with an initial integer value
	 */
	zend_declare_property_long(test_properties_privateproperties_ce, SL("someInteger"), 10, ZEND_ACC_PRIVATE);

	/**
	 * This is a private property with an initial double value
	 */
	zend_declare_property_double(test_properties_privateproperties_ce, SL("someDouble"), 10.25, ZEND_ACC_PRIVATE);

	/**
	 * This is a private property with an initial string value
	 */
	zend_declare_property_string(test_properties_privateproperties_ce, SL("someString"), "test", ZEND_ACC_PRIVATE);

	return SUCCESS;

}

PHP_METHOD(Test_Properties_PrivateProperties, getSomeNull) {

	zval *this_ptr = getThis();

	RETURN_MEMBER(getThis(), "someNull");

}

PHP_METHOD(Test_Properties_PrivateProperties, getSomeNullInitial) {

	zval *this_ptr = getThis();

	RETURN_MEMBER(getThis(), "someNullInitial");

}

PHP_METHOD(Test_Properties_PrivateProperties, getSomeFalse) {

	zval *this_ptr = getThis();

	RETURN_MEMBER(getThis(), "someFalse");

}

PHP_METHOD(Test_Properties_PrivateProperties, getSomeTrue) {

	zval *this_ptr = getThis();

	RETURN_MEMBER(getThis(), "someTrue");

}

PHP_METHOD(Test_Properties_PrivateProperties, getSomeInteger) {

	zval *this_ptr = getThis();

	RETURN_MEMBER(getThis(), "someInteger");

}

PHP_METHOD(Test_Properties_PrivateProperties, getSomeDouble) {

	zval *this_ptr = getThis();

	RETURN_MEMBER(getThis(), "someDouble");

}

PHP_METHOD(Test_Properties_PrivateProperties, getSomeString) {

	zval *this_ptr = getThis();

	RETURN_MEMBER(getThis(), "someString");

}


text:
.monaco-editor .detected-link,
.monaco-editor .detected-link-active {
	text-decoration: underline;
	text-underline-position: under;
}

.monaco-editor .detected-link-active {
	cursor: pointer;
	color: var(--vscode-editorLink-activeForeground) !important;
}


text:
from datetime import datetime
import pandas.util.testing as tm
from pandas.tseries.holiday import (
    USFederalHolidayCalendar, USMemorialDay, USThanksgivingDay,
    nearest_workday, next_monday_or_tuesday, next_monday,
    previous_friday, sunday_to_monday, Holiday, DateOffset,
    MO, Timestamp, AbstractHolidayCalendar, get_calendar,
    HolidayCalendarFactory, next_workday, previous_workday,
    before_nearest_workday, EasterMonday, GoodFriday,
    after_nearest_workday, weekend_to_monday)
import nose

class TestCalendar(tm.TestCase):

    def setUp(self):
        self.holiday_list = [
                       datetime(2012, 1, 2),
                       datetime(2012, 1, 16),
                       datetime(2012, 2, 20),
                       datetime(2012, 5, 28),
                       datetime(2012, 7, 4),
                       datetime(2012, 9, 3),
                       datetime(2012, 10, 8),
                       datetime(2012, 11, 12),
                       datetime(2012, 11, 22),
                       datetime(2012, 12, 25)]

        self.start_date = datetime(2012, 1, 1)
        self.end_date = datetime(2012, 12, 31)

    def test_calendar(self):

        calendar = USFederalHolidayCalendar()
        holidays = calendar.holidays(self.start_date,
                                     self.end_date)

        holidays_1 = calendar.holidays(
                        self.start_date.strftime('%Y-%m-%d'),
                        self.end_date.strftime('%Y-%m-%d'))
        holidays_2 = calendar.holidays(
                        Timestamp(self.start_date),
                        Timestamp(self.end_date))

        self.assertEqual(list(holidays.to_pydatetime()),
                         self.holiday_list)
        self.assertEqual(list(holidays_1.to_pydatetime()),
                         self.holiday_list)
        self.assertEqual(list(holidays_2.to_pydatetime()),
                         self.holiday_list)

class TestHoliday(tm.TestCase):

    def setUp(self):
        self.start_date = datetime(2011, 1, 1)
        self.end_date   = datetime(2020, 12, 31)

    def test_usmemorialday(self):
        holidays = USMemorialDay.dates(self.start_date,
                                       self.end_date)
        holidayList = [
                       datetime(2011, 5, 30),
                       datetime(2012, 5, 28),
                       datetime(2013, 5, 27),
                       datetime(2014, 5, 26),
                       datetime(2015, 5, 25),
                       datetime(2016, 5, 30),
                       datetime(2017, 5, 29),
                       datetime(2018, 5, 28),
                       datetime(2019, 5, 27),
                       datetime(2020, 5, 25),
                       ]
        self.assertEqual(list(holidays), holidayList)

    def test_non_observed_holiday(self):
        july_3rd = Holiday('July 4th Eve', month=7,  day=3)
        result = july_3rd.dates("2001-01-01", "2003-03-03")
        expected = [Timestamp('2001-07-03 00:00:00'),
                    Timestamp('2002-07-03 00:00:00')]
        self.assertEqual(list(result), expected)
        july_3rd = Holiday('July 4th Eve', month=7,  day=3,
                           days_of_week=(0, 1, 2, 3))
        result = july_3rd.dates("2001-01-01", "2008-03-03")
        expected = [Timestamp('2001-07-03 00:00:00'),
                    Timestamp('2002-07-03 00:00:00'),
                    Timestamp('2003-07-03 00:00:00'),
                    Timestamp('2006-07-03 00:00:00'),
                    Timestamp('2007-07-03 00:00:00')]
        self.assertEqual(list(result), expected)

    def test_easter(self):
        holidays = EasterMonday.dates(self.start_date,
                                      self.end_date)
        holidayList = [Timestamp('2011-04-25 00:00:00'),
                       Timestamp('2012-04-09 00:00:00'),
                       Timestamp('2013-04-01 00:00:00'),
                       Timestamp('2014-04-21 00:00:00'),
                       Timestamp('2015-04-06 00:00:00'),
                       Timestamp('2016-03-28 00:00:00'),
                       Timestamp('2017-04-17 00:00:00'),
                       Timestamp('2018-04-02 00:00:00'),
                       Timestamp('2019-04-22 00:00:00'),
                       Timestamp('2020-04-13 00:00:00')]

        self.assertEqual(list(holidays), holidayList)
        holidays = GoodFriday.dates(self.start_date,
                                    self.end_date)
        holidayList = [Timestamp('2011-04-22 00:00:00'),
                       Timestamp('2012-04-06 00:00:00'),
                       Timestamp('2013-03-29 00:00:00'),
                       Timestamp('2014-04-18 00:00:00'),
                       Timestamp('2015-04-03 00:00:00'),
                       Timestamp('2016-03-25 00:00:00'),
                       Timestamp('2017-04-14 00:00:00'),
                       Timestamp('2018-03-30 00:00:00'),
                       Timestamp('2019-04-19 00:00:00'),
                       Timestamp('2020-04-10 00:00:00')]
        self.assertEqual(list(holidays), holidayList)

    def test_usthanksgivingday(self):
        holidays = USThanksgivingDay.dates(self.start_date,
                                           self.end_date)
        holidayList = [
                       datetime(2011, 11, 24),
                       datetime(2012, 11, 22),
                       datetime(2013, 11, 28),
                       datetime(2014, 11, 27),
                       datetime(2015, 11, 26),
                       datetime(2016, 11, 24),
                       datetime(2017, 11, 23),
                       datetime(2018, 11, 22),
                       datetime(2019, 11, 28),
                       datetime(2020, 11, 26),
                       ]

        self.assertEqual(list(holidays), holidayList)

    def test_argument_types(self):
        holidays = USThanksgivingDay.dates(self.start_date,
                                           self.end_date)

        holidays_1 = USThanksgivingDay.dates(
                        self.start_date.strftime('%Y-%m-%d'),
                        self.end_date.strftime('%Y-%m-%d'))

        holidays_2 = USThanksgivingDay.dates(
                        Timestamp(self.start_date),
                        Timestamp(self.end_date))

        self.assertEqual(holidays, holidays_1)
        self.assertEqual(holidays, holidays_2)

    def test_special_holidays(self):
        base_date = [datetime(2012, 5, 28)]
        holiday_1 = Holiday('One-Time', year=2012, month=5, day=28)
        holiday_2 = Holiday('Range', month=5, day=28,
                            start_date=datetime(2012, 1, 1),
                            end_date=datetime(2012, 12, 31),
                            offset=DateOffset(weekday=MO(1)))

        self.assertEqual(base_date,
                         holiday_1.dates(self.start_date, self.end_date))
        self.assertEqual(base_date,
                         holiday_2.dates(self.start_date, self.end_date))

    def test_get_calendar(self):
        class TestCalendar(AbstractHolidayCalendar):
            rules = []

        calendar = get_calendar('TestCalendar')
        self.assertEqual(TestCalendar, calendar.__class__)

    def test_factory(self):
        class_1 = HolidayCalendarFactory('MemorialDay', AbstractHolidayCalendar,
                                         USMemorialDay)
        class_2 = HolidayCalendarFactory('Thansksgiving', AbstractHolidayCalendar,
                                         USThanksgivingDay)
        class_3 = HolidayCalendarFactory('Combined', class_1, class_2)

        self.assertEqual(len(class_1.rules), 1)
        self.assertEqual(len(class_2.rules), 1)
        self.assertEqual(len(class_3.rules), 2)

class TestObservanceRules(tm.TestCase):

    def setUp(self):
        self.we =   datetime(2014, 4, 9)
        self.th =   datetime(2014, 4, 10)
        self.fr =   datetime(2014, 4, 11)
        self.sa =   datetime(2014, 4, 12)
        self.su =   datetime(2014, 4, 13)
        self.mo =   datetime(2014, 4, 14)
        self.tu =   datetime(2014, 4, 15)

    def test_next_monday(self):
        self.assertEqual(next_monday(self.sa), self.mo)
        self.assertEqual(next_monday(self.su), self.mo)

    def test_next_monday_or_tuesday(self):
        self.assertEqual(next_monday_or_tuesday(self.sa), self.mo)
        self.assertEqual(next_monday_or_tuesday(self.su), self.tu)
        self.assertEqual(next_monday_or_tuesday(self.mo), self.tu)

    def test_previous_friday(self):
        self.assertEqual(previous_friday(self.sa), self.fr)
        self.assertEqual(previous_friday(self.su), self.fr)

    def test_sunday_to_monday(self):
        self.assertEqual(sunday_to_monday(self.su), self.mo)

    def test_nearest_workday(self):
        self.assertEqual(nearest_workday(self.sa), self.fr)
        self.assertEqual(nearest_workday(self.su), self.mo)
        self.assertEqual(nearest_workday(self.mo), self.mo)

    def test_weekend_to_monday(self):
        self.assertEqual(weekend_to_monday(self.sa), self.mo)
        self.assertEqual(weekend_to_monday(self.su), self.mo)
        self.assertEqual(weekend_to_monday(self.mo), self.mo)

    def test_next_workday(self):
        self.assertEqual(next_workday(self.sa), self.mo)
        self.assertEqual(next_workday(self.su), self.mo)
        self.assertEqual(next_workday(self.mo), self.tu)

    def test_previous_workday(self):
        self.assertEqual(previous_workday(self.sa), self.fr)
        self.assertEqual(previous_workday(self.su), self.fr)
        self.assertEqual(previous_workday(self.tu), self.mo)

    def test_before_nearest_workday(self):
        self.assertEqual(before_nearest_workday(self.sa), self.th)
        self.assertEqual(before_nearest_workday(self.su), self.fr)
        self.assertEqual(before_nearest_workday(self.tu), self.mo)

    def test_after_nearest_workday(self):
        self.assertEqual(after_nearest_workday(self.sa), self.mo)
        self.assertEqual(after_nearest_workday(self.su), self.tu)
        self.assertEqual(after_nearest_workday(self.fr), self.mo)

if __name__ == '__main__':
    nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
                   exit=False)


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>

#include "ctld.h"
#include "iscsi_proto.h"

static struct pdu *
text_receive(struct connection *conn)
{
	struct pdu *request;
	struct iscsi_bhs_text_request *bhstr;

	request = pdu_new(conn);
	pdu_receive(request);
	if ((request->pdu_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) !=
	    ISCSI_BHS_OPCODE_TEXT_REQUEST)
		log_errx(1, "protocol error: received invalid opcode 0x%x",
		    request->pdu_bhs->bhs_opcode);
	bhstr = (struct iscsi_bhs_text_request *)request->pdu_bhs;
#if 0
	if ((bhstr->bhstr_flags & ISCSI_BHSTR_FLAGS_FINAL) == 0)
		log_errx(1, "received Text PDU without the \"F\" flag");
#endif
	/*
	 * XXX: Implement the C flag some day.
	 */
	if ((bhstr->bhstr_flags & BHSTR_FLAGS_CONTINUE) != 0)
		log_errx(1, "received Text PDU with unsupported \"C\" flag");
	if (ISCSI_SNLT(ntohl(bhstr->bhstr_cmdsn), conn->conn_cmdsn)) {
		log_errx(1, "received Text PDU with decreasing CmdSN: "
		    "was %u, is %u", conn->conn_cmdsn, ntohl(bhstr->bhstr_cmdsn));
	}
	if (ntohl(bhstr->bhstr_expstatsn) != conn->conn_statsn) {
		log_errx(1, "received Text PDU with wrong StatSN: "
		    "is %u, should be %u", ntohl(bhstr->bhstr_expstatsn),
		    conn->conn_statsn);
	}
	conn->conn_cmdsn = ntohl(bhstr->bhstr_cmdsn);
	if ((bhstr->bhstr_opcode & ISCSI_BHS_OPCODE_IMMEDIATE) == 0)
		conn->conn_cmdsn++;

	return (request);
}

static struct pdu *
text_new_response(struct pdu *request)
{
	struct pdu *response;
	struct connection *conn;
	struct iscsi_bhs_text_request *bhstr;
	struct iscsi_bhs_text_response *bhstr2;

	bhstr = (struct iscsi_bhs_text_request *)request->pdu_bhs;
	conn = request->pdu_connection;

	response = pdu_new_response(request);
	bhstr2 = (struct iscsi_bhs_text_response *)response->pdu_bhs;
	bhstr2->bhstr_opcode = ISCSI_BHS_OPCODE_TEXT_RESPONSE;
	bhstr2->bhstr_flags = BHSTR_FLAGS_FINAL;
	bhstr2->bhstr_lun = bhstr->bhstr_lun;
	bhstr2->bhstr_initiator_task_tag = bhstr->bhstr_initiator_task_tag;
	bhstr2->bhstr_target_transfer_tag = bhstr->bhstr_target_transfer_tag;
	bhstr2->bhstr_statsn = htonl(conn->conn_statsn++);
	bhstr2->bhstr_expcmdsn = htonl(conn->conn_cmdsn);
	bhstr2->bhstr_maxcmdsn = htonl(conn->conn_cmdsn);

	return (response);
}

static struct pdu *
logout_receive(struct connection *conn)
{
	struct pdu *request;
	struct iscsi_bhs_logout_request *bhslr;

	request = pdu_new(conn);
	pdu_receive(request);
	if ((request->pdu_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) !=
	    ISCSI_BHS_OPCODE_LOGOUT_REQUEST)
		log_errx(1, "protocol error: received invalid opcode 0x%x",
		    request->pdu_bhs->bhs_opcode);
	bhslr = (struct iscsi_bhs_logout_request *)request->pdu_bhs;
	if ((bhslr->bhslr_reason & 0x7f) != BHSLR_REASON_CLOSE_SESSION)
		log_debugx("received Logout PDU with invalid reason 0x%x; "
		    "continuing anyway", bhslr->bhslr_reason & 0x7f);
	if (ISCSI_SNLT(ntohl(bhslr->bhslr_cmdsn), conn->conn_cmdsn)) {
		log_errx(1, "received Logout PDU with decreasing CmdSN: "
		    "was %u, is %u", conn->conn_cmdsn,
		    ntohl(bhslr->bhslr_cmdsn));
	}
	if (ntohl(bhslr->bhslr_expstatsn) != conn->conn_statsn) {
		log_errx(1, "received Logout PDU with wrong StatSN: "
		    "is %u, should be %u", ntohl(bhslr->bhslr_expstatsn),
		    conn->conn_statsn);
	}
	conn->conn_cmdsn = ntohl(bhslr->bhslr_cmdsn);
	if ((bhslr->bhslr_opcode & ISCSI_BHS_OPCODE_IMMEDIATE) == 0)
		conn->conn_cmdsn++;

	return (request);
}

static struct pdu *
logout_new_response(struct pdu *request)
{
	struct pdu *response;
	struct connection *conn;
	struct iscsi_bhs_logout_request *bhslr;
	struct iscsi_bhs_logout_response *bhslr2;

	bhslr = (struct iscsi_bhs_logout_request *)request->pdu_bhs;
	conn = request->pdu_connection;

	response = pdu_new_response(request);
	bhslr2 = (struct iscsi_bhs_logout_response *)response->pdu_bhs;
	bhslr2->bhslr_opcode = ISCSI_BHS_OPCODE_LOGOUT_RESPONSE;
	bhslr2->bhslr_flags = 0x80;
	bhslr2->bhslr_response = BHSLR_RESPONSE_CLOSED_SUCCESSFULLY;
	bhslr2->bhslr_initiator_task_tag = bhslr->bhslr_initiator_task_tag;
	bhslr2->bhslr_statsn = htonl(conn->conn_statsn++);
	bhslr2->bhslr_expcmdsn = htonl(conn->conn_cmdsn);
	bhslr2->bhslr_maxcmdsn = htonl(conn->conn_cmdsn);

	return (response);
}

static void
discovery_add_target(struct keys *response_keys, const struct target *targ)
{
	struct port *port;
	struct portal *portal;
	char *buf;
	char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
	struct addrinfo *ai;
	int ret;

	keys_add(response_keys, "TargetName", targ->t_name);
	TAILQ_FOREACH(port, &targ->t_ports, p_ts) {
	    if (port->p_portal_group == NULL)
		continue;
	    TAILQ_FOREACH(portal, &port->p_portal_group->pg_portals, p_next) {
		ai = portal->p_ai;
		ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
		    hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
		    NI_NUMERICHOST | NI_NUMERICSERV);
		if (ret != 0) {
			log_warnx("getnameinfo: %s", gai_strerror(ret));
			continue;
		}
		switch (ai->ai_addr->sa_family) {
		case AF_INET:
			if (strcmp(hbuf, "0.0.0.0") == 0)
				continue;
			ret = asprintf(&buf, "%s:%s,%d", hbuf, sbuf,
			    port->p_portal_group->pg_tag);
			break;
		case AF_INET6:
			if (strcmp(hbuf, "::") == 0)
				continue;
			ret = asprintf(&buf, "[%s]:%s,%d", hbuf, sbuf,
			    port->p_portal_group->pg_tag);
			break;
		default:
			continue;
		}
		if (ret <= 0)
		    log_err(1, "asprintf");
		keys_add(response_keys, "TargetAddress", buf);
		free(buf);
	    }
	}
}

static bool
discovery_target_filtered_out(const struct connection *conn,
    const struct port *port)
{
	const struct auth_group *ag;
	const struct portal_group *pg;
	const struct target *targ;
	const struct auth *auth;
	int error;

	targ = port->p_target;
	ag = port->p_auth_group;
	if (ag == NULL)
		ag = targ->t_auth_group;
	pg = conn->conn_portal->p_portal_group;

	assert(pg->pg_discovery_auth_group != PG_FILTER_UNKNOWN);

	if (pg->pg_discovery_filter >= PG_FILTER_PORTAL &&
	    auth_portal_check(ag, &conn->conn_initiator_sa) != 0) {
		log_debugx("initiator does not match initiator portals "
		    "allowed for target \"%s\"; skipping", targ->t_name);
		return (true);
	}

	if (pg->pg_discovery_filter >= PG_FILTER_PORTAL_NAME &&
	    auth_name_check(ag, conn->conn_initiator_name) != 0) {
		log_debugx("initiator does not match initiator names "
		    "allowed for target \"%s\"; skipping", targ->t_name);
		return (true);
	}

	if (pg->pg_discovery_filter >= PG_FILTER_PORTAL_NAME_AUTH &&
	    ag->ag_type != AG_TYPE_NO_AUTHENTICATION) {
		if (conn->conn_chap == NULL) {
			assert(pg->pg_discovery_auth_group->ag_type ==
			    AG_TYPE_NO_AUTHENTICATION);

			log_debugx("initiator didn't authenticate, but target "
			    "\"%s\" requires CHAP; skipping", targ->t_name);
			return (true);
		}

		assert(conn->conn_user != NULL);
		auth = auth_find(ag, conn->conn_user);
		if (auth == NULL) {
			log_debugx("CHAP user \"%s\" doesn't match target "
			    "\"%s\"; skipping", conn->conn_user, targ->t_name);
			return (true);
		}

		error = chap_authenticate(conn->conn_chap, auth->a_secret);
		if (error != 0) {
			log_debugx("password for CHAP user \"%s\" doesn't "
			    "match target \"%s\"; skipping",
			    conn->conn_user, targ->t_name);
			return (true);
		}
	}

	return (false);
}

void
discovery(struct connection *conn)
{
	struct pdu *request, *response;
	struct keys *request_keys, *response_keys;
	const struct port *port;
	const struct portal_group *pg;
	const char *send_targets;

	pg = conn->conn_portal->p_portal_group;

	log_debugx("beginning discovery session; waiting for Text PDU");
	request = text_receive(conn);
	request_keys = keys_new();
	keys_load(request_keys, request);

	send_targets = keys_find(request_keys, "SendTargets");
	if (send_targets == NULL)
		log_errx(1, "received Text PDU without SendTargets");

	response = text_new_response(request);
	response_keys = keys_new();

	if (strcmp(send_targets, "All") == 0) {
		TAILQ_FOREACH(port, &pg->pg_ports, p_pgs) {
			if (discovery_target_filtered_out(conn, port)) {
				/* Ignore this target. */
				continue;
			}
			discovery_add_target(response_keys, port->p_target);
		}
	} else {
		port = port_find_in_pg(pg, send_targets);
		if (port == NULL) {
			log_debugx("initiator requested information on unknown "
			    "target \"%s\"; returning nothing", send_targets);
		} else {
			if (discovery_target_filtered_out(conn, port)) {
				/* Ignore this target. */
			} else {
				discovery_add_target(response_keys, port->p_target);
			}
		}
	}
	keys_save(response_keys, response);

	pdu_send(response);
	pdu_delete(response);
	keys_delete(response_keys);
	pdu_delete(request);
	keys_delete(request_keys);

	log_debugx("done sending targets; waiting for Logout PDU");
	request = logout_receive(conn);
	response = logout_new_response(request);

	pdu_send(response);
	pdu_delete(response);
	pdu_delete(request);

	log_debugx("discovery session done");
}


text:
{{vm.contactu._id ? 'Edit Contactu' : 'New Contactu'}}

    <form name="vm.form.contactuForm" class="form-horizontal" ng-submit="vm.save(vm.form.contactuForm.$valid)" novalidate>
      <fieldset>

          Name
          <input name="name" type="text" ng-model="vm.contactu.name" id="name" class="form-control" placeholder="Name" required>

Contactu name is required.

          <button type="submit" class="btn btn-default">{{vm.contactu._id ? 'Update' : 'Create'}}</button>

      </fieldset>
    </form>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>pytorch-inference: Normalization_Impl.hpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

pytorch-inference

Namespaces |
Functions

Normalization_Impl.hpp File Reference

#include <arrayfire.h>

Go to the source code of this file.

Namespaces

  	pytorch::functional

Functions

af::array 	pytorch::functional::batchnorm2d (const af::array &gamma, const af::array &beta, const af::array &running_mean, const af::array &running_variance, const float &epsilon, const af::array &input)

include

modules

Normalization_Impl.hpp

Generated by

     1.8.13


text:
@class WMSVoiceInformation, WMSSpeechSynthesisStream, WMSSpeechSynthesizer;
@protocol WMSIVoiceInformation, WMSIInstalledVoicesStatic, WMSISpeechSynthesisStream, WMSISpeechSynthesizer;

// Windows.Media.SpeechSynthesis.VoiceGender
enum _WMSVoiceGender {
	WMSVoiceGenderMale = 0,
	WMSVoiceGenderFemale = 1,
};
typedef unsigned WMSVoiceGender;

#include "WindowsStorageStreams.h"
#include "WindowsFoundationCollections.h"
#include "WindowsFoundation.h"
#include "WindowsMedia.h"

#import <Foundation/Foundation.h>

// Windows.Media.SpeechSynthesis.VoiceInformation
#ifndef __WMSVoiceInformation_DEFINED__
#define __WMSVoiceInformation_DEFINED__

WINRT_EXPORT
@interface WMSVoiceInformation : RTObject
@property (readonly) NSString * description;
@property (readonly) NSString * displayName;
@property (readonly) WMSVoiceGender gender;
@property (readonly) NSString * id;
@property (readonly) NSString * language;
@end

#endif // __WMSVoiceInformation_DEFINED__

// Windows.Foundation.IClosable
#ifndef __WFIClosable_DEFINED__
#define __WFIClosable_DEFINED__

@protocol WFIClosable
- (void)close;
@end

#endif // __WFIClosable_DEFINED__

// Windows.Storage.Streams.IInputStream
#ifndef __WSSIInputStream_DEFINED__
#define __WSSIInputStream_DEFINED__

@protocol WSSIInputStream <WFIClosable>
- (void)readAsync:(RTObject<WSSIBuffer>*)buffer count:(unsigned int)count options:(WSSInputStreamOptions)options success:(void (^)(RTObject<WSSIBuffer>*))success progress:(void (^)(unsigned int))progress failure:(void (^)(NSError*))failure;
- (void)close;
@end

#endif // __WSSIInputStream_DEFINED__

// Windows.Storage.Streams.IOutputStream
#ifndef __WSSIOutputStream_DEFINED__
#define __WSSIOutputStream_DEFINED__

@protocol WSSIOutputStream <WFIClosable>
- (void)writeAsync:(RTObject<WSSIBuffer>*)buffer success:(void (^)(unsigned int))success progress:(void (^)(unsigned int))progress failure:(void (^)(NSError*))failure;
- (void)flushAsyncWithSuccess:(void (^)(BOOL))success failure:(void (^)(NSError*))failure;
- (void)close;
@end

#endif // __WSSIOutputStream_DEFINED__

// Windows.Storage.Streams.IRandomAccessStream
#ifndef __WSSIRandomAccessStream_DEFINED__
#define __WSSIRandomAccessStream_DEFINED__

@protocol WSSIRandomAccessStream <WFIClosable, WSSIInputStream, WSSIOutputStream>
@property (readonly) BOOL canRead;
@property (readonly) BOOL canWrite;
@property (readonly) uint64_t position;
@property uint64_t size;
- (RTObject<WSSIInputStream>*)getInputStreamAt:(uint64_t)position;
- (RTObject<WSSIOutputStream>*)getOutputStreamAt:(uint64_t)position;
- (void)seek:(uint64_t)position;
- (RTObject<WSSIRandomAccessStream>*)cloneStream;
- (void)close;
- (void)readAsync:(RTObject<WSSIBuffer>*)buffer count:(unsigned int)count options:(WSSInputStreamOptions)options success:(void (^)(RTObject<WSSIBuffer>*))success progress:(void (^)(unsigned int))progress failure:(void (^)(NSError*))failure;
- (void)writeAsync:(RTObject<WSSIBuffer>*)buffer success:(void (^)(unsigned int))success progress:(void (^)(unsigned int))progress failure:(void (^)(NSError*))failure;
- (void)flushAsyncWithSuccess:(void (^)(BOOL))success failure:(void (^)(NSError*))failure;
@end

#endif // __WSSIRandomAccessStream_DEFINED__

// Windows.Storage.Streams.IContentTypeProvider
#ifndef __WSSIContentTypeProvider_DEFINED__
#define __WSSIContentTypeProvider_DEFINED__

@protocol WSSIContentTypeProvider
@property (readonly) NSString * contentType;
@end

#endif // __WSSIContentTypeProvider_DEFINED__

// Windows.Storage.Streams.IRandomAccessStreamWithContentType
#ifndef __WSSIRandomAccessStreamWithContentType_DEFINED__
#define __WSSIRandomAccessStreamWithContentType_DEFINED__

@protocol WSSIRandomAccessStreamWithContentType <WSSIRandomAccessStream, WFIClosable, WSSIInputStream, WSSIOutputStream, WSSIContentTypeProvider>
- (RTObject<WSSIInputStream>*)getInputStreamAt:(uint64_t)position;
- (RTObject<WSSIOutputStream>*)getOutputStreamAt:(uint64_t)position;
- (void)seek:(uint64_t)position;
- (RTObject<WSSIRandomAccessStream>*)cloneStream;
- (void)close;
- (void)readAsync:(RTObject<WSSIBuffer>*)buffer count:(unsigned int)count options:(WSSInputStreamOptions)options success:(void (^)(RTObject<WSSIBuffer>*))success progress:(void (^)(unsigned int))progress failure:(void (^)(NSError*))failure;
- (void)writeAsync:(RTObject<WSSIBuffer>*)buffer success:(void (^)(unsigned int))success progress:(void (^)(unsigned int))progress failure:(void (^)(NSError*))failure;
- (void)flushAsyncWithSuccess:(void (^)(BOOL))success failure:(void (^)(NSError*))failure;
@end

#endif // __WSSIRandomAccessStreamWithContentType_DEFINED__

// Windows.Media.SpeechSynthesis.SpeechSynthesisStream
#ifndef __WMSSpeechSynthesisStream_DEFINED__
#define __WMSSpeechSynthesisStream_DEFINED__

WINRT_EXPORT
@interface WMSSpeechSynthesisStream : RTObject <WSSIRandomAccessStreamWithContentType, WSSIContentTypeProvider, WSSIRandomAccessStream, WSSIOutputStream, WFIClosable, WSSIInputStream>
@property (readonly) NSArray* markers;
@property (readonly) NSString * contentType;
@property uint64_t size;
@property (readonly) BOOL canRead;
@property (readonly) BOOL canWrite;
@property (readonly) uint64_t position;
- (RTObject<WSSIInputStream>*)getInputStreamAt:(uint64_t)position;
- (RTObject<WSSIOutputStream>*)getOutputStreamAt:(uint64_t)position;
- (void)seek:(uint64_t)position;
- (RTObject<WSSIRandomAccessStream>*)cloneStream;
- (void)close;
- (void)readAsync:(RTObject<WSSIBuffer>*)buffer count:(unsigned int)count options:(WSSInputStreamOptions)options success:(void (^)(RTObject<WSSIBuffer>*))success progress:(void (^)(unsigned int))progress failure:(void (^)(NSError*))failure;
- (void)writeAsync:(RTObject<WSSIBuffer>*)buffer success:(void (^)(unsigned int))success progress:(void (^)(unsigned int))progress failure:(void (^)(NSError*))failure;
- (void)flushAsyncWithSuccess:(void (^)(BOOL))success failure:(void (^)(NSError*))failure;
@end

#endif // __WMSSpeechSynthesisStream_DEFINED__

// Windows.Media.SpeechSynthesis.SpeechSynthesizer
#ifndef __WMSSpeechSynthesizer_DEFINED__
#define __WMSSpeechSynthesizer_DEFINED__

WINRT_EXPORT
@interface WMSSpeechSynthesizer : RTObject <WFIClosable>
+ (instancetype)create ACTIVATOR;
@property (copy) WMSVoiceInformation* voice;
+ (NSArray*)allVoices;
+ (WMSVoiceInformation*)defaultVoice;
- (void)synthesizeTextToStreamAsync:(NSString *)text success:(void (^)(WMSSpeechSynthesisStream*))success failure:(void (^)(NSError*))failure;
- (void)synthesizeSsmlToStreamAsync:(NSString *)Ssml success:(void (^)(WMSSpeechSynthesisStream*))success failure:(void (^)(NSError*))failure;
- (void)close;
@end

#endif // __WMSSpeechSynthesizer_DEFINED__


text:
sgs-auth
========

Sagacify's server-side authentication and authorization module.


text:
CREATE TABLE gas_meter_device (
    id bigserial NOT NULL,
    creation_time timestamp without time zone NOT NULL,
    modification_time timestamp without time zone NOT NULL,
    version bigint,
    device_identification character varying(40) NOT NULL unique,
    smart_meter_id character varying(40) NOT NULL,
    channel smallint not null
);

ALTER TABLE public.gas_meter_device OWNER TO osp_admin;

ALTER TABLE public.gas_meter_device_id_seq OWNER TO osp_admin;

ALTER SEQUENCE gas_meter_device_id_seq OWNED BY smart_metering_device.id;

ALTER TABLE ONLY gas_meter_device ALTER COLUMN id SET DEFAULT nextval('gas_meter_device_id_seq'::regclass);

ALTER TABLE ONLY gas_meter_device ADD CONSTRAINT gas_meter_device_pkey PRIMARY KEY (id);