text:
import logging

from erlyvideo import ErlyvideoEvent

from django.contrib.auth.models import User
from django.core.urlresolvers import get_callable
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt

from djerlyvideo.conf.settings import ERLYVIDEO_PUBLISH_AUTH_FUNC, ERLYVIDEO_PLAY_AUTH_FUNC
from djerlyvideo.decorators import test_access
from djerlyvideo.models import Server
from djerlyvideo.signals import server_event, publish_auth as _publish_auth, play_auth as _play_auth

__docformat__ = "restructuredtext"

logger = logging.getLogger('djerlyvideo')

def public_auth_sample(server, ip, file, user_id, session_id):
    """
    Пример функции проверки разрешено ли пользователю публиковать поток

    :param server: сервер ``djerlyvideo.models.Server`` отправивший запрос
    :param ip: IP адресс пользователя публикующего поток
    :param file: имя потока
    :param user_id: ID пользователя переданного в данных сессии
    :param session_id: ID сессии
    :return: True - разрешено, False - запрещено
    """
    return True

def play_auth_sample(server, ip, file, user_id, session_id):
    """
    Пример функции проверки разрешено ли пользователю просматривать поток

    :param server: сервер ``djerlyvideo.models.Server`` отправивший запрос
    :param ip: IP адресс пользователя просматривающего поток
    :param file: имя потока
    :param user_id: ID пользователя переданного в данных сессии
    :param session_id: ID сессии
    :return: True - разрешено, False - запрещено
    """
    return True

@csrf_exempt
@test_access
def event_handlers(request):
    logger.debug("%s" % request.POST)

    json_str = request.POST.self.keys()[0]
    event_info = ErlyvideoEvent.load_from_json(json_str)

    try:
        server = Server.objects.get(host=event_info.host)
    except Server.DoesNotExist:
        logger.warning('Erlyvideo server %s not found.' % event_info.host)
        return HttpResponseForbidden()

    server_event.send(sender=ErlyvideoEvent, server=server, event_info=event_info)

    return HttpResponse()

@csrf_exempt
@test_access
def publish_auth(request):
    """
    Авторизация при побликации потока
    """
    server_host = request.META['SERVER_NAME']
    try:
        server = Server.objects.get(host=server_host)
    except Server.DoesNotExist:
        logger.warning('Erlyvideo server %s not found.' % server_host)
        return HttpResponseForbidden()

    func = get_callable(ERLYVIDEO_PUBLISH_AUTH_FUNC)
    if func(server, request.GET['ip'], request.GET['file'], request.GET['user_id'], request.GET['session_id']):
        _publish_auth.send(sender=User, server=None, ip=request.GET['ip'], file=request.GET['file'],
                           user_id=request.GET['user_id'], session_id=request.GET['session_id'])
        return HttpResponse()
    else:
        return HttpResponseForbidden()

@csrf_exempt
@test_access
def play_auth(request):
    """
    Авторизация при проигрывании потока
    """
    server_host = request.META['SERVER_NAME']
    try:
        server = Server.objects.get(host=server_host)
    except Server.DoesNotExist:
        logger.warning('Erlyvideo server %s not found.' % server_host)
        return HttpResponseForbidden()

    func = get_callable(ERLYVIDEO_PLAY_AUTH_FUNC)
    if func(server, request.GET['ip'], request.GET['file'], request.GET['user_id'], request.GET['session_id']):
        _play_auth.send(sender=User, server=None, ip=request.GET['ip'], file=request.GET['file'],
                        user_id=request.GET['user_id'], session_id=request.GET['session_id'])
        return HttpResponse()
    else:
        return HttpResponseForbidden()


text:
import os
from lxml import etree
from pprint import pprint
from forms.parseutil import ted_documents, Extractor
from collections import defaultdict
from common import engine, documents_table, contracts_table, cpvs_table, references_table

def select_form(form, lang):
    lang = lang.split()[0]
    children = form.getchildren()
    if len(children) == 1:
        return children.pop()
    orig = None
    for child in children:
        if child.get('LG') == 'EN':
            return child
        if child.get('LG') == lang:
            orig = child
    return orig

def parse(filename, file_content):
    #fh = open(filename, 'rb')
    xmldata = file_content.replace('xmlns="', 'xmlns_="')
    #fh.close()
    #print xmldata.decode('utf-8').encode('ascii', 'replace')
    root = etree.fromstring(xmldata)
    form = root.find('.//FORM_SECTION')
    form.getparent().remove(form)
    ext = Extractor(root)
    cpvs = [{'code': e.get('CODE'), 'text': e.text} for e in root.findall('.//NOTICE_DATA/ORIGINAL_CPV')]
    ext.ignore('./CODED_DATA_SECTION/NOTICE_DATA/ORIGINAL_CPV')

    refs = [e.text for e in root.findall('.//NOTICE_DATA/REF_NOTICE/NO_DOC_OJS')]
    ext.ignore('./CODED_DATA_SECTION/NOTICE_DATA/REF_NOTICE/NO_DOC_OJS')

    data = {
        'technical_reception_id': ext.text('./TECHNICAL_SECTION/RECEPTION_ID'),
        'technical_comments': ext.text('./TECHNICAL_SECTION/COMMENTS'),
        'technical_deletion_date': ext.text('./TECHNICAL_SECTION/DELETION_DATE'),
        'technical_form_lang': ext.text('./TECHNICAL_SECTION/FORM_LG_LIST'),
        'reception_id': ext.text('./TECHNICAL_SECTION/RECEPTION_ID'),
        'oj_collection': ext.text('.//REF_OJS/COLL_OJ'),
        'oj_number': ext.text('.//REF_OJS/NO_OJ'),
        'oj_date': ext.text('.//REF_OJS/DATE_PUB'),
        'doc_no': ext.text('.//NOTICE_DATA/NO_DOC_OJS'),
        'doc_url': ext.text('.//NOTICE_DATA//URI_DOC[@LG="EN"]') or ext.text('.//NOTICE_DATA//URI_DOC'),
        'info_url': ext.text('.//NOTICE_DATA/IA_URL_GENERAL'),
        'etendering_url': ext.text('.//NOTICE_DATA/IA_URL_ETENDERING'),
        'orig_language': ext.text('.//NOTICE_DATA/LG_ORIG'),
        'orig_nuts': ext.text('.//NOTICE_DATA/ORIGINAL_NUTS'),
        'orig_nuts_code': ext.attr('.//NOTICE_DATA/ORIGINAL_NUTS', 'CODE'),
        'iso_country': ext.attr('.//NOTICE_DATA/ISO_COUNTRY', 'VALUE'),
        'original_cpv': cpvs,
        'references': refs,
        'dispatch_date': ext.text('.//CODIF_DATA/DS_DATE_DISPATCH'),
        'request_document_date': ext.text('.//CODIF_DATA/DD_DATE_REQUEST_DOCUMENT'),
        'submission_date': ext.text('.//CODIF_DATA/DT_DATE_FOR_SUBMISSION'),
        'heading': ext.text('.//CODIF_DATA/HEADING'),
        'directive': ext.attr('.//CODIF_DATA/DIRECTIVE', 'VALUE'),
        'authority_type_code': ext.attr('.//CODIF_DATA/AA_AUTHORITY_TYPE', 'CODE'),
        'authority_type': ext.text('.//CODIF_DATA/AA_AUTHORITY_TYPE'),
        'document_type_code': ext.attr('.//CODIF_DATA/TD_DOCUMENT_TYPE', 'CODE'),
        'document_type': ext.text('.//CODIF_DATA/TD_DOCUMENT_TYPE'),
        'contract_nature_code': ext.attr('.//CODIF_DATA/NC_CONTRACT_NATURE', 'CODE'),
        'contract_nature': ext.text('.//CODIF_DATA/NC_CONTRACT_NATURE'),
        'procedure_code': ext.attr('.//CODIF_DATA/PR_PROC', 'CODE'),
        'procedure': ext.text('.//CODIF_DATA/PR_PROC'),
        'regulation_code': ext.attr('.//CODIF_DATA/RP_REGULATION', 'CODE'),
        'regulation': ext.text('.//CODIF_DATA/RP_REGULATION'),
        'bid_type_code': ext.attr('.//CODIF_DATA/TY_TYPE_BID', 'CODE'),
        'bid_type': ext.text('.//CODIF_DATA/TY_TYPE_BID'),
        'award_criteria_code': ext.attr('.//CODIF_DATA/AC_AWARD_CRIT', 'CODE'),
        'award_criteria': ext.text('.//CODIF_DATA/AC_AWARD_CRIT'),
        'main_activities_code': ext.attr('.//CODIF_DATA/MA_MAIN_ACTIVITIES', 'CODE'),
        'main_activities': ext.text('.//CODIF_DATA/MA_MAIN_ACTIVITIES'),
        'title_text': ext.text('.//ML_TITLES/ML_TI_DOC[@LG="EN"]/TI_TEXT'),
        'title_town': ext.text('.//ML_TITLES/ML_TI_DOC[@LG="EN"]/TI_TOWN'),
        'title_country': ext.text('.//ML_TITLES/ML_TI_DOC[@LG="EN"]/TI_CY'),
        'authority_name': ext.text('./TRANSLATION_SECTION/ML_AA_NAMES/AA_NAME')
    }

    ext.ignore('./LINKS_SECTION/FORMS_LABELS_LINK')
    ext.ignore('./LINKS_SECTION/OFFICIAL_FORMS_LINK')
    ext.ignore('./LINKS_SECTION/ORIGINAL_NUTS_LINK')
    ext.ignore('./LINKS_SECTION/ORIGINAL_CPV_LINK')
    ext.ignore('./LINKS_SECTION/XML_SCHEMA_DEFINITION_LINK')

    # TODO: Figure out if we need any of this, even with the forms.
    ext.ignore('./CODED_DATA_SECTION/NOTICE_DATA/VALUES_LIST/VALUES/SINGLE_VALUE/VALUE')
    ext.ignore('./CODED_DATA_SECTION/NOTICE_DATA/VALUES_LIST')
    ext.ignore('./CODED_DATA_SECTION/NOTICE_DATA/VALUES_LIST/VALUES/RANGE_VALUE/VALUE')

    ext.ignore('./TRANSLATION_SECTION/TRANSLITERATIONS/TRANSLITERATED_ADDR/TOWN')
    ext.ignore('./TRANSLATION_SECTION/TRANSLITERATIONS/TRANSLITERATED_ADDR/POSTAL_CODE')
    ext.ignore('./TRANSLATION_SECTION/TRANSLITERATIONS/TRANSLITERATED_ADDR/PHONE')
    ext.ignore('./TRANSLATION_SECTION/TRANSLITERATIONS/TRANSLITERATED_ADDR/ORGANISATION/OFFICIALNAME')
    ext.ignore('./TRANSLATION_SECTION/TRANSLITERATIONS/TRANSLITERATED_ADDR/FAX')
    ext.ignore('./TRANSLATION_SECTION/TRANSLITERATIONS/TRANSLITERATED_ADDR/COUNTRY')
    ext.ignore('./TRANSLATION_SECTION/TRANSLITERATIONS/TRANSLITERATED_ADDR/CONTACT_POINT')
    ext.ignore('./TRANSLATION_SECTION/TRANSLITERATIONS/TRANSLITERATED_ADDR/ATTENTION')
    ext.ignore('./TRANSLATION_SECTION/TRANSLITERATIONS/TRANSLITERATED_ADDR/ADDRESS')
    ext.audit()

    form_ = select_form(form, data['orig_language'])
    contracts = []
    if form_.tag.startswith('CONTRACT_AWARD_'):
        from forms.contract_award import parse_form
        contracts = parse_form(form_)

    # save to DB
    doc_no = data['doc_no']
    engine.begin()
    cpvs_table.delete(doc_no=doc_no)
    references_table.delete(doc_no=doc_no)
    contracts_table.delete(doc_no=doc_no)
    documents_table.delete(doc_no=doc_no)

    for cpv in data.pop('original_cpv'):
        cpv['doc_no'] = doc_no
        cpvs_table.insert(cpv)

    for ref in data.pop('references'):
        obj = {'doc_no': doc_no, 'ref': ref}
        references_table.insert(obj)

    for contract in contracts:
        contract['doc_no'] = doc_no
        contracts_table.insert(contract)

    documents_table.insert(data)
    engine.commit()
    #pprint(data)

