text:
package edu.ucar.unidata.rosetta.service.wizard;

import edu.ucar.unidata.rosetta.domain.GlobalMetadata;
import edu.ucar.unidata.rosetta.domain.RosettaAttribute;
import edu.ucar.unidata.rosetta.domain.RosettaGlobalAttribute;
import edu.ucar.unidata.rosetta.domain.Template;
import edu.ucar.unidata.rosetta.domain.Variable;
import edu.ucar.unidata.rosetta.domain.VariableInfo;
import edu.ucar.unidata.rosetta.domain.VariableMetadata;
import edu.ucar.unidata.rosetta.domain.wizard.UploadedFile;
import edu.ucar.unidata.rosetta.domain.wizard.UploadedFile.FileType;
import edu.ucar.unidata.rosetta.domain.wizard.UploadedFileCmd;
import edu.ucar.unidata.rosetta.domain.wizard.WizardData;
import edu.ucar.unidata.rosetta.exceptions.RosettaFileException;
import edu.ucar.unidata.rosetta.repository.wizard.GlobalMetadataDao;
import edu.ucar.unidata.rosetta.repository.wizard.UploadedFileDao;
import edu.ucar.unidata.rosetta.repository.wizard.VariableDao;
import edu.ucar.unidata.rosetta.repository.wizard.WizardDataDao;
import edu.ucar.unidata.rosetta.util.JsonUtils;
import edu.ucar.unidata.rosetta.util.PropertyUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Implements uploaded file manager functionality.
 */
public class UploadedFileManagerImpl implements UploadedFileManager {

  private static final Logger logger = LogManager.getLogger();

  private GlobalMetadataDao globalMetadataDao;
  private UploadedFileDao uploadedFileDao;
  private VariableDao variableDao;
  private WizardDataDao wizardDataDao;

  @Resource(name = "fileManager")
  private FileManager fileManager;

  @Resource(name = "metadataManager")
  private MetadataManager metadataManager;

  /**
   * Returns the data file corresponding to the given ID as an UploadedFile object.
   *
   * @param id The ID corresponding to the stored file.
   * @return The data file as an UploadedFile object.
   */
  public UploadedFile getDataFile(String id) {
    UploadedFile dataFile = null;
    UploadedFileCmd uploadedFileCmd = lookupPersistedDataById(id);
    for (UploadedFile uploadedFile : uploadedFileCmd.getUploadedFiles()) {
      if (uploadedFile.getFileType() == FileType.DATA) {
        dataFile = uploadedFile;
        break;
      }
    }
    return dataFile;
  }

  /**
   * Returns the positional file corresponding to the given ID as an UploadedFile object.
   *
   * @param id The ID corresponding to the stored file.
   * @return The positional file as an UploadedFile object.
   */
  public UploadedFile getPositionalFile(String id) {
    UploadedFile dataFile = null;
    UploadedFileCmd uploadedFileCmd = lookupPersistedDataById(id);
    for (UploadedFile uploadedFile : uploadedFileCmd.getUploadedFiles()) {
      if (uploadedFile.getFileType() == FileType.POSITIONAL) {
        dataFile = uploadedFile;
        break;
      }
    }
    return dataFile;
  }

  /**
   * Returns the template file corresponding to the given ID as an UploadedFile object.
   *
   * @param id The ID corresponding to the stored file.
   * @return The template file as an UploadedFile object.
   */
  public UploadedFile getTemplateFile(String id) {
    UploadedFile dataFile = null;
    UploadedFileCmd uploadedFileCmd = lookupPersistedDataById(id);
    for (UploadedFile uploadedFile : uploadedFileCmd.getUploadedFiles()) {
      if (uploadedFile.getFileType() == FileType.TEMPLATE) {
        dataFile = uploadedFile;
        break;
      }
    }
    return dataFile;
  }

  /**
   * Looks up and retrieves a uploaded file data using the given id.
   *
   * @param id The ID corresponding to the data to retrieve.
   * @return The persisted uploaded file data.
   */
  @Override
  public UploadedFileCmd lookupPersistedDataById(String id) {
    return uploadedFileDao.lookupById(id);
  }

  /**
   * Retrieves the data file from disk and parses it by line, converting it into a JSON string.
   *
   * @param id The unique id associated with the file (a subdir in the user files directory).
   * @param dataFileName The file to parse.
   * @return A JSON String of the file data parsed by line.
   * @throws RosettaFileException For any file I/O or JSON conversions problems.
   */
  @Override
  public String parseDataFileByLine(String id, String dataFileName) throws RosettaFileException {
    String filePath = FilenameUtils.concat(FilenameUtils.concat(PropertyUtils.getUserFilesDir(), id), dataFileName);
    return fileManager.parseByLine(filePath);
  }

  /**
   * Finds and persists and data from an uploaded template file.
   *
   * @param id The unique ID corresponding to thsi transaction.
   * @param templateFile The rosetta template file to use.
   * @throws RosettaFileException If unable to collect data from template file.
   */
  private void persistTemplateData(String id, UploadedFile templateFile) throws RosettaFileException {
    String jsonString =
        this.fileManager.getJsonStringFromTemplateFile(PropertyUtils.getUserFilesDir(), id, templateFile.getFileName());
    try {
      // Get the template data in the form of a Template object.
      Template templateData = JsonUtils.mapJsonToTemplateObject(jsonString);

      // Get persisted wizard data from the template.
      WizardData wizardData = wizardDataDao.lookupWizardDataById(id);
      // Delimiter.
      String delimiter = templateData.getDelimiter();
      if (delimiter != null) {
        wizardData.setDelimiter(delimiter);
      }
      // Header line numbers.
      List<Integer> headerLineNumberList = templateData.getHeaderLineNumbers();
      if (headerLineNumberList != null && !headerLineNumberList.isEmpty()) {
        String headerLineNumbers =
            headerLineNumberList.stream().map(n -> String.valueOf(n)).collect(Collectors.joining(","));
        wizardData.setHeaderLineNumbers(headerLineNumbers);
      }
      // Persist data updated with template info.
      wizardDataDao.updatePersistedWizardData(wizardData);

      /* PERSIST GLOBAL METADATA FROM TEMPLATE */

      // Need to convert the list of RosettaGlobalAttribute objects to a list of GlobalMetadata objects.
      List<RosettaGlobalAttribute> rosettaGlobalAttributes = templateData.getGlobalMetadata();

      if (rosettaGlobalAttributes != null) {

        List<GlobalMetadata> globalMetadataObjects = new ArrayList<>(rosettaGlobalAttributes.size());
        for (RosettaGlobalAttribute rosettaGlobalAttribute : templateData.getGlobalMetadata()) {
          GlobalMetadata globalMetadata = new GlobalMetadata();
          globalMetadata.setWizardDataId(id);
          globalMetadata.setMetadataGroup(rosettaGlobalAttribute.getGroup());
          globalMetadata.setMetadataKey(rosettaGlobalAttribute.getName());
          globalMetadata.setMetadataValue(rosettaGlobalAttribute.getValue());
          globalMetadata.setMetadataValueType(rosettaGlobalAttribute.getType());
          globalMetadataObjects.add(globalMetadata);
        }

        // Look up any persisted data corresponding to the id.
        List<GlobalMetadata> persisted = globalMetadataDao.lookupGlobalMetadata(id);

        if (persisted.size() > 0) {
          // Update the persisted data.
          globalMetadataDao.updatePersistedGlobalMetadata(id, globalMetadataObjects);
        } else {
          // No persisted data; this is the first time we are persisting it.
          globalMetadataDao.persistGlobalMetadata(id, globalMetadataObjects);
        }
      }

      /* PERSIST VARIABLE METADATA FROM TEMPLATE */

      // Need to convert the list of VariableInfo objects to a list of Variable objects.
      List<VariableInfo> variableInfoObjects = templateData.getVariableInfoList();
      if (variableInfoObjects != null) {
        List<Variable> variableObjects = new ArrayList<>();
        for (VariableInfo variableInfo : variableInfoObjects) {
          Variable variable = new Variable();
          variable.setWizardDataId(id);
          variable.setColumnNumber(variableInfo.getColumnId());
          variable.setVariableName(variableInfo.getName());

          // Get rosetta control metadata.
          List<RosettaAttribute> rosettaControlMetadata = variableInfo.getRosettaControlMetadata();
          if (rosettaControlMetadata != null) {
            // This should always be true if column data is used.
            for (RosettaAttribute rosettaAttributeControlMetadata : rosettaControlMetadata) {
              if (rosettaAttributeControlMetadata.getName().equals("coordinateVariableType")) {
                variable.setMetadataTypeStructure(rosettaAttributeControlMetadata.getValue());
              }
              if (rosettaAttributeControlMetadata.getName().equals("coordinateVariable")) {
                variable.setMetadataType(rosettaAttributeControlMetadata.getValue());
              }
              if (rosettaAttributeControlMetadata.getName().equals("type")) {
                variable.setMetadataValueType(rosettaAttributeControlMetadata.getValue());
              }
              if (rosettaAttributeControlMetadata.getName().equals("positive")) {
                variable.setVerticalDirection(rosettaAttributeControlMetadata.getValue());
              }
            }
          }

          // Initialize empty VariableMetadata lists.
          List<VariableMetadata> required = new ArrayList<>();
          List<VariableMetadata> recommended = new ArrayList<>();
          List<VariableMetadata> additional = new ArrayList<>();

          // Get variable metadata.
          List<RosettaAttribute> variableMetadata = variableInfo.getVariableMetadata();
          if (variableMetadata != null) {

            // This should always be true if column data is used.
            for (RosettaAttribute rosettaAttributeVariableMetadata : variableMetadata) {
              // Ascertain the compliance level.
              String complianceLevel =
                  metadataManager.getComplianceLevelForAttribute(id, rosettaAttributeVariableMetadata.getName());
              if (complianceLevel != null) {
                VariableMetadata varMetadata = new VariableMetadata();
                varMetadata.setComplianceLevel(complianceLevel);
                varMetadata.setMetadataKey(rosettaAttributeVariableMetadata.getName());
                varMetadata.setMetadataValue(rosettaAttributeVariableMetadata.getValue());
                // Populate the correct list with the VariableMetadata object.
                if (complianceLevel.equals("required")) {
                  required.add(varMetadata);
                }
                if (complianceLevel.equals("recommended")) {
                  recommended.add(varMetadata);
                }
                if (complianceLevel.equals("additional")) {
                  additional.add(varMetadata);
                }
              }
            }
          }
          variable.setRequiredMetadata(required);
          if (!recommended.isEmpty()) {
            variable.setRecommendedMetadata(recommended);
          }
          if (!additional.isEmpty()) {
            variable.setAdditionalMetadata(additional);
          }
          variableObjects.add(variable);
        }

        // Look up any persisted data corresponding to the id.
        List<Variable> persisted = variableDao.lookupVariables(id);

        // Get the variable IDs and columns numbers from persisted data.
        Map<Integer, Integer> variableMap = new HashMap<>(persisted.size());
        if (persisted.size() > 0) {
          // Create map of column numbers to variable ids.
          for (Variable persistedVar : persisted) {
            int variableId = persistedVar.getVariableId();
            int columnNumber = persistedVar.getColumnNumber();
            variableMap.put(columnNumber, variableId);
          }
          // Update new variables with column numbers.
          for (Variable variable : variableObjects) {
            int variableId = variableMap.get(variable.getColumnNumber());
            variable.setVariableId(variableId);
            variable.setWizardDataId(id);
          }
          variableDao.updatePersistedVariables(variableObjects);
        } else {
          // No persisted data; this is the first time we are persisting it.
          variableDao.persistVariables(id, variableObjects);
        }
      }

    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
      throw new RosettaFileException("Unable to convert template file data to Template object: " + e);
    }
  }

