text:
// Copyright 2021. thzll <tanghuizll@gmail.com>. All rights reserved.
// Use of this source code is governed by a MIT license that can
// be found in the LICENSE file.

package component

const (
	KeyF1         = "<F1>"
	KeyF2         = "<F2>"
	KeyF3         = "<F3>"
	KeyF4         = "<F4>"
	KeyF5         = "<F5>"
	KeyF6         = "<F6>"
	KeyF7         = "<F7>"
	KeyF8         = "<F8>"
	KeyF9         = "<F9>"
	KeyF10        = "<F10>"
	KeyF11        = "<F11>"
	KeyF12        = "<F12>"
	KeyInsert     = "<Insert>"
	KeyDelete     = "<Delete>"
	KeyHome       = "<Home>"
	KeyEnd        = "<End>"
	KeyPgup       = "<PageUp>"
	KeyPgdn       = "<PageDown>"
	KeyArrowUp    = "<Up>"
	KeyArrowDown  = "<Down>"
	KeyArrowLeft  = "<Left>"
	KeyArrowRight = "<Right>"

	KeyCtrlSpace  = "<C-<Space>>" //  KeyCtrl2  KeyCtrlTilde
	KeyCtrlA      = "<C-a>"
	KeyCtrlB      = "<C-b>"
	KeyCtrlC      = "<C-c>"
	KeyCtrlD      = "<C-d>"
	KeyCtrlE      = "<C-e>"
	KeyCtrlF      = "<C-f>"
	KeyCtrlG      = "<C-g>"
	KeyBackspace  = "<C-<Backspace>>" //  KeyCtrlH
	KeyTab        = "<Tab>"           //  KeyCtrlI
	KeyCtrlJ      = "<C-j>"
	KeyCtrlK      = "<C-k>"
	KeyCtrlL      = "<C-l>"
	KeyEnter      = "<Enter>" //  KeyCtrlM
	KeyCtrlN      = "<C-n>"
	KeyCtrlO      = "<C-o>"
	KeyCtrlP      = "<C-p>"
	KeyCtrlQ      = "<C-q>"
	KeyCtrlR      = "<C-r>"
	KeyCtrlS      = "<C-s>"
	KeyCtrlT      = "<C-t>"
	KeyCtrlU      = "<C-u>"
	KeyCtrlV      = "<C-v>"
	KeyCtrlW      = "<C-w>"
	KeyCtrlX      = "<C-x>"
	KeyCtrlY      = "<C-y>"
	KeyCtrlZ      = "<C-z>"
	KeyEsc        = "<Escape>" //  KeyCtrlLsqBracket  KeyCtrl3
	KeyCtrl4      = "<C-4>"    //  KeyCtrlBackslash
	KeyCtrl5      = "<C-5>"    //  KeyCtrlRsqBracket
	KeyCtrl6      = "<C-6>"
	KeyCtrl7      = "<C-7>" //  KeyCtrlSlash  KeyCtrlUnderscore
	KeySpace      = "<Space>"
	KeyBackspace2 = "<Backspace>" //  KeyCtrl8:
)

func isCharKey(keyId string) bool {
	if len(keyId) > 0 && keyId[0] != '<' {
		return true
	}
	return false
}

repository: thzll/termuix

repo_name: thzll/termuix


text:
@Article{pmid9510461,
  Author="Andersen, J. B.  and Szumlanski, C.  and Weinshilboum, R. M.  and Schmiegelow, K. ",
  Title="{{P}harmacokinetics, dose adjustments, and 6-mercaptopurine/methotrexate drug interactions in two patients with thiopurine methyltransferase deficiency}",
  Journal="Acta Paediatr.",
  Year="1998",
  Volume="87",
  Number="1",
  Pages="108--111",
  Month="Jan"
}

license: MIT

repository: larmcr/px

license_type: permissive

repo_name: larmcr/px

branch_name: refs/heads/master

extension: bib


text:
SRCREV_edk2           ?= "fff6d81270b57ee786ea18ad74f43149b9f03494"
SRCREV_edk2-platforms ?= "982212662c71b6c734b7578526071d6b78da3bcc"

require edk2-firmware.inc

repository: Nuvoton-Israel/openbmc

repo_name: Nuvoton-Israel/openbmc

branch_name: refs/heads/npcm-master

gha_license_id: NOASSERTION

gha_language: Python

extension: bb


text:
require ti-xdctools.inc

PV = "3_20_08_88"

SRC_URI[xdcbin.md5sum] = "068447e935adb54f0cacf0e294a281f9"
SRC_URI[xdcbin.sha256sum] = "a4616fae3cc2a9f46b5b4377bb57af7f7932297cda210a6cbcc5f942256db196"

repository: mrchapp/arago-oe-dev

repo_name: mrchapp/arago-oe-dev


text:
package rbac

import (
	"context"

	"github.com/go-gorp/gorp"
	"github.com/lib/pq"
	"github.com/rockbears/log"

	"github.com/ovh/cds/engine/api/database/gorpmapping"
	"github.com/ovh/cds/engine/gorpmapper"
	"github.com/ovh/cds/sdk"
)

func insertRBACProject(ctx context.Context, db gorpmapper.SqlExecutorWithTx, rbacProject *rbacProject) error {
	if err := gorpmapping.InsertAndSign(ctx, db, rbacProject); err != nil {
		return err
	}

	for _, projectKey := range rbacProject.RBACProjectKeys {
		if err := insertRBACProjectKey(ctx, db, rbacProject.ID, projectKey); err != nil {
			return err
		}
	}
	for _, rbUserID := range rbacProject.RBACUsersIDs {
		if err := insertRBACProjectUser(ctx, db, rbacProject.ID, rbUserID); err != nil {
			return err
		}
	}
	for _, rbGroupID := range rbacProject.RBACGroupsIDs {
		if err := insertRBACProjectGroup(ctx, db, rbacProject.ID, rbGroupID); err != nil {
			return err
		}
	}
	return nil
}

func insertRBACProjectKey(ctx context.Context, db gorpmapper.SqlExecutorWithTx, rbacParentID int64, projectKey string) error {
	rpk := rbacProjectKey{
		RbacProjectID: rbacParentID,
		ProjectKey:    projectKey,
	}
	if err := gorpmapping.InsertAndSign(ctx, db, &rpk); err != nil {
		return err
	}
	return nil
}

func insertRBACProjectUser(ctx context.Context, db gorpmapper.SqlExecutorWithTx, rbacProjectID int64, userID string) error {
	rgu := rbacProjectUser{
		RbacProjectID:     rbacProjectID,
		RbacProjectUserID: userID,
	}
	if err := gorpmapping.InsertAndSign(ctx, db, &rgu); err != nil {
		return err
	}
	return nil
}

func insertRBACProjectGroup(ctx context.Context, db gorpmapper.SqlExecutorWithTx, rbacProjectID int64, groupID int64) error {
	rgu := rbacProjectGroup{
		RbacProjectID:      rbacProjectID,
		RbacProjectGroupID: groupID,
	}
	if err := gorpmapping.InsertAndSign(ctx, db, &rgu); err != nil {
		return err
	}
	return nil
}

func getAllRBACProjects(ctx context.Context, db gorp.SqlExecutor, q gorpmapping.Query) ([]rbacProject, error) {
	var rbacProjects []rbacProject
	if err := gorpmapping.GetAll(ctx, db, q, &rbacProjects); err != nil {
		return nil, err
	}

	projectsFiltered := make([]rbacProject, 0, len(rbacProjects))
	for _, projectDatas := range rbacProjects {
		isValid, err := gorpmapping.CheckSignature(projectDatas, projectDatas.Signature)
		if err != nil {
			return nil, sdk.WrapError(err, "error when checking signature for rbac_project %d", projectDatas.ID)
		}
		if !isValid {
			log.Error(ctx, "rbac.getAllRBACProjects> rbac_project %d data corrupted", projectDatas.ID)
			continue
		}
		projectsFiltered = append(projectsFiltered, projectDatas)
	}
	return projectsFiltered, nil
}

func loadRBACProjectsByRoleAndIDs(ctx context.Context, db gorp.SqlExecutor, role string, rbacProjectIDs []int64) ([]rbacProject, error) {
	q := gorpmapping.NewQuery(`SELECT * from rbac_project WHERE role = $1 AND id = ANY($2)`).Args(role, pq.Int64Array(rbacProjectIDs))
	return getAllRBACProjects(ctx, db, q)
}

func loadRBACProjectByRoleAndPublic(ctx context.Context, db gorp.SqlExecutor, role string) ([]rbacProject, error) {
	q := gorpmapping.NewQuery(`SELECT * from rbac_project WHERE role = $1 AND all_users = true`).Args(role)
	return getAllRBACProjects(ctx, db, q)
}

repository: ovh/cds

repo_name: ovh/cds

gha_language: Go

extension: go


text:
SUMMARY = "Jupyter Widgets for Jupyter Notebook"
LICENSE = "BSD-3-Clause"
LIC_FILES_CHKSUM = "file://LICENSE;md5=20a40995a0b2f0ae1f2a70d2dc995bbf"

SRC_URI[sha256sum] = "bfa01945156f2bfd9a386bfc51b54ec5bfa26006d26bb75e5351e226f870fafb"
PYPI_PACKAGE = "widgetsnbextension"
inherit pypi setuptools3

DEPENDS += " \
    ${PYTHON_PN}-jupyter-packaging-native \
    "

RDEPENDS:${PN} += " \
    ${PYTHON_PN}-notebook \
    "

FILES:${PN} += " \
    ${datadir}/jupyter/nbextensions/* \
    ${datadir}/etc/jupyter/* \
    ${prefix}/etc/jupyter/nbconfig/notebook.d/widgetsnbextension.json \
    "

repository: Xilinx/meta-jupyter

repo_name: Xilinx/meta-jupyter

gha_license_id: MIT

gha_language: BitBake


text:
SUMMARY = "XSL stylesheets for the yelp help browser"
LICENSE = "LGPLv2.1 & GPLv2"
LIC_FILES_CHKSUM = " \
    file://COPYING;md5=3e2bad3c5e3990988f9fa1bc5785b147 \
    file://COPYING.GPL;md5=eb723b61539feef013de476e68b5c50a \
    file://COPYING.LGPL;md5=a6f89e2100d9b6cdffcea4f398e37343 \
"

inherit gnomebase gettext

DEPENDS += "libxml2 itstool-native"

SRC_URI[archive.md5sum] = "f8c4e777aee8b055251c333ef48a0cd0"
SRC_URI[archive.sha256sum] = "e8063aee67d1df634f3d062f1c28130b2dabb3c0c66396b1af90388f34e14ee2"

RDEPENDS_${PN} += "libxml2 itstool"

BBCLASSEXTEND = "native"


text:
package handler

import (
	"net/http"

	"github.com/sithumonline/quick-note/config"
)

// GetHealth godoc
// @Summary Returns health of the service
// @Router /healthz [get]
func GetHealth(w http.ResponseWriter, r *http.Request) {
	RespondWithJSON(w, http.StatusOK, "Go Note up and running version: "+config.GetEnv("quick-note.VERSION"))
}

repository: sithumonline/quick-note

repo_name: sithumonline/quick-note

branch_name: refs/heads/main


text:
package cmd

import (
	"fmt"
	"net/url"
	"os"
	"strconv"

	flags "github.com/jessevdk/go-flags"
	"github.com/mitchellh/cli"
	v1auth "github.com/nerdalize/nerd/nerd/client/auth/v1"
	v1payload "github.com/nerdalize/nerd/nerd/client/auth/v1/payload"
	"github.com/nerdalize/nerd/nerd/conf"
	"github.com/nerdalize/nerd/nerd/oauth"
	"github.com/nerdalize/nerd/pkg/kubeconfig"
	"github.com/nerdalize/nerd/pkg/populator"
	"github.com/pkg/errors"
)

//ClusterList command
type ClusterList struct {
	*command
}

//ClusterListFactory creates the command
func ClusterListFactory(ui cli.Ui) cli.CommandFactory {
	cmd := &ClusterList{}
	cmd.command = createCommand(ui, cmd.Execute, cmd.Description, cmd.Usage, cmd, &ConfOpts{}, flags.None, "nerd cluster list")
	t, ok := cmd.advancedOpts.(*ConfOpts)
	if !ok {
		return nil
	}
	t.ConfigFile = cmd.setConfig
	t.SessionFile = cmd.setSession
	return func() (cli.Command, error) {
		return cmd, nil
	}
}