if __name__ == '__main__':
    import sys
    for file_name, file_content in ted_documents():
        parse(file_name, file_content)
        #break
    #parse_all(sys.argv[1])

redpajama_set_name: RedPajamaGithub


text:
layout: sidebar-right
title: 'Open Space – What is happiness and how can we build it for ourselves?'
date: 2016-03-05 10:00:05+00:00
author: sarah-lungley
categories: health, news
excerpt: Feedback from an Open Space session about what happiness is and how we can build and create it for ourselves.
breadcrumb: health
sidebar: health
---
![Open Space logo](/images/featured/featured-open-space-logo.jpg)

Here's feedback from another great Open Space session – This time we looked at what happiness is and how we can build and create it for ourselves.

(Answers in bold were the most common answers)

What is happiness?

  * Something that makes you smile
  * A feeling, atmosphere, people/ places
  * Something that’s evasive
  * Gives you a nice feeling inside
  * Music
  * Bodybuilding
  * Exercise
  * A positive feeling/ sensation which makes you feel good
  * **Friends**
  * A feeling
  * **Animals**
  * **It’s a feeling but I think it is a succession of feelings. You start with feeling well, then wellbeing, then making your own happiness, then happy – Yippee!**
  * Happy – feeling good in the moment
  * Play on my laptop
  * **Feeling at peace**

How can we build it for ourselves?

  * Playing with pets
  * **Laughing**
  * A smile
  * **Sunshine**
  * Warm weather
  * **Feeling if I have accomplished something**
  * **Making other people feel happier, by helping others**
  * Being outside
  * Music
  * **Exercise**
  * Making money
  * Uno Cappucino
  * **Doing things I enjoy**
  * Knitting
  * Arts and Crafts
  * Cinema
  * Running
  * Watching films
  * Fond memories
  * **Shopping- treating yourself**
  * **Connecting with people**
  * **Talking to someone**
  * Healthy diet – protein, slow release sugar
  * Travelling
  * Cup of tea
  * **Food**
  * Letting feelings out
  * Mum’s make us happy
  * Pets ie. Cats and dogs
  * Sunny days
  * Clothes
  * Jokes
  * **Eat and drinking **
  * **Socialising, being with others **
  * **Music**
  * Reading and writing
  * Comedies (movies). Some TV
  * Snow
  * Family
  * Days out
  * Church bells
  * Birds
  * Library groups
  * Candles
  * Singing
  * CD
  * Instruments
  * Gardening
  * Pamper
  * Chocolate
  * Sport
  * Radio
  * **Friends**


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>

    <copyright>
      <year>2011</year><year>2016</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>Common Test Hooks</title>
    <prepared>Lukas Larsson</prepared>
    <docno></docno>
    <date></date>
    <rev></rev>
    <file>ct_hooks_chapter.xml</file>

    <marker id="general"></marker>
    <title>General</title>

      The Common Test Hook (CTH) framework allows
      extensions of the default behavior of <c>Common Test</c> using hooks
      before and after all test suite calls. CTHs allow advanced <c>Common Test</c>
      users to abstract out behavior that is common to multiple test suites
      without littering all test suites with library calls. this can be used
      for logging, starting, and monitoring external systems,
      building C files needed by the tests, and so on.

In brief, CTH allows you to do the following:

    <list type="bulleted">
      <item>Manipulate the runtime configuration before each suite
      configuration call.</item>
      <item>Manipulate the return of all suite configuration calls, and in
      extension, the result of the tests themselves.</item>
    </list>

The following sections describe how to use CTHs, when they are run,
      and how to manipulate the test results in a CTH.

    <warning>
When executing within a CTH, all timetraps are shut off. So
	if your CTH never returns, the entire test run is stalled.

    </warning>

    <marker id="installing"></marker>
    <title>Installing a CTH</title>

A CTH can be installed in multiple ways in your test run. You can do it
      for all tests in a run, for specific test suites, and for specific groups
      within a test suite. If you want a CTH to be present in all test suites
      within your test run, there are three ways to accomplish that, as follows:

    <list type="bulleted">
      <item>Add <c>-ct_hooks</c> as an argument to
      <seealso marker="run_test_chapter#ct_run">ct_run</seealso>.
      To add multiple CTHs using this method, append them to each other
      using the keyword <c>and</c>, that is,
      <c>ct_run -ct_hooks cth1 [{debug,true}] and cth2 ...</c>.</item>
      <item>Add tag <c>ct_hooks</c> to your
      <seealso marker="run_test_chapter#test_specifications">
      Test Specification</seealso>.</item>
      <item>Add tag <c>ct_hooks</c> to your call to
      <seealso marker="ct#run_test-1">ct:run_test/1</seealso>.</item>
    </list>

CTHs can also be added within a test suite. This is done by returning
    <c>{ct_hooks,[CTH]}</c> in the configuration list from
    <seealso marker="common_test#Module:suite-0">suite/0</seealso>,
    <seealso marker="common_test#Module:init_per_suite-1">
      init_per_suite/1</seealso>, or
      <seealso marker="common_test#Module:init_per_group-2">
    init_per_group/2</seealso>.

In this case, <c>CTH</c> can either be only the module name of the CTH
    or a tuple with the module name and the initial arguments, and optionally
    the hook priority of the CTH. For example, one of the following:

    <list type="bulleted">
    <item><c>{ct_hooks,[my_cth_module]}</c></item>
    <item><c>{ct_hooks,[{my_cth_module,[{debug,true}]}]}</c></item>
    <item><c>{ct_hooks,[{my_cth_module,[{debug,true}],500}]}</c></item>
    </list>

      <title>Overriding CTHs</title>

By default, each installation of a CTH causes a new instance of it
	to be activated. This can cause problems if you want to override
	CTHs in test specifications while still having them in the
	suite information function. The
	<seealso marker="ct_hooks#Module:id-1">id/1</seealso>
	callback exists to address this problem. By returning the same
	<c>id</c> in both places, <c>Common Test</c> knows that this CTH
	is already installed and does not try to install it again.

      <title>CTH Execution Order</title>

By default, each CTH installed is executed in the order that
      they are installed for init calls, and then reversed for end calls.
      This is not always desired, so <c>Common Test</c> allows
      the user to specify a priority for each hook. The priority can either
      be specified in the CTH function
      <seealso marker="ct_hooks#Module:init-2">init/2</seealso> or when
      installing the hook. The priority specified at installation overrides the
      priority returned by the CTH.

    <marker id="scope"/>
    <title>CTH Scope</title>

Once the CTH is installed into a certain test run it remains there until
      its scope is expired. The scope of a CTH depends on when it is
      installed, see the following table.
      Function <seealso marker="ct_hooks#Module:init-2">init/2</seealso> is
      called at the beginning of the scope and function
      <seealso marker="ct_hooks#Module:terminate-1">terminate/1</seealso>
      is called when the scope ends.

      <row>
	<cell>CTH installed in</cell>
	<cell>CTH scope begins before</cell>
	<cell>CTH scope ends after</cell>
      </row>
      <row>
	<cell><seealso marker="run_test_chapter#ct_run">ct_run</seealso></cell>
	<cell>the first test suite is to be run</cell>
	<cell>the last test suite has been run</cell>
      </row>
      <row>
	<cell><seealso marker="ct#run_test-1">ct:run_test</seealso></cell>
	<cell>the first test suite is run</cell>
	<cell>the last test suite has been run</cell>
      </row>
      <row>
	<cell><seealso marker="run_test_chapter#test_specifications">
	  Test Specification</seealso></cell>
	<cell>the first test suite is run</cell>
	<cell>the last test suite has been run</cell>
      </row>
      <row>
	<cell><seealso marker="common_test#Module:suite-0">suite/0
	</seealso></cell>
	<cell><seealso marker="ct_hooks#Module:pre_init_per_suite-3">
	    pre_init_per_suite/3</seealso> is called</cell>
	<cell><seealso marker="ct_hooks#Module:post_end_per_suite-4">
	  post_end_per_suite/4</seealso> has been called for that test suite</cell>
      </row>
      <row>
	<cell><seealso marker="common_test#Module:init_per_suite-1">
	  init_per_suite/1</seealso></cell>
	<cell><seealso marker="ct_hooks#Module:post_init_per_suite-4">
	    post_init_per_suite/4</seealso> is called</cell>
	<cell><seealso marker="ct_hooks#Module:post_end_per_suite-4">
	  post_end_per_suite/4</seealso> has been called for that test suite</cell>
      </row>
      <row>
	<cell><seealso marker="common_test#Module:init_per_group-2">
	  init_per_group/2</seealso></cell>
	<cell><seealso marker="ct_hooks#Module:post_init_per_group-4">
	    post_init_per_group/4</seealso> is called</cell>
	<cell><seealso marker="ct_hooks#Module:post_end_per_suite-4">
	  post_end_per_group/4</seealso> has been called for that group</cell>
      </row>
    <tcaption>Scope of a CTH</tcaption>

      <title>CTH Processes and Tables</title>

CTHs are run with the same process scoping as normal test suites,
	that is, a different process executes the <c>init_per_suite</c> hooks then the
	<c>init_per_group</c> or <c>per_testcase</c> hooks. So if you want to spawn a
	process in the CTH, you cannot link with the CTH process, as it exits
	after the post hook ends. Also, if you for some reason need an ETS
	table with your CTH, you must spawn a process that handles it.

      <title>External Configuration Data and Logging</title>

Configuration data values in the CTH can be read
	by calling
	<seealso marker="ct#get_config-1"><c>ct:get_config/1,2,3</c></seealso>
	(as explained in section
	<seealso marker="config_file_chapter#require_config_data">Requiring and Reading Configuration Data</seealso>).
	The configuration variables in question must, as always, first have been
	required by a suite-, group-, or test case information function,
	or by function <seealso marker="ct#require-1"><c>ct:require/1/2</c></seealso>.
	The latter can also be used in CT hook functions.

The CT hook functions can call any logging function
	in the <c>ct</c> interface to print information to the log files, or to
	add comments in the suite overview page.

     <marker id="manipulating"/>
    <title>Manipulating Tests</title>