  /**
   * Processes the data submitted by the user containing uploaded file information. Writes the
   * uploaded files to disk. Updates the persisted data corresponding to the provided unique ID
   * with the uploaded file information.
   *
   * @param id The unique ID corresponding to already persisted data.
   * @param uploadedFileCmd The user-submitted data containing the uploaded file information.
   * @throws RosettaFileException If unable to write file(s) to disk or a file conversion exception
   *         occurred.
   */
  @Override
  public void processFileUpload(String id, UploadedFileCmd uploadedFileCmd) throws RosettaFileException {

    // Get the persisted data corresponding to this ID
    // (This object is created even if there is not any persisted data.)
    UploadedFileCmd persistedData = lookupPersistedDataById(id);

    // Save uploaded files to disk.
    List<UploadedFile> uploadedFiles = uploadedFileCmd.getUploadedFiles();
    for (UploadedFile uploadedFile : uploadedFiles) {
      // Only bother with saving files that actually exist.
      if (StringUtils.trimToNull(uploadedFile.getFileName()) != null) {

        // Examine the UploadedFile objects (can be "empty") to determine if data
        // has been persisted prior (in which case the object will not be "empty").
        for (UploadedFile persistedFile : persistedData.getUploadedFiles()) {
          // Get the matching file type.
          if (uploadedFile.getFileType().equals(persistedFile.getFileType())) {

            // Save file only if name is NOT the same as the one that is persisted.
            // (If the user visits the prior step in the wizard and doesn't update
            // the uploaded file data, we don't need to process that resubmitted data.)
            if (!uploadedFile.getFileName().equals(persistedFile.getFileName())) {
              int index = uploadedFiles.indexOf(uploadedFile);
              // Write data file to disk.
              String fileName = fileManager.writeUploadedFileToDisk(PropertyUtils.getUserFilesDir(), id,
                  uploadedFile.getFileName(), uploadedFile.getFile());
              // Update file name with CSV version.
              uploadedFile.setFileName(fileName);
              // Update the uploaded files list.
              uploadedFiles.set(index, uploadedFile);

              // Persist file data.
              uploadedFileDao.persistData(id, uploadedFileCmd);

              // If uploaded file is a rosetta TEMPLATE file, parse and persist the data.
              if (uploadedFile.getFileType().equals(FileType.TEMPLATE)) {
                persistTemplateData(id, uploadedFile);
              }
            }
          }
        }
      }
    }
  }

  /**
   * Sets the data access object (DAO) for the GlobalMetadata object.
   *
   * @param globalMetadataDao The service DAO representing a GlobalMetadata object.
   */
  public void setGlobalMetadataDao(GlobalMetadataDao globalMetadataDao) {
    this.globalMetadataDao = globalMetadataDao;
  }

  /**
   * Sets the data access object (DAO) for the UploadedFile object.
   *
   * @param uploadedFileDao The service DAO representing a UploadedFile object.
   */
  public void setUploadedFileDao(UploadedFileDao uploadedFileDao) {
    this.uploadedFileDao = uploadedFileDao;
  }

  /**
   * Sets the data access object (DAO) for the Variable object.
   *
   * @param variableDao The service DAO representing a Variable object.
   */
  public void setVariableDao(VariableDao variableDao) {
    this.variableDao = variableDao;
  }

  /**
   * Sets the data access object (DAO) for the WizardData object.
   *
   * @param wizardDataDao The service DAO representing a WizardData object.
   */
  public void setWizardDataDao(WizardDataDao wizardDataDao) {
    this.wizardDataDao = wizardDataDao;
  }

}


text:
The robust file system package. Its an easier way to approach files as arrays without the complexity of javas json based libraries.

Keep in mind this is still being worked on, if youd like to help send me a message over at jelch2002@gmail.com

#### Version -0.0.0.3

redpajama_set_name: RedPajamaGithub


text:
using System.Diagnostics;
using System.Globalization;

namespace Octokit
{
    /// <summary>
    /// Represents updatable fields for a users subscription to a given thread
    /// </summary>
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class NewThreadSubscription
    {
        /// <summary>
        /// Determines if notifications should be received from this thread
        /// </summary>
        public bool Subscribed { get; set; }

        /// <summary>
        /// Determines if all notifications should be blocked from this thread
        /// </summary>
        public bool Ignored { get; set; }

        internal string DebuggerDisplay
        {
            get
            {
                return string.Format(CultureInfo.InvariantCulture, "Subscribed: {0} Ignored: {1}", Subscribed, Ignored);
            }
        }
    }
}


text:
"""Common util functions."""

import datetime
import logging
import random
import re
import string
import sys
import yaml

import pkg_resources

_FORMATTER = logging.Formatter(
    '%(levelname)8s - %(lineno)4s:%(filename)30s - %(message)s')

def abs_filepaths(paths):
    """Return absolute filepaths for the given input paths.

    Args:
        paths: list of str, filepath names.

    Yields:
        str, absolute filepath name.
    """
    for path in paths:
        filepath = pkg_resource_filename(path)
        yield filepath

def pkg_resource_filename(path):
    """Return absolute filepath for the given input path.

    Args:
        path: str, filepath name.

    Returns
        str, absolute filepath name.
    """
    path_vals = path.split('/')
    abs_filename = pkg_resources.resource_filename('.'.join(path_vals[:-1]),
                                                   path_vals[-1])
    return abs_filename

def log_to_console(level=logging.INFO):
    """Output logging statements to stdout.

    Args:
        level: logging level.
    """
    has_stdout = False
    logr = logging.getLogger()
    for handler in logr.handlers:
        if handler.stream == sys.stdout:
            has_stdout = True
            break

    if not has_stdout:
        handler = logging.StreamHandler(sys.stdout)
        handler.setFormatter(_FORMATTER)
        logr.addHandler(handler)
    logr.setLevel(level)

def process_yaml(filepath):
    """Process yaml at filepath and return an object.

    Args:
      filepath: str, file path for the YAML file.

    Returns:
      object, yaml data as dict.
    """
    logging.info('Processing yaml file: %s', filepath)
    data = {}
    try:
        with open(filepath, 'r') as cfile:
            data = yaml.load(cfile.read(), Loader=yaml.SafeLoader)
    except FileNotFoundError:
        logging.error('No file exists at path: %s', filepath)
    return data

def process_yaml_from_text(yaml_text):
    """Process yaml from given string data.

    Args:
      yaml_text: str, input for yaml processing.

    Returns:
      object, yaml data as dict.
    """
    data = yaml.load(yaml_text, Loader=yaml.SafeLoader)
    return data

def today():
    """Returns datetime as yyyy-mm-dd format."""
    return datetime.datetime.now().strftime('%Y-%m-%d')

def timestamp():
    """Return timestamp in yyyy-mm-dd hh:mm:ss format"""
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def zulu_timestamp(delta_days=0, delta_seconds=60):
    """Return timestamp in zulu format."""
    now = datetime.datetime.now()
    delta = datetime.timedelta(days=delta_days, seconds=delta_seconds)
    time = now + delta
    return time.strftime('%Y-%m-%dT%H:%M:%S.%fZ')