//Execute runs the command
func (cmd *ClusterList) Execute(args []string) (err error) {
	// TODO move this part to another func
	env := os.Getenv("NERD_ENV")
	if env == "staging" {
		cmd.config = conf.StagingDefaults()
	} else if env == "dev" {
		cmd.config = conf.DevDefaults(os.Getenv("NERD_API_ENDPOINT"))
	}

	if len(args) > 0 {
		return errShowUsage(MessageNoArgumentRequired)
	}
	authbase, err := url.Parse(cmd.config.Auth.APIEndpoint)
	if err != nil {
		return errors.Wrapf(err, "auth endpoint '%v' is not a valid URL", cmd.config.Auth.APIEndpoint)
	}
	authOpsClient := v1auth.NewOpsClient(v1auth.OpsClientConfig{
		Base:   authbase,
		Logger: cmd.Logger(),
	})
	client := v1auth.NewClient(v1auth.ClientConfig{
		Base:               authbase,
		OAuthTokenProvider: oauth.NewConfigProvider(authOpsClient, cmd.config.Auth.SecureClientID, cmd.config.Auth.SecureClientSecret, cmd.session),
		Logger:             cmd.Logger(),
	})

	kubeConfig, err := kubeconfig.GetPath(cmd.globalOpts.KubeConfig)
	if err != nil {
		return err
	}
	conf, err := populator.ReadConfigOrNew(kubeConfig)
	if err != nil {
		return err
	}

	clusters, err := client.ListClusters()
	if err != nil {
		return renderClientError(err, "failed to get your cluster list")
	}

	// TODO Add role (admin, team member ...)
	hdr := []string{"ID", "CLUSTER NAME", "VCPUS", "MEMORY", "PODS"}
	rows := [][]string{}
	for x, cluster := range clusters.Clusters {
		if cluster.Name == "" {
			cluster.Name = cluster.ShortName
		}
		if clusterMatchContext(cluster, conf.CurrentContext) {
			cluster.Name = fmt.Sprintf("%s *", cluster.Name)
		}
		id := strconv.Itoa(x + 1)
		rows = append(rows, []string{
			id,
			cluster.Name,
			fmt.Sprintf("%.1f/%.1f", cluster.Usage.CPU, cluster.Capacity.CPU),
			fmt.Sprintf("%s/%s", renderFloatToMem(cluster.Usage.Memory), renderFloatToMem(cluster.Capacity.Memory)),
			fmt.Sprintf("%d/%d", cluster.Usage.Pods, cluster.Capacity.Pods),
		})
	}

	return cmd.out.Table(hdr, rows)
}

func renderFloatToMem(n float64) string {
	return fmt.Sprintf("%.1f", n/1000/1000/1000)
}

func clusterMatchContext(cluster *v1payload.GetClusterOutput, context string) bool {
	if len(cluster.Namespaces) > 0 {
		for x := range cluster.Namespaces {
			if fmt.Sprintf("%s-%s-%s", populator.Prefix, cluster.ShortName, cluster.Namespaces[x].Name) == context {
				return true
			}
		}
	}
	return fmt.Sprintf("%s-%s", populator.Prefix, cluster.ShortName) == context
}

// Description returns long-form help text
func (cmd *ClusterList) Description() string { return cmd.Synopsis() }

// Synopsis returns a one-line
func (cmd *ClusterList) Synopsis() string { return "Returns an overview of your clusters." }

// Usage shows usage
func (cmd *ClusterList) Usage() string { return "nerd cluster list [OPTIONS]" }


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

  Program:   Robarts Visualization Toolkit
  Module:    $RCSfile: vtkCompactSupportRBFTransform.h,v $
  Language:  C++
  Date:      $Date: 2007/05/04 14:34:34 $
  Version:   $Revision: 1.1 $

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// .NAME vtkCompactSupportRBFTransform - a nonlinear warp transformation
// .SECTION Description
// vtkCompactSupportRBFTransform describes a nonlinear warp transform defined
// by a set of source and target landmarks. Any point on the mesh close to a
// source landmark will be moved to a place close to the corresponding target
// landmark. The points in between are interpolated smoothly using
// Bookstein's Thin Plate Spline algorithm.
// .SECTION Caveats
// 1) The inverse transform is calculated using an iterative method,
// and is several times more expensive than the forward transform.
// 2) Whenever you add, subtract, or set points you must call Modified()
// on the vtkPoints object, or the transformation might not update.
// 3) Collinear point configurations (except those that lie in the XY plane)
// result in an unstable transformation.
// .SECTION see also
// vtkGridTransform vtkGeneralTransform

#ifndef __vtkCompactSupportRBFTransform_h
#define __vtkCompactSupportRBFTransform_h

#include "vtkRobartsRegistrationExport.h"

#include "vtkWarpTransform.h"

#define VTK_RBF_CUSTOM 0
#define VTK_RBF_CS3D0C 1
#define VTK_RBF_CS3D2C 2
#define VTK_RBF_CS3D4C 3

class vtkRobartsRegistrationExport vtkCompactSupportRBFTransform : public vtkWarpTransform
{
public:
  vtkTypeMacro(vtkCompactSupportRBFTransform, vtkWarpTransform);
  void PrintSelf(ostream& os, vtkIndent indent);
  static vtkCompactSupportRBFTransform* New();

  // Description:
  // Specify the 'stiffness' of the spline. The default is 1.0.
  vtkGetMacro(Sigma, double);
  vtkSetMacro(Sigma, double);

  // Description:
  // Specify the radial basis function to use.  The default is
  // R2LogR which is what most people use as the thin plate spline.
  void SetBasis(int basis);
  vtkGetMacro(Basis, int);
  void SetBasisToCS3D0C() { this->SetBasis(VTK_RBF_CS3D0C); };
  void SetBasisToCS3D2C() { this->SetBasis(VTK_RBF_CS3D2C); };
  void SetBasisToCS3D4C() { this->SetBasis(VTK_RBF_CS3D4C); };
  const char* GetBasisAsString();

  //BTX
  // Description:
  // Set the radial basis function to a custom function.  You must
  // supply both the function and its derivative with respect to r.
  void SetBasisFunction(double (*U)(double r))
  {
    if (this->BasisFunction == U) { return; }
    this->SetBasis(VTK_RBF_CUSTOM);
    this->BasisFunction = U;
    this->Modified();
  };
  void SetBasisDerivative(double (*dUdr)(double r, double& dU))
  {
    this->BasisDerivative = dUdr;
    this->Modified();
  };
  //ETX

  // Description:
  // Set the source landmarks for the warp.  If you add or change the
  // vtkPoints object, you must call Modified() on it or the transformation
  // might not update.
  void SetSourceLandmarks(vtkPoints* source);
  vtkGetObjectMacro(SourceLandmarks, vtkPoints);

  // Description:
  // Set the target landmarks for the warp.  If you add or change the
  // vtkPoints object, you must call Modified() on it or the transformation
  // might not update.
  void SetTargetLandmarks(vtkPoints* target);
  vtkGetObjectMacro(TargetLandmarks, vtkPoints);

  // Description:
  // Get the MTime.
  vtkMTimeType GetMTime();

  // Description:
  // Make another transform of the same type.
  vtkAbstractTransform* MakeTransform();

protected:
  vtkCompactSupportRBFTransform();
  ~vtkCompactSupportRBFTransform();

  // Description:
  // Prepare the transformation for application.
  void InternalUpdate();

  // Description:
  // This method does no type checking, use DeepCopy instead.
  void InternalDeepCopy(vtkAbstractTransform* transform);

  void ForwardTransformPoint(const float in[3], float out[3]);
  void ForwardTransformPoint(const double in[3], double out[3]);

  void ForwardTransformDerivative(const float in[3], float out[3],
                                  float derivative[3][3]);
  void ForwardTransformDerivative(const double in[3], double out[3],
                                  double derivative[3][3]);

  double Sigma;
  vtkPoints* SourceLandmarks;
  vtkPoints* TargetLandmarks;

  //BTX
  // the radial basis function to use
  double (*BasisFunction)(double r);
  double (*BasisDerivative)(double r, double& dUdr);
  //ETX
  int Basis;

  int NumberOfPoints;
  double** MatrixW;
private:
  vtkCompactSupportRBFTransform(const vtkCompactSupportRBFTransform&);  // Not implemented.
  void operator=(const vtkCompactSupportRBFTransform&);  // Not implemented.
};

#endif

repository: jcfr/RobartsVTK

repo_name: jcfr/RobartsVTK

extension: h