Through CTHs the results of tests and configuration functions can be manipulated.
    The main purpose to do this with CTHs is to allow common
    patterns to be abstracted out from test suites and applied to
    multiple test suites without duplicating any code. All the callback
    functions for a CTH follow a common interface described hereafter.

<c>Common Test</c> always calls all available hook functions, even pre-
      and post hooks for configuration functions that are not implemented in the suite.
      For example, <c>pre_init_per_suite(x_SUITE, ...)</c> and
      <c>post_init_per_suite(x_SUITE, ...)</c> are called for test suite
      <c>x_SUITE</c>, even if it does not export <c>init_per_suite/1</c>.
      With this feature hooks can be used as configuration fallbacks, and all
      configuration functions can be replaced with hook functions.

      <marker id="pre"/>
      <title>Pre Hooks</title>

	In a CTH, the behavior can be hooked in before the following functions:

     <list type="bulleted">
       <item><seealso marker="common_test#Module:init_per_suite-1"><c>init_per_suite</c></seealso></item>
       <item><seealso marker="common_test#Module:init_per_group-2"><c>init_per_group</c></seealso></item>
       <item><seealso marker="common_test#Module:init_per_testcase-2"><c>init_per_testcase</c></seealso></item>
       <item><seealso marker="common_test#Module:end_per_testcase-2"><c>end_per_testcase</c></seealso></item>
       <item><seealso marker="common_test#Module:end_per_group-2"><c>end_per_group</c></seealso></item>
       <item><seealso marker="common_test#Module:end_per_suite-1"><c>end_per_suite</c></seealso></item>
     </list>

	This is done in the CTH functions called pre_<name of function>.
	These functions take the same three arguments, <c>Name</c>,
	<c>Config</c>, and <c>CTHState</c>. The return value of the CTH function
	is always a combination of a result for the suite/group/test and an
	updated <c>CTHState</c>.

To let the test suite continue on executing, return the configuration
	list that you want the test to use as the result. To skip or
	fail the test, return a tuple with <c>skip</c> or <c>fail</c>, and a reason
	as the result.