def seconds_in_a_day():
    """Return total seconds(int) in a day."""
    return 60 * 60 * 24

def is_date_in_zulu_format(date_str):
    """Check if the given input date string is in zulu format.

    Args:
        date_str: str, date string.

    Returns: bool.
    """
    pattern = re.compile(
        r'^\d{4}-+\d{2}-+\d{2}T+\d{2}:+\d{2}:+\d{2}.+\d{1,}Z+$')
    matched = pattern.match(date_str)
    return matched

def get_unique_id():
    """Generate a unique id."""
    char_set = string.ascii_uppercase + string.digits
    return ''.join(random.choice(char_set) for _ in range(32))


text:
// Package enca provides a minimal cgo bindings for libenca
//
// Source code and project home:
// https://github.com/endeveit/go-enca
//
package enca

/*
#cgo pkg-config: enca

#include <enca.h>
*/
import "C"

import (
	"fmt"
	"strings"
	"sync"
	"unsafe"
)

const (
	// Default, implicit charset name in Enca
	NAME_STYLE_ENCA = 0 << iota
	// RFC 1345 or otherwise canonical charset name
	NAME_STYLE_RFC1345
	// Cstocs charset name (may not exist)
	NAME_STYLE_CSTOCS
	// Iconv charset name (may not exist)
	NAME_STYLE_ICONV
	// Human comprehensible description
	NAME_STYLE_HUMAN
	// Preferred MIME name (may not exist)
	NAME_STYLE_MIME
)

var availableLanguages []string

func init() {
	n := C.size_t(0)
	l := C.enca_get_languages(&n)

	availableLanguages = getStrings(l, n)

	C.free(unsafe.Pointer(l))
}

type EncaAnalyser struct {
	sync.Mutex
	// Language for which the analyser is initialized
	Language string
	enca     C.EncaAnalyser
}

// Returns list of available languages
func GetAvailableLanguages() []string {
	return availableLanguages
}

// Returns a new EncaAnalyzer object for the given language.
func New(lang string) (*EncaAnalyser, error) {
	if !keyExists(lang, availableLanguages) {
		return nil, fmt.Errorf(
			"Invalid language '%s'. Available languages are: '%s'",
			lang,
			strings.Join(availableLanguages, "', '"))
	}

	cLang := C.CString(lang)
	cOne := C.int(1)

	defer C.free(unsafe.Pointer(cLang))

	analyzer := &EncaAnalyser{Language: lang, enca: C.enca_analyser_alloc(cLang)}
	C.enca_set_threshold(analyzer.enca, C.double(1.38))
	C.enca_set_multibyte(analyzer.enca, cOne)
	C.enca_set_ambiguity(analyzer.enca, cOne)
	C.enca_set_garbage_test(analyzer.enca, cOne)

	return analyzer, nil
}

// Returns encoding of provided byte array
func (ea *EncaAnalyser) FromBytes(bytes []byte, nameStyle int) (result string, err error) {
	ea.Lock()
	defer ea.Unlock()
	cText := (*C.uchar)(unsafe.Pointer(&bytes[0]))

	encoding := C.enca_analyse_const(ea.enca, cText, C.size_t(len(bytes)))

	if encoding.charset == C.int(-1) {
		errno := C.enca_errno(ea.enca)
		err = fmt.Errorf("Error %d: %s", errno, C.GoString(C.enca_strerror(ea.enca, errno)))
	} else {
		result = C.GoString(C.enca_charset_name(encoding.charset, C.EncaNameStyle(nameStyle)))
	}

	return result, err
}

// Helper function that returns encoding of provided string
func (ea *EncaAnalyser) FromString(text string, nameStyle int) (string, error) {
	return ea.FromBytes([]byte(text), nameStyle)
}

// Frees memory used by EncaAnalyser
func (ea *EncaAnalyser) Free() {
	C.enca_analyser_free(ea.enca)
}

// Helper function that converts C "const char**" into Go []string
func getStrings(x **C.char, n C.size_t) []string {
	q := ((*[1 << 30]*C.char)(unsafe.Pointer(x)))[:n]
	r := make([]string, n)

	for i, cs := range q {
		r[i] = C.GoString(cs)
	}

	return r
}

// Check if key exists
func keyExists(a string, list []string) bool {
	for _, b := range list {
		if b == a {
			return true
		}
	}

	return false
}


text:
echo "Stopping oozie";
/home/admin/daemons/oozie-stop.sh;
echo "Stopping hive";
/home/admin/daemons/hive-stop.sh;
echo "Stopping hbase";
/home/admin/daemons/hbase-stop.sh;
echo "Stopping zookeeper";
/home/admin/daemons/zookeeper-stop.sh;
echo "Stopping hadoop";
/home/admin/stacks/hadoop-stop.sh;


text:
//
// Copyright (c) Microsoft.  All rights reserved.
//
// 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.
//

using Microsoft.Azure.Management.BackupServices;
using Microsoft.Azure.Management.BackupServices.Models;
using Microsoft.Azure.Test;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace BackupServices.Tests
{
    public class CSMAzureBackupItem : BackupServicesTestsBase
    {
        //[Fact]
        public void EnableAzureBackupProtectionTest()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetServiceClient<BackupServicesManagementClient>();
                CSMSetProtectionRequest input = new CSMSetProtectionRequest();
                input.Properties = new CSMSetProtectionRequestProperties();
                input.Properties.PolicyId = ConfigurationManager.AppSettings["PolicyId"];
                string itemName = ConfigurationManager.AppSettings["AzureBackupItemName"];
                string containerName = ConfigurationManager.AppSettings["ContainerName"];

                var response = client.DataSource.EnableProtectionCSM(BackupServicesTestsBase.ResourceGroupName,
                    BackupServicesTestsBase.ResourceName,
                    GetCustomRequestHeaders(),
                    containerName,
                    itemName,
                    input);

                Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
            }
        }

        //[Fact]
        public void UpdateAzureBackupProtectionTest()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetServiceClient<BackupServicesManagementClient>();

                CSMUpdateProtectionRequest input = new CSMUpdateProtectionRequest();
                input.Properties = new CSMUpdateProtectionRequestProperties();
                string itemName = ConfigurationManager.AppSettings["AzureBackupItemName"];
                string containerName = ConfigurationManager.AppSettings["ContainerName"];
                input.Properties.PolicyId = string.Empty;

                var response = client.DataSource.UpdateProtectionCSM(BackupServicesTestsBase.ResourceGroupName,
                    BackupServicesTestsBase.ResourceName,
                    GetCustomRequestHeaders(),
                    containerName,
                    itemName,
                    input);

                Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
            }
        }

        //[Fact]
        public void DisableAzureBackupProtectionTest()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();
                var client = GetServiceClient<BackupServicesManagementClient>();

                string itemName = ConfigurationManager.AppSettings["AzureBackupItemName"];
                string containerName = ConfigurationManager.AppSettings["ContainerName"];
                var response = client.DataSource.DisableProtectionCSM(BackupServicesTestsBase.ResourceGroupName,
                    BackupServicesTestsBase.ResourceName,
                    GetCustomRequestHeaders(),
                    containerName,
                    itemName);

                Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
            }
        }

        [Fact]
        public void ListAzureBackupItemPOTest()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();

                CSMItemQueryObject POQueryParam = new CSMItemQueryObject()
                {
                    Status = null,
                    Type = null
                };

                var client = GetServiceClient<BackupServicesManagementClient>();

                var response = client.ProtectableObject.ListCSMAsync(BackupServicesTestsBase.ResourceGroupName, BackupServicesTestsBase.ResourceName, POQueryParam, GetCustomRequestHeaders()).Result;

                Assert.True(response.CSMItemListResponse.Value.Count > 0, "Protectable Object Result count can't be less than 1");

                foreach (var po in response.CSMItemListResponse.Value)
                {
                    Assert.True(!string.IsNullOrEmpty(po.Properties.ContainerId), "ContainerId can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(po.Properties.FriendlyName), "FriendlyName can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(po.Properties.ItemType), "ItemType can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(po.Properties.Status), "Status can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(po.Name), "Name can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(po.Type), "Type can't be null or empty");
                }

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            }
        }

        [Fact]
        public void ListAzureBackupItemDSTest()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();

                CSMProtectedItemQueryObject DSQueryParam = new CSMProtectedItemQueryObject()
                {
                    ProtectionStatus = null,
                    Status = null,
                    Type = null
                };

                var client = GetServiceClient<BackupServicesManagementClient>();

                var response = client.DataSource.ListCSMAsync(BackupServicesTestsBase.ResourceGroupName, BackupServicesTestsBase.ResourceName, DSQueryParam, GetCustomRequestHeaders()).Result;
                foreach (var ds in response.CSMProtectedItemListResponse.Value)
                {
                    Assert.True(!string.IsNullOrEmpty(ds.Properties.ContainerId), "ContainerId can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(ds.Properties.FriendlyName), "FriendlyName can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(ds.Properties.ItemType), "ItemType can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(ds.Properties.ProtectionPolicyId), "ProtectionPolicyId can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(ds.Properties.ProtectionStatus), "ProtectionStatus can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(ds.Properties.RecoveryPointsCount.ToString()), "RecoveryPointsCount can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(ds.Properties.Status), "Status can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(ds.Name), "Name can't be null or empty");
                    Assert.True(!string.IsNullOrEmpty(ds.Type), "Type can't be null or empty");
                }

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            }
        }
    }
}


text:
package org.wso2.es.ui.integration.test.store;

