text:
"""The Homewizard integration."""
import logging

from aiohwenergy import DisabledError

from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_IP_ADDRESS
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.update_coordinator import UpdateFailed

from .const import DOMAIN, PLATFORMS
from .coordinator import HWEnergyDeviceUpdateCoordinator as Coordinator

_LOGGER = logging.getLogger(__name__)

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Homewizard from a config entry."""

    _LOGGER.debug("__init__ async_setup_entry")

    # Migrate `homewizard_energy` (custom_component) to `homewizard`
    if entry.source == SOURCE_IMPORT and "old_config_entry_id" in entry.data:
        # Remove the old config entry ID from the entry data so we don't try this again
        # on the next setup
        data = entry.data.copy()
        old_config_entry_id = data.pop("old_config_entry_id")

        hass.config_entries.async_update_entry(entry, data=data)
        _LOGGER.debug(
            (
                "Setting up imported homewizard_energy entry %s for the first time as "
                "homewizard entry %s"
            ),
            old_config_entry_id,
            entry.entry_id,
        )

        ent_reg = er.async_get(hass)
        for entity in er.async_entries_for_config_entry(ent_reg, old_config_entry_id):
            _LOGGER.debug("Removing %s", entity.entity_id)
            ent_reg.async_remove(entity.entity_id)

            _LOGGER.debug("Re-creating %s for the new config entry", entity.entity_id)
            # We will precreate the entity so that any customizations can be preserved
            new_entity = ent_reg.async_get_or_create(
                entity.domain,
                DOMAIN,
                entity.unique_id,
                suggested_object_id=entity.entity_id.split(".")[1],
                disabled_by=entity.disabled_by,
                config_entry=entry,
                original_name=entity.original_name,
                original_icon=entity.original_icon,
            )
            _LOGGER.debug("Re-created %s", new_entity.entity_id)

            # If there are customizations on the old entity, apply them to the new one
            if entity.name or entity.icon:
                ent_reg.async_update_entity(
                    new_entity.entity_id, name=entity.name, icon=entity.icon
                )

        # Remove the old config entry and now the entry is fully migrated
        hass.async_create_task(hass.config_entries.async_remove(old_config_entry_id))

    # Create coordinator
    coordinator = Coordinator(hass, entry.data[CONF_IP_ADDRESS])
    try:
        await coordinator.initialize_api()

    except DisabledError:
        _LOGGER.error("API is disabled, enable API in HomeWizard Energy app")
        return False

    except UpdateFailed as ex:
        raise ConfigEntryNotReady from ex

    await coordinator.async_config_entry_first_refresh()

    # Finalize
    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = coordinator

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    _LOGGER.debug("__init__ async_unload_entry")

    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

    if unload_ok:
        config_data = hass.data[DOMAIN].pop(entry.entry_id)
        await config_data.api.close()

    return unload_ok


text:
#ifndef SSDB_OPTION_H_
#define SSDB_OPTION_H_

#include <ostream>
#include "../util/config.h"

#ifdef USE_LEVELDB
class Options
{
public:
    Options();
    ~Options(){}

    void load(Config *conf);

    Options() {
        this->load(c);
    }

    Config* c = nullptr;

    size_t cache_size;
    size_t max_open_files;
    size_t write_buffer_size;
    size_t block_size;
    int compaction_speed;
    std::string compression;
    bool binlog;
    size_t binlog_capacity;

};
#else

#define UNIT_MB (1024 * 1024)
#define UNIT_KB (1024)

struct Options {
    bool create_if_missing = true;
    bool create_missing_column_families = true;
    int write_buffer_size = 64;
    int max_open_files = 5000;

    // default target_file_size_base and multiplier is the save as rocksdb
    bool compression = true;
    bool rdb_compression = true;
    bool transfer_compression = true;
    bool level_compaction_dynamic_level_bytes = false;
    bool use_direct_reads = false;
    bool optimize_filters_for_hits = false;
    bool cache_index_and_filter_blocks = false;
    bool expire_enable = false;

    int min_write_buffer_number_to_merge = 2;
    int max_write_buffer_number = 3;
    int max_background_flushes = 4;
    int max_background_compactions = 4;

    size_t sim_cache = 100;
    size_t cache_size = 100;
    size_t block_size = 4;
    size_t compaction_readahead_size = 4;
    size_t max_bytes_for_level_base = 256;
    size_t max_bytes_for_level_multiplier = 10;

    size_t target_file_size_base = 64;

    int level0_file_num_compaction_trigger = 4; //start compaction
    int level0_slowdown_writes_trigger = 20; //slow write
    int level0_stop_writes_trigger = 36;  //block write

    std::string upstream_ip;
    int upstream_port = 0;

    void load(Config *conf);

    Options() {
        this->load(c);
    }

    Config* c = nullptr;

    friend std::ostream &operator<<(std::ostream &os, const Options &options);
};

#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
package cat.calidos.morfeu.utils.injection;

import static org.junit.jupiter.api.Assertions.*;

import java.util.List;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

/**
*	@author daniel giribet
*///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class SQLModuleTest extends SQLTezt {

@Test @DisplayName("Test connection")
public void okResultTest() throws Exception {

	dropPersonsTable();

	String create = "CREATE TABLE Persons (\n" +
					"    PersonID int,\n" +
					"    LastName varchar(255),\n" +
					"    FirstName varchar(255),\n" +
					"    Address varchar(255),\n" +
					"    City varchar(255) \n" +
					") ";
	int update = SQLModule.update(statement, create);
	assertEquals(0, update);
	List<List<String>> output = SQLModule.query(statement, "SHOW TABLES");
	assertAll("show tables asserts",
		() -> assertEquals(2, output.size()),
		() -> assertEquals(2, output.get(0).size()),
		() -> assertTrue(output.get(0).contains("TABLE_NAME")),
		() -> assertTrue(output.get(0).contains("TABLE_SCHEMA")),
		() -> assertTrue(output.get(1).contains("PERSONS")),
		() -> assertTrue(output.get(1).contains("PUBLIC"))
	);

}

}

/*
 *    Copyright 2020 Daniel Giribet
 *
 *   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.
 */


text:
create or replace
PROCEDURE Tissue_specimen_event_migrate(event_name in varchar2)
IS
  counter                   INTEGER;
  form_context_id           INTEGER;
  seqval                    NUMBER(25);
  specimen_event_identifier INTEGER;
  specimen_id               INTEGER;
  specimen_event_user_id    INTEGER;
  specimen_event_param_id   INTEGER;
  specimen_comments         VARCHAR2(2000);
  specimen_timestamp        TIMESTAMP;
  parent_specimen_id        INTEGER;
  flag                      INTEGER;
  dispo_neo                 NUMBER(25);
  dispo_nec                 NUMBER(25);
  dispo_lym                 NUMBER(25, 5);
  dispo_tot                 NUMBER(25, 5);
  dispo_his                 VARCHAR2(255);
  query_text                VARCHAR2(2000);
  query_text_form           VARCHAR2(2000);
  v_code                    NUMBER;
  v_errm                    VARCHAR2(2000);
  CURSOR mig_cursor IS
    SELECT spec.identifier,
           spec.specimen_id,
           spec.event_timestamp,
           spec.user_id,
           spec.comments,
           tis.neoplastic_cellularity_per,
           tis.necrosis_percentage,
           tis.lymphocytic_percentage,
           tis.total_cellularity_percentage,
           tis.histological_quality,
           absspec.parent_specimen_id
    FROM   catissue_tis_spe_event_param tis,
           catissue_specimen_event_param spec,
           catissue_specimen se,
           catissue_abstract_specimen absspec
    WHERE  tis.identifier = spec.identifier
           AND spec.specimen_id = se.identifier
           AND absspec.identifier = se.identifier;
BEGIN
  -----------------------------query for form contex id--------------------------------------
  SELECT formcontext.identifier
  INTO   form_context_id
  FROM   dyextn_abstract_form_context formcontext
         join dyextn_container dcontainer
           ON formcontext.container_id = dcontainer.identifier
         join dyextn_entity ent
           ON ent.identifier = dcontainer.abstract_entity_id
         join dyextn_abstract_metadata meta
           ON meta.NAME = event_name
              AND meta.identifier = ent.identifier
         join dyextn_abstract_metadata meta2
           ON meta2.NAME = 'SpecimenEvents'
         join dyextn_entity_group eg
           ON eg.identifier = meta2.identifier
              AND eg.identifier = ent.entity_group_id
              AND formcontext.activity_status = 'Active';

  -----------------------------------calling function--------------------------------------------------------------- */
  SELECT Query_formation(event_name)
  INTO   query_text
  FROM   dual;

  -- DBMS_OUTPUT.PUT_LINE(query_text);
  --DBMS_OUTPUT.PUT_LINE(form_context_id);
  counter := 0;

  ------------------------------------------------------------------------------------------------------------------
  OPEN mig_cursor;

  LOOP
      FETCH mig_cursor INTO specimen_event_identifier, specimen_id,
      specimen_timestamp
      , specimen_event_user_id, specimen_comments, dispo_neo, dispo_nec,
      dispo_lym
      ,
      dispo_tot, dispo_his, parent_specimen_id;

      EXIT WHEN mig_cursor%notfound;

      SELECT COUNT(*)
      INTO   flag
      FROM   catissue_received_event_param rec,
             catissue_specimen_event_param spec
      WHERE  spec.specimen_id = parent_specimen_id
             AND spec.event_timestamp = specimen_timestamp
             AND spec.identifier = rec.identifier;

      IF flag = 0 THEN
        --
        BEGIN
            -------------------------------------------------------------------
            INSERT INTO dyextn_abstract_record_entry
                        (identifier,
                         modified_date,
                         activity_status,
                         abstract_form_context_id)
            VALUES      (dyextn_abstract_re_seq.nextval,
                         SYSDATE,
                         'Active',
                         form_context_id);

            --DBMS_OUTPUT.PUT_LINE('dyextn_abstract_record_entry');
            -------------------------------------------------------------------
            INSERT INTO catissue_action_app_rcd_entry
                        (identifier)
            VALUES     (dyextn_abstract_re_seq.currval);

            -- DBMS_OUTPUT.PUT_LINE('catissue_action_app_rcd_entry');
            -----------------------------
            query_text_form := 'insert into CATISSUE_ABSTRACT_APPLICATION(identifier,timestamp,user_details,comments)      values(:1, :2, :3, :4)';

            EXECUTE IMMEDIATE query_text_form
            USING specimen_event_identifier, specimen_timestamp,
            specimen_event_user_id,
            specimen_comments;

            -------------------------------------------------------------------
            INSERT INTO catissue_action_application
                        (identifier,
                         specimen_id,
                         action_app_record_entry_id)
            VALUES     (specimen_event_identifier,
                        specimen_id,
                        dyextn_abstract_re_seq.currval);

            -------------------------------------------------------------------
            SELECT dyextn_abstract_re_seq.currval
            INTO   seqval
            FROM   dual;

            -- DBMS_OUTPUT.PUT_LINE(specimen_id||'  '||specimen_event_identifier||'  '||seqval);
            EXECUTE IMMEDIATE query_text
            USING dispo_his, specimen_event_identifier, dispo_lym, dispo_nec,
            dispo_neo,
            dispo_tot, seqval;

            -- DBMS_OUTPUT.PUT_LINE('h='||dispo_HIS||' tot= '||dispo_TOT||' neo= '||dispo_NEO||' nec= '||dispo_NEC||' lym= '||dispo_LYM||' id= '||specimen_event_identifier||' seq= '|| seqval);
            --DBMS_OUTPUT.PUT_LINE('dybtbl');
            counter := counter + 1;

            NULL;
        EXCEPTION
            WHEN OTHERS THEN
              v_code := SQLCODE;

              v_errm := Substr(sqlerrm, 1, 1000);

              dbms_output.Put_line('exception occer''Error code '
                                   || v_code
                                   ||' '
                                   ||v_errm
                                   ||' '
                                   ||counter);

              dbms_output.Put_line(counter);
        END;
      END IF;
  END LOOP;

  CLOSE mig_cursor;
------------------------------------------------------------------
EXCEPTION
  WHEN dup_val_on_index THEN
             ROLLBACK;

             dbms_output.Put_line('Duplicate value on an index');
WHEN OTHERS THEN
             ROLLBACK;

             v_code := SQLCODE;

             v_errm := Substr(sqlerrm, 1, 1000);

             dbms_output.Put_line('exception occer''Error code '
                                  || v_code
                                  ||','
                                  ||v_errm
                                  ||','
                                  ||counter);
END tissue_specimen_event_migrate;


text:
module Forml.CLI where

import Control.Monad.State hiding (lift)
import Control.Monad.Trans.Error (ErrorT(..))

import System.Console.ANSI
import System.Exit
import System.Info
import System.IO
import System.Process

import Data.String.Utils

data TestMode  = NoTest | Node | Phantom

data RunConfig = RunConfig { inputs :: [String]
                           , output :: String
                           , show_types :: Bool
                           , optimize :: Bool
                           , silent :: Bool
                           , flush :: Bool
                           , remote :: Bool
                           , pretty :: Bool
                           , run_tests :: TestMode
                           , write_docs :: Bool
                           , implicit_prelude :: Bool
                           , watch :: Bool }

parseArgs :: [String] -> RunConfig
parseArgs = fst . runState argsParser
  where argsParser = do args <- get
                        case args of
                          []      -> return $ RunConfig [] "default" False True False False False False Phantom False True False
                          (x':xs) -> do put xs
                                        case x' of
                                          "-w"          -> do x <- argsParser
                                                              return $ x { watch = True }
                                          "-docs"       -> do x <- argsParser
                                                              return $ x { write_docs = True }
                                          "-t"          -> do x <- argsParser
                                                              return $ x { show_types = True }
                                          "-no-prelude" -> do x <- argsParser
                                                              return $ x { implicit_prelude = False }
                                          "-no-opt"     -> do x <- argsParser
                                                              return $ x { optimize = False }
                                          "-silent"     -> do x <- argsParser
                                                              return $ x { silent = True }
                                          "-flush"      -> do x <- argsParser
                                                              return $ x { flush = True }
                                          "-remote"     -> do x <- argsParser
                                                              return $ x { remote = True }
                                          "-pretty"     -> do x <- argsParser
                                                              return $ x { pretty = True }
                                          "-no-test"    -> do x <- argsParser
                                                              return $ x { run_tests = NoTest }
                                          "-node-test"  -> do x <- argsParser
                                                              return $ x { run_tests = Node }
                                          "-o"          -> do (name:ys) <- get
                                                              put ys
                                                              RunConfig a _ c d e f g h i j k l <- argsParser
                                                              return $ RunConfig a name c d e f g h i j k l
                                          ('-':_)       -> error "Could not parse options"
                                          z             -> do RunConfig a _ c d e f g h i j k l <- argsParser
                                                              let b = last $ split "/" $ head $ split "." z
                                                              return $ RunConfig (x':a) b c d e f g h i j k l

type StatusLogger a = String -> a -> IO a

status_logger :: [SGR] -> String -> StatusLogger a
status_logger sgrs rep =
  let logger str out =
        colors ((putStrLn $ "[" ++ rep ++ "] " ++ str) >> return out) $
        do  putStr "\r["
            setSGR sgrs
            putStr rep
            setSGR [Reset]
            putStrLn$ "] " ++ str
            return out in
  logger

success :: String -> a -> IO a
success = status_logger [SetColor Foreground Dull Green] "*"

warn :: String -> a -> IO a
warn = status_logger [SetColor Foreground Dull Yellow] "-"

failure :: String -> a -> IO a
failure = status_logger [SetColor Foreground Dull Red] "X"

colors :: IO a -> IO a -> IO a
colors failure success =
    if os == "mingw32"
        then success
        else do
            (_, Just std_out', _, p) <-
                createProcess (shell "tput colors 2> /dev/null") { std_out = CreatePipe }
            waitForProcess p
            c <- hGetContents std_out'
            case reads (strip c) of
               [(x, "")] | x > (2 :: Integer) -> success
               _ -> failure

type Runner a = String -> IO (Either [String] a) -> IO a

singleError :: ErrorT String IO a -> IO (Either [String] a)
singleError = liftM (either (Left . (:[])) Right) . runErrorT

run_silent :: Runner a
run_silent _ d =
  do  d' <- d
      case d' of
        Right y -> do return y
        Left  y -> do exitFailure

monitor :: Runner a
monitor x d = do colors (return ()) $ putStr $ "[ ] " ++ x
                 hFlush stdout
                 d' <- d
                 case d' of
                   Right y -> success x y
                   Left  y -> do  failure x y
                                  if length y <= 5
                                    then mapM putStrLn y >> return ()
                                    else mapM putStrLn (take 5 y) >> putStrLn ("\n" ++ show (length y - 5) ++ " additional errors")
                                  exitFailure


text:
<!doctype html>

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

    <meta name="mobile-web-app-capable" content="yes">
    <link rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="EMP3 Map Widget">
    <link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

    <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
    <meta name="msapplication-TileColor" content="#3372DF">
    <link href="vendor/mil-sym/renderer.css" rel="stylesheet" type="text/css" />
    <link href="css/material.font.css" rel="stylesheet">
    <link href="css/material.icons.css" rel="stylesheet">
    <link href="css/material.cyan-orange.min.css" rel="stylesheet">

hello world!<button onclick="setCamera();"> Set Camera </button>


text:
package org.apache.kerby.kerberos.kerb.crypto.cksum;

import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Aes128Provider;
import org.apache.kerby.kerberos.kerb.crypto.key.AesKeyMaker;
import org.apache.kerby.kerberos.kerb.spec.base.CheckSumType;

public class HmacSha1Aes128CheckSum extends HmacKcCheckSum {

    public HmacSha1Aes128CheckSum() {
        super(new Aes128Provider(), 20, 12);

        keyMaker(new AesKeyMaker((Aes128Provider) encProvider()));
    }

    public int confounderSize() {
        return 16;
    }

    public CheckSumType cksumType() {
        return CheckSumType.HMAC_SHA1_96_AES128;
    }

    public boolean isSafe() {
        return true;
    }

    public int cksumSize() {
        return 12;  // bytes
    }

    public int keySize() {
        return 16;   // bytes
    }
}


text:
import createServer from '../../../src/createServer';
import request from 'supertest';

const app = createServer();

describe('India Price Route Test', () => {

    it('Check route metro', async () => {
        const res = await request(app.listen())
            .get('/cost/IN/metro');
        expect(res.status).toBe(200);
        expect(res.type).toBe('application/json');
        expect(res.body.metro.length > 0).toBe(true);
    });

    it('Check route capital', async () => {
        const res = await request(app.listen())
            .get('/cost/IN/capital');
        expect(res.status).toBe(200);
        expect(res.type).toBe('application/json');
    });

    it('Check route states', async () => {
        const res = await request(app.listen())
            .get('/cost/IN/states');
        expect(res.status).toBe(200);
        expect(res.type).toBe('application/json');
        expect(res.body.states.length > 0).toBe(true);
    });

    it('Check route state/:stateName', async () => {
        const res = await request(app.listen())
            .get('/cost/IN/state/Bihar');
        expect(res.status).toBe(200);
        expect(res.type).toBe('application/json');
        expect(res.body.Bihar.length > 0).toBe(true);
    });

    it('Check route city/:cityName', async () => {
        const res = await request(app.listen())
            .get('/cost/IN/city/Sheohar');
        expect(res.status).toBe(200);
        expect(res.type).toBe('application/json');
        expect(res.body.Sheohar.length > 0).toBe(true);
    });

    it('Default route', async () => {
        try {
            const res = await request(app.listen())
                .get('/cost/IN');
        } catch (error) {
            expect(res.status).toBe(200);
            expect(res.type).toBe('application/json');
            expect(res.body.undefined).toEqual("Data not found");
        }
    });

    it('Check error handling', async () => {
        try {
            const res = await request(app.listen())
                .get('/cost/IN?error=true');
        } catch (error) {
            expect(res.status).toBe(500);
            expect(res.type).toBe('application/json');
            expect(res.body.error.message).toEqual('Key can\'t be blank');
        }
    });

})


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Newtonsoft.Json;
using RestSharp;
using Typeform.Dotnet.Data;
using Typeform.Dotnet.Exceptions;

namespace Typeform.Dotnet.Core
{
    public class Client
    {
        protected const string TypeformApiBaseUrl = "https://api.typeform.com/v1";
        protected const string ApiKeyName = "key";
        protected const string ContentTypeHeader = "Content-Type";
        protected const string ContentTypeValue = "application/json";
        protected const string AcceptHeader = "Accept";
        protected const string AcceptValue = "application/json";
        protected const string AcceptCharsetHeader = "Accept-Charset";
        protected const string AcceptCharsetValue = "UTF-8";
        protected const string UserAgentHeader = "User-Agent";
        protected const string UserAgentValue = "typeform-dotnet/1.0.0";
        protected const string FormIdUrlReplacementParameter = "{formId}";
        protected const string FormIdUrlReplacementName = "formId";
        protected const string DateFormat = "yyyy-MM-dd HH:mm:ss";

        protected readonly string Url;
        protected readonly string Resource;
        protected readonly Authentication Auth;

        public Client(string url, string resource, Authentication authentication)
        {
            if (authentication == null)
                throw new ArgumentNullException(nameof(authentication));

            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException(nameof(url));

            if (string.IsNullOrEmpty(resource))
                throw new ArgumentNullException(nameof(resource));

            Url = url;
            Resource = resource;
            Auth = authentication;
        }

        protected virtual ClientResponse<T> Get<T>(Dictionary<string, string> headers = null,
            Dictionary<string, string> parameters = null, string resource = null, string formId = null) where T : class
        {
            IRestClient client = BuildClient();
            IRestRequest request = BuildRequest(httpMethod: Method.GET, headers: headers, parameters: parameters,
                resource: resource, formId: formId);
            IRestResponse response = client.Execute(request);

            var clientResponse = HandleResponse<T>(response);

            return clientResponse;
        }

        //protected virtual T GetAlternate<T>(Dictionary<string, string> headers = null,
        //    Dictionary<string, string> parameters = null, string resource = null, string formId = null) where T : new()
        //{
        //    IRestClient client = BuildClient();
        //    IRestRequest request = BuildRequest(httpMethod: Method.GET, headers: headers, parameters: parameters,
        //        resource: resource, formId: formId);

        //    var response = client.Execute<T>(request);

        //    return response.Data;
        //}

        protected virtual IRestClient BuildClient()
        {
            RestClient client = new RestClient(Url) { Authenticator = new ApiKeyAuthenticator(ApiKeyName, Auth.ApiKey) };

            // TODO - Potentially come back here to clean this up
            //client.ClearHandlers();
            //client.AddHandler("application/json", new TypeformDeserializer());
            //client.AddHandler("text/json", new TypeformDeserializer());
            //client.AddHandler("*+json", new TypeformDeserializer());

            return client;
        }

        protected virtual IRestRequest BuildRequest(Method httpMethod = Method.GET,
            Dictionary<string, string> headers = null, Dictionary<string, string> parameters = null, string body = null,
            string resource = null, string formId = null)
        {
            string finalResource = string.IsNullOrEmpty(resource) ? Resource : resource;

            if(finalResource.Contains(FormIdUrlReplacementParameter) && string.IsNullOrEmpty(formId))
                throw new ArgumentNullException(formId);

            IRestRequest request = new RestRequest(finalResource, httpMethod);
            if (finalResource.Contains(FormIdUrlReplacementParameter))
                request.AddParameter(FormIdUrlReplacementName, formId, ParameterType.UrlSegment);

            request.AddHeader(ContentTypeHeader, ContentTypeValue);
            request.AddHeader(AcceptCharsetHeader, AcceptCharsetValue);
            request.AddHeader(AcceptHeader, AcceptValue);
            request.AddHeader(UserAgentHeader, UserAgentValue);

            if (headers != null && headers.Any())
                AddHeaders(request, headers);

            if (parameters != null && parameters.Any())
                AddParameters(request, parameters);

            if (!string.IsNullOrEmpty(body))
                AddBody(request, body);

            return request;
        }

        protected virtual void AddHeaders(IRestRequest request, Dictionary<string, string> headers)
        {
            if (request == null)
                throw new ArgumentNullException(nameof(request));

            if (headers == null)
                throw new ArgumentNullException(nameof(headers));

            foreach (var header in headers)
            {
                request.AddParameter(header.Key, header.Value, ParameterType.HttpHeader);
            }
        }

        protected virtual void AddParameters(IRestRequest request, Dictionary<string, string> parameters)
        {
            if (request == null)
                throw new ArgumentNullException(nameof(request));
            if (parameters == null)
                throw new ArgumentNullException(nameof(parameters));

            foreach (var parameter in parameters)
            {
                request.AddParameter(parameter.Key, parameter.Value, ParameterType.QueryString);
            }
        }

        protected virtual void AddBody(IRestRequest request, string body)
        {
            if (request == null)
                throw new ArgumentNullException(nameof(request));

            if (!string.IsNullOrEmpty(body))
                request.AddParameter("application/json", body, ParameterType.RequestBody);
        }

        protected virtual ClientResponse<T> HandleResponse<T>(IRestResponse response) where T : class
        {
            ClientResponse<T> clientResponse;
            int statusCode = (int)response.StatusCode;

            if (statusCode >= 200 && statusCode < 300)
                clientResponse = HandleNormalResponse<T>(response);
            else
            {
                clientResponse = HandleErrorReponse<T>(response);
            }

            return clientResponse;
        }

        protected ClientResponse<T> HandleNormalResponse<T>(IRestResponse response) where T : class
        {
            return new ClientResponse<T>(response, Deserialize<T>(response.Content));
        }

        protected ClientResponse<T> HandleErrorReponse<T>(IRestResponse response) where T : class
        {
            if (string.IsNullOrEmpty(response.Content))
            {
                return new ClientResponse<T>(response);
            }
            else
            {
                Errors errors = Deserialize<Errors>(response.Content);
                return new ClientResponse<T>(response, errors: errors);
            }
        }

        protected T Deserialize<T>(string data) where T : class
        {
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                DateFormatString = DateFormat,
                //DateParseHandling = DateParseHandling.DateTimeOffset,
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            };

            return JsonConvert.DeserializeObject<T>(data, settings);
        }

        protected void AssertIfAnyErrors<T>(ClientResponse<T> response) where T : class
        {
            if (response.Errors?.ErrorsList != null && response.Errors.ErrorsList.Any())
            {
                throw new TypeformApiException((int)response.Response.StatusCode,
                    response.Response.StatusDescription,
                    response.Errors,
                    response.Response.Content);
            }
        }
    }
}


text:
OpenNote [![Build Status](https://travis-ci.org/FoxUSA/OpenNote.png?branch=master)](https://travis-ci.org/FoxUSA/OpenNote)
=============
![][responsive]
In a post 9/11 world of mass digital surveillance, there is only one way to keep your digital information safe.
In the United States, you do not have have 5th amendment rights if you entrust you information to a third party.

The fix is to take personal responsibility and host applications yourself.

OpenNote was built to be a open source(MIT License), web based note taking software.
It is designed to be self hosted and gives you ownership of your data.

Please support this project by:
- [Using GitTip][GitTip],
- [donating bitcoins][Bitcoins],
- and/or like on [Alternative To][Alternative].

Thank you!

[Download using Docker][Docker]

[or download manually from here.][Download]

Demo
-------
https://foxusa.github.io/OpenNote/OpenNote/

![][topLevel]
Features
--------
- BYOS(Bring Your Own Server)
- Full WYSIWYG editor
- Touch friendly and mouse friendly ui
- Upload manager (not enabled in demo :) )
- Light weight
- Multi user support
- Search
- Offline App
- CouchDB Sync via PouchDB
- Move Folders(Drag into another folder in the list view.)
- Rename/Delete Folders(Click on folder title to get menu.)
- Responsive

Upcoming Features
-----------------
- Tags (You win)
- Email to note
- Implement history viewer
- Install script
- Move Notes (Feature lost when migrating to Angular based list)
- Mobile App

Documentation
-----------------
[How to install][Install]

[How to upgrade][Upgrade]

[How to build][Build]

[Themes][Themes]

[PHP backend][php]

![][dark]
License
-------
	JQuery - Distributed under the MIT License
	Angular - Distributed under the MIT License
	Bootstrap - Distributed under the MIT License
	CKEditor - Distributed under the MPL License
	Angular UI Tree - Distributed under the MIT License
	Alertify.js - Distributed under the MIT License
	PouchDB - Distributed under the Apache License
	Dragula - Distributed under the MIT License
	Into.js - Distributed with license from Afshin Mehrabani Copyright (C) 2012

	OpenNote Code - Distributed under the MIT License

	© Jacob Liscom 2015

Credits
-------
	J. Liscom - Supreme Programmer

	Kam Bnkamalesh - His TODO project heavily influenced my UI design

[topLevel]: https://raw.github.com/FoxUSA/OpenNote/master/Doc/screenShots/topLevel.png
[dark]: https://raw.github.com/FoxUSA/OpenNote/master/Doc/screenShots/dark1.png
[responsive]: https://raw.githubusercontent.com/FoxUSA/OpenNote/master/Doc/screenShots/OpenNote.png

[Install]: https://github.com/FoxUSA/OpenNote/blob/master/Doc/Install.md
[Upgrade]: https://github.com/FoxUSA/OpenNote/blob/master/Doc/Upgrade.md
[Build]: https://github.com/FoxUSA/OpenNote/blob/master/Doc/Build.md
[PHP]: https://github.com/FoxUSA/OpenNoteService-PHP
[Dependencies]: https://github.com/FoxUSA/OpenNote/blob/master/Doc/Dependencies.md
[Themes]: https://github.com/FoxUSA/OpenNote/blob/master/Doc/Themes.md
[GitTip]: https://www.gittip.com/FoxUSA/
[Bitcoins]: http://blockchain.info/address/15Q2jhnTvxDQm4LvTku68vTzU8j8dcLnLB
[Alternative]: http://alternativeto.net/software/opennote/
[Download]: https://github.com/FoxUSA/OpenNote/releases
[Docker]: https://registry.hub.docker.com/u/foxusa/opennote/


text:
using System;
using GSoft.Dynamite.Taxonomy;

namespace GSoft.Dynamite.Publishing.Contracts.Constants
{
    /// <summary>
    /// Term definitions for the publishing module
    /// </summary>
    public static class PublishingTermInfos
    {
        /// <summary>
        /// The news term
        /// </summary>
        /// <returns>The term</returns>
        public static TermInfo News
        {
            get
            {
                return new TermInfo()
                {
                    Id = new Guid("a681794e-c2bc-4145-b95a-3122388d65bf"),
                    Label = "News"
                };
            }
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="stylesheet" href="/css/app.css" />

    {% seo %}
    <meta name="keywords" content="contract development, web consultancy, web developer, python developer, xquery developer, xsl developer, scrum master, scrum" />

    <meta http-equiv="imagetoolbar" content="no" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="robots" content="index,follow" />
    <meta name="language" content="english" />

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css">

Oldham-Made Ltd

Delivery-focussed Elixir, Python, XSL/XQuery, (No)SQL, and Agile consultancy, specialising in content migration, API design, and (micro)services.

      	  Email
      	  LinkedIn
      	  Twitter
      	  Octocat
      	  RSS

{{ content }}

© {{ site.time | date: "%Y" }} Oldham-Made Ltd


text:
<!---
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
-->

# cordova-plugin-media

Этот плагин предоставляет возможность записывать и воспроизводить аудио файлы на устройство.

**Примечание**: Текущая реализация не соответствует спецификации W3C для захвата СМИ и предоставляется только для удобства. Будущее осуществление будет придерживаться последней спецификации W3C и может Опознайте текущих API.

## Установка

    cordova plugin add cordova-plugin-media

## Поддерживаемые платформы

*   Android
*   BlackBerry 10
*   iOS
*   Windows Phone 7 и 8
*   Tizen
*   Windows 8

## Windows Phone причуды

*   Только один файл может воспроизводиться одновременно.

*   Существуют строгие ограничения в отношении как ваше приложение взаимодействует с другими средствами массовой информации. Смотрите в [документации Microsoft для подробной информации][1].

 [1]: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh184838(v=vs.92).aspx

## Аудио и видео

    var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]);

### Параметры

*   **src**: URI, содержащий аудио-контент. *(DOMString)*

*   **mediaSuccess**: (необязательно) обратного вызова, который выполняется после `Media` объект завершения текущего воспроизведения, записи или стоп действий. *(Функция)*

*   **mediaError**: (необязательно) обратного вызова, который выполняется при возникновении ошибки. *(Функция)*

*   **mediaStatus**: (необязательно) обратного вызова, который выполняется для отображения изменений состояния. *(Функция)*

### Константы

Следующие константы сообщается как единственный параметр для `mediaStatus` обратного вызова:

*   `Media.MEDIA_NONE` = 0;
*   `Media.MEDIA_STARTING` = 1;
*   `Media.MEDIA_RUNNING` = 2;
*   `Media.MEDIA_PAUSED` = 3;
*   `Media.MEDIA_STOPPED` = 4;

### Методы

*   `media.getCurrentPosition`: Возвращает текущую позицию в аудиофайл.

*   `media.getDuration`: Возвращает продолжительность звукового файла.

*   `media.play`: Начать или возобновить воспроизведение звукового файла.

*   `media.pause`: Приостановка воспроизведения звукового файла.

*   `media.release`: Выпускает аудио ресурсы базовой операционной системы.

*   `media.seekTo`: Перемещает положение в пределах звукового файла.

*   `media.setVolume`: Задайте громкость воспроизведения звука.

*   `media.startRecord`: Начните запись звукового файла.

*   `media.stopRecord`: Остановите запись аудио файлов.

*   `media.stop`: Остановка воспроизведения звукового файла.

### Дополнительные ReadOnly параметры

*   **позиции**: позиция в аудио воспроизведения в секундах.

    *   Не автоматически обновляются во время игры; Вызовите `getCurrentPosition` для обновления.

*   **Продолжительность**: продолжительность СМИ, в секундах.

## media.getCurrentPosition

Возвращает текущую позицию в звуковой файл. Также обновляет `Media` объекта `position` параметр.

    media.getCurrentPosition(mediaSuccess, [mediaError]);

### Параметры

*   **mediaSuccess**: обратный вызов, который передается в текущую позицию в секундах.

*   **mediaError**: (необязательно) обратного вызова для выполнения, если происходит ошибка.

### Краткий пример

    // Audio player
    //
    var my_media = new Media(src, onSuccess, onError);

    // Update media position every second
    var mediaTimer = setInterval(function () {
        // get media position
        my_media.getCurrentPosition(
            // success callback
            function (position) {
                if (position > -1) {
                    console.log((position) + " sec");
                }
            },
            // error callback
            function (e) {
                console.log("Error getting pos=" + e);
            }
        );
    }, 1000);

## media.getDuration

Возвращает продолжительность аудио файла в секундах. Если длительность неизвестна, она возвращает значение -1.

    media.getDuration();

### Краткий пример

    // Audio player
    //
    var my_media = new Media(src, onSuccess, onError);

    // Get duration
    var counter = 0;
    var timerDur = setInterval(function() {
        counter = counter + 100;
        if (counter > 2000) {
            clearInterval(timerDur);
        }
        var dur = my_media.getDuration();
        if (dur > 0) {
            clearInterval(timerDur);
            document.getElementById('audio_duration').innerHTML = (dur) + " sec";
        }
    }, 100);

## Media.Pause

Приостанавливает воспроизведение звукового файла.

    media.pause();

### Краткий пример

    // Play audio
    //
    function playAudio(url) {
        // Play the audio file at url
        var my_media = new Media(url,
            // success callback
            function () { console.log("playAudio():Audio Success"); },
            // error callback
            function (err) { console.log("playAudio():Audio Error: " + err); }
        );

        // Play audio
        my_media.play();

        // Pause after 10 seconds
        setTimeout(function () {
            media.pause();
        }, 10000);
    }

## Media.Play

Запускает или возобновляет воспроизведение звукового файла.

    media.play();

### Краткий пример

    // Play audio
    //
    function playAudio(url) {
        // Play the audio file at url
        var my_media = new Media(url,
            // success callback
            function () {
                console.log("playAudio():Audio Success");
            },
            // error callback
            function (err) {
                console.log("playAudio():Audio Error: " + err);
            }
        );
        // Play audio
        my_media.play();
    }

### Особенности iOS

*   **numberOfLoops**: этот параметр, чтобы передать `play` метод, чтобы указать количество раз, вы хотите, чтобы средства массовой информации файла для воспроизведения, например:

        var myMedia = new Media("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3")
        myMedia.play({ numberOfLoops: 2 })

*   **playAudioWhenScreenIsLocked**: передайте этот параметр для `play` метод, чтобы указать, хотите ли вы разрешить воспроизведение, когда экран заблокирован. Если значение `true` (значение по умолчанию), состояние оборудования безгласную кнопку игнорируется, например:

        var myMedia = new Media("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3")
        myMedia.play({ playAudioWhenScreenIsLocked : false })

*   **Порядок поиска файла**: когда предоставляется только имя файла или простой путь, iOS ищет в `www` каталог для файла, а затем в приложении `documents/tmp` каталога:

        var myMedia = new Media("audio/beer.mp3")
        myMedia.play()  // first looks for file in www/audio/beer.mp3 then in <application>/documents/tmp/audio/beer.mp3

## media.release

Освобождает ресурсы аудио базовой операционной системы. Это особенно важно для Android, так как существует конечное количество экземпляров OpenCore для воспроизведения мультимедиа. Приложения должны вызвать `release` функция для любого `Media` ресурс, который больше не нужен.

    media.release();

### Краткий пример

    // Audio player
    //
    var my_media = new Media(src, onSuccess, onError);

    my_media.play();
    my_media.stop();
    my_media.release();

## media.seekTo

Задает текущую позицию в течение звукового файла.

    media.seekTo(milliseconds);

### Параметры

*   **МС**: позиции задать позицию воспроизведения в аудио, в миллисекундах.

### Краткий пример

    // Audio player
    //
    var my_media = new Media(src, onSuccess, onError);
        my_media.play();
    // SeekTo to 10 seconds after 5 seconds
    setTimeout(function() {
        my_media.seekTo(10000);
    }, 5000);

### Особенности BlackBerry 10

*   Не поддерживается на устройствах BlackBerry OS 5.

## media.setVolume

Задайте громкость звукового файла.

    media.setVolume(volume);

### Параметры

*   **объем**: тома, чтобы задать для воспроизведения. Значение должно быть в диапазоне от 0.0 до 1.0.

### Поддерживаемые платформы

*   Android
*   iOS

### Краткий пример

    // Play audio
    //
    function playAudio(url) {
        // Play the audio file at url
        var my_media = new Media(url,
            // success callback
            function() {
                console.log("playAudio():Audio Success");
            },
            // error callback
            function(err) {
                console.log("playAudio():Audio Error: "+err);
        });

        // Play audio
        my_media.play();

        // Mute volume after 2 seconds
        setTimeout(function() {
            my_media.setVolume('0.0');
        }, 2000);

        // Set volume to 1.0 after 5 seconds
        setTimeout(function() {
            my_media.setVolume('1.0');
        }, 5000);
    }

## media.startRecord

Начинает запись аудио файлов.

    media.startRecord();

### Поддерживаемые платформы

*   Android
*   iOS
*   Windows Phone 7 и 8
*   Windows 8

### Краткий пример

    // Record audio
    //
    function recordAudio() {
        var src = "myrecording.mp3";
        var mediaRec = new Media(src,
            // success callback
            function() {
                console.log("recordAudio():Audio Success");
            },

            // error callback
            function(err) {
                console.log("recordAudio():Audio Error: "+ err.code);
            });

        // Record audio
        mediaRec.startRecord();
    }

### Особенности Android

*   Android устройств записи аудио в формате адаптивной мульти ставка. Указанный файл должен заканчиваться *.amr* расширение.

### Особенности iOS

*   iOS только записи в файлы типа *.wav* и возвращает ошибку, если расширение не исправить.

*   Если полный путь не указан, запись помещается в приложения `documents/tmp` каталог. Это могут быть доступны через `File` API с помощью `LocalFileSystem.TEMPORARY` . Любой подкаталог, указанный на время записи должны уже существовать.

*   Файлы могут быть и сыграны записываются обратно, используя документы URI:

        var myMedia = new Media("documents://beer.mp3")

### Совместимости Windows 8

*   Если не указан полный путь, запись помещается в каталоге AppData/temp. Это могут быть доступны через `Файл` С помощью API `LocalFileSystem.TEMPORARY` или ' ms-appdata: / / / temp /<filename>' URI.

*   Любой подкаталог указанного в рекордное время должна уже существовать.

### Особенности Tizen

*   Не поддерживается на устройствах Tizen.

## media.stop

Останавливает воспроизведение звукового файла.

    media.stop();

### Краткий пример

    // Play audio
    //
    function playAudio(url) {
        // Play the audio file at url
        var my_media = new Media(url,
            // success callback
            function() {
                console.log("playAudio():Audio Success");
            },
            // error callback
            function(err) {
                console.log("playAudio():Audio Error: "+err);
            }
        );

        // Play audio
        my_media.play();

        // Pause after 10 seconds
        setTimeout(function() {
            my_media.stop();
        }, 10000);
    }

## media.stopRecord

Прекращает запись аудио файлов.

    media.stopRecord();

### Поддерживаемые платформы

*   Android
*   iOS
*   Windows Phone 7 и 8
*   Windows 8

### Краткий пример

    // Record audio
    //
    function recordAudio() {
        var src = "myrecording.mp3";
        var mediaRec = new Media(src,
            // success callback
            function() {
                console.log("recordAudio():Audio Success");
            },

            // error callback
            function(err) {
                console.log("recordAudio():Audio Error: "+ err.code);
            }
        );

        // Record audio
        mediaRec.startRecord();

        // Stop recording after 10 seconds
        setTimeout(function() {
            mediaRec.stopRecord();
        }, 10000);
    }

### Особенности Tizen

*   Не поддерживается на устройствах Tizen.

## MediaError

A `MediaError` объект возвращается к `mediaError` функции обратного вызова при возникновении ошибки.

### Параметры

*   **code**: один из стандартных кодов ошибок, перечисленных ниже.

*   **сообщение**: сообщение об ошибке, с подробными сведениями об ошибке.

### Константы

*   `MediaError.MEDIA_ERR_ABORTED`= 1
*   `MediaError.MEDIA_ERR_NETWORK`= 2
*   `MediaError.MEDIA_ERR_DECODE`= 3
*   `MediaError.MEDIA_ERR_NONE_SUPPORTED`= 4


text:
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import define, options
define("port", default=8000, help="run no the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        greeting = self.get_argument('greeting', 'Hello')
        self.write(greeting + ', welcome you to read: www.baidu.com')

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()


text:
package serverstarter

import (
	"fmt"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"strconv"
	"strings"
	"syscall"
)

const (
	stdFdCount          = 3 // stdin, stdout, stderr
	defaultEnvListenFDs = "LISTEN_FDS"
)

// Starter is a server starter.
type Starter struct {
	envListenFDs                  string
	workingDirectory              string
	listeners                     []net.Listener
	gracefulShutdownSignalToChild syscall.Signal
}

// Option is the type for configuring a Starter.
type Option func(s *Starter)

// New returns a new Starter.
func New(options ...Option) *Starter {
	s := &Starter{
		envListenFDs:                  defaultEnvListenFDs,
		gracefulShutdownSignalToChild: syscall.SIGTERM,
	}
	for _, o := range options {
		o(s)
	}
	return s
}

// SetEnvName sets the environment variable name for passing the listener file descriptor count to the worker process.
// When this options is not called, the environment variable name will be "LISTEN_FDS".
func SetEnvName(name string) Option {
	return func(s *Starter) {
		s.envListenFDs = name
	}
}

// SetGracefulShutdownSignalToChild sets the signal to send to child for graceful shutdown.
// If no SetGracefulShutdownSignalToChild is called, the default value is syscall.SIGTERM.
func SetGracefulShutdownSignalToChild(sig syscall.Signal) Option {
	return func(s *Starter) {
		s.gracefulShutdownSignalToChild = sig
	}
}

// RunMaster starts a worker process and run the loop for starting and stopping the worker
// on signals.
//
// If the master process receives a SIGHUP, it starts a new worker and stop the old worker
// by sending a signal set by SetGracefulShutdownSignalToChild.
// If the master process receives a SIGINT or a SIGTERM, it sends the SIGTERM to the worker
// and exists.
func (s *Starter) RunMaster(listeners ...net.Listener) error {
	s.listeners = listeners
	wd, err := os.Getwd()
	if err != nil {
		return fmt.Errorf("error in RunMaster after failing to get working directory; %v", err)
	}
	s.workingDirectory = wd

	childPID, err := s.startProcess()
	if err != nil {
		return fmt.Errorf("error in RunMaster after starting worker; %v", err)
	}

	signals := make(chan os.Signal, 1)
	// NOTE: The signals SIGKILL and SIGSTOP may not be caught by a program.
	// https://golang.org/pkg/os/signal/#hdr-Types_of_signals
	signal.Notify(signals, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
	for {
		sig := <-signals
		switch sig {
		case syscall.SIGHUP:
			newChildPid, err := s.startProcess()
			if err != nil {
				return fmt.Errorf("error in RunMaster after starting new worker; %v", err)
			}

			err = syscall.Kill(childPID, s.gracefulShutdownSignalToChild)
			if err != nil {
				return fmt.Errorf("error in RunMaster after sending signal %q to worker pid=%d after receiving SIGHUP; %v", s.gracefulShutdownSignalToChild, childPID, err)
			}

			_, err = syscall.Wait4(childPID, nil, 0, nil)
			if err != nil {
				return fmt.Errorf("error in RunMaster after waiting worker pid=%d; %v", childPID, err)
			}

			childPID = newChildPid

		case syscall.SIGINT, syscall.SIGTERM:
			err := syscall.Kill(childPID, syscall.SIGTERM)
			if err != nil {
				return fmt.Errorf("error in RunMaster after sending SIGTERM to worker pid=%d after receiving %v; %v", childPID, sig, err)
			}
			return nil
		}
	}
}

func (s *Starter) startProcess() (pid int, err error) {
	// This code is based on
	// https://github.com/facebookgo/grace/blob/4afe952a37a495ae4ac0c1d4ce5f66e91058d149/gracenet/net.go#L201-L248

	type filer interface {
		File() (*os.File, error)
	}

	files := make([]*os.File, len(s.listeners))
	for i, l := range s.listeners {
		f, err := l.(filer).File()
		if err != nil {
			return 0, fmt.Errorf("error in startProcess after getting file from listener; %v", err)
		}
		files[i] = f
		defer files[i].Close()
	}

	// Use the original binary location. This works with symlinks such that if
	// the file it points to has been changed we will use the updated symlink.
	argv0, err := exec.LookPath(os.Args[0])
	if err != nil {
		return 0, fmt.Errorf("error in startProcess after looking path of the original binary location; %v", err)
	}

	// Pass on the environment and replace the old count key with the new one.
	envListenFDsPrefix := s.envListenFDs + "="
	var env []string
	for _, v := range os.Environ() {
		if !strings.HasPrefix(v, envListenFDsPrefix) {
			env = append(env, v)
		}
	}
	envFDs := strconv.AppendInt([]byte(envListenFDsPrefix), int64(len(s.listeners)), 10)
	env = append(env, string(envFDs))

	allFiles := append([]*os.File{os.Stdin, os.Stdout, os.Stderr}, files...)
	process, err := os.StartProcess(argv0, os.Args, &os.ProcAttr{
		Dir:   s.workingDirectory,
		Env:   env,
		Files: allFiles,
	})
	if err != nil {
		return 0, fmt.Errorf("error in startProcess after starting worker process; %v", err)
	}
	return process.Pid, nil
}

// IsMaster returns whether this process is the master or not.
// It returns true if this process is the master, and returns false if this process is the worker.
func (s *Starter) IsMaster() bool {
	_, isWorker := os.LookupEnv(s.envListenFDs)
	return !isWorker
}

// Listeners returns the listeners passed from the master if this is called by the worker process.
// It returns nil when this is called by the master process.
func (s *Starter) Listeners() ([]net.Listener, error) {
	countStr, isWorker := os.LookupEnv(s.envListenFDs)
	if !isWorker {
		return nil, nil
	}

	count, err := strconv.Atoi(countStr)
	if err != nil {
		return nil, fmt.Errorf("error in Listeners after getting invalid listener count; %v", err)
	}
	listeners := make([]net.Listener, count)
	for i := 0; i < count; i++ {
		fd := uintptr(i + stdFdCount)
		file := os.NewFile(fd, "listener")
		l, err := net.FileListener(file)
		if err != nil {
			return nil, fmt.Errorf("error in Listeners after failing to create listener; %v", err)
		}
		listeners[i] = l
	}
	return listeners, nil
}


text:
local states8 = {  -- table shows 8 steps. Double-stepping is allowed, then uses only states 1 3 5 7
 {1,0,0,1},
 {1,0,0,0},
 {1,1,0,0},
 {0,1,0,0},
 {0,1,1,0},
 {0,0,1,0},
 {0,0,1,1},
 {0,0,0,1},
}
Stepper = {}
Stepper.__index = Stepper

-- halfstep true/false
function Stepper.new(pin1)
    local self = setmetatable({}, Stepper)
    self.pin1 = pin1
    self.posn = 0
    self.stepsleft = 0
    self.phase = 0
    for c=0, 3
    do
        gpio.mode (pin1+c, gpio.OUTPUT)
        gpio.write(pin1+c, gpio.LOW)
    end
    self.timer = tmr.create()
    return self
end

-- tmr.alarm() callback passes only the timer-id as function parameter (nodelua constraint)
-- but we have kept a key-value lookup table from which we can retrieve stepper object id.

function Stepper.step1(self)
    -- execution time abt 1 mSec, or abt 22mSec for mcp23017 extended GPIOs!
    -- and fastest timer is 1mSec. So best performance is 500 steps or doublesteps / sec.
    if self.stepsleft>0 then self.stepsleft = self.stepsleft-math.abs(self.dir) end
    local left = self.stepsleft
    if self.limitpin and (gpio.read(self.limitpin) == self.pol) then self.stepsleft=0 end
    self.posn = self.posn+self.dir
    if self.posn%2==1 and math.abs(self.dir)==2 then self.posn = self.posn+1 end -- doublestep resync
    local phase = (self.posn % 8)+1
    local c for c=0, 3 do
        gpio.write(self.pin1+c, states8[phase][1+c])
    end

    if self.stepsleft==0 or self.stepsleft==(-1) then
        for c=0, 3 do
            gpio.write(self.pin1+c, 0)
        end
        if self.callback then self.callback(self, left) end
        return
    end
    self.timer:alarm(self.speed, 0,  function(t) self:step1() end)
    -- manually rearm timer. This way we can't accumulate a stack of pending callbacks
    -- which can occur using a repeating timer at full stepper speed
    -- and which will cause a crash
end

-- speed is ms per step, min 1
-- steps: max. stepsleft reduces until 0.  if <=(-2), no limit
-- dir -1=rev 1=fwd 0=stop -2=rev/dblstep or 2 =fwd/dblstep
-- optional callback on stop
-- will stop if limitpin goes to "polarity"

function Stepper.run(self, dir, speed, steps, callback, limitpin, polarity )
    if dir==0 then tmr.stop(self.timer) return end
    self.limitpin = limitpin
    self.dir = dir  -- -2 to +2
    self.callback = callback
    speed = speed or 2
    self.speed = (speed<3) and 1 or (speed-1) -- min 1, otherwise as requested less 1 (as step task is 1 msec)
    self.stepsleft=steps or (-2)
    self.pol = polarity or 1
    if limitpin then
        gpio.mode (limitpin, gpio.INPUT, gpio.PULLUP)
    end
    self.timer:alarm( 1, 0, function(t) self:step1() end)
print("run")
end


text:
<?php

class Presenter_Home_Upcoming extends Presenter
{
    public function view()
    {

        $upcoming_bookings_table = '';

        $bookings_section_data = [
            'heading' => 'Upcoming Bookings',
            'unique_id' => Str::random('uuid'),
            'groups' => [
                $upcoming_bookings_table
            ]
        ];

        $bookings_section = View::forge('form/section', $bookings_section_data);

        $this->upcoming_form = View::forge('form/container', [
            'sections' => [
                $bookings_section,
            ],
            'name' => 'bookings',
            'type' => 'form-horizontal'
        ]);

    }
}


text:
<?xml version="1.0" encoding="utf-8"?><items total="4" termsofuse="http://boardgamegeek.com/xmlapi/termsofuse">			<item type="boardgameexpansion" id="137136">
			<name type="primary" value="Pandemic: In the Lab"/>
							<yearpublished value="2013" />
					</item>
			<item type="boardgameexpansion" id="40849">
			<name type="primary" value="Pandemic: On the Brink"/>
							<yearpublished value="2009" />
					</item>
			<item type="boardgameexpansion" id="185403">
			<name type="primary" value="Pandemic: Promo Roles"/>
							<yearpublished value="2015" />
					</item>
			<item type="boardgameexpansion" id="168703">
			<name type="primary" value="Pandemic: State of Emergency"/>
							<yearpublished value="2015" />
					</item>
	</items>


text:
package io.crate.planner.node.ddl;

import io.crate.analyze.AnalyzedCreateUser;
import io.crate.user.UserManager;
import io.crate.data.Row;
import io.crate.data.Row1;
import io.crate.data.RowConsumer;
import io.crate.execution.support.OneRowActionListener;
import io.crate.planner.DependencyCarrier;
import io.crate.planner.Plan;
import io.crate.planner.PlannerContext;
import io.crate.planner.operators.SubQueryResults;
import io.crate.user.SecureHash;
import io.crate.user.UserActions;

public class CreateUserPlan implements Plan {

    private final AnalyzedCreateUser createUser;
    private final UserManager userManager;

    public CreateUserPlan(AnalyzedCreateUser createUser, UserManager userManager) {
        this.createUser = createUser;
        this.userManager = userManager;
    }

    @Override
    public StatementType type() {
        return StatementType.DDL;
    }

    @Override
    public void executeOrFail(DependencyCarrier dependencies,
                              PlannerContext plannerContext,
                              RowConsumer consumer,
                              Row params, SubQueryResults subQueryResults) throws Exception {
        SecureHash newPassword = UserActions.generateSecureHash(
            createUser.properties(),
            params,
            plannerContext.transactionContext(),
            plannerContext.nodeContext());

        userManager.createUser(createUser.userName(), newPassword)
            .whenComplete(new OneRowActionListener<>(consumer, rCount -> new Row1(rCount == null ? -1 : rCount)));
    }
}