Example:

 pre_init_per_suite(SuiteName, Config, CTHState) ->
   case db:connect() of
     {error,_Reason} ->
       {{fail, "Could not connect to DB"}, CTHState};
     {ok, Handle} ->
       {[{db_handle, Handle} | Config], CTHState#state{ handle = Handle }}
   end.

  <note>
If you use multiple CTHs, the first part of the return tuple is
  used as input for the next CTH. So in the previous example the next CTH can
  get <c>{fail,Reason}</c> as the second parameter. If you have many CTHs
  interacting, do not let each CTH return <c>fail</c> or <c>skip</c>.
  Instead, return that an action is to be taken through the <c>Config</c>
  list and implement a CTH that, at the end, takes the correct action.
</note>

      <marker id="post"/>
      <title>Post Hooks</title>

In a CTH, behavior can be hooked in after the following functions:

      <list type="bulleted">
       <item><seealso marker="common_test#Module:init_per_suite-1"><c>init_per_suite</c></seealso></item>
       <item><seealso marker="common_test#Module:init_per_group-2"><c>init_per_group</c></seealso></item>
       <item><seealso marker="common_test#Module:init_per_testcase-2"><c>init_per_testcase</c></seealso></item>
       <item><seealso marker="common_test#Module:end_per_testcase-2"><c>end_per_testcase</c></seealso></item>
       <item><seealso marker="common_test#Module:end_per_group-2"><c>end_per_group</c></seealso></item>
       <item><seealso marker="common_test#Module:end_per_suite-1"><c>end_per_suite</c></seealso></item>
     </list>

      This is done in the CTH functions called <c>post_<name of function></c>.
      These functions take the same four arguments, <c>Name</c>,
      <c>Config</c>, <c>Return</c>, and <c>CTHState</c>. <c>Config</c> in this
      case is the same <c>Config</c> as the testcase is called with.
      <c>Return</c> is the value returned by the testcase. If the testcase
      fails by crashing, <c>Return</c> is
      <c>{'EXIT',{{Error,Reason},Stacktrace}}</c>.

The return value of the CTH function is always a combination of a
	result for the suite/group/test and an updated <c>CTHState</c>. If
	you do not want the callback to affect the outcome of the test,
	return the <c>Return</c> data as it is given to the CTH. You can also
	modify the test result. By returning the <c>Config</c> list
	with element <c>tc_status</c> removed, you can recover from a test
	failure. As in all the pre hooks, it is also possible to fail/skip
	the test case in the post hook.

Example:

 post_end_per_testcase(_TC, Config, {'EXIT',{_,_}}, CTHState) ->
   case db:check_consistency() of
     true ->
       %% DB is good, pass the test.
       {proplists:delete(tc_status, Config), CTHState};
     false ->
       %% DB is not good, mark as skipped instead of failing
       {{skip, "DB is inconsisten!"}, CTHState}
   end;
 post_end_per_testcase(_TC, Config, Return, CTHState) ->
   %% Do nothing if tc does not crash.
   {Return, CTHState}.

      <note>
Do recover from a testcase failure using CTHs only a last resort.
      If used wrongly, it can be very difficult to determine which tests that
      pass or fail in a test run.
</note>

      <title>Skip and Fail Hooks</title>

	After any post hook has been executed for all installed CTHs,
	<seealso marker="ct_hooks#Module:on_tc_fail-3">on_tc_fail</seealso>
	or <seealso marker="ct_hooks#Module:on_tc_skip-3">on_tc_skip</seealso>
	is called if the testcase failed or was skipped, respectively.
	You cannot affect the outcome of the tests any further at this point.

     <marker id="synchronizing"/>
    <title>Synchronizing External User Applications with Common Test</title>

CTHs can be used to synchronize test runs with external user applications.
    The init function can, for example, start and/or communicate with an application that
    has the purpose of preparing the SUT for an upcoming test run, or
    initialize a database for saving test data to during the test run. The
    terminate function can similarly order such an application to reset the SUT
    after the test run, and/or tell the application to finish active sessions
    and terminate.
    Any system error- or progress reports generated during the init- or
    termination stage are saved in the
    <seealso marker="run_test_chapter#pre_post_test_io_log">Pre- and Post Test I/O Log</seealso>.
    (This is also true for any printouts made
    with <c>ct:log/2</c> and <c>ct:pal/2</c>).

To ensure that <c>Common Test</c> does not start executing tests, or
    closes its log files and shuts down, before the external application
    is ready for it, <c>Common Test</c> can be synchronized with the application.
    During startup and shutdown, <c>Common Test</c> can be suspended, simply by
    having a CTH evaluate a <c>receive</c> expression in the init- or terminate
    function. The macros <c>?CT_HOOK_INIT_PROCESS</c> (the process executing the hook
    init function) and <c>?CT_HOOK_TERMINATE_PROCESS</c> (the process executing
    the hook terminate function) each specifies the name of the correct <c>Common Test</c>
    process to send a message to. This is done to return from the <c>receive</c>.
    These macros are defined in <c>ct.hrl</c>.

    <marker id="example"/>
     <title>Example CTH</title>

The following CTH logs information about a test run into a format
       parseable by <seealso marker="kernel:file#consult-1">file:consult/1</seealso>
       (in Kernel):

 %%% @doc Common Test Example Common Test Hook module.
 -module(example_cth).

 %% Callbacks
 -export([id/1]).
 -export([init/2]).

 -export([pre_init_per_suite/3]).
 -export([post_init_per_suite/4]).
 -export([pre_end_per_suite/3]).
 -export([post_end_per_suite/4]).

 -export([pre_init_per_group/3]).
 -export([post_init_per_group/4]).
 -export([pre_end_per_group/3]).
 -export([post_end_per_group/4]).

 -export([pre_init_per_testcase/3]).
 -export([post_init_per_testcase/4]).
 -export([pre_end_per_testcase/3]).
 -export([post_end_per_testcase/4]).

 -export([on_tc_fail/3]).
 -export([on_tc_skip/3]).

 -export([terminate/1]).

 -record(state, { file_handle, total, suite_total, ts, tcs, data }).

 %% @doc Return a unique id for this CTH.
 id(Opts) ->
   proplists:get_value(filename, Opts, "/tmp/file.log").

 %% @doc Always called before any other callback function. Use this to initiate
 %% any common state.
 init(Id, Opts) ->
     {ok,D} = file:open(Id,[write]),
     {ok, #state{ file_handle = D, total = 0, data = [] }}.

 %% @doc Called before init_per_suite is called.
 pre_init_per_suite(Suite,Config,State) ->
     {Config, State#state{ suite_total = 0, tcs = [] }}.

 %% @doc Called after init_per_suite.
 post_init_per_suite(Suite,Config,Return,State) ->
     {Return, State}.

 %% @doc Called before end_per_suite.
 pre_end_per_suite(Suite,Config,State) ->
     {Config, State}.

 %% @doc Called after end_per_suite.
 post_end_per_suite(Suite,Config,Return,State) ->
     Data = {suites, Suite, State#state.suite_total, lists:reverse(State#state.tcs)},
     {Return, State#state{ data = [Data | State#state.data] ,
                           total = State#state.total + State#state.suite_total } }.

 %% @doc Called before each init_per_group.
 pre_init_per_group(Group,Config,State) ->
     {Config, State}.

 %% @doc Called after each init_per_group.
 post_init_per_group(Group,Config,Return,State) ->
     {Return, State}.

 %% @doc Called before each end_per_group.
 pre_end_per_group(Group,Config,State) ->
     {Config, State}.

 %% @doc Called after each end_per_group.
 post_end_per_group(Group,Config,Return,State) ->
     {Return, State}.

 %% @doc Called before each init_per_testcase.
 pre_init_per_testcase(TC,Config,State) ->
     {Config, State#state{ ts = now(), total = State#state.suite_total + 1 } }.

 %% Called after each init_per_testcase (immediately before the test case).
 post_init_per_testcase(TC,Config,Return,State) ->
     {Return, State}

%% @doc Called before each end_per_testcase (immediately after the test case).
 pre_end_per_testcase(TC,Config,State) ->
     {Config, State}.

 %% @doc Called after each end_per_testcase.
 post_end_per_testcase(TC,Config,Return,State) ->
     TCInfo = {testcase, TC, Return, timer:now_diff(now(), State#state.ts)},
     {Return, State#state{ ts = undefined, tcs = [TCInfo | State#state.tcs] } }.

 %% @doc Called after post_init_per_suite, post_end_per_suite, post_init_per_group,
 %% post_end_per_group and post_end_per_testcase if the suite, group or test case failed.
 on_tc_fail(TC, Reason, State) ->
     State.

 %% @doc Called when a test case is skipped by either user action
 %% or due to an init function failing.
 on_tc_skip(TC, Reason, State) ->
     State.

 %% @doc Called when the scope of the CTH is done
 terminate(State) ->
     io:format(State#state.file_handle, "~p.~n",
                [{test_run, State#state.total, State#state.data}]),
     file:close(State#state.file_handle),
     ok.

     <marker id="builtin_cths"/>
    <title>Built-In CTHs</title>

<c>Common Test</c> is delivered with some general-purpose CTHs that
    can be enabled by the user to provide generic testing functionality.
    Some of these CTHs are enabled by default when <c>common_test</c> is started to run.
    They can be disabled by setting <c>enable_builtin_hooks</c> to
    <c>false</c> on the command line or in the test specification. The following
    two CTHs are delivered with <c>Common Test</c>:

    <taglist>
       <tag><c>cth_log_redirect</c></tag>
       <item>

Built-in

Captures all <c>error_logger</c> and SASL logging
	events and prints them to the current test case log. If an event cannot be
	associated with a test case, it is printed in the <c>Common Test</c> framework log.
	This happens for test cases running in parallel and events occuring
	in-between test cases. You can configure the level of
	<seealso marker="sasl:sasl_app">SASL</seealso> events report
	using the normal SASL mechanisms.

       </item>
       <tag><c>cth_surefire</c></tag>
       <item>

Not built-in

Captures all test results and outputs them as surefire
	XML into a file. The created file is by default
	called <c>junit_report.xml</c>. The file name can be changed by
	setting option <c>path</c> for this hook, for example:

<c>-ct_hooks cth_surefire [{path,"/tmp/report.xml"}]</c>

If option <c>url_base</c> is set, an extra
	attribute named <c>url</c> is added to each
	<c>testsuite</c> and <c>testcase</c> XML element. The value
	is constructed from <c>url_base</c> and a relative path
	to the test suite or test case log, respectively, for example:

<c>-ct_hooks cth_surefire [{url_base, "http://myserver.com/"}]</c>

gives an URL attribute value similar to

<c>"http://myserver.com/ct_run.ct@myhost.2012-12-12_11.19.39/
x86_64-unknown-linux-gnu.my_test.logs/run.2012-12-12_11.19.39/suite.log.html"</c>

Surefire XML can, for example, be used by Jenkins to display test
	results.

       </item>
     </taglist>

</chapter>


text:
'use strict';

var express   = require('express'),
    request   = require('request'),
    router    = express.Router(),
    _         = require('lodash-node'),
    maps      = require('../maps'),
    utils     = require('../utils'),
    datetime  = require('../utils/datetime'),
    OAuth     = require('../utils/oauth');

/* GET status */
router.get('/:id([0-9]+)/:subset(arrivals|departures)?', function(req, res, next) {

  var dateTimeFrom = datetime.toCET().format('YYYY-MM-DD HH:mm:ss');

  var dateTimeTo   = datetime.toCET()
    .add(1, 'hours')
    .format('YYYY-MM-DD HH:mm:ss');

  var params = {
    'dateTimeFrom'  : dateTimeFrom,
    'dateTimeTo'    : dateTimeTo,
    'searchType'    : 0,
    'stationID'     : req.params.id
  };

  request.get(new OAuth('RetrieveStationSchedule', params), function(err, resp, body) {

    if (err || resp.statusCode !== 200)
      return res.send(resp.statusCode || 500, { error: '¯\\_(ツ)_/¯' });

    body = maps.stations.station(body, req.locale);

    var sort, reject;

    if (req.params.subset === 'arrivals') {
      sort = 'arrival';
      reject = function(train) { return train.arrival === null; };
    } else if (req.params.subset === 'departures') {
      sort = 'departure';
      reject = function(train) { return train.departure === null; };
    } else {
      sort = 'departure';
      reject = utils.noop;
    }

    body.trains = _.chain(body.trains)
      .reject(reject)
      .sortBy(sort)
      .value();

    res.json(body);
  });

});

router.get('/list', function(req, res, next) {

  var params = {
    // 'LastUpdateDate': '1970-08-11 3:35:53 am'
  };

  request.get(new OAuth('RetrieveStationList', params), function(err, resp, body) {

    if (err || resp.statusCode !== 200)
      return res.send(resp.statusCode || 500, { error: '¯\\_(ツ)_/¯' });

    // basic cache control
    res.setHeader('Cache-Control', 'public, max-age=86400');
    res.setHeader('Expires', new Date(Date.now() + 86400000).toUTCString());

    res.json(maps.stations.list(body));
  });

});

module.exports = router;


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

	<title>SHTOOLS - Localized spectral analysis</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" type="text/css" href="../../css/sh.css">
	<link rel="icon" type="image/vnd.microsoft.icon" href="../../images/favicon.ico">

				HOME
				DOWNLOAD
				DOCUMENTATION
				FAQ

>  Home > Documentation > Python > Localized Spectral Analysis

SHReturnTapersM

Calculate the eigenfunctions of the spherical-cap concentration problem for a single angular order.

Usage

tapers, eigenvalues = pyshtools.SHReturnTapersM (theta0, lmax, m)

Returns

tapers : float, dimension (lmax+1, lmax+1)

The spherical harmonic coefficients of the lmax+1 localization windows, arranged in columns. The first and last rows of each column correspond to spherical harmonic degrees 0 and lmax, respectively, and the columns are arranged from best to worst concentrated.

eigenvalues : float, dimension (lmax+1)

The concentration factors of the localization windows.

Parameters

theta0 : float

The angular radius of the spherical cap in radians.

lmax : integer

The spherical harmonic bandwidth of the localization windows.

m : integer

The angular order of the localization windows.

Description

SHReturnTapersM will calculate the eigenfunctions (i.e., localization windows) of the spherical-cap concentration problem for a singular angular order. The spherical harmonic coefficients of each window are given in the columns of tapers, and the corresponding concentration factors are given in eigenvaules. The columns of tapers are ordered from best to worst concentrated, and the first and last rows of each column correspond to spherical harmonic degrees 0 and lmax, respectively. The localization windows are normalized such that they have unit power.

References

Wieczorek, M. A. and F. J. Simons, Localized spectral analysis on the sphere, Geophys. J. Int., 162, 655-675.

Simons, F.J., F.A. Dahlen, and M.A. Wieczorek, Spatiospectral concentration on a sphere, SIAM Review, 48, 504-536, 2006.

See also

shreturntapers, computedg82, computedm

>  Home > Documentation > Python > Localized Spectral Analysis

			Institut de Physique du Globe de Paris
			University of Sorbonne Paris Cité
			© 2015 Mark Wieczorek


text:
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union

import google.api_core
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1, operations_v1
from google.api_core import retry as retries
import google.auth  # type: ignore
from google.auth import credentials as ga_credentials  # type: ignore
from google.longrunning import operations_pb2  # type: ignore
from google.oauth2 import service_account  # type: ignore
import pkg_resources

from google.cloud.clouddms_v1.types import clouddms, clouddms_resources

try:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
        gapic_version=pkg_resources.get_distribution(
            "google-cloud-dms",
        ).version,
    )
except pkg_resources.DistributionNotFound:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()

class DataMigrationServiceTransport(abc.ABC):
    """Abstract transport class for DataMigrationService."""

    AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)

    DEFAULT_HOST: str = "datamigration.googleapis.com"

    def __init__(
        self,
        *,
        host: str = DEFAULT_HOST,
        credentials: ga_credentials.Credentials = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        api_audience: Optional[str] = None,
        **kwargs,
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is mutually exclusive with credentials.
            scopes (Optional[Sequence[str]]): A list of scopes.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.
        """

        scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}

        # Save the scopes.
        self._scopes = scopes

        # If no credentials are provided, then determine the appropriate
        # defaults.
        if credentials and credentials_file:
            raise core_exceptions.DuplicateCredentialArgs(
                "'credentials_file' and 'credentials' are mutually exclusive"
            )

        if credentials_file is not None:
            credentials, _ = google.auth.load_credentials_from_file(
                credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
            )
        elif credentials is None:
            credentials, _ = google.auth.default(
                **scopes_kwargs, quota_project_id=quota_project_id
            )
            # Don't apply audience if the credentials file passed from user.
            if hasattr(credentials, "with_gdch_audience"):
                credentials = credentials.with_gdch_audience(
                    api_audience if api_audience else host
                )

        # If the credentials are service account credentials, then always try to use self signed JWT.
        if (
            always_use_jwt_access
            and isinstance(credentials, service_account.Credentials)
            and hasattr(service_account.Credentials, "with_always_use_jwt_access")
        ):
            credentials = credentials.with_always_use_jwt_access(True)

        # Save the credentials.
        self._credentials = credentials

        # Save the hostname. Default to port 443 (HTTPS) if none is specified.
        if ":" not in host:
            host += ":443"
        self._host = host

    def _prep_wrapped_messages(self, client_info):
        # Precompute the wrapped methods.
        self._wrapped_methods = {
            self.list_migration_jobs: gapic_v1.method.wrap_method(
                self.list_migration_jobs,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.get_migration_job: gapic_v1.method.wrap_method(
                self.get_migration_job,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.create_migration_job: gapic_v1.method.wrap_method(
                self.create_migration_job,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.update_migration_job: gapic_v1.method.wrap_method(
                self.update_migration_job,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.delete_migration_job: gapic_v1.method.wrap_method(
                self.delete_migration_job,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.start_migration_job: gapic_v1.method.wrap_method(
                self.start_migration_job,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.stop_migration_job: gapic_v1.method.wrap_method(
                self.stop_migration_job,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.resume_migration_job: gapic_v1.method.wrap_method(
                self.resume_migration_job,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.promote_migration_job: gapic_v1.method.wrap_method(
                self.promote_migration_job,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.verify_migration_job: gapic_v1.method.wrap_method(
                self.verify_migration_job,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.restart_migration_job: gapic_v1.method.wrap_method(
                self.restart_migration_job,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.generate_ssh_script: gapic_v1.method.wrap_method(
                self.generate_ssh_script,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.list_connection_profiles: gapic_v1.method.wrap_method(
                self.list_connection_profiles,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.get_connection_profile: gapic_v1.method.wrap_method(
                self.get_connection_profile,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.create_connection_profile: gapic_v1.method.wrap_method(
                self.create_connection_profile,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.update_connection_profile: gapic_v1.method.wrap_method(
                self.update_connection_profile,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.delete_connection_profile: gapic_v1.method.wrap_method(
                self.delete_connection_profile,
                default_timeout=60.0,
                client_info=client_info,
            ),
        }

    def close(self):
        """Closes resources associated with the transport.

        .. warning::
             Only call this method if the transport is NOT shared
             with other clients - this may cause errors in other clients!
        """
        raise NotImplementedError()

    @property
    def operations_client(self):
        """Return the client designed to process long-running operations."""
        raise NotImplementedError()

    @property
    def list_migration_jobs(
        self,
    ) -> Callable[
        [clouddms.ListMigrationJobsRequest],
        Union[
            clouddms.ListMigrationJobsResponse,
            Awaitable[clouddms.ListMigrationJobsResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def get_migration_job(
        self,
    ) -> Callable[
        [clouddms.GetMigrationJobRequest],
        Union[
            clouddms_resources.MigrationJob, Awaitable[clouddms_resources.MigrationJob]
        ],
    ]:
        raise NotImplementedError()

    @property
    def create_migration_job(
        self,
    ) -> Callable[
        [clouddms.CreateMigrationJobRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def update_migration_job(
        self,
    ) -> Callable[
        [clouddms.UpdateMigrationJobRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def delete_migration_job(
        self,
    ) -> Callable[
        [clouddms.DeleteMigrationJobRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def start_migration_job(
        self,
    ) -> Callable[
        [clouddms.StartMigrationJobRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def stop_migration_job(
        self,
    ) -> Callable[
        [clouddms.StopMigrationJobRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def resume_migration_job(
        self,
    ) -> Callable[
        [clouddms.ResumeMigrationJobRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def promote_migration_job(
        self,
    ) -> Callable[
        [clouddms.PromoteMigrationJobRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def verify_migration_job(
        self,
    ) -> Callable[
        [clouddms.VerifyMigrationJobRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def restart_migration_job(
        self,
    ) -> Callable[
        [clouddms.RestartMigrationJobRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def generate_ssh_script(
        self,
    ) -> Callable[
        [clouddms.GenerateSshScriptRequest],
        Union[clouddms.SshScript, Awaitable[clouddms.SshScript]],
    ]:
        raise NotImplementedError()

    @property
    def list_connection_profiles(
        self,
    ) -> Callable[
        [clouddms.ListConnectionProfilesRequest],
        Union[
            clouddms.ListConnectionProfilesResponse,
            Awaitable[clouddms.ListConnectionProfilesResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def get_connection_profile(
        self,
    ) -> Callable[
        [clouddms.GetConnectionProfileRequest],
        Union[
            clouddms_resources.ConnectionProfile,
            Awaitable[clouddms_resources.ConnectionProfile],
        ],
    ]:
        raise NotImplementedError()

    @property
    def create_connection_profile(
        self,
    ) -> Callable[
        [clouddms.CreateConnectionProfileRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def update_connection_profile(
        self,
    ) -> Callable[
        [clouddms.UpdateConnectionProfileRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def delete_connection_profile(
        self,
    ) -> Callable[
        [clouddms.DeleteConnectionProfileRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def kind(self) -> str:
        raise NotImplementedError()

__all__ = ("DataMigrationServiceTransport",)


text:
from SimpleCV import Camera, Display, Color
import time

# Initialize the camera
cam = Camera()

# Initialize the display
display = Display()

# Take an initial picture
img = cam.getImage()

# Write a message on the image
img.drawText("Left lick to save a photo.", color=Color().getRandom())

# Show the image on the display
img.save(display)

time.sleep(5)

counter = 0
while not display.isDone():
    # Update the display with the latest image
    img = cam.getImage()

    img.save(display)

    if display.mouseLeft:
        # Save the image to the current directory
        img.save("photobooth" + str(counter) + ".jpg")
        img.drawText("Photo saved.", color=Color().getRandom())
        img.save(display)
        time.sleep(5)
        counter = counter + 1


text:
require 'csv'
class RatesheetsController < ApplicationController
  # GET /ratesheets
  # GET /ratesheets.xml
  def index
    @ratesheets = Ratesheet.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @ratesheets }
    end
  end

  # Importing CSV Sample

  def csv_import

     CSV.foreach(params[:ratesheet]) do |row|
        # use row here...
        # For example, if you had users in a CSV file like "username,email" you could do:
        Ratesheet.create(:prefix => row[0], :city => row[1], :rate => row[2], :country_id => row[3])
       end

  end

  # GET /ratesheets/1
  # GET /ratesheets/1.xml
  def show
    @ratesheet = Ratesheet.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @ratesheet }
    end
  end

  # GET /ratesheets/new
  # GET /ratesheets/new.xml
  def new
    @ratesheet = Ratesheet.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @ratesheet }
    end
  end

  # GET /ratesheets/1/edit
  def edit
    @ratesheet = Ratesheet.find(params[:id])
  end

  # POST /ratesheets
  #  # Importing actual CSV file

  def create
    @ratesheet = Ratesheet.new(params[:ratesheet])

       # @result = CSV.open(params[:ratesheet][:file], 'r', ?,, ?\r)
        #CSV::Reader.parse(params[:ratesheet][:file]) do |row|
        # use row here...
        # For example, if you had users in a CSV file like "username,email" you could do:
       # Ratesheet.create(:prefix => row[0], :city => row[1], :rate => row[2], :country_id => row[3])
       #end
       @parsed_file = CSV::Reader.parse(params[:ratesheet][:file])
       n=0
            @parsed_file.each  do |row|
            c = Ratesheet.new
            c.prefix = row[0]
            c.city = row[1]
            c.rate = row[2]
            c.country_id = row[3]
            if c.save
               n=n+1
               GC.start if n%50==0
            end
            flash.now[:message]="CSV Import Successful,  #{n} new records added to data base"
         end

    respond_to do |format|
      if @ratesheet.save
        format.html { redirect_to(@ratesheet, :notice => 'Ratesheet was successfully created.') }
        format.xml  { render :xml => @ratesheet, :status => :created, :location => @ratesheet }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @ratesheet.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /ratesheets/1
  # PUT /ratesheets/1.xml
  def update
    @ratesheet = Ratesheet.find(params[:id])

    respond_to do |format|
      if @ratesheet.update_attributes(params[:ratesheet])
        format.html { redirect_to(@ratesheet, :notice => 'Ratesheet was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @ratesheet.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /ratesheets/1
  # DELETE /ratesheets/1.xml
  def destroy
    @ratesheet = Ratesheet.find(params[:id])
    @ratesheet.destroy

    respond_to do |format|
      format.html { redirect_to(ratesheets_url) }
      format.xml  { head :ok }
    end
  end
end


text:
import React, { useEffect, useState } from 'react';
import { shape, string, number } from 'prop-types';

export default function Col ({ style, rand, str, tstr, int}) {
  const [ shouldShow, setShouldShow ] = useState(true);
  useEffect(()=> {
    if( shouldShow && (rand < ( int/ 50)) ) {
      setShouldShow(false);
    }
  }, [rand, shouldShow, setShouldShow, int]);

  return {shouldShow && str || tstr || ' '};
}

Col.propTypes = {
  style: shape({
    [string]: string
  }),
  rand: number,
  str: string,
  tstr: string,
  int: number,
}


text:
require 'spec_helper'

describe 'Yum::RpmnameGlob' do
  it { is_expected.to allow_value('python36-foobar') }
  it { is_expected.to allow_value('openssh-*') }
  it { is_expected.to allow_value('*-client') }
  # confirmed that Name: puppet:agent is not permitted
  # rpmbuild -bs ~/rpmbuild/SPECS/puppet\:agent.spec
  # error: line 28: Illegal char ':' (0x3a) in: Name: puppet:agent
  it { is_expected.not_to allow_values('puppet:agent*') }
end


text:
package com.moonlightpixels.jrpg.internal;

import com.moonlightpixels.jrpg.GameState;
import com.moonlightpixels.jrpg.map.Location;
import com.moonlightpixels.jrpg.map.character.CharacterAnimationSet;
import com.moonlightpixels.jrpg.player.Cast;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.time.Duration;
import java.util.Optional;

@EqualsAndHashCode
@ToString
public final class DefaultGameState implements GameState {
    private final Cast cast = new Cast();
    private String defaultSaveId;
    private Duration timePlayed = Duration.ZERO;

    @Override
    public Optional<String> getDefaultSaveId() {
        return Optional.ofNullable(defaultSaveId);
    }

    @Override
    public void setDefaultSaveId(final String saveId) {
        this.defaultSaveId = saveId;
    }

    @Override
    public Duration getTimePlayed() {
        return timePlayed;
    }

    @Override
    public Location getLocation() {
        return cast.getActiveParty().getLocation();
    }

    @Override
    public void setLocation(final Location location) {
        cast.getActiveParty().setLocation(location);
    }

    @Override
    public Cast getCast() {
        return cast;
    }

    @Override
    public CharacterAnimationSet.Key getHeroAnimationSet() {
        return getCast().getActiveParty().getMembers().get(0).getAnimationSet();
    }

    @Override
    public boolean isValid() {
        return cast.isValid();
    }

    @Override
    @SuppressWarnings("MagicNumber")
    public void update(final float delta) {
        timePlayed = timePlayed.plusMillis((long) (delta * 1000));
    }
}


text:
exports.name = 'gameOver';

exports.type = 0xf754c8fe;

exports.subtype = 0x06;
exports.subtypeLength = 4;	// 4 bytes -> UInt32LE

exports.pack = null;	// Only from server to client

exports.unpack = function(data) {
	return {}
}


text:
namespace aven
{
	namespace graphics
	{

#define RENDERER_MAX_SPRITES	60000
#define RENDERER_VERTEX_SIZE	sizeof(VertexData)
#define RENDERER_SPRITE_SIZE	RENDERER_VERTEX_SIZE * 4
#define RENDERER_BUFFER_SIZE	RENDERER_SPRITE_SIZE * RENDERER_MAX_SPRITES
#define RENDERER_INDICES_SIZE	RENDERER_MAX_SPRITES * 6
#define RENDERER_MAX_TEXTURES	32

#define SHADER_VERTEX_INDEX 0
#define SHADER_UV_INDEX		1
#define SHADER_TID_INDEX	2
#define SHADER_COLOR_INDEX	3

		class BatchRenderer2D : public Renderer2D
		{
		private:
			GLuint m_VAO;
			GLuint m_VBO;
			IndexBuffer* m_IBO;
			GLsizei m_IndexCount;
			VertexData* m_Buffer;

			std::vector<GLuint> m_TextureSlots;
		public:
			BatchRenderer2D();
			~BatchRenderer2D();
			void begin() override;
			void submit(const Renderable2D* rendereable) override;
			void drawString(const std::string& text, const math::Vec3& position, const Font& font, unsigned int color) override;
			void end() override;
			void flush() override;
		private:
			void init();
		};
	}
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string name="action_settings">Paramètres </string>
  <string name="lbl_level">Niveau:</string>
  <string name="lbl_time">Temps:</string>
  <string name="lbl_continue">Continuer</string>
  <string name="lbl_next">Suivant</string>
  <string name="lbl_congrats_or">--- ou bien ---</string>
  <string name="cliptype_character">Personnage</string>
  <string name="cliptype_action">Action</string>
  <string name="cliptype_result">Résultat</string>
  <string name="cliptype_place">Lieu</string>
  <string name="cliptype_signature">Détail</string>
  <string name="choose_medium">Choisir Moyenne</string>
  <string name="lbl_video">Vidéo</string>
  <string name="lbl_audio">Audio</string>
  <string name="lbl_photo">Photo</string>
  <string name="lbl_record">Enregistrer un Clip</string>
  <string name="lbl_order_media_desc">Maintenant mettez vos clips en ordre pour présenter un début clair, un milieu et une fin.</string>
  <string name="lbl_card_tap">Taper pour sélectionner un clip différent</string>
  <string name="lbl_import">Importer</string>
  <string name="lbl_capture">Capturer</string>
  <string name="menu_done">Fait</string>
  <string name="clip_order">Mettre en Ordre les clips</string>
  <!--Record Narration Dialog-->
  <string name="dialog_record">Commencer l\'Enregistrement</string>
  <string name="dialog_done">FAIT</string>
  <string name="dialog_pause">PAUSE</string>
  <string name="dialog_resume">REPRENDRE</string>
  <string name="dialog_stop">Arrêter l\'Enregistrement</string>
  <string name="dialog_redo">REFAIRE</string>
  <string name="edit_card">Editer la Carte</string>
  <string name="change_goal">Changer de But</string>
  <string name="duplicate_card">Dupliquer la Carte</string>
  <string name="duplicate_clip">Dupliquer le Clip</string>
  <string name="remove_card">Supprimer la carte</string>
  <!--THE FOLLOWING IS MERGED FROM /android-studio/sdk/extras/google/play_apk_expansion/downloader_library/res/values-->
  <!--When a download completes, a notification is displayed, and this
        string is used to indicate that the download successfully completed.
        Note that such a download could have been initiated by a variety of
        applications, including (but not limited to) the browser, an email
        application, a content marketplace.-->
  <string name="notification_download_complete">Téléchargement terminé</string>
  <!--When a download completes, a notification is displayed, and this
        string is used to indicate that the download failed.
        Note that such a download could have been initiated by a variety of
        applications, including (but not limited to) the browser, an email
        application, a content marketplace.-->
  <string name="notification_download_failed">Téléchargement non réussi</string>
  <string name="state_unknown">Début...\"</string>
  <string name="state_idle">Attente de début de téléchargement</string>
  <string name="state_fetching_url">Recherche des ressources à télécharger </string>
  <string name="state_connecting">Connexion au serveur de téléchargement</string>
  <string name="state_downloading">téléchargement des ressources</string>
  <string name="state_completed">Téléchargement terminé</string>
  <string name="state_paused_network_unavailable">Téléchargement mis en pause parce qu\'il n\'y a pas de réseau disponible.</string>
  <string name="state_paused_network_setup_failure">Téléchargement mis en pause. Tester un site web dans le navigateur</string>
  <string name="state_paused_by_request">Téléchargement mis en pause</string>
  <string name="state_paused_wifi_unavailable">Téléchargement mis en pause parce que le Wifi n\'est pas disponible.</string>
  <string name="state_paused_wifi_disabled">Téléchargement mis en pause parce que le Wifi est fermé.</string>
  <string name="state_paused_roaming">Télécharger en pause parce que vous êtes en itinérance</string>
  <string name="state_paused_sdcard_unavailable">Télécharger en pause parce que le stockage externe est indisponible</string>
  <string name="state_failed_unlicensed">Le téléchargement a échoué parce qu\'il se peut que vous n\'avez pas  acheté cette application</string>
  <string name="state_failed_fetching_url">Le téléchargement a échoué parce que les ressources sont introuvables</string>
  <string name="state_failed_sdcard_full">Le téléchargement a échoué parce que la mémoire externe est pleine</string>
  <string name="state_failed_cancelled">Téléchargement annulé</string>
  <string name="state_failed">Téléchargement a échoué</string>
  <string name="kilobytes_per_second">%1$s KB/s</string>
  <string name="time_remaining">Temps restant: %1$s</string>
  <string name="time_remaining_notification">Reste %1$s</string>
  <string name="add_clips_before_narrating">Ajouter quelques Clips avant d\'ajouter une narration</string>
  <string name="add_clips_before_reordering">Ajouter quelques clips avant de changer leur ordre</string>
  <string name="add_clips_generic">Ajouter des Clips d\'abord</string>
  <string name="title_section3">Section 3</string>
  <string name="title_section2">Section 2</string>
  <string name="title_section1">Section 1</string>
  <string name="title_activity_test_drag">Test de déplacement</string>
  <!--Screen title before and during recording-->
  <!--Screen title after recording-->
  <!--Screen title while playing back a recording-->
  <!--Label shown during recording-->
  <string name="recording">Enregistrement</string>
  <!--Label shown when the recording is stopped for a reason other than the user stopping it (e.g. the sd card was removed)-->
  <string name="recording_stopped">Enregistrement arrêté </string>
  <!--label shown when there is not enough space to record something-->
  <string name="storage_is_full">mémoire pleine</string>
  <!--label shown when the recording has reached maximum allowed file size-->
  <string name="max_length_reached">Longueur Maximale Atteinte</string>
  <!--label shown when there is no sd card available to record to-->
  <string name="insert_sd_card">Carte SD est nécessaire </string>
  <!--label shown when there is more than 1 minute but less than 9 minutes of space left to record-->
  <!--label shown when there is less than 1 minute of space left to record-->
  <!--button to accept the current recording and return it to the caller-->
  <!--button to discard the current recording and return to the caller-->
  <!--acknowlegement button in a number of dialogs-->
  <string name="button_ok">Ok</string>
  <!--Do not translate. Format of the timer that shows how much has been recorded so far-->
  <!--label shown before the user has recorded anything-->
  <!--the name under which recordings will be visible in the media database is formatted like this-->
  <!--all recordings will show up in the media database with this 'artist' name-->
  <string name="audio_db_artist_name">Vos enregistrements</string>
  <!--all recordings will show up in the media database with this 'album' name-->
  <string name="audio_db_album_name">Enregistrements Audio</string>
  <!--all recordings will show up in the media database in a playlist with this name-->
  <string name="audio_db_playlist_name">Mes Enregistrements</string>
  <!--shown as the message in a dialog when an error occured because of an error accessing the sd card-->
  <string name="error_sdcard_access">Impossible d'accéder au stockage externe ou interne </string>
  <!--shown as the message in a dialog when the app encountered an unspecified internal error-->
  <string name="error_app_internal">Erreur d\'application Interne</string>
  <!--shown as the message in a dialog when the recording could not be added to the media database-->
  <string name="error_mediadb_new_record">Impossible de sauvegarder le son enregistré</string>
  <!--shown as the message in a dialog when an export will tak up too much space-->
  <string name="error_storage_space" formatted="false">Whoops, nous n\'avons pas d\'espace suffisant, veuillez libérer environ %.2f%nMB et essayez de nouveau!</string>
  <!--add for libra begin-->
  <string name="default_record_name">Enregistrement sans titre</string>
  <string name="menu_view_record_list">Voir la Liste d\'enregistrement</string>
  <string name="menu_setting">Paramètres </string>
  <string name="delete_dialog_title">Voulez-vous supprimer l\'enregistrement en cours?</string>
  <string name="overwrite_dialog_title">%s existe déjà. Voulez-vous l\'écraser? </string>
  <string name="preferences_title">Paramètres </string>
  <string name="pref_title_record_type">Type de Fichier d\'enregistrement</string>
  <string name="prefDialogTitle_recordType">Veuillez sélectionner le type de fichier</string>
  <string name="prefDefault_recordType">audio/3gpp</string>
  <string name="pref_title_enable_high_quality">Activer la haute qualité</string>
  <string name="pref_summary_enable_high_quality">Le fichier Audio avec une haute qualité peut être plus grand</string>
  <string name="pref_title_enable_sound_effect">Activer l\'effet audio</string>
  <string name="pref_summary_enable_sound_effect">Lecture des effets Audio quand l\'état est modifié</string>
  <string name="notification_recording">Enregistrement...</string>
  <string name="notification_stopped">Enregistrement arrêté</string>
  <string name="notification_warning">Mémoire faible(moins que %d minutes)...</string>
  <string name="sd_card_not_available">Carte SD n\'est pas disponible</string>
  <string name="open_file_explorer">Ouvrir l\'explorateur de fichier</string>
  <string name="alert_message_delete_record">Voulez-vous supprimer l\'enregistrement sélectionné?</string>
  <string name="recording_narration">Enregistrement de la narration</string>
  <string name="could_not_start_narration">Impossible de démarrer la narration!</string>
  <string name="jumble">Désordre</string>
  <string name="order">Mettre en ordre</string>
  <string name="narrate">Narrer </string>
  <string name="publish">Publier</string>
  <string name="total">Total</string>
  <string name="cancel">Annuler</string>
  <string name="trim_clip">Couper le Clip</string>
  <string name="narration">Narration</string>
  <string name="this_story_has_no_clips_to_publish">Cette histoire n\'a aucun clip à publier!</string>
  <string name="clip_with_no_duration">Impossible de publier le clip! %1$s a une durée de 0. Est-ce vide ou une image?</string>
  <string name="clips_with_no_duration">Impossible de publier les clips! %1$s ont une durée de 0. Sont-ils vide ou des images?</string>
  <string name="clip_audio_tracks">Piste audio du clip</string>
  <!--add for libra end-->
</resources>


text:
<?php
/** This file is part of load.link (https://github.com/deuiore/load.link).
 * View the LICENSE file for full license information.
 **/

class Auth
{
    const LOGIN_PATH = 'login';
    const LOGOUT_PATH = 'logout';

    const COOKIE_EXPIRATION = 31536000;
    protected $isAuthorized;
    protected $token;

    public function __construct()
    {
        $this->isAuthorized = FALSE;
    }

    public function isAuthorized()
    {
        return $this->isAuthorized;
    }

    public static function checkPassword($password)
    {
        $login = Config::get()->getSection('login');

        if (hash_hmac('sha512',
                $password, $login['salt']) == $login['password'])
        {
            return TRUE;
        }

        return FALSE;
    }

    public function authorizeFromToken($token)
    {
        if (DB::get()->getSession($token))
        {
            $this->isAuthorized = TRUE;
            $this->token = $token;
            return TRUE;
        }
        return FALSE;
    }

    public function authorizeFromCookies()
    {
        if (isset($_COOKIE['token']))
        {
            if (DB::get()->getSession($_COOKIE['token']))
            {
                $this->token = $_COOKIE['token'];
                $this->isAuthorized = TRUE;
                return TRUE;
            }
        }
        return FALSE;
    }

    public function authorizeFromLogin($username, $password)
    {
        if ($username == Config::get()->getValue('login', 'username')
            && self::checkPassword($password))
        {
            $this->token = DB::get()->addSession();
            $this->isAuthorized = TRUE;
            return TRUE;
        }
        return FALSE;
    }

    public function unauthorize()
    {
        DB::get()->delSession($this->token);
        unset($this->token);
    }

    public function unauthorizeAll()
    {
        DB::get()->delAllSessions();
        unset($this->token);
    }

    public function setCookie()
    {
        setcookie('token', $this->token, time() + self::COOKIE_EXPIRATION,
            Config::get()->getValue('routing', 'baseurl'));
    }

    public function unsetCookie()
    {
        unset($_COOKIE['token']);
        setcookie('token', '', time() - 42000,
            Config::get()->getValue('routing', 'baseurl'));
    }

    public function getToken()
    {
        return $this->token;
    }

    static function passwordToHashAndSalt($password)
    {
        $salt = uniqid();
        $hash = hash_hmac('sha512', $password, $salt);

        return array(
            'hash' => $hash,
            'salt' => $salt
        );
    }
}


text:
<!DOCTYPE html>

  <title>Ship To It - Company Packing List</title>
  <link href="https://fonts.googleapis.com/css?family=Lato: 100,300,400,700|Luckiest+Guy|Oxygen:300,400" rel="stylesheet">
  <link href="style.css" type="text/css" rel="stylesheet">

Action List

Profiles

Settings

Search the table


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('authentication', '0003_auto_20160804_0610'),
    ]

    operations = [
        migrations.AddField(
            model_name='account',
            name='is_registered',
            field=models.BooleanField(default=False),
        ),
        migrations.AlterField(
            model_name='account',
            name='is_active',
            field=models.BooleanField(default=True),
        ),
    ]


text:
import { setPropertiesFromJSON } from '../../json-helper';

import ObservationComponent from '../finding/ObservationComponent';

/**
 * Generated class for shr.core.Depth.
 * @extends ObservationComponent
 */
class Depth extends ObservationComponent {

  /**
   * Get the value (aliases quantity).
   * @returns {Quantity} The shr.core.Quantity
   */
  get value() {
    return this._quantity;
  }

  /**
   * Set the value (aliases quantity).
   * @param {Quantity} value - The shr.core.Quantity
   */
  set value(value) {
    this._quantity = value;
  }

  /**
   * Get the Quantity.
   * @returns {Quantity} The shr.core.Quantity
   */
  get quantity() {
    return this._quantity;
  }

  /**
   * Set the Quantity.
   * @param {Quantity} quantity - The shr.core.Quantity
   */
  set quantity(quantity) {
    this._quantity = quantity;
  }

  /**
   * Deserializes JSON data to an instance of the Depth class.
   * The JSON must be valid against the Depth JSON schema, although this is not validated by the function.
   * @param {object} json - the JSON data to deserialize
   * @returns {Depth} An instance of Depth populated with the JSON data
   */
  static fromJSON(json={}) {
    const inst = new Depth();
    setPropertiesFromJSON(inst, json);
    return inst;
  }
}
export default Depth;


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<template type="basic" name="CpH1N15amideCNTCT" author="Agilent" investigator=""
        time_created="20111219T120000" tabname="BioSolidsPack" menu1="Calibration(ahX)" menu2="HX Contact Time" apptype="solidsseq1d"
        application="BioSolids" scans="CpH1N15amideCNTCT" seqfil="ahX">
  <protocol title="CpH1N15amideCNTCT" type="protocol">
    <action  type="LIB" status="Ready" lock="off" title="CpH1N15amideCNTCT" exp="CpH1N15amideCNTCT"
        time="1:45" macro="CpH1N15amideCNTCT" data="" />
  </protocol>
</template>


text: <title>ThreatConnect Javascript SDK - Tasks Retrieve Tags</title>


text:
.monaco-editor .margin-view-overlays .folding {
	background-repeat: no-repeat;
	background-origin: border-box;
	background-position: 3px center;
	background-size: 15px;
	margin-left: 5px;
	cursor: pointer;
}

.monaco-editor .margin-view-overlays:hover .folding {
	background-image: url('arrow-expand.svg');
}

.monaco-editor .margin-view-overlays .folding.collapsed {
	background-image: url('arrow-collapse.svg');
}

.monaco-editor.vs-dark .margin-view-overlays:hover .folding {
	background-image: url('arrow-expand-dark.svg');
}

.monaco-editor.vs-dark .margin-view-overlays .folding.collapsed {
	background-image: url('arrow-collapse-dark.svg');
}

/* High-contrast theme */
.monaco-editor.hc-black .margin-view-overlays:hover .folding {
	background-image: url('arrow-expand-dark.svg');
}

.monaco-editor.hc-black .margin-view-overlays .folding.collapsed {
	background-image: url('arrow-collapse-dark.svg');
}

.monaco-editor .inline-folded:after {
	color: grey;
	margin: 0.1em 0.2em 0 0.2em;
	content: "⋯";
	display: inline;
	line-height: 1em;
	cursor: pointer;
}


text:
package org.apache.jackrabbit.oak.whiteboard;

import org.apache.jackrabbit.oak.api.ContentRepository;
import org.apache.jackrabbit.oak.osgi.OsgiWhiteboard;
import org.apache.jackrabbit.oak.spi.whiteboard.AbstractServiceTracker;
import org.apache.sling.testing.mock.osgi.junit.OsgiContext;
import org.jetbrains.annotations.NotNull;
import org.junit.Rule;
import org.junit.Test;

import java.util.Collections;
import java.util.Map;

import static javax.jcr.Repository.REP_VENDOR_DESC;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;

public class AbstractServiceTrackerTest {

    @Rule
    public final OsgiContext context = new OsgiContext();

    @Test
    public void testTrack() {
        TestServiceTracker tracker = new TestServiceTracker();
        try {
            tracker.start(new OsgiWhiteboard(context.bundleContext()));
            tracker.assertSize(0);

            context.registerService(ContentRepository.class, mock(ContentRepository.class), Collections.emptyMap());
            tracker.assertSize(1);

            context.registerService(ContentRepository.class, mock(ContentRepository.class), Collections.singletonMap(REP_VENDOR_DESC, "value"));
            tracker.assertSize(2);

            context.registerService(ContentRepository.class, mock(ContentRepository.class), Collections.singletonMap("differentProperty", "Oak"));
            tracker.assertSize(3);

            context.registerService(ContentRepository.class, mock(ContentRepository.class), Collections.singletonMap(REP_VENDOR_DESC, "Oak"));
            tracker.assertSize(4);

            context.registerService(ContentRepository.class, mock(ContentRepository.class), Collections.singletonMap(REP_VENDOR_DESC, "Oak"));
            tracker.assertSize(5);
        } finally {
            tracker.stop();
            tracker.assertSize(0);
        }
    }

    @Test
    public void testTrackWithProperties() {
        TestServiceTracker tracker = new TestServiceTracker(Collections.singletonMap(REP_VENDOR_DESC, "Oak"));
        try {
            tracker.start(new OsgiWhiteboard(context.bundleContext()));
            tracker.assertSize(0);

            context.registerService(ContentRepository.class, mock(ContentRepository.class), Collections.emptyMap());
            tracker.assertSize(0);

            context.registerService(ContentRepository.class, mock(ContentRepository.class), Collections.singletonMap(REP_VENDOR_DESC, "mismatch"));
            tracker.assertSize(0);

            context.registerService(ContentRepository.class, mock(ContentRepository.class), Collections.singletonMap("differentProperty", "Oak"));
            tracker.assertSize(0);

            context.registerService(ContentRepository.class, mock(ContentRepository.class), Collections.singletonMap(REP_VENDOR_DESC, "Oak"));
            tracker.assertSize(1);

            context.registerService(ContentRepository.class, mock(ContentRepository.class), Collections.singletonMap(REP_VENDOR_DESC, "Oak"));
            tracker.assertSize(2);
        } finally {
            tracker.stop();
            tracker.assertSize(0);
        }
    }

    @Test(expected = IllegalStateException.class)
    public void testStartTwice() {
        TestServiceTracker tracker = new TestServiceTracker();
        tracker.start(new OsgiWhiteboard(context.bundleContext()));
        tracker.start(new OsgiWhiteboard(context.bundleContext()));
    }

    @Test()
    public void testStartStart() {
        TestServiceTracker tracker = new TestServiceTracker();
        tracker.stop();
        tracker.start(new OsgiWhiteboard(context.bundleContext()));

        context.registerService(ContentRepository.class, mock(ContentRepository.class), Collections.emptyMap());
        tracker.assertSize(1);
    }

    private static final class TestServiceTracker extends AbstractServiceTracker<ContentRepository> {
        protected TestServiceTracker() {
            super(ContentRepository.class);
        }

        protected TestServiceTracker(@NotNull Map<String, String> filterProperties) {
            super(ContentRepository.class, filterProperties);
        }

        void assertSize(int expectedSize) {
            assertEquals(expectedSize, getServices().size());
        }
    }

}


text:
/*****************************************************************************

  tb.cpp --

  Original Author: Martin Janssen, Synopsys, Inc., 2002-02-15

 *****************************************************************************/

/*****************************************************************************

  MODIFICATION LOG - modifiers, enter your name, affiliation, date and
  changes you are making here.

      Name, Affiliation, Date:
  Description of Modification:

 *****************************************************************************/

#include "tb.h"
#include "define.h"

void tb::entry()
{
  cout << "Begin Simulation" << endl;

  cout << "End Simulation" << endl;

  sc_stop();

}


text:
class TokyoMetro::Required::All::Factory::Seed::Api::StationFacility < TokyoMetro::Required

  def self.other_files
    [ List.files , Info.files ]
  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
  <ImageView
  	  android:id="@+id/image"
	  android:layout_width="50dip"
	  android:layout_height="50dip" android:src="@drawable/stub" android:scaleType="centerCrop"/>
  <TextView
  	  android:id="@+id/text"
  	  android:layout_width="fill_parent"
	  android:layout_height="wrap_content"
	  android:layout_weight="1" android:layout_gravity="left|center_vertical" android:textSize="20dip" android:layout_marginLeft="10dip"/>
</LinearLayout>


text:
using System;
using System.Collections.Generic;
using OpenMetaverse;

namespace OpenSim.Services.Interfaces
{
    /// <summary>
    /// Records user information specific to a grid but which is not part of a user's account.
    /// </summary>
    public class GridUserInfo
    {
        public string UserID;

        public UUID HomeRegionID;
        public Vector3 HomePosition;
        public Vector3 HomeLookAt;

        public UUID LastRegionID;
        public Vector3 LastPosition;
        public Vector3 LastLookAt;

        public bool Online;
        public DateTime Login;
        public DateTime Logout;

        public GridUserInfo() {}

        public GridUserInfo(Dictionary<string, object> kvp)
        {
            if (kvp.ContainsKey("UserID"))
                UserID = kvp["UserID"].ToString();

            if (kvp.ContainsKey("HomeRegionID"))
                UUID.TryParse(kvp["HomeRegionID"].ToString(), out HomeRegionID);
            if (kvp.ContainsKey("HomePosition"))
                Vector3.TryParse(kvp["HomePosition"].ToString(), out HomePosition);
            if (kvp.ContainsKey("HomeLookAt"))
                Vector3.TryParse(kvp["HomeLookAt"].ToString(), out HomeLookAt);

            if (kvp.ContainsKey("LastRegionID"))
                UUID.TryParse(kvp["LastRegionID"].ToString(), out LastRegionID);
            if (kvp.ContainsKey("LastPosition"))
                Vector3.TryParse(kvp["LastPosition"].ToString(), out LastPosition);
            if (kvp.ContainsKey("LastLookAt"))
                Vector3.TryParse(kvp["LastLookAt"].ToString(), out LastLookAt);

            if (kvp.ContainsKey("Login"))
                DateTime.TryParse(kvp["Login"].ToString(), out Login);
            if (kvp.ContainsKey("Logout"))
                DateTime.TryParse(kvp["Logout"].ToString(), out Logout);
            if (kvp.ContainsKey("Online"))
                Boolean.TryParse(kvp["Online"].ToString(), out Online);

        }

        public Dictionary<string, object> ToKeyValuePairs()
        {
            Dictionary<string, object> result = new Dictionary<string, object>();
            result["UserID"] = UserID;

            result["HomeRegionID"] = HomeRegionID.ToString();
            result["HomePosition"] = HomePosition.ToString();
            result["HomeLookAt"] = HomeLookAt.ToString();

            result["LastRegionID"] = LastRegionID.ToString();
            result["LastPosition"] = LastPosition.ToString();
            result["LastLookAt"] = LastLookAt.ToString();

            result["Online"] = Online.ToString();
            result["Login"] = Login.ToString();
            result["Logout"] = Logout.ToString();

            return result;
        }
    }

    public interface IGridUserService
    {
        GridUserInfo LoggedIn(string userID);
        bool LoggedOut(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt);

        bool SetHome(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt);
        bool SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt);

        GridUserInfo GetGridUserInfo(string userID);
    }
}


text:
/*
    // Reboots all the instances. This should be used for deploying the latest changes to development
 */

// move the cursor up one line
function moveCursorUp () {
    process.stdout.write('\033[1A\r');
}

// this function exits but allows time for things to get flushed.
function exit (err, cb, result){
    if (!cb) {
        var code = (err) ? 1 : 0;
        setTimeout(function () {
            process.exit(code);
        }, 1000);
    }
    else {
        cb (err, result);
    }
}

function getInstances (EC2, type, cb){
    var instances = [];
    var instanceMap = {};
    var async = require ("async");
    if (EC2){
        EC2.describeInstances (function(error, data) {
            if (error) { cb && cb (error);}
            else {
                async.eachSeries (data.Reservations, function (reservation, done){
                    async.eachSeries (reservation.Instances, function (instance, _done){
                        if (instance.PublicDnsName){
                            EC2.describeInstanceAttribute ({Attribute: "userData", InstanceId:instance.InstanceId}, function (err, data){
                                if (!err && data.UserData && data.UserData.Value){
                                    var userData = new Buffer(data.UserData.Value, 'base64').toString ();
                                    if (userData) {
                                        try{userData = JSON.parse (userData);}
                                        catch (err){}
                                    }
                                    if (userData && userData.type === type){
                                        var id = instance.InstanceId;
                                        if (!instanceMap[id]){
                                            instances.push ({id:id, dns:instance.PublicDnsName,
                                                userData:userData});
                                            instanceMap[id] = true;
                                        }
                                    }
                                }
                                _done ();
                            });
                        } else {
                            _done ();
                        }
                    }, function (){
                        done ();
                    });
                }, function (err){
                    cb && cb (err, instances);
                });
            }
        });
    }
    else { cb && cb ("AWS is not configured correctly"); }

}

function init (_params, cb) {
    var error;
    var EC2;
    var AWS = require('aws-sdk');
    var params;

    // get Params
    if (!_params) {
        var argv = require('minimist')(process.argv.slice(2));
        var params = {};
        params.awsFileName = argv.aws;
        params.type = argv.type;
    }
    else{
        params = _params;
    }

    // config AWS
    if (!params.awsFileName) {
        error = "Missing AWS config file name";
        cb(error);
    }
    else if (!params.type) {
        error = "Missing AWS config file name";
        cb(error);
    }
    else {
        try {
            AWS && AWS.config.loadFromPath(params.awsFileName);
        }
        catch (err) {
            error = err;
        }
        finally {
            if (!error) {
                EC2 = AWS && new AWS.EC2();
                params.AWS = AWS;
                params.EC2 = EC2;
                cb(null, params);
            }
            else {
                cb(error);
            }
        }
    }
}

function main (params, cb){
    init (params, function (err, params) {
        if (err) {
            exit(err, cb);
        }
        else {
            getInstances(params.EC2, params.type, function (err, instances) {
                if (!err) {
                    var instanceIds = [];
                    if (instances && instances.length) {
                        for (var i = 0; i < instances.length; ++i) {
                            instanceIds.push(instances[i].id);
                        }
                        params.EC2.rebootInstances({InstanceIds: instanceIds, DryRun: false}, function (err, data) {
                            if (err) {
                                exit("EC2 Error", cb);
                            }
                            else {
                                console.log("Successfully rebooted (" + instances.length + ")");
                                exit(null, cb);
                            }
                        });
                    }
                    else {
                        console.log("No Instances found");
                        exit(null, cb);
                    }

                }
                else {
                    exit(err, cb);
                }
            });
        }
    });
}

var isModule = !(process.argv[1].indexOf ('rebootAllInstances.js') !== -1);

// if this isn't being called from module pull the parmas off of the commandline
if (!isModule) {
    main (null, function (err, result){
        if (err){
            console.log ("Error: " + err);
        }
        else{
            console.log (result);
        }
        exit (err);
    });
}

// else this is being loaded as a module so support a cb and passing in the params
else {
    exports.reboot = function (awsFileName, type, cb) {
        main ({awsFileName:awsFileName, type:type}, function (err, result){
            cb && cb (err, result);
        });
    }
}


text:
@interface BasePostViewController : BaseViewController
{
    NSMutableDictionary*    m_postObj;

    BOOL m_bIsPublished;
}

- (void) setResultDic:(NSDictionary* ) result image:(UIImage*) imagePhoto;
- (void) onShare;

- (void) changeCaptionText:(NSString *)textCaption;

@end


text:
import { Component, OnInit,  Input, Output, trigger, state, style, transition, animate, ViewChild, ElementRef, Renderer, ViewContainerRef, EventEmitter} from '@angular/core';
import {Observable} from 'rxjs/Rx';
import {BikeService } from './bikes/bike.service';
import {BikeStation} from './bikes/bike';
import {MapComponent} from './map/map.component';
import {TopNavigation} from './component/top.navigation.component';
import {BlackOverlay} from './component/blackoverlay.component';
import {Info} from './component/info.panel';
import {SearchBar} from './component/search.bar.component';
import {Analyze} from './component/analystics.component';
import {LoginComponent} from './component/login.component';
import {AgmCoreModule} from 'angular2-google-maps/core';
import {AlertComponent } from 'ng2-bootstrap/ng2-bootstrap';
import {NgModel} from '@angular/forms';
import {Coords} from './models/location';
import {FilterPanel} from './component/filter.panel';
import { CarouselComponent } from './component/instruction.component';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';

declare var google: any;
declare var Slider: any;

function userExist() {
  try {
    if(localStorage.getItem("userInfo") !== null){
      return true;
    }else {
      return false;
    }
  }
  catch (e) {
    return false;
  }
};

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  providers: []
})

export class AppComponent implements OnInit {
  private viewContainerRef: ViewContainerRef;
  public onlineOffline: boolean = navigator.onLine;
  bRegister:boolean = false;
  router:Router;
  bMapDone:boolean = false;

  @ViewChild(MapComponent)
  private MapComponent:MapComponent;

  @ViewChild(FilterPanel)
  private filter:FilterPanel;

  @ViewChild(TopNavigation)
  private topNav:TopNavigation;

  @ViewChild(BlackOverlay)
  private blackOverlay: BlackOverlay;

  @ViewChild(Analyze)
  private analyze: Analyze;

  @ViewChild(SearchBar)
  private SearchBar: SearchBar;

  @ViewChild(LoginComponent)
  private loginComponent: LoginComponent;

  @ViewChild(Info)
  private info: Info;

  @ViewChild(CarouselComponent)
  private carouselComponent: CarouselComponent;

  stations : BikeStation[];
  data : string
  // google maps zoom level
  zoom: number = 14;

  // initial center position for the map
  lat: number = 60.1712179;
  long: number = 24.9418765;

  ngOnInit(){
    document.body.style.background = 'rgb(234, 237, 242)';
    this.blackOverlay.setState('full');
    this.filter.load(this.MapComponent);
    this.info.load(this.MapComponent);
    this.analyze.load(this.MapComponent,this.carouselComponent);
    if(!userExist()){
      let timer = Observable.timer(2000,1000);
      timer.subscribe(()=> {
        this.register();
      });
    }else {
      this.bRegister = true;
    }
  }

  constructor(private _router: Router, viewContainerRef:ViewContainerRef ) {
    this.router = _router;
    this.viewContainerRef = viewContainerRef;
    window.addEventListener('online', () => {this.onlineOffline = true});
    window.addEventListener('offline', () => {this.onlineOffline = false});
  }

  public closeAll():void{
    this.blackOverlay.setState('close');
    //this.UserComponent.setState('close');
  }

  public loadData(event:boolean){    //call only if map is completely loaded. receive boolean true
    if (event==true){
      this.bMapDone = true;
      this.topNavOpen();
    }
  }
  public register(){
    if(!userExist()){
      this.bRegister = false;
    }else {
      this.bRegister = true;
    }

  }

  public topNavOpen(){
    if(this.bMapDone && localStorage.getItem('userInfo')){
      if(this.router.url == '/analyze' ){
        this.blackOverlay.setState('open');
        this.analyze.setState('open');
      }else {
        this.reset();
        if(this.router.url == "/bike"){
          this.MapComponent.directionDestination();
          this.MapComponent.center();
        }
        //incase there are some more components adding later
      }
    }
  }

  openHelper(){
    this.filter.OpenPanel('Bike');
  }

  reset(){
    this.analyze.setState('close');
    this.MapComponent.clearMarkers();
    this.MapComponent.clearDirection();
  }

}


text:
using System;

namespace BriLib.UI
{
  public class SelectionContainer
  {
    public ObservableProperty<ISelectable> Current = new ObservableProperty<ISelectable>();

    private Type _selectableType;
    private ISelectable _current;

    public void Initialize(Type selectableType)
    {
      _selectableType = selectableType;
      MessageManager.Instance.Bus.Subscribe<SelectionMessage>(OnSelectionMessage);
    }

    public void Deinitialize()
    {
      MessageManager.Instance.Bus.Unsubscribe<SelectionMessage>(OnSelectionMessage);
    }

    private void OnSelectionMessage(SelectionMessage obj)
    {
      var selectableType = obj.NewSelection.GetType();
      if (selectableType != _selectableType || _current == obj.NewSelection) return;
      if (_current != null) _current.Selected.Value = false;
      obj.NewSelection.Selected.Value = true;
      _current = obj.NewSelection;
      Current.Value = _current;
    }
  }
}


text:
const moment = require('moment');
const Reflux = require('reflux');
const _ = require('lodash');
const { NotificationActions, userFeed } = require('./NotificationActions');
/**
 * This store connects with GetStream and holds a bundle that contains
 * the count of unread and unseen notifications, as well as an array of
 * notification objects. The Notification Component will listen to it to
 * obtain updates in order to display accurate information.
 *
 */
const notificationStore = Reflux.createStore({
  init() {
    this.bundle = [];
    // We listen to complete pulls of the latest notifications
    this.listenTo(
      NotificationActions.fetchNotifications.completed,
      this._onFetchCompleted,
    );
    // We listen to push updates
    this.listenTo(
      NotificationActions.processEvent.completed,
      this._onUpdateReceived,
    );
    // Manually trigger the initial pull to fill up the store
    NotificationActions.fetchNotifications(); // This is so fetch
    // This opens a websocket with GetStream and passes a callback to the store
    // so that we can process push updates.
    if (!userFeed) return;
    userFeed
      .subscribe(NotificationActions.processEvent)
      .then(() => {}, this._onError);
  },
  _onFetchCompleted(bundle) {
    console.log('[notificationStore] Fetch completed');
    this.bundle = bundle;
    this.trigger(this.bundle);
  },
  _onUpdateReceived(update) {
    console.log('[notificationStore] Push update received');
    this.bundle = {
      unreadCount: update.unreadCount,
      unseenCount: update.unseenCount,
      // A push update contains only new and deleted notifications, so we:
      //   1. Add the new ones to the ones we had
      //   2. Filter the matching deleted ids in the local store
      //   3. Re-sort them
      notifications: _.sortBy(
        _.filter(
          _(this.bundle.notifications)
            .concat(update.added)
            .value(),
          function(item) {
            return _.findIndex(_.pluck(update.deleted, 'id'), item.id) === -1;
          },
        ),
        'time',
      ).reverse(),
    };
    this.trigger(this.bundle);
  },
  _onError(error) {
    console.log(
      '[notificationStore] An error happened while processing ' +
        'notifications: ' +
        error,
    );
  },
});
module.exports = notificationStore;