import org.openqa.selenium.By;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.AutomationContext;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.engine.context.beans.Tenant;
import org.wso2.carbon.automation.extensions.selenium.BrowserManager;
import org.wso2.es.ui.integration.util.BaseUITestCase;
import org.wso2.es.ui.integration.util.ESUtil;
import org.wso2.es.ui.integration.util.ESWebDriver;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

/**
 * The test first logs in the tenant admin for wso2.com and
 * then checks the behaviour of the Store Home Page
 * 1. Checks if the homepage loads (top-assets page)
 * 2. Checks if the gadget and site links are present
 * 3. Checks if the gadget listing page is rendered
 * 4. Checks if the site listing page is rendered
 */
public class ESStoreTenantUserTUHomePageTestCase extends BaseUITestCase {
    protected static final int MAX_POLL_COUNT = 30;
    @BeforeClass(alwaysRun = true)
    public void setUp() throws Exception {
        super.init();
        driver = new ESWebDriver(BrowserManager.getWebDriver());
        baseUrl = getWebAppURL();
        login();
    }

    public void login() throws Exception {
        super.init(TestUserMode.TENANT_ADMIN);
        currentUserName = userInfo.getUserName();
        currentUserPwd = userInfo.getPassword();
        buildTenantDetails(TestUserMode.TENANT_ADMIN);
        ESUtil.login(driver, baseUrl, STORE_APP, currentUserName, currentUserPwd);
    }

    public String resolveStoreUrl()  {
        String tenantDomain = tenantDetails.getDomain();
        return baseUrl + STORE_URL + ESUtil.getTenantQualifiedUrl(tenantDomain);
    }

    @Test(groups = "wso2.es.store", description = "Test accessing homepage with a logged in tenant user using " +
            "the tenant url(t/wso2.com)")
    public void testLoggedInHomePage() throws Exception {
        driver.get(resolveStoreUrl());
        assertTrue(isElementPresent(driver, By.cssSelector("a.brand")), "Home Page error: Logo missing");
        assertEquals("Gadget", driver.findElement(By.xpath("//div[@id='container-search']/div/div/div/div/a[1]/li"))
                .getText(), "Home Page error: Gadget menu missing");
        assertEquals("Site", driver.findElement(By.xpath("//div[@id='container-search']/div/div/div/div/a[2]/li"))
                .getText(), "Home Page error: Site menu missing");
    }

    @Test(groups="wso2.es.store" , description = "Test accessing asset listing page with a logged in tenant" +
            "user using the tenant url(t/wso2.com)")
    public void testAssetListingPage() throws Exception{
        driver.get(resolveStoreUrl()+"/assets/gadget/list");
        assertTrue(isElementPresent(driver, By.cssSelector("a.brand")), "Home Page error: Logo missing");
    }

    @AfterClass(alwaysRun = true)
    public void tearDown() throws Exception {
        driver.quit();
    }
}


text:
#ifndef _flint_h_
#define _flint_h_

#include <math.h>

/*
	For real-time applications you need big integers: the number
	of recorded samples will exceed the maximum 32-bit signed integer
	after only 13.5 hours. So having int64_t would be best,
	and that is indeed what Praat uses for these same purposes,
	but the Vokaturi library has to be able to run with old compilers and linkers.
	Not all old compilers support int64_t, and not all old linkers
	support 64-bit division without calling external functions.
	So we simply employ the type "double", which can contain signed integers
	up to 54 bits.
*/
typedef double flint;
/*
	On these high-precision "integers",
	the integer division (with its rounding down) and the modulo function
	cannot be performed with the usual operator symbols for integer types
	(which are "/" and "%", respectively),
	so for those operations we use inline functions instead.
*/
inline static flint flint_div (flint a, flint b) { return floor (a / b); }
inline static flint flint_mod (flint a, flint b) { return a - floor (a / b) * b; }

/* End of file flint.h */
#endif


text:
<?php namespace Raahul\LarryFour\Tests;

use \Raahul\LarryFour\Parser;
use \Raahul\LarryFour\Parser\FieldParser;
use \Raahul\LarryFour\Parser\ModelDefinitionParser;
use \Raahul\LarryFour\ModelList;
use \Raahul\LarryFour\MigrationList;
use \Raahul\LarryFour\Generator\MigrationGenerator;

/**
 * This is a helper class to get the parsed result of a sample input. It's in
 * a separate class so that it can be used by different test classes
 */
class ParsedResult
{
    /**
     * The parsed object is just created and stored once for all later use
     * @var array
     */
    private static $parsed = null;

    public static function getSampleParsedObject()
    {
        if (is_null(self::$parsed))
        {
            self::$parsed = self::getParsedOutput(self::getSampleInput());
        }

        return self::$parsed;
    }

    public static function getParsedOutput($input)
    {
        $p = new Parser(
            new FieldParser(),
            new ModelDefinitionParser(),
            new ModelList(),
            new MigrationList());
        return $p->parse($input);
    }

    public static function getSampleInput()
    {
        return <<<EOF
User users; hm Post; btm Role; mm Image imageable; hm Stuff stuffer_id; btm Thumb t_u u_id t_id;
    id increments
    username string 50; default "hello world"; nullable;
    password string 64
    email string 250
    type enum admin, moderator, user

Post; mm Image imageable; btmc Comment;
    timestamps
    title string 250
    content text
    rating decimal 5 2

Image
    timestamps
    softDeletes

Role
    timestamps

Stuff;
    timestamps
    softDeletes

Thumb
    timestamps

Comment

table my_great_table
    timestamps
    softDeletes
    title string 250
    content text
    rating decimal 5 2
    pK increments

table comment_post
    post_id integer; unsigned
    comment_id integer; unsigned
    name string
    type string
    timestamps
EOF;
    }
}


text:
package org.terracotta.statistics.archive;

import org.terracotta.statistics.Sample;
import org.terracotta.statistics.ValueStatistic;

import java.io.Serializable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.LongSupplier;

/**
 * @author cdennis
 */
public class StatisticSampler<T extends Serializable> {

  private final boolean exclusiveExecutor;
  private final ScheduledExecutorService executor;
  private final SamplingTask<T> task;

  private ScheduledFuture<?> currentExecution;
  private long period;

  public StatisticSampler(long time, TimeUnit unit, ValueStatistic<T> statistic, Consumer<Sample<T>> sink, LongSupplier timeSupplier) {
    this(null, time, unit, statistic, sink, timeSupplier);
  }

  public StatisticSampler(ScheduledExecutorService executor, long time, TimeUnit unit, ValueStatistic<T> statistic, Consumer<Sample<T>> sink, LongSupplier timeSupplier) {
    if (executor == null) {
      this.exclusiveExecutor = true;
      this.executor = Executors.newSingleThreadScheduledExecutor(new SamplerThreadFactory());
    } else {
      this.exclusiveExecutor = false;
      this.executor = executor;
    }
    this.period = unit.toNanos(time);
    this.task = new SamplingTask<>(statistic, sink, timeSupplier);
  }

  public synchronized void setPeriod(long time, TimeUnit unit) {
    this.period = unit.toNanos(time);
    if (currentExecution != null && !currentExecution.isDone()) {
      stop();
      start();
    }
  }

  public synchronized void start() {
    if (currentExecution == null || currentExecution.isDone()) {
      currentExecution = executor.scheduleAtFixedRate(task, period, period, TimeUnit.NANOSECONDS);
    } else {
      throw new IllegalStateException("Sampler is already running");
    }
  }

  public synchronized void stop() {
    if (currentExecution == null || currentExecution.isDone()) {
      throw new IllegalStateException("Sampler is not running");
    } else {
      currentExecution.cancel(false);
    }
  }

  public synchronized void shutdown() throws InterruptedException {
    if (exclusiveExecutor) {
      executor.shutdown();
      if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
        throw new IllegalStateException("Exclusive ScheduledExecutorService failed to terminate promptly");
      }
    } else {
      throw new IllegalStateException("ScheduledExecutorService was supplied externally - it must be shutdown directly");
    }
  }

  static class SamplingTask<T extends Serializable> implements Runnable {

    private final ValueStatistic<T> statistic;
    private final Consumer<Sample<T>> sink;
    private final LongSupplier timeSupplier;

    SamplingTask(ValueStatistic<T> statistic, Consumer<Sample<T>> sink, LongSupplier timeSupplier) {
      this.statistic = statistic;
      this.sink = sink;
      this.timeSupplier = timeSupplier;
    }

    @Override
    public void run() {
      sink.accept(new Sample<>(timeSupplier.getAsLong(), statistic.value()));
    }
  }

  static class SamplerThreadFactory implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
      Thread t = new Thread(r, "Statistic Sampler");
      t.setDaemon(true);
      return t;
    }
  }
}