text:
@inproceedings{pimentel-etal-2021-non,
    title = "How (Non-)Optimal is the Lexicon?",
    author = "Pimentel, Tiago  and
      Nikkarinen, Irene  and
      Mahowald, Kyle  and
      Cotterell, Ryan  and
      Blasi, Dami{\'a}n",
    booktitle = "Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
    month = jun,
    year = "2021",
    address = "Online",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2021.naacl-main.350",
    doi = "10.18653/v1/2021.naacl-main.350",
    pages = "4426--4438"
}

repository: rycolab/website

repo_name: rycolab/website


text:
require xorg-driver-video.inc
PE = "1"

DESCRIPTION = "X.Org X server -- S3 ViRGE display driver"
SRC_URI[archive.md5sum] = "4a293047e988d4ea1e9e96d3b5793f43"
SRC_URI[archive.sha256sum] = "9094115621ef73c957cf887332717ec727c751959b1059e3d00fbfe0114a978a"


text:
DESCRIPTION = "Log::Log4perl - Log4j implementation for Perl"
SECTION = "libs"
LICENSE = "Artistic|GPLv1+"
PR = "r6"

SRC_URI = "http://search.cpan.org/CPAN/authors/id/M/MS/MSCHILLI/Log-Log4perl-${PV}.tar.gz"

S = "${WORKDIR}/Log-Log4perl-${PV}"

inherit cpan

BBCLASSEXTEND="native"

SRC_URI[md5sum] = "a7bda690ec0ad0bed457fa525e28034a"
SRC_URI[sha256sum] = "ffac9cd4a6fbc59618bf4e79c389a927491a81b448528278e010a190e2483544"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020 Authors of Cilium

package install

import (
	"context"
	"encoding/json"
	"fmt"
)

type azureVersionValidation struct{}

func (m *azureVersionValidation) Name() string {
	return "az-binary"
}

func (m *azureVersionValidation) Check(ctx context.Context, k *K8sInstaller) error {
	_, err := k.azExec("version")
	if err != nil {
		return err
	}

	k.Log("✅ Detected az binary")

	return nil
}

type accountInfo struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type azurePrincipalOutput struct {
	AppID       string `json:"appId"`
	DisplayName string `json:"displayName"`
	Name        string `json:"name"`
	Password    string `json:"password"`
	Tenant      string `json:"tenant"`
}

type aksClusterInfo struct {
	NodeResourceGroup string `json:"nodeResourceGroup"`
}

func (k *K8sInstaller) aksSetup(ctx context.Context) error {
	if err := k.azureRetrieveSubscriptionID(ctx); err != nil {
		return err
	}

	if err := k.azureRetrieveAKSNodeResourceGroup(ctx); err != nil {
		return err
	}

	return k.azureSetupServicePrincipal(ctx)
}

// Retrieve subscription ID to pass to other `az` commands:
// - From user-given subscription name, if provided.
// - From default subscription, if not provided.
//
// Optionally, it might be provided via the `--azure-subscription-id` flag,
// which is currently a hidden feature not advertised to the users and intended
// for development purposes, notably CI usage where `az` CLI is not available.
// If provided, it bypasses auto-detection and `--azure-subscription`.
func (k *K8sInstaller) azureRetrieveSubscriptionID(ctx context.Context) error {
	if k.params.Azure.SubscriptionID != "" {
		k.Log("ℹ Using manually configured Azure subscription ID %s", k.params.Azure.SubscriptionID)
		return nil
	}

	args := []string{"account", "show"}
	if k.params.Azure.SubscriptionName != "" {
		args = append(args, "--subscription", k.params.Azure.SubscriptionName)
	}
	bytes, err := k.azExec(args...)
	if err != nil {
		return err
	}

	ai := accountInfo{}
	if err := json.Unmarshal(bytes, &ai); err != nil {
		return fmt.Errorf("unable to unmarshal az output: %w", err)
	}

	k.Log("✅ Derived Azure subscription ID %s from subscription %s", ai.ID, ai.Name)
	k.params.Azure.SubscriptionID = ai.ID

	return nil
}

// `az aks create` requires an existing resource group in which to create a
// new AKS cluster, but a single resource group may hold multiple AKS clusters.
//
// Internally, AKS creates an intermediate resource group (named
// `MC_{RG_name}_{cluster_name}_{location}`) to regroup all AKS nodes for
// this cluster. See Azure documentation for more details:
// https://docs.microsoft.com/en-us/azure/aks/faq#why-are-two-resource-groups-created-with-aks
//
// The CLI installs itself into this intermediate resource group, and thus
// derives it from the user-given resource group and cluster name using
// `az aks show`.
//
// Optionally, it might be provided via the `--azure-node-resource-group` flag,
// which is currently a hidden feature not advertised to the users and intended
// for development purposes, notably CI usage where `az` CLI is not available.
// If provided, it bypasses the requirement for `--azure-resource-group`.
func (k *K8sInstaller) azureRetrieveAKSNodeResourceGroup(ctx context.Context) error {
	if k.params.Azure.AKSNodeResourceGroup != "" {
		k.Log("ℹ Using manually configured Azure AKS node resource group %s", k.params.Azure.AKSNodeResourceGroup)
		return nil
	}

	if k.params.Azure.ResourceGroupName == "" {
		k.Log("❌ Azure resource group is required, please specify --azure-resource-group")
		return fmt.Errorf("missing Azure resource group name")
	}

	bytes, err := k.azExec("aks", "show", "--subscription", k.params.Azure.SubscriptionID, "--resource-group", k.params.Azure.ResourceGroupName, "--name", k.params.ClusterName)
	if err != nil {
		return err
	}

	clusterInfo := aksClusterInfo{}
	if err := json.Unmarshal(bytes, &clusterInfo); err != nil {
		return fmt.Errorf("unable to unmarshal az output: %w", err)
	}

	k.Log("✅ Derived Azure AKS node resource group %s from resource group %s", clusterInfo.NodeResourceGroup, k.params.Azure.ResourceGroupName)
	k.params.Azure.AKSNodeResourceGroup = clusterInfo.NodeResourceGroup

	return nil
}

// Use Service Principal provided by user if available, otherwise automatically create a new Service Principal
// and restrict its scope to the strict minimum (i.e. the AKS node resource group in which Cilium will be installed).
//
// We create a new Service Principal for each installation by design:
// - Having dedicated SPs with minimal privileges over their own AKS clusters is more secure.
// - Even if we wanted to re-use pre-existing SPs, it would not be possible:
// 	- The ClientSecret (password) of an SP is only displayed at creation time, and cannot be
// 		retrieved at a later time.
// 	- Specifying a name (--name) when creating a SP creates a new SP on first call, but then
// 		overwrites the existing SP with a new ClientSecret on subsequent calls, which potentially
// 		interferes with existing installations.
func (k *K8sInstaller) azureSetupServicePrincipal(ctx context.Context) error {
	if k.params.Azure.TenantID == "" && k.params.Azure.ClientID == "" && k.params.Azure.ClientSecret == "" {
		k.Log("🚀 Creating Azure Service Principal for Cilium operator...")
		bytes, err := k.azExec("ad", "sp", "create-for-rbac", "--scopes", "/subscriptions/"+k.params.Azure.SubscriptionID+"/resourceGroups/"+k.params.Azure.AKSNodeResourceGroup)
		if err != nil {
			return err
		}

		p := azurePrincipalOutput{}
		if err := json.Unmarshal(bytes, &p); err != nil {
			return fmt.Errorf("unable to unmarshal az output: %w", err)
		}

		k.Log("✅ Created Azure Service Principal for Cilium operator with App ID %s and Tenant ID %s", p.AppID, p.Tenant)
		k.Log("ℹ Its RBAC privileges are restricted to the AKS node resource group %s", k.params.Azure.AKSNodeResourceGroup)
		k.params.Azure.TenantID = p.Tenant
		k.params.Azure.ClientID = p.AppID
		k.params.Azure.ClientSecret = p.Password
	} else {
		if k.params.Azure.TenantID == "" || k.params.Azure.ClientID == "" || k.params.Azure.ClientSecret == "" {
			k.Log(`❌ All three parameters are required for using an existing Azure Service Principal:
   - Tenant ID (--azure-tenant-id)
   - Client ID (--azure-client-id)
   - Client Secret (--azure-client-secret)`)
			return fmt.Errorf("missing at least one of Azure Service Principal parameters")
		}

		k.Log("ℹ Using manually configured Azure Service Principal for Cilium operator with App ID %s and Tenant ID %s",
			k.params.Azure.ClientID, k.params.Azure.TenantID)
	}

	return nil
}

// Wrapper function forcing `az` output to be in JSON for unmarshalling purposes
// and suppressing warnings from preview, deprecated and experimental commands.
func (k *K8sInstaller) azExec(args ...string) ([]byte, error) {
	args = append(args, "--output", "json", "--only-show-errors")
	return k.Exec("az", args...)
}

repository: wazir-ahmed/cilium-cli

repo_name: wazir-ahmed/cilium-cli


text:
package grpcinfo

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io/ioutil"

	dpb "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
	"github.com/prasek/protoer/proto"
	"google.golang.org/grpc"
)

type Registry interface {
	Load(srv *grpc.Server) error
	LoadFile(file string) error
	GetMethodInfo(fqn string) MethodInfo
}

type MethodInfo interface {
	Service() Info
	Method() Info
}

type Info interface {
	GetExtension(ext interface{}) (interface{}, error)
	GetBoolExtension(ext interface{}, ifnotset bool) bool
}

func NewRegistry() Registry {
	return &registry{
		method: make(map[string]*methodInfo),
	}
}

type registry struct {
	method map[string]*methodInfo
}

func (r *registry) Load(svr *grpc.Server) error {

	for name, info := range svr.GetServiceInfo() {
		file, ok := info.Metadata.(string)
		if !ok {
			return fmt.Errorf("Service %q has unexpected metadata. Expecting a string, got %v", name, info.Metadata)
		}
		err := r.LoadFile(file)
		if err != nil {
			return err
		}
	}
	return nil
}

func (r *registry) LoadFile(file string) error {
	fd, err := loadFileDescriptorProto(file)
	if err != nil {
		return err
	}

	pkg := fd.GetPackage()

	merge := func(a, b string) string {
		if a == "" {
			return b
		} else {
			return a + "." + b
		}
	}

	for i := range fd.Service {
		svc := fd.Service[i]
		fqn := merge(pkg, svc.GetName())
		for j := range svc.Method {
			m := svc.Method[j]
			fqnMethod := fmt.Sprintf("/%s/%s", fqn, m.GetName())
			r.method[fqnMethod] = &methodInfo{service: &service{proto: svc}, method: &method{proto: m}}
		}
	}
	return nil
}

func (r *registry) GetMethodInfo(fqn string) MethodInfo {
	return r.method[fqn]
}

type methodInfo struct {
	service *service
	method  *method
}

func (mi *methodInfo) Service() Info {
	return mi.service
}
func (mi *methodInfo) Method() Info {
	return mi.method
}

type service struct {
	proto *dpb.ServiceDescriptorProto
}

func (s *service) GetExtension(ext interface{}) (interface{}, error) {
	return proto.GetExtension(s.proto.GetOptions(), ext)
}

func (s *service) GetBoolExtension(ext interface{}, ifnotset bool) bool {
	return proto.GetBoolExtension(s.proto.GetOptions(), ext, ifnotset)
}

type method struct {
	proto *dpb.MethodDescriptorProto
}

func (m *method) GetExtension(ext interface{}) (interface{}, error) {
	return proto.GetExtension(m.proto.GetOptions(), ext)
}

func (m *method) GetBoolExtension(ext interface{}, ifnotset bool) bool {
	return proto.GetBoolExtension(m.proto.GetOptions(), ext, ifnotset)
}

// loadFileDescriptor loads a registered descriptor and decodes it. If the given
// name cannot be loaded but is a known standard name, an alias will be tried by the proto,
// so the standard files can be loaded even if linked against older "known bad"
// versions of packages.
func loadFileDescriptorProto(file string) (*dpb.FileDescriptorProto, error) {
	fdb := proto.FileDescriptor(file)
	if fdb == nil {
		return nil, fmt.Errorf("Missing file descriptor %s.", file)
	}

	fd, err := decodeFileDescriptorProto(file, fdb)
	if err != nil {
		return nil, err
	}

	// the file descriptor may have been laoded with an alias,
	// so we ensure the specified name to ensure it can be linked.
	fd.Name = proto.String(file)

	return fd, nil
}

// decodeFileDescriptorProto decodes the bytes of a registered file descriptor.
// Registered file descriptors are first "proto encoded" (e.g. binary format
// for the descriptor protos) and then gzipped. So this function gunzips and
// then unmarshals into a descriptor proto.
func decodeFileDescriptorProto(element string, fdb []byte) (*dpb.FileDescriptorProto, error) {
	raw, err := decompress(fdb)
	if err != nil {
		return nil, fmt.Errorf("failed to decompress %q descriptor: %v", element, err)
	}
	fd := dpb.FileDescriptorProto{}
	if err := proto.Unmarshal(raw, &fd); err != nil {
		return nil, fmt.Errorf("bad descriptor for %q: %v", element, err)
	}
	return &fd, nil
}

func decompress(b []byte) ([]byte, error) {
	r, err := gzip.NewReader(bytes.NewReader(b))
	if err != nil {
		return nil, fmt.Errorf("bad gzipped descriptor: %v", err)
	}
	out, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, fmt.Errorf("bad gzipped descriptor: %v", err)
	}
	return out, nil
}

repository: prasek/go-grpc-info

repo_name: prasek/go-grpc-info