text:
package com.example.a001.swipelistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.example.a001.swipelistview.adapters.SwipeListViewAdapter;
import com.example.a001.swipelistview.views.SlideView;
import com.example.a001.swipelistview.views.SwipeListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private List<String> list = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG,"MainActivity onCreate");
        final SwipeListView swipeListView = (SwipeListView)findViewById(R.id.list_view);
        for(int i=0;i<30;i++){
            String string = "我是一串字符"+i;
            list.add(string);
        }
        Log.d(TAG,list.toString()+ list.size());
        final SwipeListViewAdapter adapter = new SwipeListViewAdapter(this,R.layout.swipe_listview_item,list);
        swipeListView.setAdapter(adapter);
        adapter.setOnItemDeleteButtonClickListener(new SwipeListViewAdapter.ItemDeleteButonClickListerner() {
            @Override
            public void onDelete(final int position, View v) {
                final SlideView slideView = (SlideView)v;
                swipeListView.setInterceptTouchEventWhenDeleting(true);
                Log.d(TAG,"position" + position);
                slideView.setOnAnimationEndListener(new SlideView.OnAnimationEndListener() {
                    @Override
                    public void run() {
                        list.remove(position);
                        adapter.notifyDataSetChanged();
                        swipeListView.setInterceptTouchEventWhenDeleting(false);
                    }
                });
            }
        });
        Log.d(TAG,"MainActivity onCreate");
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import Home from './modules/home/main';
import TodoList from './modules/todolist/main';
import Header from './modules/common/header';
import Footer from './modules/common/footer';
import { BrowserRouter as Router, Route } from 'react-router-dom';

export class ReactSeed extends React.Component {
    render() {
        return(
            <Home />
        );
    }
}

// ReactDOM.render(
//     <Header />,
//     document.getElementById('header')
// );

ReactDOM.render(
    <Router>
        <div>
            <Route exact path="/" component={Home} />
            <Route path="/todolist" component={TodoList} />
            </div>
    </Router>,
    document.getElementById('content')
);

// ReactDOM.render(
//     <Footer />,
//     document.getElementById('footer')
// );


text:
.icon {
  display: inline-block;
  width: 1em;
  height: 1em;
  stroke-width: 0;
  stroke: currentColor;
  fill: currentColor;
}

/*


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Elsinoë menispermacearum Racib.

### Remarks
null


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script type="text/javascript">

    function openDB (name,version) {
        var version=version || 1;
        var request=window.indexedDB.open(name,version);
        request.onerror=function(e){
            console.log(e.currentTarget.error.message);
        };
        request.onsuccess=function(e){
            myDB.db=e.target.result;
        };
        request.onupgradeneeded=function(e){
            var db=e.target.result;
            if(!db.objectStoreNames.contains('students')){
                var store=db.createObjectStore('students',{keyPath: 'id'});
                store.createIndex('nameIndex','name',{unique:true});
                store.createIndex('ageIndex','age',{unique:false});
            }
            console.log('DB version changed to '+version);
        };
    }

    function closeDB(db){
        db.close();
    }

    function deleteDB(name){
        indexedDB.deleteDatabase(name);
    }

    function addData(db,storeName){
        var transaction=db.transaction(storeName,'readwrite');
        var store=transaction.objectStore(storeName);

        for(var i=0;i<students.length;i++){
            store.add(students[i]);
        }
    }

    function getDataByKey(db,storeName,value){
        var transaction=db.transaction(storeName,'readwrite');
        var store=transaction.objectStore(storeName);
        var request=store.get(value);
        request.onsuccess=function(e){
            var student=e.target.result;
            console.log(student.name);
        };
    }

    function updateDataByKey(db,storeName,value){
        var transaction=db.transaction(storeName,'readwrite');
        var store=transaction.objectStore(storeName);
        var request=store.get(value);
        request.onsuccess=function(e){
            var student=e.target.result;
            student.age=35;
            store.put(student);
        };
    }

    function deleteDataByKey(db,storeName,value){
        var transaction=db.transaction(storeName,'readwrite');
        var store=transaction.objectStore(storeName);
        store.delete(value);
    }

    function clearObjectStore(db,storeName){
        var transaction=db.transaction(storeName,'readwrite');
        var store=transaction.objectStore(storeName);
        store.clear();
    }

    function deleteObjectStore(db,storeName){
        var transaction=db.transaction(storeName,'versionchange');
        db.deleteObjectStore(storeName);
    }

    function fetchStoreByCursor(db,storeName){
        var transaction=db.transaction(storeName);
        var store=transaction.objectStore(storeName);
        var request=store.openCursor();
        request.onsuccess=function(e){
            var cursor=e.target.result;
            if(cursor){
                console.log(cursor.key);
                var currentStudent=cursor.value;
                console.log(currentStudent.name);
                cursor.continue();
            }
        };
    }

    function getDataByIndex(db,storeName){
        var transaction=db.transaction(storeName);
        var store=transaction.objectStore(storeName);
        var index = store.index("ageIndex");
        index.get(26).onsuccess=function(e){
            var student=e.target.result;
            console.log(student.id);
        }
    }

    function getMultipleData(db,storeName){
        var transaction=db.transaction(storeName);
        var store=transaction.objectStore(storeName);
        var index = store.index("nameIndex");
        var request=index.openCursor(null,IDBCursor.prev);
        request.onsuccess=function(e){
            var cursor=e.target.result;
            if(cursor){
                var student=cursor.value;
                console.log(student.name);
                cursor.continue();
            }
        }
    }

    var myDB={
        name:'test',
        version:1,
        db:null
    };

    var students=[{
        id:1001,
        name:"Byron",
        age:24
    },{
        id:1002,
        name:"Frank",
        age:30
    },{
        id:1003,
        name:"Aaron",
        age:26
    },{
        id:1004,
        name:"Casper",
        age:26
    }];
</script>
</body>
</html>


text:
package log

// TODO: This test is very simple and can be improved.

import (
	"fmt"
	"testing"
)

func TestLogLevel(t *testing.T) {
	const (
		msg1 = "log line1"
		msg2 = "log line2"
		msg3 = "log line3"
	)
	setMockLogger(fmt.Sprintf("%shello: %s", msg2, msg3), false)

	level := "info"
	SetLevel(level)
	if GetLevel() != level {
		t.Fatalf("Expected %q, got %q", level, GetLevel())
	}
	Debug.Println(msg1)             // not logged
	Info.Print(msg2)                // logged
	Error.Printf("hello: %s", msg3) // logged

	globals().defaultLogger.(*mockLogger).Verify(t)
}

func TestDisable(t *testing.T) {
	setMockLogger("Starting server...", false)
	SetLevel("debug")
	Debug.Printf("Starting server...")
	SetLevel("disabled")
	Error.Printf("Important stuff you'll miss!")
	globals().defaultLogger.(*mockLogger).Verify(t)
}

func TestFatal(t *testing.T) {
	const msg = "will abort anyway"

	setMockLogger(msg, true)

	SetLevel("error")
	Info.Fatal(msg)

	globals().defaultLogger.(*mockLogger).Verify(t)
}

func TestAt(t *testing.T) {
	SetLevel("info")

	if At("debug") {
		t.Errorf("Debug is expected to be disabled when level is info")
	}
	if !At("error") {
		t.Errorf("Error is expected to be enabled when level is info")
	}
}

func TestRemoteLogging(t *testing.T) {
	const (
		msg           = "hi, hello, how are you?"
		fatalExpected = true
	)
	mockExternal := &mockLogger{
		expected: msg,
	}
	Register(mockExternal)
	setMockLogger(msg, !fatalExpected)

	Print(msg)

	mockExternal.Verify(t)
	globals().defaultLogger.(*mockLogger).Verify(t)
}

func TestDisableLocal(t *testing.T) {
	SetOutput(nil) // disable local logging.
	Print("not printed")
}

func setMockLogger(expected string, fatalExpected bool) {
	state.defaultLogger = &mockLogger{
		expected:      expected,
		fatalExpected: fatalExpected,
	}
}

type mockLogger struct {
	fatal         bool
	logged        string
	expected      string
	fatalExpected bool
}

func (ml *mockLogger) Printf(format string, v ...interface{}) {
	ml.logged += fmt.Sprintf(format, v...)
}

func (ml *mockLogger) Print(v ...interface{}) {
	ml.logged += fmt.Sprint(v...)
}

func (ml *mockLogger) Println(v ...interface{}) {
	ml.logged += fmt.Sprintln(v...)
}

func (ml *mockLogger) Fatal(v ...interface{}) {
	ml.fatal = true
	ml.Print(v...)
}

func (ml *mockLogger) Fatalf(format string, v ...interface{}) {
	ml.fatal = true
	ml.Printf(format, v...)
}

func (ml *mockLogger) Verify(t *testing.T) {
	if ml.logged != ml.expected {
		t.Errorf("Expected %q, got %q", ml.expected, ml.logged)
	}
	if ml.fatal != ml.fatalExpected {
		t.Errorf("Expected fatal %v, got %v", ml.fatalExpected, ml.fatal)
	}
}

// mockLogger is also an ExternalLogger.
func (ml *mockLogger) Flush() {
}
func (ml *mockLogger) Log(l Level, s string) {
	ml.Print(s)
}


text:
export const mbuAPI = process.env.MBU_API || 'http://localhost:3099/mbu-api';

export const GET_STUDENTS = 'student/GET_STUDENTS';
export const GET_STUDENT_BY_ID = 'student/GET_STUDENT_BY_ID';
export const UPDATE_STUDENT = 'student/UPDATE_STUDENT';
export const DELETE_STUDENT = 'student/DELETE_STUDENT';
export const RESET_CURRENT_STUDENT = 'student/RESET_CURRENT_STUDENT';

export const GET_SCHEDULED_COURSES = 'student/GET_SCHEDULED_COURSES';


text:
class RokuDiscovery < NSObject

  DISCOVERY_HOST   = '239.255.255.250'
  DISCOVERY_PORT   = 1900
  DISCOVERY_PACKET = "M-SEARCH * HTTP/1.1\n"                       \
                     "Host: #{DISCOVERY_HOST}:#{DISCOVERY_PORT}\n" \
                     "Man: \"ssdp:discover\"\n"                    \
                     "ST: roku:ecp\n\n"

  attr_accessor :roku_service, :roku_id, :last_error

  def initialize(delegate)
    @state    = :idle
    @delegate = delegate
    self.roku_service = nil
    self.roku_id      = nil
    self.last_error   = nil
  end

  # 'manual' entry validation, allowing:
  #   i) full service description : http://192.168.1.128:8060
  #  ii) ip and port only         :        192.168.1.128:8060
  # iii) ip only                  :        192.168.1.128
  def roku_service=(service)
    if service.nil?
      @roku_service = nil
      return
    end

    if service.match /HTTP:\/\//i
      fail "Bad Service Format '#{service}'." unless service.match /^HTTP:\/\/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+\/?$/i
      service += '/' unless service.end_with? '/'
    elsif service.match /:[0-9]+$/
      fail "Bad Service Format '#{service}'." unless service.match /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+$/
      service = "http://#{service}/"
    else
      fail "Bad Service Format '#{service}'." unless service.match /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/
      service = "http://#{service}:8060/"
    end
    @roku_service = service
  end

  # search for local Roku devices with SSDP
  # if not found before timeout (in floating seconds) expires, prompt to Retry/Manually-Enter/Exit
  def search(timeout)
    fail "RokuDiscovery.search_begin called during invalid state: #{@state}." if @state != :idle

    @timeout = timeout
    @socket  =  GCDAsyncUdpSocket.alloc.initWithDelegateOnMainQueue self

    self.last_error = nil
    error_ptr = Pointer.new :object

    unless @socket.bindToPort 0, error: error_ptr
      error = error_ptr[0]
      self.last_error = "Error creating UDP listener (during bind)\n#{error}"
      @delegate.roku_device_found
      return
    end

    unless @socket.beginReceiving error_ptr
      @socket.close
      error = error_ptr[0]
      self.last_error = "Error creating UDP listener (during begin)\n#{error}"
      @delegate.roku_device_found
      return
    end

    @state = :searching
    data = DISCOVERY_PACKET.dataUsingEncoding NSUTF8StringEncoding
    @socket.sendData data, toHost: DISCOVERY_HOST, port: DISCOVERY_PORT, withTimeout: -1, tag: 0
    performSelector 'search_timeout:', withObject: nil, afterDelay: @timeout
  end

  # we'll get called whether or not a timeout has occured
  def search_timeout(_object)
    return if roku_service
    begin
      search_stop
    rescue
      # we could possibly run into a timing issue here.
      # rescue search_stop errors if it happened to be working while we were.
      @socket.close
      @state = :idle
    end
    return if roku_service

    # show our Retry/Manul/Exit prompt
    first_manual_attempt = true
    while true
      alert = NSAlert.alertWithMessageText 'No Roku device found.',
                            defaultButton: 'Retry Search',
                          alternateButton: 'Enter Manually',
                              otherButton: 'Exit',
                informativeTextWithFormat: (first_manual_attempt ? 'Roku IP address:' : 'The address entered was not correctly formatted.')
      roku_service = NSTextField.alloc.initWithFrame NSMakeRect(0, 0, 200, 24)
      roku_service.setStringValue '192.168.'
      alert.setAccessoryView roku_service

      result = alert.runModal
      if result == NSAlertDefaultReturn
        search @timeout
        return
      elsif result == NSAlertAlternateReturn
        roku_service.validateEditing
        begin
          self.roku_service = roku_service.stringValue
        rescue
          # invalid manual entry
          first_manual_attempt = false
        end
        if first_manual_attempt
          # valid manual entry
          @delegate.roku_device_found
          return
        end
      else
        NSApp.terminate self
        return
      end
    end
  end

  # stop listening socket when a device is found || timeout reached
  def search_stop
    fail "RokuDiscovery.search_stop called during invalid state: #{@state}." if @state != :searching
    @socket.close
    @state = :idle
  end

  def udpSocket(socket, didReceiveData: data, fromAddress: address, withFilterContext: _filter)
    return if roku_service

    message = NSString.alloc.initWithData data, encoding: NSUTF8StringEncoding
    return unless message

    lines = message.gsub("\r\n", "\n").split "\n"
    return unless lines.grep(/HTTP\/[0-9](\.[0-9]) 200 OK/).count == 1
    return unless lines.grep(/ST: ROKU:ECP/i).count == 1

    service_line = lines.grep /LOCATION: HTTP:\/\//i
    if service_line.count == 1
      service_line = service_line[0]
      found_service = service_line.match /HTTP:\/\/.+$/i
      self.roku_service = found_service[0] if found_service && found_service.length == 1
    end
    return unless roku_service

    id_line = lines.grep /USN: UUID:ROKU:ECP:*/i
    if id_line.count == 1
      id_line = id_line[0]
      found_id = id_line.match /[^:]+$/
      self.roku_id = found_id[0] if found_id && found_id.length == 1
    end

    @socket.close
    @state = :idle
    @delegate.roku_device_found
  end

end


text:
<!doctype html>

<meta charset="utf-8">
<title>Page Not Found – Marco Mengoli's Blog</title>
<meta name="description" content="Page not found. Your pixels are in another canvas.">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Page Not Found">
<meta property="og:description" content="Page not found. Your pixels are in another canvas.">
<meta property="og:url" content="/404.html">
<meta property="og:site_name" content="Marco Mengoli's Blog">

<link rel="canonical" href="/404.html">
<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Marco Mengoli's Blog Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>

<link rel="stylesheet" href="/assets/css/main.css">
<link rel="stylesheet" href="/assets/css/jquery.mmenu.all.css">
<link rel="stylesheet" href="/assets/css/jquery.floating-social-share.min.css">

<link href="//fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic" rel="stylesheet" type="text/css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="/favicon.ico">

<link rel="shortcut icon" href="/favicon.png">

<link rel="apple-touch-icon-precomposed" href="/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/images/apple-touch-icon-144x144-precomposed.png">

 Marco Mengoli's Blog

About

Categories

.NET core

Computer vision

Go Programming

Programming Python

Tutorial

Tags

Home

Page Not Found

Home

Tags

Categories

.NET core

Computer vision

Go Programming

Programming Python

Tutorial

About

Sorry, but the page you were trying to view does not exist — perhaps you can try searching for it below.

<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.3/cookieconsent.min.css" />

    © 2016 Marco Mengoli. Powered by Jekyll using the Neo-HPSTR Theme.


text:
"use strict";
let auth = require("../security/auth");

/**
 * A data store for navigation items
 */
class NavigationItemStore {

    list() {
        return [{
            name: "Drug search",
            icon: "medkit",
            route: "/drugs"
        }, {
            name: "Manufacturer search",
            icon: "hospital-o",
            route: "/manufacturers"
        }, {
            name: "My saved drugs",
            icon: "star",
            route: "/myDrugs"
        }, {
            name: "My profile",
            icon: "user",
            route: "/myProfile"
        }, {
            name: "Logout",
            icon: "sign-out",
            action: () => auth.logout()
        }];
    }
}

module.exports = NavigationItemStore;


text:
<?php

namespace Workshop;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

class ContainerFactory
{
    private $cacheDir;
    private $configDir;

    public function __construct($cacheDir, $configDir)
    {
        $this->cacheDir = $cacheDir;
        $this->configDir = $configDir;
    }

    /**
     * @return ContainerInterface
     */
    public function create($loadCallable)
    {
        $container = new ContainerBuilder();

        // create a service definition file loader for .yml files
        $loader = new YamlFileLoader($container, new FileLocator($this->configDir));

        // allow the client to load service definition files, add compiler passes, etc.
        $loadCallable($container, $loader);

        // compile the container (i.e. run compiler passes)
        $container->compile();

        // dump the container as executable PHP code
        $dumpedContainerFile = $this->cacheDir . '/container.php';
        $dumper = new PhpDumper($container);
        file_put_contents(
            $dumpedContainerFile,
            $dumper->dump()
        );

        // load the container
        require $dumpedContainerFile;

        return new \ProjectServiceContainer();
    }
}


text:
package com.baidu.openrasp.plugin.checker.policy.server;

import com.baidu.openrasp.HookHandler;
import com.baidu.openrasp.cloud.model.ErrorType;
import com.baidu.openrasp.cloud.utils.CloudUtils;
import com.baidu.openrasp.plugin.checker.CheckParameter;
import com.baidu.openrasp.plugin.info.EventInfo;
import com.baidu.openrasp.plugin.info.SecurityPolicyInfo;
import com.baidu.openrasp.tool.model.ApplicationModel;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *   * @Description: 检测JBoss的JMX Console配置
 *   * @author anyang
 *   * @date 2018/7/30 15:51
 */
public class JBossSecurityChecker extends ServerPolicyChecker {
    public JBossSecurityChecker() {
        super();
    }

    public JBossSecurityChecker(boolean canBlock) {
        super(canBlock);
    }

    private static final String JBOSS_SECURITY_CHECK_ERROR = "jboss_security_check_error";
    private static final String SECURITY_DOMAIN = "security-domain";
    private static final String SECURITY_CONSTRAINT = "security-constraint";
    private static final String WEB_RESOURCE_COLLECTION = "web-resource-collection";
    private static final String WEB_RESOURCE_NAME = "web-resource-name";
    private static final String URL_PATTERN = "url-pattern";
    private static final String AUTH_CONSTRAINT = "auth-constraint";
    private static final String[] WEB_RESOURCE_NAME_VALUES = new String[]{"htmladaptor"};
    private static final String[] URL_PATTERN_VALUES = new String[]{"/*"};
    public static final Logger LOGGER = Logger.getLogger(HookHandler.class.getName());