text:
@article{greenman2022multi,
  title={Multi-fidelity prediction of molecular optical peaks with deep learning},
  author={Greenman, Kevin P. and Green, William H. and G{\'{o}}mez-Bombarelli, Rafael},
  journal={Chemical Science},
  year={2022},
  volume={13},
  issue={4},
  pages={1152-1162},
  publisher={The Royal Society of Chemistry},
  doi={10.1039/D1SC05677H},
  url={http://dx.doi.org/10.1039/D1SC05677H}
}

repository: learningmatter-mit/uvvisml

repo_name: learningmatter-mit/uvvisml

gha_language: Jupyter Notebook


text:
package disabledashboard

// Copyright 2019 Google LLC
//
// 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
//
// 	https://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.

import (
	"context"
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/googlecloudplatform/security-response-automation/clients/stubs"
	"github.com/googlecloudplatform/security-response-automation/services"
	"google.golang.org/api/container/v1"
)

func TestDisableDashboard(t *testing.T) {
	ctx := context.Background()

	test := []struct {
		name            string
		expectedRequest *container.SetAddonsConfigRequest
	}{
		{
			name: "disable dashboard",
			expectedRequest: &container.SetAddonsConfigRequest{
				AddonsConfig: &container.AddonsConfig{
					KubernetesDashboard: &container.KubernetesDashboard{
						Disabled: true,
					},
				},
			},
		},
	}
	for _, tt := range test {
		svcs, contStub := disableDashboardSetup()
		values := &Values{
			ProjectID: "project-test",
			Zone:      "us-central1-a",
			ClusterID: "test-cluster",
		}
		if err := Execute(ctx, values, &Services{
			Container: svcs.Container,
			Resource:  svcs.Resource,
			Logger:    svcs.Logger,
		}); err != nil {
			t.Errorf("%s test failed want:%q", tt.name, err)
		}
		if diff := cmp.Diff(contStub.UpdatedAddonsConfig, tt.expectedRequest); diff != "" {
			t.Errorf("%v failed\n exp:%v\n got:%v", tt.name, tt.expectedRequest, contStub.UpdatedAddonsConfig)
		}
	}
}

func disableDashboardSetup() (*services.Global, *stubs.ContainerStub) {
	loggerStub := &stubs.LoggerStub{}
	log := services.NewLogger(loggerStub)
	contStub := &stubs.ContainerStub{}
	cont := services.NewContainer(contStub)
	crmStub := &stubs.ResourceManagerStub{}
	storageStub := &stubs.StorageStub{}
	resource := services.NewResource(crmStub, storageStub)
	return &services.Global{Logger: log, Resource: resource, Container: cont}, contStub
}


text:
package vocabulary

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"sync"
	"time"

	"github.com/saeub/hubullu/pkg/translation"
)

// Vocabulary is a collection of vocabulary items.
// Can be serialized to JSON.
type Vocabulary struct {
	filename string
	Items    []Item `json:"items"`
}

// Item represents a single translation and all of its backtranslations for a word.
// Can be serialized to JSON.
type Item struct {
	Word             string                    `json:"word"`
	Translation      translation.Translation   `json:"translation"`
	Backtranslations []translation.Translation `json:"backtranslations"`
}

// Add adds an item to the vocabulary.
func (v *Vocabulary) Add(item Item) {
	v.Items = append(v.Items, item)
}

// NewVocabulary returns a new, empty vocabulary without an associated filename.
func NewVocabulary() *Vocabulary {
	return &Vocabulary{}
}

func getArbitraryFilename() string {
	base := time.Now().Format("vocab_060102-150405")
	suffix := 0
	extension := ".json"
	var fn string
	for {
		if suffix == 0 {
			fn = fmt.Sprintf("%s", base) + extension
		} else {
			fn = fmt.Sprintf("%s_%d", base, suffix) + extension
		}
		_, err := os.Stat(fn)
		if os.IsNotExist(err) {
			break
		}
		suffix++
	}
	return fn
}

// LoadVocabulary loads a vocabulary from a JSON file at the specified location.
// If the file does not exist, it will create it and return an empty vocabulary.
func LoadVocabulary(filename string) (*Vocabulary, error) {
	vocab := Vocabulary{
		filename: filename,
	}
	data, err := ioutil.ReadFile(filename)
	if os.IsNotExist(err) {
		// try to create the file so the name won't get stolen
		_, err = os.Create(filename)
		return &vocab, err
	}
	if err != nil {
		return &vocab, err
	}
	err = json.Unmarshal(data, &vocab)
	return &vocab, err
}

// Save saves the vocabulary to a JSON file.
// If the vocabulary does not already have a filename associated with it,
// an arbitrary non-existing one in the working directory will be picked.
func (v *Vocabulary) Save() error {
	if v.filename == "" {
		v.filename = getArbitraryFilename()
	}
	data, err := json.Marshal(*v)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(v.filename, data, 0644)
	return err
}

// CreateItems fetches translations and backtranslations
// using the given translator and compiles them in vocabulary items.
func CreateItems(word string, t translation.Translator) (items []Item, err error) {
	trls, err := t.Translate(word)
	if err != nil {
		return nil, err
	}
	var wg sync.WaitGroup
	for i, trl := range trls {
		item := Item{
			Word:        word,
			Translation: trl,
		}
		items = append(items, item)
		wg.Add(1)
		go func(i int) {
			text := items[i].Translation.Text
			if text != "" {
				items[i].Backtranslations, _ = t.Translate(text)
			}
			wg.Done()
		}(i)
	}
	wg.Wait()
	return items, nil
}

repository: saeub/hubullu

repo_name: saeub/hubullu


text:
# Copyright (C) 2014, O.S. Systems Software Ltda. All Rights Reserved
# Released under the MIT license (see meta-openembedded layer's COPYING.MIT)

TESSERACT_LANG = "tel"

require tesseract-lang.inc

SRC_URI[md5sum] = "349d203ef88864eab8d1201672ca84be"
SRC_URI[sha256sum] = "f36af3d5ca9f8ff6e606485fe5db835f96b42e7d2380ac5d61af6b41827834fd"

branch_name: refs/heads/fido


text:
# Copyright (C) 2018 蒼時弦也 <contact@frost.tw>
# Released under the MIT license (see COPYING.MIT for the terms)

LICENSE = "APACHE"
LIC_FILES_CHKSUM = "file://LICENSE.md;md5=e3fc50a88d0a364313df4b21ef20c29e"

PR = "r0"

BPV = "0.4.0"
PV = "${BPV}"
SRCREV = "80f737100d8413e59db215a4a9ad84dcb896ceab"

S = "${WORKDIR}/git"

SRC_URI = " \
    git://github.com/tamashii-io/tamashii-agent.git \
    "

inherit rubygems

BBCLASSEXTEND = "native"

RDEPENDS_${PN} += " \
     tamashii-common \
     tamashii-client \
     tamashii-config \
     tamashii-hookable \
     websocket-driver \
     nio4r \
     pi-piper \
     tamashii-mfrc522 \
     tamashii-nfc \
     i2c \
     aasm \
     concurrent-ruby \
"

repository: tamashii-io/meta-tamashii

repo_name: tamashii-io/meta-tamashii


text:
#include <fstream>
#include <iostream>

#include "CDHMM.h"
#include "Kmeans.h"

void Continuous_Density_Hidden_Markov_Model::Search_State_Sequence(int event_index, int state_index, int state_sequence[], vector<int*> gamma){
	state_sequence[event_index] = state_index;
	for (int t = event_index - 1; t >= 0; t--){
		state_sequence[t] = gamma[t + 1][state_sequence[t + 1]];
	}
}

bool Continuous_Density_Hidden_Markov_Model::Access_State(int previous_state_index, int state_index){
	int i = previous_state_index;
	int j = state_index;

	return (type_model == "ergodic") || (j - i == 0) || (j - i == 1);
}

double Continuous_Density_Hidden_Markov_Model::Backward_Algorithm(int length_event, vector<int> state, double **beta, double likelihood[]){
	double log_likelihood = 0;

	for (int t = length_event - 1; t >= 0; t--){
		double scale = 0;

		if (t == length_event - 1){
			for (int i = 0; i < state.size(); i++){
				scale += (beta[t][i] = (type_model == "ergodic" || i == state.size() - 1));
			}
		}
		else{
			for (int i = 0; i < state.size(); i++){
				double sum = 0;

				for (int j = 0; j < state.size(); j++){
					int k = state[i];
					int l = state[j];

					if (state_connection[k].find(l) != state_connection[k].end() && Access_State(i, j)){
						sum += transition_probability[k].find(l)->second * likelihood[(t + 1) * number_states + l] * beta[t + 1][j];
					}
				}
				scale += (beta[t][i] = sum);
			}
		}
		if (!_finite(log(scale = 1 / scale)) || _isnan(log(scale))){
			cerr << "[Backward Algorithm], scale[" << t << "]: " << scale << endl;
		}
		else {
			// log_likelihood += log(scale);
		}
		for (int i = 0; i < state.size(); i++) {
			beta[t][i] *= scale;
		}
	}
	return -log_likelihood;
}
double Continuous_Density_Hidden_Markov_Model::Forward_Algorithm(int length_event, vector<int> state, double **alpha, double likelihood[]){
	double log_likelihood = 0;

	for (int t = 0; t < length_event; t++){
		double scale = 0;

		if (t == 0){
			for (int i = 0; i < state.size(); i++) {
				int j = state[i];

				scale += (alpha[t][i] = (type_model == "ergodic" || i == 0) * initial_probability[j] * likelihood[t * number_states + j]);
			}
		}
		else{
			for (int i = 0; i < state.size(); i++){
				double sum = 0;

				for (int j = 0; j < state.size(); j++){
					int k = state[i];
					int l = state[j];

					if (state_connection[l].find(k) != state_connection[l].end() && Access_State(j, i)){
						sum += alpha[t - 1][j] * transition_probability[l].find(k)->second;
					}
				}
				scale += (alpha[t][i] = sum * likelihood[t * number_states + state[i]]);
			}
		}

		// scale
		if (!_finite(log(scale = 1 / scale)) || _isnan(log(scale))){
			cerr << "[Forward Algorithm], scale[" << t << "]: " << scale << endl;
		}
		else {
			log_likelihood += log(scale);
		}
		for (int i = 0; i < state.size(); i++) {
			alpha[t][i] *= scale;
		}
	}
	return -log_likelihood;
}

Continuous_Density_Hidden_Markov_Model::Continuous_Density_Hidden_Markov_Model(string path) {
	ifstream file(path);

	if (file.is_open()) {
		file >> type_covariance;
		file >> type_model;
		file >> dimension_event;
		file >> number_gaussian_components;
		file >> number_states;

		state_connection = new set<int>[number_states];
		initial_probability = new double[number_states];
		transition_probability = new unordered_map<int, double>[number_states];
		valid_transition = new unordered_map<int, double>[number_states];

		for (int i = 0, size; i < number_states; i++) {
			file >> size;

			for (int j = 0, id; j < size; j++) {
				file >> id;
				state_connection[i].insert(id);
			}
		}
		for (int i = 0; i < number_states; i++) {
			string label;

			if (i == 0) {
				getline(file, label);
			}
			getline(file, label);
			state_label.push_back(label);
		}

		for (int i = 0; i < number_states; i++) {
			file >> initial_probability[i];
		}
		for (int i = 0, size; i < number_states; i++) {
			file >> size;

			for (int j = 0, id; j < size; j++) {
				double value;

				file >> id >> value;
				transition_probability[i].insert(pair<int, double>(id, value));
			}
		}
		for (int i = 0; i < number_states; i++) {
			valid_transition[i].clear();
		}
		for (int i = 0; i < number_states; i++) {
			for (auto p = transition_probability[i].begin(); p != transition_probability[i].end(); p++) {
				if (p->second) {
					valid_transition[p->first].insert(pair<int, double>(i, p->second));
				}
			}
		}

		if (!file.eof()) {
			GMM = new Gaussian_Mixture_Model*[number_states];

			for (int i = 0; i < number_states; i++) {
				GMM[i] = new Gaussian_Mixture_Model(type_covariance, dimension_event, number_gaussian_components);
			}

			for (int i = 0; i < number_states; i++) {
				for (int j = 0; j < number_gaussian_components; j++) {
					file >> GMM[i]->weight[j];
				}
			}

			for (int i = 0; i < number_states; i++) {
				for (int j = 0; j < number_gaussian_components; j++) {
					for (int k = 0; k < dimension_event; k++) {
						file >> GMM[i]->mean[j][k];
					}
				}
			}
			for (int i = 0; i < number_states; i++) {
				for (int j = 0; j < number_gaussian_components; j++) {
					for (int k = 0; k < dimension_event; k++) {
						if (type_covariance == "diagonal") {
							file >> GMM[i]->diagonal_covariance[j][k];
						}
						else {
							for (int l = 0; l < dimension_event; l++) {
								file >> GMM[i]->covariance[j][k][l];
							}
						}
					}
				}
			}
		}
		file.close();
	}
	else {
		cerr << "[Continuous_Density_Hidden_Markov_Model], " + path + " not found" << endl;
	}
}
Continuous_Density_Hidden_Markov_Model::Continuous_Density_Hidden_Markov_Model(set<int> state_connection[], string type_model, vector<string> state_label, int dimension_event, int number_states, string type_covariance, int number_gaussian_components){
	this->type_covariance	= type_covariance;
	this->type_model		= type_model;
	this->dimension_event	= dimension_event;
	this->number_states		= number_states;
	this->state_connection	= new set<int>[number_states];

	for (int i = 0; i < number_states; i++){
		this->state_connection[i].insert(state_connection[i].begin(), state_connection[i].end());
		this->state_label.push_back(state_label[i]);
	}
	initial_probability		= new double[number_states];
	transition_probability	= new unordered_map<int, double>[number_states];
	valid_transition		= new unordered_map<int, double>[number_states];

	if (number_gaussian_components) {
		GMM = new Gaussian_Mixture_Model*[number_states];

		for (int i = 0; i < number_states; i++) {
			GMM[i] = new Gaussian_Mixture_Model(type_covariance, dimension_event, number_gaussian_components);
		}
		this->number_gaussian_components = number_gaussian_components;
	}
}
Continuous_Density_Hidden_Markov_Model::~Continuous_Density_Hidden_Markov_Model(){
	if (GMM) {
		for (int i = 0; i < number_states; i++) {
			delete GMM[i];
		}
		delete GMM;
	}
	if(initial_probability)		delete[] initial_probability;
	if(state_connection)		delete[] state_connection;
	if(transition_probability)	delete[] transition_probability;
	if(valid_transition)		delete[] valid_transition;
}

void Continuous_Density_Hidden_Markov_Model::Initialize(int number_events, int length_event[], double **_event){
	for (int i = 0; i < number_states; i++){
		initial_probability[i] = 1.0 / number_states;
		transition_probability[i].clear();
	}

	if (GMM) {
		int number_data = 0;

		double **data;

		KMeans kmeans = KMeans(dimension_event, number_gaussian_components);

		for (int i = 0; i < number_events; i++){
			number_data += length_event[i];
		}
		data = new double*[number_data];

		for (int i = 0, index = 0; i < number_events; i++){
			for (int j = 0; j < length_event[i]; j++){
				data[index++] = &_event[i][j * dimension_event];
			}
		}

		kmeans.Initialize(number_data, data);
		while (kmeans.Cluster(number_data, data));

		for (int i = 0; i < this->number_states; i++) {
			for (int j = 0; j < number_gaussian_components; j++) {
				for (int k = 0; k < dimension_event; k++) {
					if (type_covariance == "diagonal") {
						GMM[i]->diagonal_covariance[j][k] = 1;
					}
					else {
						for (int l = 0; l < dimension_event; l++) {
							GMM[i]->covariance[j][k][l] = (k == l);
						}
					}
					GMM[i]->mean[j][k] = kmeans.centroid[j][k];
				}
				GMM[i]->weight[j] = 1.0 / number_gaussian_components;
			}
		}
		delete[] data;
	}
}
void Continuous_Density_Hidden_Markov_Model::Save_Model(string path) {
	ofstream file(path);

	file << type_covariance << endl;
	file << type_model << endl;
	file << dimension_event << endl;
	file << number_gaussian_components << endl;
	file << number_states << endl;

	for (int i = 0; i < number_states; i++) {
		file << state_connection[i].size() << endl;

		for (auto c = state_connection[i].begin(); c != state_connection[i].end(); c++) {
			file << *c << endl;
		}
	}
	for (int i = 0; i < number_states; i++) {
		file << state_label[i] << endl;
	}

	for (int i = 0; i < number_states; i++) {
		file << initial_probability[i] << endl;
	}
	for (int i = 0; i < number_states; i++) {
		file << transition_probability[i].size() << endl;

		for (auto p = transition_probability[i].begin(); p != transition_probability[i].end(); p++) {
			file << p->first << endl << p->second << endl;
		}
	}

	if (GMM) {
		for (int i = 0; i < number_states; i++) {
			for (int j = 0; j < number_gaussian_components; j++) {
				file << GMM[i]->weight[j] << endl;
			}
		}
		for (int i = 0; i < number_states; i++) {
			for (int j = 0; j < number_gaussian_components; j++) {
				for (int k = 0; k < dimension_event; k++) {
					file << GMM[i]->mean[j][k] << endl;
				}
			}
		}
		for (int i = 0; i < number_states; i++) {
			for (int j = 0; j < number_gaussian_components; j++) {
				for (int k = 0; k < dimension_event; k++) {
					if (type_covariance == "diagonal") {
						file << GMM[i]->diagonal_covariance[j][k] << endl;
					}
					else {
						for (int l = 0; l < dimension_event; l++) {
							file << GMM[i]->covariance[j][k][l] << endl;
						}
					}
				}
			}
		}
	}
	file.close();
}

double Continuous_Density_Hidden_Markov_Model::Baum_Welch_Algorithm(int number_events, int length_event[], vector<int> state[], double minimum_variance, double **_event){
	double log_likelihood = 0;

	double *new_initial_probability = new double[this->number_states];
	unordered_map<int, double> *new_transition_probability[2] = { new unordered_map<int, double>[this->number_states], new unordered_map<int, double>[this->number_states] };

	double ***new_weight = new double**[number_gaussian_components];
	double ****new_mean = new double***[number_gaussian_components];
	double ****new_diagonal_covariance = 0;
	double *****new_covariance = 0;

	for (int i = 0; i < this->number_states; i++){
		new_initial_probability[i] = 0;
	}
	for (int h = 0; h < number_events; h++){
		for (int i = 0; i < state[h].size(); i++){
			for (int j = 0; j < state[h].size(); j++){
				auto p = transition_probability[state[h][i]].find(state[h][j]);

				if (p == transition_probability[state[h][i]].end()){
					transition_probability[state[h][i]].insert(pair<int, double>(state[h][j], 1.0 / this->number_states));
				}
				if ((p = new_transition_probability[0][state[h][i]].find(state[h][j])) == new_transition_probability[0][state[h][i]].end()){
					new_transition_probability[0][state[h][i]].insert(pair<int, double>(state[h][j], 0));
				}
				if ((p = new_transition_probability[1][state[h][i]].find(state[h][j])) == new_transition_probability[1][state[h][i]].end()){
					new_transition_probability[1][state[h][i]].insert(pair<int, double>(state[h][j], 0));
				}
			}
		}
	}

	for (int j = 0; j < number_gaussian_components; j++){
		new_mean[j] = new double**[this->number_states];
		new_weight[j] = new double*[this->number_states];

		for (int i = 0; i < this->number_states; i++){
			new_mean[j][i] = new double*[dimension_event];
			new_weight[j][i] = new double[2];

			for (int k = 0; k < dimension_event; k++){
				new_mean[j][i][k] = new double[2];
				new_mean[j][i][k][0] = 0;
				new_mean[j][i][k][1] = 0;
			}
			new_weight[j][i][0] = 0;
			new_weight[j][i][1] = 0;
		}
	}

	if (type_covariance == "diagonal"){
		new_diagonal_covariance = new double***[number_gaussian_components];

		for (int i = 0; i < number_gaussian_components; i++){
			new_diagonal_covariance[i] = new double**[this->number_states];

			for (int j = 0; j < this->number_states; j++){
				new_diagonal_covariance[i][j] = new double*[dimension_event];

				for (int k = 0; k < dimension_event; k++){
					new_diagonal_covariance[i][j][k] = new double[2];
					new_diagonal_covariance[i][j][k][0] = 0;
					new_diagonal_covariance[i][j][k][1] = 0;
				}
			}
		}
	}
	else{
		new_covariance = new double****[number_gaussian_components];

		for (int j = 0; j < number_gaussian_components; j++){
			new_covariance[j] = new double***[this->number_states];

			for (int i = 0; i < this->number_states; i++){
				new_covariance[j][i] = new double**[dimension_event];

				for (int k = 0; k < dimension_event; k++){
					new_covariance[j][i][k] = new double*[dimension_event];

					for (int l = 0; l < dimension_event; l++){
						new_covariance[j][i][k][l] = new double[2];
						new_covariance[j][i][k][l][0] = 0;
						new_covariance[j][i][k][l][1] = 0;
					}
				}
			}
		}
	}

	#pragma omp parallel for
	for (int h = 0; h < number_events; h++){
		int number_states = static_cast<int>(state[h].size());

		double *likelihood = new double[length_event[h] * this->number_states];

		double **alpha = new double*[length_event[h]];
		double **beta = new double*[length_event[h]];
		double **gamma = new double*[length_event[h]];

		double ***gaussian_distribution = new double**[length_event[h]];
		double ***theta = new double**[number_states];

		for (int t = 0; t < length_event[h]; t++){
			alpha[t] = new double[number_states];
			beta[t] = new double[number_states];
			gamma[t] = new double[number_states];
			gaussian_distribution[t] = new double*[number_states];

			for (int i = 0; i < number_states; i++){
				gaussian_distribution[t][i] = new double[number_gaussian_components];
			}
		}
		for (int i = 0; i < number_states; i++){
			theta[i] = new double*[number_gaussian_components];

			for (int j = 0; j < number_gaussian_components; j++){
				theta[i][j] = new double[length_event[h]];
			}
		}

		for (int t = 0; t < length_event[h]; t++){
			for (int i = 0; i < number_states; i++) {
				int k = state[h][i];

				for (int j = 0; j < number_gaussian_components; j++) {
					gaussian_distribution[t][i][j] = GMM[k]->Gaussian_Distribution(&_event[h][t * dimension_event], j);
				}
				likelihood[t * this->number_states + k] = GMM[k]->Calculate_Likelihood(&_event[h][t * dimension_event], gaussian_distribution[t][i]);
			}
		}

		#pragma omp atomic
		log_likelihood += Forward_Algorithm(length_event[h], state[h], alpha, likelihood);
		Backward_Algorithm(length_event[h], state[h], beta, likelihood);

		for (int t = 0; t < length_event[h]; t++){
			double sum = 0;
			double sum_theta = 0;

			for (int i = 0; i < number_states; i++){
				sum += (gamma[t][i] = alpha[t][i] * beta[t][i]);
			}
			for (int i = 0; i < number_states; i++){
				gamma[t][i] = (gamma[t][i] == 0) ? (0) : (gamma[t][i] / sum);
			}

			if (t < length_event[h] - 1){
				double sum_delta = 0;

				double **delta = new double*[number_states];

				for (int i = 0; i < number_states; i++){
					delta[i] = new double[number_states];
				}

				for (int i = 0; i < number_states; i++){
					for (int j = 0; j < number_states; j++){
						int k = state[h][i];
						int l = state[h][j];

						if (Access_State(i, j) && state_connection[k].find(l) != state_connection[k].end()) {
							sum_delta += (delta[i][j] = alpha[t][i] * transition_probability[k].find(l)->second * likelihood[(t + 1) * this->number_states + l] * beta[t + 1][j]);
						}
						else {
							delta[i][j] = 0;
						}
					}
				}
				for (int i = 0; i < number_states; i++){
					for (int j = 0; j < number_states; j++){
						delta[i][j] = (delta[i][j] == 0) ? (0) : (delta[i][j] / sum_delta);
					}
				}

				for (int i = 0; i < number_states; i++){
					for (int j = 0; j < number_states; j++){
						#pragma omp atomic
						new_transition_probability[0][state[h][i]].find(state[h][j])->second += delta[i][j];
					}
				}

				for (int i = 0; i < number_states; i++){
					delete[] delta[i];
				}
				delete[] delta;
			}

			for (int i = 0; i < number_states; i++) {
				int l = state[h][i];

				if (t == 0) {
					for (int j = 0; j < number_gaussian_components; j++) {
						sum_theta += (theta[i][j][t] = (type_model == "ergodic" || i == 0) * initial_probability[l] * GMM[l]->weight[j] * gaussian_distribution[t][i][j] * beta[t][i]);
					}
				}
				else
					if (t >= 1) {
						double *sum = new double[number_gaussian_components];

						memset(sum, 0, sizeof(double) * number_gaussian_components);

						for (int k = 0; k < number_states; k++) {
							int m = state[h][k];

							if (Access_State(k, i) && state_connection[m].find(l) != state_connection[m].end()) {
								for (int j = 0; j < number_gaussian_components; j++) {
									sum[j] += alpha[t - 1][k] * transition_probability[m].find(l)->second;
								}
							}
						}
						for (int j = 0; j < number_gaussian_components; j++) {
							sum_theta += (theta[i][j][t] = sum[j] * GMM[l]->weight[j] * gaussian_distribution[t][i][j] * beta[t][i]);
						}
						delete[] sum;
					}
			}

			for (int i = 0; i < number_states; i++) {
				for (int j = 0; j < number_gaussian_components; j++) {
					theta[i][j][t] = (theta[i][j][t] == 0) ? (0) : (theta[i][j][t] / sum_theta);
				}
			}
		}

		for (int i = 0; i < this->number_states; i++){
			double sum = 0;

			for (int k = 0; k < number_states; k++){
				if (i == state[h][k]){
					sum += gamma[0][k];
				}
			}
			#pragma omp atomic
			new_initial_probability[i] += sum;
		}

		for (int l = 0; l < number_states; l++){
			double sum = 0;

			for (int t = 0; t < length_event[h] - 1; t++){
				sum += gamma[t][l];
			}
			for (int j = 0; j < number_states; j++){
				#pragma omp atomic
				new_transition_probability[1][state[h][l]].find(state[h][j])->second += sum;
			}
		}

		for (int j = 0; j < number_gaussian_components; j++) {
			for (int l = 0; l < number_states; l++) {
				double sum[2] = { 0, };

				for (int t = 0; t < length_event[h]; t++) {
					sum[0] += theta[l][j][t];
					sum[1] += gamma[t][l];
				}
				#pragma omp atomic
				new_weight[j][state[h][l]][0] += sum[0];
				#pragma omp atomic
				new_weight[j][state[h][l]][1] += sum[1];
			}
		}

		for (int j = 0; j < number_gaussian_components; j++) {
			for (int k = 0; k < dimension_event; k++) {
				for (int m = 0; m < number_states; m++) {
					double sum[2] = { 0, };

					for (int t = 0; t < length_event[h]; t++) {
						sum[0] += theta[m][j][t] * _event[h][t * dimension_event + k];
						sum[1] += theta[m][j][t];
					}
					#pragma omp atomic
					new_mean[j][state[h][m]][k][0] += sum[0];
					#pragma omp atomic
					new_mean[j][state[h][m]][k][1] += sum[1];
				}
			}
		}

		for (int j = 0; j < number_gaussian_components; j++) {
			for (int k = 0; k < dimension_event; k++) {
				if (type_covariance == "diagonal") {
					for (int n = 0; n < number_states; n++) {
						double sum[2] = { 0, };

						for (int t = 0; t < length_event[h]; t++) {
							sum[0] += theta[n][j][t] * (_event[h][t * dimension_event + k] - GMM[state[h][n]]->mean[j][k]) * (_event[h][t * dimension_event + k] - GMM[state[h][n]]->mean[j][k]);
							sum[1] += theta[n][j][t];
						}
						#pragma omp atomic
						new_diagonal_covariance[j][state[h][n]][k][0] += sum[0];
						#pragma omp atomic
						new_diagonal_covariance[j][state[h][n]][k][1] += sum[1];
					}
				}
				else {
					for (int l = 0; l < dimension_event; l++) {
						for (int n = 0; n < number_states; n++) {
							double sum[2] = { 0, };

							for (int t = 0; t < length_event[h]; t++) {
								sum[0] += theta[n][j][t] * (_event[h][t * dimension_event + k] - GMM[state[h][n]]->mean[j][k]) * (_event[h][t * dimension_event + l] - GMM[state[h][n]]->mean[j][l]);
								sum[1] += theta[n][j][t];
							}
							#pragma omp atomic
							new_covariance[j][state[h][n]][k][l][0] += sum[0];
							#pragma omp atomic
							new_covariance[j][state[h][n]][k][l][1] += sum[1];
						}
					}
				}
			}
		}

		for (int i = 0; i < number_states; i++){
			for (int j = 0; j < number_gaussian_components; j++){
				delete[] theta[i][j];
			}
			delete[] theta[i];
		}
		delete[] theta;

		for (int t = 0; t < length_event[h]; t++){
			for (int i = 0; i < number_states; i++){
				delete[] gaussian_distribution[t][i];
			}
			delete[] alpha[t];
			delete[] beta[t];
			delete[] gamma[t];
			delete[] gaussian_distribution[t];
		}
		delete[] alpha;
		delete[] beta;
		delete[] gamma;
		delete[] gaussian_distribution;
		delete[] likelihood;
	}

	#pragma omp parallel for
	for (int i = 0; i < this->number_states; i++){
		initial_probability[i] = new_initial_probability[i] / number_events;

		for (auto p = new_transition_probability[0][i].begin(); p != new_transition_probability[0][i].end(); p++){
			transition_probability[i].find(p->first)->second = (p->second == 0) ? (0) : (p->second / new_transition_probability[1][i].find(p->first)->second);
		}
		for (int j = 0; j < number_gaussian_components; j++) {
			GMM[i]->weight[j] = (new_weight[j][i][0] == 0) ? (0) : (new_weight[j][i][0] / new_weight[j][i][1]);
		}
		for (int j = 0; j < number_gaussian_components; j++) {
			for (int k = 0; k < dimension_event; k++) {
				GMM[i]->mean[j][k] = (new_mean[j][i][k][0] == 0) ? (0) : (new_mean[j][i][k][0] / new_mean[j][i][k][1]);
			}
		}
		for (int j = 0; j < number_gaussian_components; j++) {
			for (int k = 0; k < dimension_event; k++) {
				if (type_covariance == "diagonal") {
					GMM[i]->diagonal_covariance[j][k] = (new_diagonal_covariance[j][i][k][0] == 0) ? (0) : (new_diagonal_covariance[j][i][k][0] / new_diagonal_covariance[j][i][k][1]);

					if (GMM[i]->diagonal_covariance[j][k] < minimum_variance) {
						GMM[i]->diagonal_covariance[j][k] = minimum_variance;
					}
				}
				else {
					for (int l = 0; l < dimension_event; l++) {
						GMM[i]->covariance[j][k][l] = (new_covariance[j][i][k][l][0] == 0) ? (0) : (new_covariance[j][i][k][l][0] / new_covariance[j][i][k][l][1]);
					}
				}
			}
		}
	}

	for (int i = 0; i < this->number_states; i++){
		valid_transition[i].clear();
	}
	for (int i = 0; i < this->number_states; i++){
		for (auto p = transition_probability[i].begin(); p != transition_probability[i].end(); p++){
			if (p->second){
				valid_transition[p->first].insert(pair<int, double>(i, p->second));
			}
		}
	}

	if (type_covariance == "diagonal"){
		for (int j = 0; j < number_gaussian_components; j++){
			for (int i = 0; i < this->number_states; i++){
				for (int k = 0; k < dimension_event; k++){
					delete[] new_diagonal_covariance[j][i][k];
				}
				delete[] new_diagonal_covariance[j][i];
			}
			delete[] new_diagonal_covariance[j];
		}
		delete[] new_diagonal_covariance;
	}
	else{
		for (int j = 0; j < number_gaussian_components; j++){
			for (int i = 0; i < this->number_states; i++){
				for (int k = 0; k < dimension_event; k++){
					for (int l = 0; l < dimension_event; l++){
						delete[] new_covariance[j][i][k][l];
					}
					delete[] new_covariance[j][i][k];
				}
				delete[] new_covariance[j][i];
			}
			delete[] new_covariance[j];
		}
		delete[] new_covariance;
	}

	for (int j = 0; j < number_gaussian_components; j++){
		for (int i = 0; i < this->number_states; i++){
			for (int k = 0; k < dimension_event; k++){
				delete[] new_mean[j][i][k];
			}
			delete[] new_mean[j][i];
			delete[] new_weight[j][i];
		}
		delete[] new_mean[j];
		delete[] new_weight[j];
	}
	delete[] new_mean;
	delete[] new_weight;

	for (int i = 0; i < this->number_states; i++){
		new_transition_probability[0][i].clear();
		new_transition_probability[1][i].clear();
	}
	delete[] new_initial_probability;
	delete[] new_transition_probability[0];
	delete[] new_transition_probability[1];

	return log_likelihood / number_events;
}
double Continuous_Density_Hidden_Markov_Model::Evaluation(int length_event, double **_event){
	double log_likelihood = 0;

	double **alpha = new double*[length_event];

	for (int t = 0; t < length_event; t++){
		alpha[t] = new double[number_states];
	}
	for (int t = 0; t < length_event; t++){
		double scale;
		double sum_alpha = 0;

		if (t == 0){
			for (int i = 0; i < number_states; i++){
				sum_alpha += (alpha[t][i] = initial_probability[i] * GMM[i]->Calculate_Likelihood(_event[t]));
			}
		}
		else
		if (t >= 1){
			for (int i = 0; i < number_states; i++){
				double sum = 0;

				for (auto p = valid_transition[i].begin(); p != valid_transition[i].end(); p++){
					sum += alpha[t - 1][p->first] * p->second;
				}
				sum_alpha += (alpha[t][i] = sum * GMM[i]->Calculate_Likelihood(_event[t]));
			}
		}
		if (sum_alpha == 0){
			log_likelihood = -std::numeric_limits<double>::infinity();
			break;
		}

		scale = 1.0 / sum_alpha;
		for (int i = 0; i < number_states; i++){
			alpha[t][i] *= scale;
		}
		log_likelihood += log(scale);
	}

	for (int t = 0; t < length_event; t++){
		delete[] alpha[t];
	}
	delete[] alpha;

	return log_likelihood;
}
double Continuous_Density_Hidden_Markov_Model::Viterbi_Algorithm(string *optimal_label_sequence, int **optimal_state_sequence, int length_event, double *_event){
	int *state_sequence = new int[length_event];

	double log_likelihood = 0;

	double *_likelihood = new double[length_event * number_states];

	vector<int*>	gamma;
	vector<double*> delta;
	vector<string*> label;

	for (int t = 0; t < length_event * number_states; t++) {
		_likelihood[t] = GMM[t % number_states]->Calculate_Likelihood(&_event[t / number_states * dimension_event]);
	}
	for (int t = 0; t < length_event; t++){
		double scale;
		double sum = 0;
		double sum_delta = 0;

		double *likelihood = &_likelihood[t * number_states];

		gamma.push_back(new int[number_states]);
		delta.push_back(new double[number_states]);
		label.push_back(new string[number_states]);

		for (int i = 0; i < number_states; i++){
			sum += likelihood[i];
		}
		if (sum == 0){
			log_likelihood = -std::numeric_limits<double>::infinity();
			delete[] likelihood;
			break;
		}

		for (int i = 0; i < number_states; i++){
			if ((likelihood[i] /= sum) == 0){
				continue;
			}

			if (t == 0){
				delta[t][i] = initial_probability[i] * likelihood[i];
				label[t][i] = state_label[i];
			}
			else{
				int argmax;

				double max = -1;

				for (auto q = valid_transition[i].begin(); q != valid_transition[i].end(); q++){
					double p = delta[t - 1][q->first] * q->second;

					if (max < p){
						argmax = q->first;
						max = p;
					}
				}
				delta[t][i] = max * likelihood[i];
				gamma[t][i] = argmax;

				if (state_label[i] != state_label[argmax] /*|| i % 3 == 0 && argmax % 3 == 2*/){
					label[t][i] = state_label[i];
				}
			}
			sum_delta += delta[t][i];
		}
		if (sum_delta == 0){
			log_likelihood = -std::numeric_limits<double>::infinity();
			delete[] likelihood;
			break;
		}

		if (t == length_event - 1){
			int argmax;

			double max = -1;

			for (int i = 0; i < number_states; i++){
				if (max < delta[t][i]){
					max = delta[t][argmax = i];
				}
			}
			Search_State_Sequence(t, argmax, state_sequence, gamma);
		}
		log_likelihood -= log(scale = 1 / sum_delta);

		for (int i = 0; i < number_states; i++){
			delta[t][i] *= scale;
		}
	}

	if (_finite(log_likelihood)){
		if (optimal_label_sequence){
			string label_sequence;

			for (int t = 0; t < length_event; t++){
				if (!label[t][state_sequence[t]].empty()){
					if (!label_sequence.empty()){
						label_sequence += ' ';
					}
					label_sequence += label[t][state_sequence[t]];
				}
			}
			(*optimal_label_sequence) = label_sequence;
		}
		if (optimal_state_sequence){
			(*optimal_state_sequence) = new int[length_event];

			for (int t = 0; t < length_event; t++){
				(*optimal_state_sequence)[t] = state_sequence[t];
			}
		}
	}

	for (int t = 0; t < length_event; t++){
		delete[] delta[t];
		delete[] gamma[t];
		delete[] label[t];
	}
	delete[] _likelihood;
	delete[] state_sequence;

	delta.clear();
	gamma.clear();
	label.clear();

	return log_likelihood;
}

#ifdef Neural_Networks_H
double Continuous_Density_Hidden_Markov_Model::Baum_Welch_Algorithm(int number_events, int length_event[], vector<int> state[], double minimum_variance, double **_event, Neural_Networks *NN) {
	double log_likelihood = 0;

	double *new_initial_probability = new double[this->number_states];

	unordered_map<int, double> *new_transition_probability[2] = { new unordered_map<int, double>[this->number_states], new unordered_map<int, double>[this->number_states] };

	for (int i = 0; i < this->number_states; i++) {
		new_initial_probability[i] = 0;
	}
	for (int h = 0; h < number_events; h++) {
		for (int i = 0; i < state[h].size(); i++) {
			for (int j = 0; j < state[h].size(); j++) {
				auto p = transition_probability[state[h][i]].find(state[h][j]);

				if (p == transition_probability[state[h][i]].end()) {
					transition_probability[state[h][i]].insert(pair<int, double>(state[h][j], 1.0 / this->number_states));
				}
				if ((p = new_transition_probability[0][state[h][i]].find(state[h][j])) == new_transition_probability[0][state[h][i]].end()) {
					new_transition_probability[0][state[h][i]].insert(pair<int, double>(state[h][j], 0));
				}
				if ((p = new_transition_probability[1][state[h][i]].find(state[h][j])) == new_transition_probability[1][state[h][i]].end()) {
					new_transition_probability[1][state[h][i]].insert(pair<int, double>(state[h][j], 0));
				}
			}
		}
	}

#pragma omp parallel for
	for (int h = 0; h < number_events; h++) {
		int number_states = state[h].size();

		double *likelihood = new double[length_event[h] * this->number_states];

		double **alpha = new double*[length_event[h]];
		double **beta = new double*[length_event[h]];
		double **gamma = new double*[length_event[h]];

		for (int t = 0; t < length_event[h]; t++) {
			alpha[t] = new double[number_states];
			beta[t] = new double[number_states];
			gamma[t] = new double[number_states];
		}

#pragma omp critical
		{
			NN->Test(_event[h], likelihood, length_event[h]);
		}

#pragma omp atomic
		log_likelihood += Forward_Algorithm(length_event[h], state[h], alpha, likelihood);
		Backward_Algorithm(length_event[h], state[h], beta, likelihood);

		for (int t = 0; t < length_event[h]; t++) {
			double sum = 0;
			double sum_theta = 0;

			for (int i = 0; i < number_states; i++) {
				sum += (gamma[t][i] = alpha[t][i] * beta[t][i]);
			}
			for (int i = 0; i < number_states; i++) {
				gamma[t][i] = (gamma[t][i] == 0) ? (0) : (gamma[t][i] / sum);
			}

			if (t < length_event[h] - 1) {
				double sum_delta = 0;

				double **delta = new double*[number_states];

				for (int i = 0; i < number_states; i++) {
					delta[i] = new double[number_states];
				}

				for (int i = 0; i < number_states; i++) {
					for (int j = 0; j < number_states; j++) {
						int k = state[h][i];
						int l = state[h][j];

						if (Access_State(i, j) && state_connection[k].find(l) != state_connection[k].end()) {
							sum_delta += (delta[i][j] = alpha[t][i] * transition_probability[k].find(l)->second * likelihood[(t + 1) * this->number_states + l] * beta[t + 1][j]);
						}
						else {
							delta[i][j] = 0;
						}
					}
				}
				for (int i = 0; i < number_states; i++) {
					for (int j = 0; j < number_states; j++) {
						delta[i][j] = (delta[i][j] == 0) ? (0) : (delta[i][j] / sum_delta);
					}
				}

				for (int i = 0; i < number_states; i++) {
					for (int j = 0; j < number_states; j++) {
#pragma omp atomic
						new_transition_probability[0][state[h][i]].find(state[h][j])->second += delta[i][j];
					}
				}

				for (int i = 0; i < number_states; i++) {
					delete[] delta[i];
				}
				delete[] delta;
			}
		}

		for (int i = 0; i < this->number_states; i++) {
			double sum = 0;

			for (int k = 0; k < number_states; k++) {
				if (i == state[h][k]) {
					sum += gamma[0][k];
				}
			}
#pragma omp atomic
			new_initial_probability[i] += sum;
		}

		for (int l = 0; l < number_states; l++) {
			double sum = 0;

			for (int t = 0; t < length_event[h] - 1; t++) {
				sum += gamma[t][l];
			}
			for (int j = 0; j < number_states; j++) {
#pragma omp atomic
				new_transition_probability[1][state[h][l]].find(state[h][j])->second += sum;
			}
		}

		for (int t = 0; t < length_event[h]; t++) {
			delete[] alpha[t];
			delete[] beta[t];
			delete[] gamma[t];
		}
		delete[] alpha;
		delete[] beta;
		delete[] gamma;
		delete[] likelihood;
	}

#pragma omp parallel for
	for (int i = 0; i < this->number_states; i++) {
		initial_probability[i] = new_initial_probability[i] / number_events;

		for (auto p = new_transition_probability[0][i].begin(); p != new_transition_probability[0][i].end(); p++) {
			transition_probability[i].find(p->first)->second = (p->second == 0) ? (0) : (p->second / new_transition_probability[1][i].find(p->first)->second);
		}
	}

	for (int i = 0; i < this->number_states; i++) {
		valid_transition[i].clear();
	}
	for (int i = 0; i < this->number_states; i++) {
		for (auto p = transition_probability[i].begin(); p != transition_probability[i].end(); p++) {
			if (p->second) {
				valid_transition[p->first].insert(pair<int, double>(i, p->second));
			}
		}
	}

	for (int i = 0; i < this->number_states; i++) {
		new_transition_probability[0][i].clear();
		new_transition_probability[1][i].clear();
	}
	delete[] new_initial_probability;
	delete[] new_transition_probability[0];
	delete[] new_transition_probability[1];

	return log_likelihood;
}
double Continuous_Density_Hidden_Markov_Model::Viterbi_Algorithm(string *optimal_label_sequence, int **optimal_state_sequence, int length_event, double *_event, Neural_Networks *NN) {
	int *state_sequence = new int[length_event];

	double log_likelihood = 0;

	double *_likelihood = new double[length_event * number_states];

	vector<int*>	gamma;
	vector<double*> delta;
	vector<string*> label;

	NN->Test(_event, likelihood, length_event);

	for (int t = 0; t < length_event; t++) {
		double scale;
		double sum = 0;
		double sum_delta = 0;

		double *likelihood = &_likelihood[t * number_states];

		gamma.push_back(new int[number_states]);
		delta.push_back(new double[number_states]);
		label.push_back(new string[number_states]);

		for (int i = 0; i < number_states; i++) {
			if (t == 0) {
				delta[t][i] = initial_probability[i] * likelihood[i];
				label[t][i] = state_label[i];
			}
			else {
				int argmax;

				double max = -1;

				for (auto q = valid_transition[i].begin(); q != valid_transition[i].end(); q++) {
					double p = delta[t - 1][q->first] * q->second;

					if (max < p) {
						argmax = q->first;
						max = p;
					}
				}
				delta[t][i] = max * likelihood[i];
				gamma[t][i] = argmax;

				if (state_label[i] != state_label[argmax] /*|| i % 3 == 0 && argmax % 3 == 2*/) {
					label[t][i] = state_label[i];
				}
			}
			sum_delta += delta[t][i];
		}
		if (sum_delta == 0) {
			log_likelihood = -std::numeric_limits<double>::infinity();
			delete[] likelihood;
			break;
		}

		if (t == length_event - 1) {
			int argmax;

			double max = -1;

			for (int i = 0; i < number_states; i++) {
				if (max < delta[t][i]) {
					max = delta[t][argmax = i];
				}
			}
			Search_State_Sequence(t, argmax, state_sequence, gamma);
		}
		log_likelihood -= log(scale = 1 / sum_delta);

		for (int i = 0; i < number_states; i++) {
			delta[t][i] *= scale;
		}
	}

	if (_finite(log_likelihood)) {
		if (optimal_label_sequence) {
			string label_sequence;

			for (int t = 0; t < length_event; t++) {
				if (!label[t][state_sequence[t]].empty()) {
					if (!label_sequence.empty()) {
						label_sequence += ' ';
					}
					label_sequence += label[t][state_sequence[t]];
				}
			}
			(*optimal_label_sequence) = label_sequence;
		}
		if (optimal_state_sequence) {
			(*optimal_state_sequence) = new int[length_event];

			for (int t = 0; t < length_event; t++) {
				(*optimal_state_sequence)[t] = state_sequence[t];
			}
		}
	}

	for (int t = 0; t < length_event; t++) {
		delete[] delta[t];
		delete[] gamma[t];
		delete[] label[t];
	}
	delete[] _likelihood;
	delete[] state_sequence;

	delta.clear();
	gamma.clear();
	label.clear();

	return log_likelihood;
}
#endif

repository: paperrune/CDHMM

repo_name: paperrune/CDHMM

extension: cpp


text:
package generate

import (
	"math/rand"
	"net/url"
	"time"

	"github.com/qri-io/dataset/datatypes"
)

// RandomValue generates a randomized value for a given datatype
func RandomValue(t datatypes.Type) interface{} {
	switch t {
	case datatypes.Unknown:
		return nil
	case datatypes.Any:
		return RandomValue(datatypes.Type((rand.Intn(datatypes.NumDatatypes) + 1) - 2))
	case datatypes.String:
		return randString(rand.Intn(100))
	case datatypes.Float:
		return rand.Float32()
	case datatypes.Integer:
		return rand.Int()
	case datatypes.Boolean:
		return rand.Intn(10) > 4
	case datatypes.JSON:
		if rand.Intn(2) == 1 {
			return map[string]interface{}{}
		}
		return []interface{}{}
	case datatypes.Date:
		return time.Now().Add(time.Hour * 24 * time.Duration(rand.Intn(30)+1))
	case datatypes.URL:
		return &url.URL{
			Scheme: "http",
			Host:   "bit.ly",
			Path:   randString(6),
		}
	}

	return nil
}

// RandomStringValue is RandomValue that always returns a string
func RandomStringValue(t datatypes.Type) string {
	switch t {
	case datatypes.Unknown:
		return ""
	case datatypes.Any:
		return RandomStringValue(datatypes.Type((rand.Intn(datatypes.NumDatatypes) + 1) - 2))
	case datatypes.String:
		return randString(rand.Intn(100))
	case datatypes.Float:
		str, _ := datatypes.Float.ValueToString(rand.Float32())
		return str
	case datatypes.Integer:
		str, _ := datatypes.Integer.ValueToString(rand.Int())
		return str
	case datatypes.Boolean:
		if rand.Intn(10) > 4 {
			return "true"
		}
		return "false"
	case datatypes.JSON:
		if rand.Intn(2) > 1 {
			return "{}"
		}
		return "[]"
	case datatypes.Date:
		return time.Now().Add(time.Hour * 24 * time.Duration(rand.Intn(30)+1)).Format(time.ANSIC)
	case datatypes.URL:
		return "http://bit.ly/" + randString(6)
	}

	return ""
}

repository: jonnycrunch/dataset

repo_name: jonnycrunch/dataset


text:
package scribo

import (
	"net/http"

	"github.com/gorilla/mux"
)

// NewRouter is the controller for our microservice. It creates a router
// from the API routes defined in the routes object then adds static asset
// handling and other types of template handling as well.
func NewRouter() *mux.Router {

	// Instantiate the router
	router := mux.NewRouter().StrictSlash(true)

	// Add the API routes
	for _, route := range routes {

		var handler http.Handler
		handler = route.Handler
		handler = logger(handler, route.Name)

		router.
			Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(handler)
	}

	// Add a static file server pointing at the assets directory
	static := http.StripPrefix("/assets/", http.FileServer(http.Dir("./assets/")))
	router.PathPrefix("/assets/").Handler(logger(static, "Assets"))

	return router
}

repository: waffle-iron/scribo

repo_name: waffle-iron/scribo


text:
package main

import (
	"fmt"
	"log"

	"github.com/akrylysov/algnhsa"
	"github.com/madappgang/identifo/model"
	"github.com/madappgang/identifo/server"
	"github.com/madappgang/identifo/server/boltdb"
	"github.com/madappgang/identifo/server/dynamodb"
	"github.com/madappgang/identifo/server/fake"
	"github.com/madappgang/identifo/server/mgo"
)

const (
	testAppID       = "bk9o707k3t4c72q2qqqq"
	appsImportPath  = "./import/apps.json"
	usersImportPath = "./import/users.json"
)

func main() {
	srv := initServer()
	algnhsa.ListenAndServe(srv.Router(), &algnhsa.Options{BinaryContentTypes: []string{"application/javascript", "font/woff", "image/x-icon"}})
}

func initServer() model.Server {
	dbTypes := make(map[model.DatabaseType]bool)
	var partialComposers []server.PartialDatabaseComposer

	dbTypes[server.ServerSettings.Storage.AppStorage.Type] = true
	dbTypes[server.ServerSettings.Storage.UserStorage.Type] = true
	dbTypes[server.ServerSettings.Storage.TokenStorage.Type] = true
	dbTypes[server.ServerSettings.Storage.VerificationCodeStorage.Type] = true

	for dbType := range dbTypes {
		pc, err := initPartialComposer(dbType, server.ServerSettings.Storage)
		if err != nil {
			log.Panicf("Cannot init partial composer for db type %s: %s\n", dbType, err)
		}
		partialComposers = append(partialComposers, pc)
	}

	dbComposer, err := server.NewComposer(server.ServerSettings, partialComposers)
	if err != nil {
		log.Panicln("Cannot init database composer:", err)
	}

	srv, err := server.NewServer(server.ServerSettings, dbComposer, nil, nil)
	if err != nil {
		log.Panicln("Cannot init server:", err)
	}

	if _, err = srv.AppStorage().AppByID(testAppID); err != nil {
		log.Println("Error getting app storage:", err)
		if err = srv.ImportApps(appsImportPath); err != nil {
			log.Println("Error importing apps:", err)
		}
		if err = srv.ImportUsers(usersImportPath); err != nil {
			log.Println("Error importing users:", err)
		}
	}

	return srv
}

func initPartialComposer(dbType model.DatabaseType, settings model.StorageSettings) (server.PartialDatabaseComposer, error) {
	switch dbType {
	case model.DBTypeBoltDB:
		return boltdb.NewPartialComposer(settings)
	case model.DBTypeMongoDB:
		return mgo.NewPartialComposer(settings)
	case model.DBTypeDynamoDB:
		return dynamodb.NewPartialComposer(settings)
	case model.DBTypeFake:
		return fake.NewPartialComposer(settings)
	}
	return nil, fmt.Errorf("Unknown db type: %s", dbType)
}

repository: isgasho/identifo

repo_name: isgasho/identifo


text:
# https://developer.apple.com/documentation/corefoundation

if(NOT APPLE)
	dk_undepend(core_foundation)
	dk_return()
endif()

dk_findLibrary(CoreFoundation)

repository: aquawicket/DigitalKnob

repo_name: aquawicket/DigitalKnob

extension: cmake


text:
package pack

func mdwAPIOnly() HandlerFunc {
	return func(c *Context) {
		if c.IsAPIOnly() {
			c.Writer.Header().Del("Set-Cookie")
		}

		c.Next()
	}
}

repository: saputradharma/appy

repo_name: saputradharma/appy


text:
DESCRIPTION = "Image Gallery"
HOMEPAGE = "https://gitorious.org/image-gallery"
SECTION = "multimedia"
LICENSE = "BSD-3-Clause"
LIC_FILES_CHKSUM = "file://LICENSE;md5=9c57cc1cdee589f97cbba69e95a89a15"

require recipes-core/matrix/matrix-gui-paths.inc

inherit qt5

PR = "r5"

BRANCH = "master"
SRCREV = "d9a2f2e27f59f3bbcde91efc6afba8cd04f3b4be"

SRC_URI = "git://git.ti.com/git/matrix-gui-v2/image-gallery.git;protocol=https;branch=${BRANCH}"

S = "${WORKDIR}/git"

do_install() {
	install -d ${D}/${bindir}
	install -m 0755 ${B}/image-gallery ${D}/${bindir}/image-gallery
	install -d ${D}${MATRIX_APP_DIR}/qt-image-gallery
	cp -rf ${S}/matrix-files/*  ${D}${MATRIX_APP_DIR}/qt-image-gallery
}

PACKAGES += "matrix-gui-apps-image-gallery"

RDEPENDS:matrix-gui-apps-image-gallery  = "matrix-gui-apps-images matrix-gui-submenus-camera ${PN}"

FILES:matrix-gui-apps-image-gallery += "${MATRIX_APP_DIR}/*"

repository: rcn-ee/meta-arago

repo_name: rcn-ee/meta-arago


text:
// +build !ignore_autogenerated

// This file was autogenerated by openapi-gen. Do not edit it manually!

package v1alpha1

import (
	spec "github.com/go-openapi/spec"
	common "k8s.io/kube-openapi/pkg/common"
)

func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition {
	return map[string]common.OpenAPIDefinition{
		"./pkg/apis/onap/v1alpha1.PrometheusRemoteEndpoint":       schema_pkg_apis_onap_v1alpha1_PrometheusRemoteEndpoint(ref),
		"./pkg/apis/onap/v1alpha1.PrometheusRemoteEndpointSpec":   schema_pkg_apis_onap_v1alpha1_PrometheusRemoteEndpointSpec(ref),
		"./pkg/apis/onap/v1alpha1.PrometheusRemoteEndpointStatus": schema_pkg_apis_onap_v1alpha1_PrometheusRemoteEndpointStatus(ref),
		"./pkg/apis/onap/v1alpha1.RemoteFilterAction":             schema_pkg_apis_onap_v1alpha1_RemoteFilterAction(ref),
		"./pkg/apis/onap/v1alpha1.RemoteFilterActionSpec":         schema_pkg_apis_onap_v1alpha1_RemoteFilterActionSpec(ref),
		"./pkg/apis/onap/v1alpha1.RemoteFilterActionStatus":       schema_pkg_apis_onap_v1alpha1_RemoteFilterActionStatus(ref),
	}
}

func schema_pkg_apis_onap_v1alpha1_PrometheusRemoteEndpoint(ref common.ReferenceCallback) common.OpenAPIDefinition {
	return common.OpenAPIDefinition{
		Schema: spec.Schema{
			SchemaProps: spec.SchemaProps{
				Description: "PrometheusRemoteEndpoint is the Schema for the prometheusremoteendpoints API",
				Type:        []string{"object"},
				Properties: map[string]spec.Schema{
					"kind": {
						SchemaProps: spec.SchemaProps{
							Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
							Type:        []string{"string"},
							Format:      "",
						},
					},
					"apiVersion": {
						SchemaProps: spec.SchemaProps{
							Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources",
							Type:        []string{"string"},
							Format:      "",
						},
					},
					"metadata": {
						SchemaProps: spec.SchemaProps{
							Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"),
						},
					},
					"spec": {
						SchemaProps: spec.SchemaProps{
							Ref: ref("./pkg/apis/onap/v1alpha1.PrometheusRemoteEndpointSpec"),
						},
					},
					"status": {
						SchemaProps: spec.SchemaProps{
							Ref: ref("./pkg/apis/onap/v1alpha1.PrometheusRemoteEndpointStatus"),
						},
					},
				},
			},
		},
		Dependencies: []string{
			"./pkg/apis/onap/v1alpha1.PrometheusRemoteEndpointSpec", "./pkg/apis/onap/v1alpha1.PrometheusRemoteEndpointStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"},
	}
}

func schema_pkg_apis_onap_v1alpha1_PrometheusRemoteEndpointSpec(ref common.ReferenceCallback) common.OpenAPIDefinition {
	return common.OpenAPIDefinition{
		Schema: spec.Schema{
			SchemaProps: spec.SchemaProps{
				Description: "PrometheusRemoteEndpointSpec defines the desired state of PrometheusRemoteEndpoint",
				Type:        []string{"object"},
				Properties: map[string]spec.Schema{
					"adapterURL": {
						SchemaProps: spec.SchemaProps{
							Type:   []string{"string"},
							Format: "",
						},
					},
					"filterSelector": {
						SchemaProps: spec.SchemaProps{
							Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"),
						},
					},
					"type": {
						SchemaProps: spec.SchemaProps{
							Type:   []string{"string"},
							Format: "",
						},
					},
					"kafkaConfig": {
						SchemaProps: spec.SchemaProps{
							Type:   []string{"string"},
							Format: "",
						},
					},
					"queueConfig": {
						SchemaProps: spec.SchemaProps{
							Ref: ref("./pkg/apis/onap/v1alpha1.QueueConfig"),
						},
					},
					"remoteTimeout": {
						SchemaProps: spec.SchemaProps{
							Type:   []string{"string"},
							Format: "",
						},
					},
				},
				Required: []string{"adapterURL", "type"},
			},
		},
		Dependencies: []string{
			"./pkg/apis/onap/v1alpha1.QueueConfig", "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"},
	}
}

func schema_pkg_apis_onap_v1alpha1_PrometheusRemoteEndpointStatus(ref common.ReferenceCallback) common.OpenAPIDefinition {
	return common.OpenAPIDefinition{
		Schema: spec.Schema{
			SchemaProps: spec.SchemaProps{
				Description: "PrometheusRemoteEndpointStatus defines the observed state of PrometheusRemoteEndpoint",
				Type:        []string{"object"},
				Properties: map[string]spec.Schema{
					"prometheusInstance": {
						SchemaProps: spec.SchemaProps{
							Description: "INSERT ADDITIONAL STATUS FIELD - define observed state of cluster Important: Run \"operator-sdk generate k8s\" to regenerate code after modifying this file Add custom validation using kubebuilder tags: https://book-v1.book.kubebuilder.io/beyond_basics/generating_crd.html Status can be Error, Enabled",
							Type:        []string{"string"},
							Format:      "",
						},
					},
					"status": {
						SchemaProps: spec.SchemaProps{
							Type:   []string{"string"},
							Format: "",
						},
					},
					"kafkaWriterID": {
						SchemaProps: spec.SchemaProps{
							Type:   []string{"string"},
							Format: "",
						},
					},
					"remoteURL": {
						SchemaProps: spec.SchemaProps{
							Type:   []string{"string"},
							Format: "",
						},
					},
				},
				Required: []string{"status"},
			},
		},
	}
}

func schema_pkg_apis_onap_v1alpha1_RemoteFilterAction(ref common.ReferenceCallback) common.OpenAPIDefinition {
	return common.OpenAPIDefinition{
		Schema: spec.Schema{
			SchemaProps: spec.SchemaProps{
				Description: "RemoteFilterAction is the Schema for the remotefilteractions API",
				Type:        []string{"object"},
				Properties: map[string]spec.Schema{
					"kind": {
						SchemaProps: spec.SchemaProps{
							Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
							Type:        []string{"string"},
							Format:      "",
						},
					},
					"apiVersion": {
						SchemaProps: spec.SchemaProps{
							Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources",
							Type:        []string{"string"},
							Format:      "",
						},
					},
					"metadata": {
						SchemaProps: spec.SchemaProps{
							Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"),
						},
					},
					"spec": {
						SchemaProps: spec.SchemaProps{
							Ref: ref("./pkg/apis/onap/v1alpha1.RemoteFilterActionSpec"),
						},
					},
					"status": {
						SchemaProps: spec.SchemaProps{
							Ref: ref("./pkg/apis/onap/v1alpha1.RemoteFilterActionStatus"),
						},
					},
				},
			},
		},
		Dependencies: []string{
			"./pkg/apis/onap/v1alpha1.RemoteFilterActionSpec", "./pkg/apis/onap/v1alpha1.RemoteFilterActionStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"},
	}
}

func schema_pkg_apis_onap_v1alpha1_RemoteFilterActionSpec(ref common.ReferenceCallback) common.OpenAPIDefinition {
	return common.OpenAPIDefinition{
		Schema: spec.Schema{
			SchemaProps: spec.SchemaProps{
				Description: "RemoteFilterActionSpec defines the desired state of RemoteFilterAction",
				Type:        []string{"object"},
				Properties: map[string]spec.Schema{
					"action": {
						SchemaProps: spec.SchemaProps{
							Type:   []string{"string"},
							Format: "",
						},
					},
					"regex": {
						SchemaProps: spec.SchemaProps{
							Type:   []string{"string"},
							Format: "",
						},
					},
					"sourceLabels": {
						VendorExtensible: spec.VendorExtensible{
							Extensions: spec.Extensions{
								"x-kubernetes-list-type": "set",
							},
						},
						SchemaProps: spec.SchemaProps{
							Description: "SourceLabels are the labels of the each metric",
							Type:        []string{"array"},
							Items: &spec.SchemaOrArray{
								Schema: &spec.Schema{
									SchemaProps: spec.SchemaProps{
										Type:   []string{"string"},
										Format: "",
									},
								},
							},
						},
					},
					"targetLabel": {
						SchemaProps: spec.SchemaProps{
							Type:   []string{"string"},
							Format: "",
						},
					},
					"replacement": {
						SchemaProps: spec.SchemaProps{
							Type:   []string{"string"},
							Format: "",
						},
					},
				},
			},
		},
	}
}

func schema_pkg_apis_onap_v1alpha1_RemoteFilterActionStatus(ref common.ReferenceCallback) common.OpenAPIDefinition {
	return common.OpenAPIDefinition{
		Schema: spec.Schema{
			SchemaProps: spec.SchemaProps{
				Description: "RemoteFilterActionStatus defines the observed state of RemoteFilterAction",
				Type:        []string{"object"},
			},
		},
	}
}

repository: onap/demo

repo_name: onap/demo

gha_language: C


text:
// Copyright 2017 Zhang Peihao <zhangpeihao@gmail.com>

package httpapi

import (
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/golang/glog"
	"github.com/zhangpeihao/shutdown"
	"github.com/zhangpeihao/zim/pkg/broker"
	"github.com/zhangpeihao/zim/pkg/protocol"
	"github.com/zhangpeihao/zim/pkg/util"
)

// Subscribe 订阅
func (b *BrokerImpl) Subscribe(tag string, handler broker.SubscribeHandler) error {
	glog.Infof("broker::httpapi::Subscribe(%s)\n", tag)
	defer glog.Infof("broker::httpapi::Subscribe(%s) done\n", tag)
	if err := shutdown.ExitWaitGroupAdd(b.ctx, 1); err != nil {
		glog.Errorf("broker::httpapi::Subscribe(%s) ExitWaitGroupAdd error: %s", tag, err)
		return err
	}
	defer shutdown.ExitWaitGroupDone(b.ctx)
	queue := make(chan *protocol.Command, b.queueSize)
	b.Lock()
	b.queues[tag] = queue
	b.Unlock()
FOR_LOOP:
	for {
		select {
		case cmd := <-queue:
			func() {
				util.RecoverFromPanic()
				handler(tag, cmd)
			}()
		case <-b.ctx.Done():
			glog.Infof("broker::httpapi::Subscribe(%s) break by context", tag)
			break FOR_LOOP
		}
	}
	return nil
}

// ServeHTTP 处理HTTP链接
func (b *BrokerImpl) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	glog.Infoln("broker::httpapi::ServeHTTP()")
	defer r.Body.Close()

	tag := strings.ToLower(strings.Trim(r.URL.Path, "/"))
	glog.Infoln("broker::httpapi::ServeHTTP() tag: ", tag)
	if tag == "debug.html" {
		if b.Debug {
			//			b.HandleDebug(w, r)
		} else {
			glog.Warningln("broker::httpapi::ServeHTTP() not in debug mode")
			w.WriteHeader(404)
			return
		}
	} else {
		b.Lock()
		queue, ok := b.queues[tag]
		b.Unlock()
		if !ok {
			glog.Warningln("broker::httpapi::ServeHTTP() no tag(", tag, ")")
			w.WriteHeader(404)
			return
		}

		if payload, err := ioutil.ReadAll(r.Body); err != nil {
			glog.Warningf("broker::httpapi::ServeHTTP() Read payload error: %s\n",
				err)
			w.WriteHeader(400)
		} else {
			if cmd, err := ParseCommand(b.ctx, tag, r.Header, payload, b.timeout); err != nil {
				glog.Warningf("broker::httpapi::ServeHTTP() ParseCommand error: %s\n",
					err)
				w.WriteHeader(400)
			} else {
				queue <- cmd
				w.WriteHeader(200)
			}
		}
	}
}

repository: zhangpeihao/zim

repo_name: zhangpeihao/zim