    @Override
    public void checkServer(CheckParameter checkParameter, List<EventInfo> infos) {
        String jbossBaseDir = System.getProperty("jboss.home.dir");
        String serverVersion = ApplicationModel.getVersion();
        if (serverVersion != null) {
            String jbossWebXmlPath = "deploy" + File.separator + "jmx-console.war" + File.separator + "WEB-INF" + File.separator + "jboss-web.xml";
            String webXmlPath = "deploy" + File.separator + "jmx-console.war" + File.separator + "WEB-INF" + File.separator + "web.xml";
            if (serverVersion.startsWith("4") || serverVersion.startsWith("5")) {
                jbossWebXmlPath = jbossBaseDir + File.separator + "server" + File.separator + "default" + File.separator + jbossWebXmlPath;
                webXmlPath = jbossBaseDir + File.separator + "server" + File.separator + "default" + File.separator + webXmlPath;
            } else if (serverVersion.startsWith("6")) {
                jbossWebXmlPath = jbossBaseDir + File.separator + "common" + File.separator + jbossWebXmlPath;
                webXmlPath = jbossBaseDir + File.separator + "common" + File.separator + webXmlPath;
            } else {
                String message = JBOSS_SECURITY_CHECK_ERROR + " :" + "JBoss supported 4.x-6.x";
                int errorCode = ErrorType.PLUGIN_ERROR.getCode();
                LOGGER.error(CloudUtils.getExceptionObject(message, errorCode));
            }
            checkJBossWebXml(jbossWebXmlPath, infos);
            checkWebXml(webXmlPath, infos);
        }
    }

    /**
     * 检测JBoss的JBoss-web.xml是否配置security-domain
     */
    public void checkJBossWebXml(String path, List<EventInfo> infos) {
        Document root = getXMLDocument(path);
        if (root != null) {
            NodeList list = root.getElementsByTagName(SECURITY_DOMAIN);
            if (list.getLength() == 0) {
                handleError(SECURITY_DOMAIN, path, infos,SECURITY_DOMAIN);
            }
        }
    }

    /**
     * 检测JBoss的web.xml是否配置security-constraint
     */
    public void checkWebXml(String path, List<EventInfo> infos) {
        Document root = getXMLDocument(path);
        if (root != null) {
            NodeList list = root.getElementsByTagName(SECURITY_CONSTRAINT);
            if (list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    Element element = (Element) list.item(i);
                    NodeList webResource = element.getElementsByTagName(WEB_RESOURCE_COLLECTION);
                    if (webResource.getLength() > 0) {
                        Element subElement = (Element) list.item(i);
                        checkXmlElement(subElement, WEB_RESOURCE_NAME, Arrays.asList(WEB_RESOURCE_NAME_VALUES), infos, path,WEB_RESOURCE_NAME);
                        checkXmlElement(subElement, URL_PATTERN, Arrays.asList(URL_PATTERN_VALUES), infos, path,URL_PATTERN);
                    } else {
                        handleError(WEB_RESOURCE_COLLECTION, path, infos,WEB_RESOURCE_COLLECTION);
                    }

                    NodeList authConstraint = element.getElementsByTagName("auth-constraint");
                    if (authConstraint.getLength() == 0) {
                        handleError(AUTH_CONSTRAINT, path, infos,AUTH_CONSTRAINT);
                    }
                }

            } else {
                handleError(SECURITY_CONSTRAINT, path, infos,SECURITY_CONSTRAINT);
            }
        }
    }

    /**
     * 获取xml文件的root元素
     */
    public Document getXMLDocument(String path) {
        File file = new File(path);
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.parse(file);
        } catch (Exception e) {
            String message = JBOSS_SECURITY_CHECK_ERROR + ": " + e.getMessage();
            int errorCode = ErrorType.PLUGIN_ERROR.getCode();
            LOGGER.error(CloudUtils.getExceptionObject(message, errorCode), e);
        }
        return null;
    }

    public void checkXmlElement(Element element, String key, List<String> reference, List<EventInfo> infos, String path, String type) {
        NodeList list = element.getElementsByTagName(key);
        if (list.getLength() > 0) {
            for (int i = 0; i < list.getLength(); i++) {
                if (!reference.contains(list.item(i).getTextContent().toLowerCase())) {
                    handleError(key, path, infos, type);
                }
            }
        } else {
            handleError(key, path, infos, type);
        }
    }

    public void handleError(String tagName, String path, List<EventInfo> infos, String type) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("config_file", path);
        params.put("type",type);
        infos.add(new SecurityPolicyInfo(SecurityPolicyInfo.Type.JBOSS_JMX_CONSOLE, "JBoss security baseline - Auth constraint " +
                "for /jmx-console/HTMLAdaptor is not enabled in " + path + "(" + tagName + " is missing or wrong)", true, params));
    }
}


text:
using System;
using System.Collections;
using MbUnit.Core.Invokers;

namespace MbUnit.Core.Collections
{
    /// <summary>
    /// A collection of elements of type IRunInvoker
    /// </summary>
    public sealed class RunInvokerCollection: System.Collections.CollectionBase
    {
        /// <summary>
        /// Initializes a new empty instance of the IRunInvokerCollection class.
        /// </summary>
        public RunInvokerCollection()
        {}

        /// <summary>
        /// Adds an instance of type IRunInvoker to the end of this IRunInvokerCollection.
        /// </summary>
        /// <param name="value">
        /// The IRunInvoker to be added to the end of this IRunInvokerCollection.
        /// </param>
        public void Add(IRunInvoker value)
        {
            if (value == null)
                throw new ArgumentNullException("value");
            this.List.Add(value);
        }

        /// <summary>
        /// Determines whether a specfic IRunInvoker value is in this IRunInvokerCollection.
        /// </summary>
        /// <param name="value">
        /// The IRunInvoker value to locate in this IRunInvokerCollection.
        /// </param>
        /// <returns>
        /// true if value is found in this IRunInvokerCollection;
        /// false otherwise.
        /// </returns>
        public bool Contains(IRunInvoker value)
        {
            return this.List.Contains(value);
        }

        /// <summary>
        /// Gets or sets the IRunInvoker at the given index in this IRunInvokerCollection.
        /// </summary>
        public IRunInvoker this[int index]
        {
            get
            {
                return (IRunInvoker) this.List[index];
            }
        }

        /// <summary>
        /// Removes the first occurrence of a specific IRunInvoker from this IRunInvokerCollection.
        /// </summary>
        /// <param name="value">
        /// The IRunInvoker value to remove from this IRunInvokerCollection.
        /// </param>
        public void Remove(IRunInvoker value)
        {
            this.List.Remove(value);
        }

        /// <summary>
        /// Type-specific enumeration class, used by IRunInvokerCollection.GetEnumerator.
        /// </summary>
        public sealed class Enumerator: System.Collections.IEnumerator
        {
            private System.Collections.IEnumerator wrapped;

            public Enumerator(RunInvokerCollection collection)
            {
                this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
            }

            public IRunInvoker Current
            {
                get
                {
                    return (IRunInvoker) (this.wrapped.Current);
                }
            }

            object System.Collections.IEnumerator.Current
            {
                get
                {
                    return (IRunInvoker) (this.wrapped.Current);
                }
            }

            public bool MoveNext()
            {
                return this.wrapped.MoveNext();
            }

            public void Reset()
            {
                this.wrapped.Reset();
            }
        }

        /// <summary>
        /// Returns an enumerator that can iterate through the elements of this IRunInvokerCollection.
        /// </summary>
        /// <returns>
        /// An object that implements System.Collections.IEnumerator.
        /// </returns>
        public new RunInvokerCollection.Enumerator GetEnumerator()
        {
            return new RunInvokerCollection.Enumerator(this);
        }
    }

}


text:
from typing import Any

from marshmallow import fields
from marshmallow.decorators import post_load

from azure.ai.ml._restclient.v2020_09_01_dataplanepreview.models import (
    BatchJob,
    DataVersion,
    UriFileJobInput,
    UriFolderJobInput,
)
from azure.ai.ml._schema.core.fields import ArmStr, NestedField
from azure.ai.ml._schema.core.schema import PathAwareSchema
from azure.ai.ml._schema.core.schema_meta import PatchedSchemaMeta
from azure.ai.ml.constants import AssetTypes
from azure.ai.ml.constants._common import AzureMLResourceType
from azure.ai.ml.constants._endpoint import EndpointYamlFields
from azure.ai.ml.entities import ComputeConfiguration
from azure.ai.ml.entities._inputs_outputs import Input

from .batch_deployment_settings import BatchRetrySettingsSchema
from .compute_binding import ComputeBindingSchema

class OutputDataSchema(metaclass=PatchedSchemaMeta):
    datastore_id = ArmStr(azureml_type=AzureMLResourceType.DATASTORE)
    path = fields.Str()

    @post_load
    def make(self, data: Any, **kwargs: Any) -> Any:
        return DataVersion(**data)

class BatchJobSchema(PathAwareSchema):
    compute = NestedField(ComputeBindingSchema)
    dataset = fields.Str()
    error_threshold = fields.Int()
    input_data = fields.Dict()
    mini_batch_size = fields.Int()
    name = fields.Str(data_key="job_name")
    output_data = fields.Dict()
    output_dataset = NestedField(OutputDataSchema)
    output_file_name = fields.Str()
    retry_settings = NestedField(BatchRetrySettingsSchema)

    @post_load
    def make(self, data: Any, **kwargs: Any) -> Any:
        if data.get(EndpointYamlFields.BATCH_JOB_INPUT_DATA, None):
            for key, input_data in data[EndpointYamlFields.BATCH_JOB_INPUT_DATA].items():
                if isinstance(input_data, Input):
                    if input_data.type == AssetTypes.URI_FILE:
                        data[EndpointYamlFields.BATCH_JOB_INPUT_DATA][key] = UriFileJobInput(uri=input_data.path)
                    elif input_data.type == AssetTypes.URI_FOLDER:
                        data[EndpointYamlFields.BATCH_JOB_INPUT_DATA][key] = UriFolderJobInput(uri=input_data.path)
        if data.get(EndpointYamlFields.COMPUTE, None):
            data[EndpointYamlFields.COMPUTE] = ComputeConfiguration(
                **data[EndpointYamlFields.COMPUTE]
            )._to_rest_object()

        if data.get(EndpointYamlFields.RETRY_SETTINGS, None):
            data[EndpointYamlFields.RETRY_SETTINGS] = data[EndpointYamlFields.RETRY_SETTINGS]._to_rest_object()

        return BatchJob(**data)


text:
/**
 * This ThoughtProcess is responsible for keeping the robot
 * on a straight line as it attempts the straight line
 * speed challenge
 * http://piwars.org/2015-competition/challenges/straight-line-speed-test/
 *
 * Currently we make use of the SenseHAT, via the RTIMU library, to
 * determine our current heading.
 */

#include <cstdint>
#include <cstddef>
#include <unistd.h>

#include "ThoughtProcess.h"
#include "ThoughtProcess_StraightLine.h"
#include "SensorRTIMU.h"
#include "PiWars.h"
#include "Powertrain.h"
#include <iostream>

namespace PiWars {

ThoughtProcess_StraightLine::ThoughtProcess_StraightLine(PiWars *robot) : ThoughtProcess(robot), _rtimu(new SensorRTIMU()) {
}

ThoughtProcess_StraightLine::~ThoughtProcess_StraightLine() {
  if(_rtimu) {
    _rtimu->disable();
    delete _rtimu;
    _rtimu = nullptr;
  }
}

const std::string &ThoughtProcess_StraightLine::name() {
  static std::string name("StraightLine");

  return name;
}

bool ThoughtProcess_StraightLine::available() {
  return _rtimu->exists();
}

bool ThoughtProcess_StraightLine::prepare() {
  return _rtimu->enable();
}

void ThoughtProcess_StraightLine::run(std::atomic<bool> &running) {
  float lastPowerLeft = -1.0, lastPowerRight = -1.0;
  float pitch, roll, yaw;

  std::chrono::time_point<std::chrono::system_clock> start, end;
  float heading;

  // Let the sensor settle down
  std::this_thread::sleep_for (std::chrono::seconds(2));

  // Get the heading that we want to maintain
  _rtimu->fusion(pitch, roll, yaw);
  heading = yaw + 180;

  std::cout << __func__ << "Selected heading " << heading << std::endl;

  // Start the motors off at 50% so we don't pull too much current when we jump to 66%
  // IMPROVE: Update the PowerTrain, or Arduino code, to handle this ramp up
  // automatically
  robot()->powertrain()->setPower(0.50, 0.50);

  // Note the start time
  start = std::chrono::system_clock::now();

  while(running.load())
  {
    float currentHeading, offset, powerLeft, powerRight;

    // Get the heading that we want to maintain
    _rtimu->fusion(pitch, roll, yaw);

    // Work out our offset versus the heading
    currentHeading = yaw + 180;

    // What's the difference?
    offset = currentHeading - heading;

    // Output the heading, followed by a line feed so the next heading will overwrite it
    std::cout << "Current heading " << currentHeading << " offset " << offset << "\r" << std::flush;

    // Very simple checks
    if(offset > 0) {
      // We want to move left slightly
      powerLeft = 0.55;
      powerRight = 0.66;
    }
    else if(offset < 0) {
      // Move right
      powerLeft = 0.66;
      powerRight = 0.55;
    }
    else {
      // straight on!
      powerLeft = 0.66;
      powerRight = 0.66;
    }

    // Set the motors
    if(lastPowerLeft != powerLeft || lastPowerRight != powerRight) {
      robot()->powertrain()->setPower(powerLeft, powerRight);
      //std::cerr << "setting power to " << powerLeft << ":" << powerRight << std::endl;
      lastPowerLeft = powerLeft;
      lastPowerRight = powerRight;
    }

    // Let the robot actually move
    std::this_thread::sleep_for (std::chrono::milliseconds(10));

    end = std::chrono::system_clock::now();
    std::chrono::duration<float> duration = end - start;

    // Travel forwards for 5 seconds
    // IMPROVE: Need to measure distance travelled, or use the range sensor to detect the end
    if(duration.count() >= 5.0){
      break;
    }
  }

  // and stop the robot
  robot()->powertrain()->stop();

  // Release the sensor
  _rtimu->disable();
}

}


text:
<!DOCTYPE html>

      <meta charset="utf-8">
      <title>Tony Lanera</title>
      <link rel=stylesheet href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
      <link rel=icon href="img/favicon.ico">

      <link href="https://fonts.googleapis.com/css?family=Didact+Gothic" rel="stylesheet">
      <link rel="stylesheet" href="mainSite.css" media="screen" charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes" />

Tony Lanera CSM

Front End JavaScript Developer

Client Focus, Collaborative, Process Improvements

                  I am a Front End JavaScript developer with Project Management. I thrive in an innovative and collaborative environment that focuses on creative solutions. Providing exceptional customer satisfaction and striving for process improvement is a main objective of my career.

Coding Examples

                 The subsites and code examples below were developed as part of the
                 Udemy: The Web Developer Bootcamp course.
                 A demo, github code repository and ReadMe file is available for each example.
                 This site and subsite are built on the AWS platform: Route53 for Domain Management,
                 EC2 for Computing. The Yelp Camp site uses SES for emailing password reset.

Memory Game (React)

                        Built in React. Utilizing an object to store the various card colors.
                        The app includes a custom built array shuffle algorithm,
                        which allows for randomly assigning a color to each card.

                        Demo

                        Code

Yelp Camp

                        A full stack application built on Node.js, Express and MongoDB. RESTful Routing was implemented using Method-Override.
                        Responsive styling is done with BootstrapJS. The site allows user generated content and comments.

                        Demo

                        Code

The Color Game

                        This is my first site developed with HTML5, CSS3 and JavaScript.
                        The goal of this exercise is to gain understanding and practice utilizing the DOM and Javascript.

                        Demo

                        Code

Key Board Play Site

                        KeyBoardPlay site displays circles in random location and plays a corresponding sound when pressing a key between "a" to "z".
                        Libaries used are paperjs for graphics and animation and howler.js for sound play.
                        The site is based on patatap.com.

                        Demo

                        Code

&copy 2018 Created by Tony Lanera


text:
package org.jboss.pnc.datastore.repositories.internal;

import org.jboss.pnc.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface ProductSpringRepository extends JpaRepository<Product, Integer>, JpaSpecificationExecutor<Product> {
}


text:
package de.vogella.jersey.first;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

// Plain old Java Object it does not extend as class or implements
// an interface

// The class registers its methods for the HTTP GET request using the @GET annotation.
// Using the @Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML.

// The browser requests per default the HTML MIME type.

//Sets the path to base URL + /hello
@Path("/hello")
public class Hello {

  // This method is called if TEXT_PLAIN is request
  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public String sayPlainTextHello() {
    return "Hello Jersey";
  }

  // This method is called if XML is request
  @GET
  @Produces(MediaType.TEXT_XML)
  public String sayXMLHello() {
    return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
  }

  // This method is called if HTML is request
  @GET
  @Produces(MediaType.TEXT_HTML)
  public String sayHtmlHello() {
    return " " + "<title>" + "Hello Jersey" + "</title>"
        + "
" + "Hello Jersey" + "
" + " ";
  }

}


text:
export default {
    en: {
        enabledHeading: 'Enabled',
        homepage: 'Homepage',
        imagesHeading: 'Images',
        nameHeading: 'Name',
        new: 'New',
        newModalTitle: 'Add new product',
        noResults: 'No results',
        sectionsHeading: 'Sections',
        stockHeading: 'Stock',
        skuHeading: 'SKU',
        title: 'Products',
        upload: 'Upload',
        uploadModalTitle: 'Products Upload'
    },
    es: {
        enabledHeading: 'Activar',
        homepage: 'Página Principal',
        imagesHeading: 'Imagenes',
        nameHeading: 'Nombre',
        new: 'Nuevo',
        newModalTitle: 'Crear nuevo Producto',
        noResults: 'No existen Productos momentaneamente',
        sectionsHeading: 'Secciones',
        stockHeading: 'Stock',
        skuHeading: 'SKU',
        title: 'Productos',
        upload: 'Upload',
        uploadModalTitle: 'Upload de Productos'
    }
};


text:
using Log.Core;
using Spring.Data.NHibernate.Generic.Support;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Log
{
    public class SampleDao:HibernateDaoSupport,ISampleDao
    {
        public string GetTime()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public string GetDate()
        {
            return Session.GetNamedQuery("SampleDao_GetDate")
                .UniqueResult<DateTime>().ToString();
        }
    }
}