text:
using DCISDBManager.objLib.Rates;
using DCISDBManager.objLib.TaxDetails;
using DCISDBManager.objLib.Usr;
using DCISDBManager.trnLib.CheckAuth;
using DCISDBManager.trnLib.CustomerRequestManagement;
using DCISDBManager.trnLib.RateManagement;
using DCISDBManager.trnLib.TaxManagement;
using DCISDBManager.trnLib.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DSCMS.Views.Customer
{
    public partial class CustomerTaxAssign : System.Web.UI.Page
    {
        UserSession userSession;
        string CustomerId=null;
        string SVAT = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            userSession = new UserSession();

            UserAutentication();

            Dropdownlist();
            string cus = Request.QueryString["cus"];
            if (cus == null && drpCustomer.SelectedValue == "no")
            {
                divcontent.Visible = false;
            }
            else {
                divcontent.Visible = true;

            }

        }

        private void UserAutentication()
        {
            try
            {
                if (userSession.User_Id == "")
                {
                    Response.Redirect("~/Views/Home/Login.aspx");
                }
                string groupId = userSession.User_Group;
                CheckAuthManager Am = new CheckAuthManager();
                bool auth = Am.IsUserGroupAuthorised(groupId, "CuTxA");
                if (auth == false)
                {
                    Response.Redirect("~/Views/Home/Forbidden.aspx");
                }
            }
            catch (Exception ex)
            {
                ErrorLog.LogError(ex);
                Response.Redirect("~/Views/Home/Login.aspx");
            }
        }

        private void Dropdownlist()
        {
            try
            {

                CustomerId = drpCustomer.SelectedValue.ToString();
                if (!IsPostBack)
                {

                    GetAllCustomer();
                    getTaxdetails();

                }

                if (CustomerId != "no")
                {
                    divcontent.Visible = true;
                }

                getAllTaxdetail(CustomerId);
                CustomerId = drpCustomer.SelectedValue;

            }
            catch (Exception ex)
            {
                ErrorLog.LogError(ex);

            }
        }

        private void getTaxdetails()
        {
            try
            {
                TaxManager tax = new TaxManager();

                drpTax.DataSource = tax.getTaxDetails("Y","0");
                drpTax.DataValueField = "TaxCode1";
                drpTax.DataTextField = "TaxName1";
                drpTax.DataBind();

                RateManager Rm = new RateManager();
                droRate.DataSource = Rm.getAllRates("Y");
                droRate.DataValueField = "RateId1";
                droRate.DataTextField = "RateName1";
                droRate.DataBind();

            }
            catch (Exception ex)
            {
                ErrorLog.LogError(ex);

            }

        }

        private void GetAllCustomer()
        {
            try{
            CustomerDetailManager cm = new CustomerDetailManager();

            drpCustomer.DataSource = cm.getAllCustomer("Y");
            drpCustomer.DataValueField = "CustomerId1";
            drpCustomer.DataTextField = "CustomerName1";
            drpCustomer.DataBind();
            }
            catch (Exception ex)
            {
                ErrorLog.LogError(ex);

            }
        }

        private void getAllTaxdetail(string CustomerId)
        {
            try{
                if (CustomerId != "no")
            {

                TaxManager tax = new TaxManager();
                gvTax.DataSource = tax.getUserTaxDetails(CustomerId,"Y");
                gvTax.DataBind();
                RateManager Rm = new RateManager();
                gvRate.DataSource = Rm.getCustomerRates(CustomerId,"Y");
                gvRate.DataBind();

            }
            }
            catch (Exception ex)
            {
                ErrorLog.LogError(ex);

            }
        }

        private  void SVATMassage()
        {
            string msg = null;
            msg += "
";
            msg += " ×";
            msg += " This is SVAT Customer
";

            ErrorMessage.InnerHtml = msg;
        }

        protected void Edit_Click(object sender, EventArgs e)
        {
         try{
            using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
            {

                txtTaxCode.Text = row.Cells[0].Text;
                txtTaxName.Text = row.Cells[1].Text;
                txtTaxPercentage.Text = row.Cells[2].Text;
                txtRegNo.Text = row.Cells[3].Text;
                mp1.Show();

            }
         }
         catch (Exception ex)
         {
             ErrorLog.LogError(ex);

         }

        }

        protected void Rate_Edit_Click(object sender, EventArgs e)
        {
            try
            {
                using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
                {

                    txtRateId.Text = row.Cells[0].Text;
                    txtRateName.Text = row.Cells[1].Text;
                    txtRateValue1.Text = row.Cells[2].Text;

                    mp3.Show();

                }
            }
            catch (Exception ex)
            {
                ErrorLog.LogError(ex);

            }

        }

        protected void UpdateRegNo(object sender, EventArgs e)
        {
            try {
            CustometTaxDetailManager taxmanger = new CustometTaxDetailManager();
            setCustomerTaxDetails taxdata = new setCustomerTaxDetails();
            taxdata.TaxCode1 = txtTaxCode.Text;
            taxdata.CustomerId1 = CustomerId;
            taxdata.TaxRegistrationNo1 = txtRegNo.Text;
            taxdata.IsActive1 = "Y";
            taxmanger.ModifyTaxData(taxdata);
           // Response.Redirect("CustomerTaxAssign.aspx?cus="+CustomerId, false);
                }catch(Exception ex){
                    ErrorLog.LogError(ex);
                    string qu = null;
                    qu += "
";
                    qu += " ×";
                    qu += " Update Prosess Failed.Check Your Inputs
";

                    ErrorMessage.InnerHtml = qu;
                }
            getAllTaxdetail(CustomerId);
        }

        protected void UpdateRate(object sender, EventArgs e)
        {
            try
            {
                RateManager Rm = new RateManager();
                Rates Ratedata = new Rates();
                Ratedata.RatesId1 = txtRateId.Text;
                Ratedata.CustomerId1 = CustomerId;
                Ratedata.Rates1 = Convert.ToDecimal(txtRateValue1.Text);
                Rm.ModifyRateData(Ratedata);
               // Response.Redirect("CustomerTaxAssign.aspx?cus=" + CustomerId, false);
            }
            catch (Exception ex)
            {
                ErrorLog.LogError(ex);
                string qu = null;
                qu += "
";
                qu += " ×";
                qu += " Update Prosess Failed.Check Your Inputs
";

                ErrorMessage.InnerHtml = qu;
            }
            getAllTaxdetail(CustomerId);
        }

        protected void AddTax(object sender, EventArgs e)
        {
            try{
            if (CustomerId != null)
            {

                    CustometTaxDetailManager taxmanger = new CustometTaxDetailManager();
                    setCustomerTaxDetails taxdata = new setCustomerTaxDetails();

                    taxdata.CustomerId1 = CustomerId;
                    taxdata.TaxCode1 = drpTax.SelectedValue.ToString();
                    taxdata.TaxRegistrationNo1 = txtTaxReg.Text;
                    taxdata.IsActive1 = "Y";
                    bool SvatChecker = true;
                    if (RbtnSVAT.SelectedValue=="1")
                    {
                        string IsvatCode = System.Configuration.ConfigurationManager.AppSettings["VatCode"];
                       if( IsvatCode== drpTax.SelectedValue.ToString()){
                           SvatChecker = false;
                           SVATMassage();
                       }
                    }
                 bool check=true;
                 bool check1 = true;
                 if (SvatChecker)
                 {
                     check = taxmanger.setTaxData(taxdata);

                 }
                 else {
                      check1 = false;
                 }
                    if (check == false)
                    {
                        string qu = null;
                        qu += "
";
                        qu += " ×";
                        qu += " Tax Already Add For this User.
";
                        ErrorMessage.InnerHtml = qu;
                    }

                    else
                    {
                        if (check1)
                        {
                            string qu = null;
                            qu += "
";
                            qu += " ×";
                            qu += " Save Success.
";
                            ErrorMessage.InnerHtml = qu;
                        }
                        else {
                            string qu = null;
                            qu += "
";
                            qu += " ×";
                            qu += " Can not add VAT for SVAT Customer
";
                            ErrorMessage.InnerHtml = qu;
                        }

                    }

            }
            else
            {
                string qu = null;
                qu += "
";
                qu += " ×";
                qu += " Select Customer First.
";

                ErrorMessage.InnerHtml = qu;
            }
            }
            catch (Exception ex)
            {
                ErrorLog.LogError(ex);

            }
            getAllTaxdetail(CustomerId);
        }

        protected void AddRate(object sender, EventArgs e)
        {
            try
            {
                if (CustomerId != null)
                {
                    if (txtRateValue.Text != "")
                    {
                        RateManager taxmanger = new RateManager();
                        Rates taxdata = new Rates();

                        taxdata.CustomerId1 = CustomerId;
                        taxdata.RatesId1 = droRate.SelectedValue.ToString();
                        taxdata.Rates1 = Convert.ToDecimal(txtRateValue.Text);
                        bool check = taxmanger.setCustomerRate(taxdata);
                        if (check == false)
                        {

                            string qu = null;
                            qu += "
";
                            qu += " ×";
                            qu += " Rate Already Add For this User.
";

                            ErrorMessage.InnerHtml = qu;
                        }

                        else
                        {
                            string qu = null;
                            qu += "
";
                            qu += " ×";
                            qu += " Save Success.
";

                            ErrorMessage.InnerHtml = qu;
                        }
                    }
                    else
                    {
                        string qu = null;
                        qu += "
";
                        qu += " ×";
                        qu += " Add Process Failed. Check Your Inputs.
";

                        ErrorMessage.InnerHtml = qu;

                    }
                }
                else
                {
                    string qu = null;
                    qu += "
";
                    qu += " ×";
                    qu += " Select Customer First.
";

                    ErrorMessage.InnerHtml = qu;
                }
            }
            catch (Exception ex)
            {
                ErrorLog.LogError(ex);

            }
            getAllTaxdetail(CustomerId);
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
         try{
            using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
            {

                lblTaxId.Text = row.Cells[0].Text;

                mp4.Show();

            }
         }
         catch (Exception ex)
         {
             ErrorLog.LogError(ex);

         }

        }

        protected void DeleteTax(object sender, EventArgs e)
        {
            try
            {
                CustometTaxDetailManager taxmanger = new CustometTaxDetailManager();
                setCustomerTaxDetails taxdata = new setCustomerTaxDetails();
                taxdata.TaxCode1 = lblTaxId.Text;
                taxdata.CustomerId1 = CustomerId;
                taxdata.TaxRegistrationNo1 = txtRegNo.Text;
                taxdata.IsActive1 = "N";
                taxmanger.ModifyTaxData(taxdata);
               // Response.Redirect("CustomerTaxAssign.aspx?cus=" + CustomerId, false);
            }
            catch (Exception ex)
            {
                ErrorLog.LogError(ex);
                string qu = null;
                qu += "
";
                qu += " ×";
                qu += " Update Prosess Failed.Check Your Inputs
";

                ErrorMessage.InnerHtml = qu;
            }
            getAllTaxdetail(CustomerId);
        }

        protected void Save_Click(object sender, EventArgs e)
        {
            TaxManager Tm = new TaxManager();
            string CustomerId=drpCustomer.SelectedValue;
            string VATId=System.Configuration.ConfigurationManager.AppSettings["VatCode"];
            string Vat=RbtnSVAT.Text;

            bool check=Tm.ModifySVATData(Vat, VATId, CustomerId);
            if (check) {
                string qu = null;
                qu += "
";
                qu += " ×";
                qu += "Success Fully Saved
";

                ErrorMessage.InnerHtml = qu;
            }
            else {
                string qu = null;
                qu += "
";
                qu += " ×";
                qu += "This Customer Had VAT
";

                ErrorMessage.InnerHtml = qu;
            }

        }

        protected void drpCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            string cus = Request.QueryString["cus"];
            if (cus == null && drpCustomer.SelectedValue == "no")
            {
                divcontent.Visible = false;
            }
            else
            {
                CustomerId = drpCustomer.SelectedValue;
                TaxManager tax = new TaxManager();
                getTaxDetails details = tax.getCustometSVAT(CustomerId);
                SVAT = details.SVAt1;
                getAllTaxdetail(CustomerId);

                    if (SVAT == "1")
                    {

                        RbtnSVAT.SelectedValue = SVAT;
                        SVATMassage();

                    }
                    else
                    {
                        RbtnSVAT.SelectedValue = SVAT;
                    }
                }

        }
    }
}


text:
[react-bs-datatable](../README.md) / [components/TableHeader](../modules/components_TableHeader.md) / TableHeaderClasses

# Interface: TableHeaderClasses

[components/TableHeader](../modules/components_TableHeader.md).TableHeaderClasses

This is an interface for customizing the classes for
the `TableHeaderClasses` component.

## Table of contents

### Properties

- [th](components_TableHeader.TableHeaderClasses.md#th)
- [thead](components_TableHeader.TableHeaderClasses.md#thead)
- [tr](components_TableHeader.TableHeaderClasses.md#tr)

## Properties

### th

• `Optional` **th**: `string`

The class for all `th` tags inside each `tr` tag.

#### Defined in

[components/TableHeader.tsx:29](https://github.com/imballinst/react-bs-datatable/blob/798f739/src/components/TableHeader.tsx#L29)

___

### thead

• `Optional` **thead**: `string`

The class for the `thead` tag.

#### Defined in

[components/TableHeader.tsx:25](https://github.com/imballinst/react-bs-datatable/blob/798f739/src/components/TableHeader.tsx#L25)

___

### tr

• `Optional` **tr**: `string`

The class for all `tr` tags inside `tbody`.

#### Defined in

[components/TableHeader.tsx:27](https://github.com/imballinst/react-bs-datatable/blob/798f739/src/components/TableHeader.tsx#L27)

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: What's in Your PowerShell Profile?
tags: [PowerShell, Profile]
author: Matt McNabb
comments: true
---

[PortableProfile]: /posts/portable-profile

"What's in Your Profile?"

This is a question you see often in PowerShell blogs and forums. PowerShell profiles can be a powerful way to automate your command line environment and most importantly save typing and time.

In my [previous post][PortableProfile] I went over how to make a portable PowerShell profile. In this post I'll go over what I have in my profile scripts and why.

### The Main Profile

In this profile script I configure most of the settings that will apply to both the PowerShell console and the ISE:

<!--more-->

{% gist 57aff66df11c7e97c3fb10db552d3730 1.ps1 %}

Let's walk through this bit-by-bit. The first two lines import credential objects that I have previously saved using the New-SavedCredential function and saves them in variables. This saves the username and password securely in an XML file that represents a PowerShell credential object. I typically run powershell with a standard user account and use these credentials in commands that require more privilege. I save the credentials in SAM and UPN formats - SAM format is for things like domain servers and Active Directory, and the UPN credentials can be used against web services like Office 365.

{% gist 57aff66df11c7e97c3fb10db552d3730 2.ps1 %}

Next I extend the PowerShell module path to include my script library; this adds quick access to modules stored in OneDrive. I also remove my local documents modules folder from the modulepath variable. I do this because I often work over a VPN connection and my documents are stored on a file server in our datacenter. This can mean that automatic module enumeration is very slow over the WAN connection. This cripples tab-completion and Intellisense because it constantly checks your module path to discover commands and parameters.

{% gist 57aff66df11c7e97c3fb10db552d3730 3.ps1 %}

Next in line is a prompt function. When you create a function named prompt, the text output of that function will be used as the command-line prompt. I like mine with some color and it also displays the execution time of the last command run.

{% gist 57aff66df11c7e97c3fb10db552d3730 4.ps1 %}

{% gist 57aff66df11c7e97c3fb10db552d3730 5.ps1 %}

Next I load several modules that I work with on a regular basis. Since PowerShell version 3.0 this is not really necessary since modules when auto-load when they are called upon, but I prefer that they load at startup to save time later. Besides that I still sometimes run PowerShell version 2.0 which does not auto-load modules, so this ensures the right modules are loaded when I run PowerShell. I have recently begun using the Windows Azure module but I don't really want to load it when I launch the shell, so I save the path to the module in a variable and call that later when I need to access the Azure cmdlets.

{% gist 57aff66df11c7e97c3fb10db552d3730 6.ps1 %}

I manage a print server on a daily basis and use cmdlets in the PrintManagement module to do so. These modules leverage WMI/CIM to retrieve and configure printer settings. For quick access I like to have a CIM session to my print server already open when I load PowerShell. I use one of my imported admin credentials to establish this connection.

{% gist 57aff66df11c7e97c3fb10db552d3730 7.ps1 %}

I use the $PSDefaultParameterValues automatic variable to configure default values when I run certain commands. This is a huge time-saver if you find yourself typing the same parameter values in on a regular basis. An example of this is setting the -CimSession parameter of all of the PrintManagement cmdlets with a value of $CimPs01 from the previous line in my profile script. This makes sure that I am always running printer cmdlets against the right computer without having to enter the parameter at the command line.

{% gist 57aff66df11c7e97c3fb10db552d3730 8.ps1 %}

Lastly, if the current PowerShell host is the ISE editor, I import a module called ISELibrary with a collection of functions for interacting with the ISE. I then run another profile script that makes some changes like the default pane view and loading custom add-ins.

{% gist 57aff66df11c7e97c3fb10db552d3730 9.ps1 %}

{% gist 57aff66df11c7e97c3fb10db552d3730 10.ps1 %}

### Other scripts

The ISEConfig script above also calls another profile script - load-addons.ps1. This script uses some of the functions in my ISELibrary module to create ISE add-ons. These add-ons take advantage of the extensibility of the ISE object model and allow you to create ISE menu items that run PowerShell code and can be called with a keyboard shortcut.

{% gist 57aff66df11c7e97c3fb10db552d3730 11.ps1 %}

Well, that's my PowerShell profile! I hope this wasn't too long-winded but instead illustrates how flexible and dynamic PowerShell profiles can be.

So, what's in your profile?


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Enyim.Caching.Memcached.KeyTransformers
{
    public static class KeyTransformerUtility
    {
        public static string ToSHA1Hash(string key)
        {
            return new SHA1KeyTransformer().Transform(key);
        }
    }
}


text:
package org.apache.helix.controller.rebalancer.waged.model;

import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.helix.HelixException;

/**
 * This class wraps the required input for the rebalance algorithm.
 */
public class ClusterModel {
  private final ClusterContext _clusterContext;
  // Map to track all the assignable replications. <Resource Name, Set<Replicas>>
  private final Map<String, Set<AssignableReplica>> _assignableReplicaMap;
  // The index to find the replication information with a certain state. <Resource, <Key(resource_partition_state), Replica>>
  // Note that the identical replicas are deduped in the index.
  private final Map<String, Map<String, AssignableReplica>> _assignableReplicaIndex;
  private final Map<String, AssignableNode> _assignableNodeMap;

  /**
   * @param clusterContext         The initialized cluster context.
   * @param assignableReplicas     The replicas to be assigned.
   *                               Note that the replicas in this list shall not be included while initializing the context and assignable nodes.
   * @param assignableNodes        The active instances.
   */
  ClusterModel(ClusterContext clusterContext, Set<AssignableReplica> assignableReplicas,
      Set<AssignableNode> assignableNodes) {
    _clusterContext = clusterContext;

    // Save all the to be assigned replication
    _assignableReplicaMap = assignableReplicas.stream()
        .collect(Collectors.groupingBy(AssignableReplica::getResourceName, Collectors.toSet()));

    // Index all the replicas to be assigned. Dedup the replica if two instances have the same resource/partition/state
    _assignableReplicaIndex = assignableReplicas.stream().collect(Collectors
        .groupingBy(AssignableReplica::getResourceName, Collectors
            .toMap(AssignableReplica::toString, replica -> replica,
                (oldValue, newValue) -> oldValue)));

    _assignableNodeMap = assignableNodes.parallelStream()
        .collect(Collectors.toMap(AssignableNode::getInstanceName, node -> node));
  }

  public ClusterContext getContext() {
    return _clusterContext;
  }

  public Map<String, AssignableNode> getAssignableNodes() {
    return _assignableNodeMap;
  }

  public Map<String, Set<AssignableReplica>> getAssignableReplicaMap() {
    return _assignableReplicaMap;
  }

  /**
   * Assign the given replica to the specified instance and record the assignment in the cluster model.
   * The cluster usage information will be updated accordingly.
   *
   * @param resourceName
   * @param partitionName
   * @param state
   * @param instanceName
   */
  public void assign(String resourceName, String partitionName, String state, String instanceName) {
    AssignableNode node = locateAssignableNode(instanceName);
    AssignableReplica replica = locateAssignableReplica(resourceName, partitionName, state);

    node.assign(replica);
    _clusterContext.addPartitionToFaultZone(node.getFaultZone(), resourceName, partitionName);
  }

  /**
   * Revert the proposed assignment from the cluster model.
   * The cluster usage information will be updated accordingly.
   *
   * @param resourceName
   * @param partitionName
   * @param state
   * @param instanceName
   */
  public void release(String resourceName, String partitionName, String state,
      String instanceName) {
    AssignableNode node = locateAssignableNode(instanceName);
    AssignableReplica replica = locateAssignableReplica(resourceName, partitionName, state);

    node.release(replica);
    _clusterContext.removePartitionFromFaultZone(node.getFaultZone(), resourceName, partitionName);
  }

  private AssignableNode locateAssignableNode(String instanceName) {
    AssignableNode node = _assignableNodeMap.get(instanceName);
    if (node == null) {
      throw new HelixException("Cannot find the instance: " + instanceName);
    }
    return node;
  }

  private AssignableReplica locateAssignableReplica(String resourceName, String partitionName,
      String state) {
    AssignableReplica sampleReplica =
        _assignableReplicaIndex.getOrDefault(resourceName, Collections.emptyMap())
            .get(AssignableReplica.generateReplicaKey(resourceName, partitionName, state));
    if (sampleReplica == null) {
      throw new HelixException(String
          .format("Cannot find the replication with resource name %s, partition name %s, state %s.",
              resourceName, partitionName, state));
    }
    return sampleReplica;
  }
}


text:
package raw.blockChain.services.dbHelper.implementations;

import org.apache.commons.lang3.builder.HashCodeBuilder;

import raw.blockChain.api.Merkler.IntermediateValue;
import raw.blockChain.api.implementations.DefaultHashValue;
import raw.blockChain.api.implementations.DefaultIntermediateValue;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName="intermediatevalue")
public class DataBaseIntermediateValue {

	public static final String ID_FIELD_NAME = "id";
	public static final String HASH_VALUE_FIELD_NAME = "hash";
	public static final String IS_LEFT_PAIRED_FIELD_NAME = "leftPaired";
	public static final String POSITION_IN_STACK_FIELD_NAME = "position";
	public static final String INTERMEDIATE_VALUES_COLLECTION_ID_FIELD_NAME = "intValuesId";

	@DatabaseField(generatedId = true, columnName = ID_FIELD_NAME)
	private int id;
	@DatabaseField(columnName=HASH_VALUE_FIELD_NAME)
	private String hashValue;
	@DatabaseField(columnName=IS_LEFT_PAIRED_FIELD_NAME)
	private boolean leftPaired;
	@DatabaseField(columnName=POSITION_IN_STACK_FIELD_NAME)
	private int positionInStack;
	@DatabaseField(columnName=INTERMEDIATE_VALUES_COLLECTION_ID_FIELD_NAME)
	private int intermediateValuesId;

	public DataBaseIntermediateValue() {
		// Empty constructor for ORM
	}

	public DataBaseIntermediateValue(IntermediateValue intermediateValue, int positionInStack, DataBaseIntermediateValues collection) {
		hashValue = intermediateValue.getValue().toHexString();
		leftPaired = intermediateValue.leftPaired();
		this.positionInStack = positionInStack;
		intermediateValuesId = collection.getId();
	}

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @return the hashValue
	 */
	public String getHashValue() {
		return hashValue;
	}

	/**
	 * @return the leftPaired
	 */
	public boolean isLeftPaired() {
		return leftPaired;
	}

	/**
	 * @return the intermediateValuesId
	 */
	public int getIntermediateValuesId() {
		return intermediateValuesId;
	}

	public IntermediateValue getPlainIntermediateValue(){
		DefaultIntermediateValue intValue = new DefaultIntermediateValue(new DefaultHashValue(hashValue), leftPaired);
		return intValue;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		HashCodeBuilder builder = new HashCodeBuilder();
		builder.append(hashValue)
		.append(leftPaired)
		.append(positionInStack)
		.append(intermediateValuesId);
		return builder.toHashCode();
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof DataBaseIntermediateValue){
			DataBaseIntermediateValue other = (DataBaseIntermediateValue) obj;
			boolean result = this.getPlainIntermediateValue().equals(((DataBaseIntermediateValue) obj).getPlainIntermediateValue());
			result = result && (positionInStack == other.getPositionInStack());
			result = result && (intermediateValuesId == other.getIntermediateValuesId());
			return result;
		}
		return false;
	}

	/**
	 * @return the positionInStack
	 */
	public int getPositionInStack() {
		return positionInStack;
	}

}


text:
package openadk.library.impl.surrogates;

import javax.xml.stream.XMLStreamReader;

import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.ri.model.NodePointer;

import openadk.library.*;
import openadk.library.common.CommonDTD;
import openadk.library.common.PhoneNumber;
import openadk.library.tools.xpath.SIFElementPointer;
import openadk.util.XMLWriter;

/**
 * RenderSurrogate that renders and parses the SIF 1.5r1 and SIF 1.1 PhoneNumber
 * elements into their SIF 2.0 format
 * @author Andrew
 *
 */
public class PhoneNumberSurrogate extends AbstractRenderSurrogate implements RenderSurrogate {

	public PhoneNumberSurrogate( ElementDef def ){
		super( def );
	}

	/* (non-Javadoc)
	 * @see openadk.library.impl.surrogates.RenderSurrogate#renderRaw(openadk.util.XMLWriter, openadk.library.SIFVersion, openadk.library.Element, openadk.library.SIFFormatter)
	 */
	public void renderRaw(XMLWriter writer, SIFVersion version, Element o,
			SIFFormatter formatter) throws SIFException {

		PhoneNumber pn = (PhoneNumber)o;
		if( pn != null  ){
				writer.tab();
				writer.write( "<PhoneNumber" );
				writer.write(" Format=\"NA\"" );
				String type = pn.getType();
				if( type != null ){
					writer.write(" Type=\"" );
					writer.printXmlText( type );
					writer.write( "\">" );
				}
				String number = pn.getNumber();
				if( number != null ){
					writer.printXmlText( number );
				}
				writer.write( "</PhoneNumber>" );
				writer.write( "\r\n" );

		}

	}

	/* (non-Javadoc)
	 * @see openadk.library.impl.surrogates.RenderSurrogate#readRaw(javax.xml.stream.XMLStreamReader, openadk.library.SIFVersion, openadk.library.SIFElement, openadk.library.SIFFormatter)
	 */
	public boolean readRaw(XMLStreamReader reader, SIFVersion version,
			SIFElement parent, SIFFormatter formatter) throws ADKParsingException {

		if( !reader.getLocalName().equals( "PhoneNumber" ) ){
			return false;
		}

		PhoneNumber phone = new PhoneNumber();
		String type = reader.getAttributeValue( null, "Type" );
		if( type != null ){
			phone.setType( type );
		}

		String format = reader.getAttributeValue( null, "Format" );
		if( format != null ){
			phone.setFormat( format );
		}
		String number = consumeElementTextValue( reader, version );
		if( number != null ){
			phone.setNumber( number );
		}

		formatter.addChild( parent, phone, version );

		return true;
	}

	/* (non-Javadoc)
	 * @see openadk.library.impl.surrogates.RenderSurrogate#lookupBySQP(java.lang.String)
	 */
	public ElementDef lookupBySQP(String sqp) {
		if( sqp.length() == 0 ){
			// This query pattern points to the PhoneNumber element itself. The
			// resolved ElementDef should be the PhoneNumber/Number element
			return CommonDTD.PHONENUMBER_NUMBER;
		}
		if( sqp.equals( "@Type" ) ){
			return CommonDTD.PHONENUMBER_TYPE;
		}
		return null;
	}

	public NodePointer createChild(NodePointer parentPointer, SIFFormatter formatter, SIFVersion version, JXPathContext context ) {
		PhoneNumber phone = new PhoneNumber();
		phone.setField( CommonDTD.PHONENUMBER_NUMBER, new SIFString( null ) );
		SIFElement owner = (SIFElement)parentPointer.getBaseValue();
		formatter.addChild(owner, phone, version );
		return new PhoneNumberPointer( parentPointer, phone, version );
	}

	public NodePointer createNodePointer(NodePointer parent, Element element, SIFVersion version) {
		if( !(element instanceof PhoneNumber) ){
			throw new IllegalArgumentException( "Cannot create NodePointer for Elements other than PhoneNumber" );
		}
		return new PhoneNumberPointer( parent, (PhoneNumber)element, version );
	}

	private class PhoneNumberPointer extends SIFElementPointer
	{
		/**
		 *
		 */
		private static final long serialVersionUID = -4097128904146442941L;

		PhoneNumberPointer(NodePointer parentpointer, SIFElement element, SIFVersion version) {
			super(parentpointer, element, version);
		}

		@Override
		public void setValue(Object value) {
			PhoneNumber phone = (PhoneNumber)getBaseValue();
			phone.setNumber( value.toString() );
		}

		@Override
		public Object getValue() {
			PhoneNumber phone = (PhoneNumber)getBaseValue();
			return phone.getField( CommonDTD.PHONENUMBER_NUMBER );
		}

	}

	public String getPath() {
		return "PhoneNumber";
	}

}


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

<title>Uses of Class brown.tracingplane.baggageprotocol.AtomPrefixes.KeyedHeaderPrefix</title>
<meta name="date" content="2017-05-31">
<link rel="stylesheet" type="text/css" href="../../../../javadoc-stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
brown.tracingplane.baggageprotocol.AtomPrefixes.KeyedHeaderPrefix

Packages that use AtomPrefixes.KeyedHeaderPrefix

Package
Description

brown.tracingplane.baggageprotocol

 Defines an encoding scheme for nested data structures using atoms.

Uses of AtomPrefixes.KeyedHeaderPrefix in brown.tracingplane.baggageprotocol

Methods in brown.tracingplane.baggageprotocol that return AtomPrefixes.KeyedHeaderPrefix

Modifier and Type
Method and Description

static AtomPrefixes.KeyedHeaderPrefix
AtomPrefixes.KeyedHeaderPrefix.prefixFor(int level,
         BagOptions options)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package org.real2space.neumann.congraph.core.graph;

import org.real2space.neumann.congraph.core.data.Data;
/**
 * Project Neumann
 *
 * @author RealTwo-Space
 * @version 0
 *
 * created 11/28/16
 */
abstract class Argument {
    abstract Data getDataAt(int index);
    abstract int getSize();
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
    <display-name>vui-battle</display-name>

    <servlet>
        <servlet-name>Groovy</servlet-name>
        <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Groovy</servlet-name>
        <url-pattern>*.groovy</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>


text:
module Themeable

  # Theme's basic module, automatically define methods
  #   - theme_name
  #   - root_path
  #   - theme_path
  module Theme
    def self.included(subclass)

      Themeable.add_theme(subclass)

      # set default values
      caller_file = caller.first
      if caller_file =~ %r{/lib/theme_([^/]*)\.rb}
        default_theme_name = $1.to_sym
        default_root = File.expand_path(File.join(caller_file, '../../'))
      end

      subclass.instance_eval <<-RUBY, __FILE__, __LINE__ + 1
        @theme_name = #{default_theme_name.inspect}

        # Theme name
        #
        # @return [Symbol]
        def theme_name
          @theme_name || raise("Theme name can't be resolved from path: #{__FILE__}")
        end

        @root_path = #{default_root.inspect}

        # Theme project's root path
        #
        # @return [String]
        def root_path
          @root_path || raise("Theme project's root path is no defined")
        end

        # Theme's relative path, 'theme' by default
        #
        # @return [String] default is 'theme'
        def theme_path
          @theme_path || 'theme'
        end

      RUBY
    end
  end
end


text: require File.join(File.expand_path(File.dirname(__FILE__)), "..","resque_stuck_queue")


text:
using content::WebContents;

DEFINE_WEB_CONTENTS_USER_DATA_KEY(web_modal::WebContentsModalDialogManager);

namespace web_modal {

WebContentsModalDialogManager::~WebContentsModalDialogManager() {
  DCHECK(child_dialogs_.empty());
}

void WebContentsModalDialogManager::ShowDialog(
    NativeWebContentsModalDialog dialog) {
  child_dialogs_.push_back(dialog);

  native_manager_->ManageDialog(dialog);

  if (child_dialogs_.size() == 1) {
    if (delegate_ && delegate_->IsWebContentsVisible(web_contents()))
      native_manager_->ShowDialog(dialog);
    BlockWebContentsInteraction(true);
  }
}

bool WebContentsModalDialogManager::IsShowingDialog() const {
  return !child_dialogs_.empty();
}

void WebContentsModalDialogManager::FocusTopmostDialog() {
  DCHECK(!child_dialogs_.empty());
  native_manager_->FocusDialog(child_dialogs_.front());
}

content::WebContents* WebContentsModalDialogManager::GetWebContents() const {
  return web_contents();
}

void WebContentsModalDialogManager::WillClose(
    NativeWebContentsModalDialog dialog) {
  WebContentsModalDialogList::iterator i(
      std::find(child_dialogs_.begin(), child_dialogs_.end(), dialog));

  // The Views tab contents modal dialog calls WillClose twice.  Ignore the
  // second invocation.
  if (i == child_dialogs_.end())
    return;

  bool removed_topmost_dialog = i == child_dialogs_.begin();
  child_dialogs_.erase(i);
  if (!child_dialogs_.empty() && removed_topmost_dialog &&
      !closing_all_dialogs_)
    native_manager_->ShowDialog(child_dialogs_.front());

  BlockWebContentsInteraction(!child_dialogs_.empty());
}

void WebContentsModalDialogManager::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(type == content::NOTIFICATION_WEB_CONTENTS_VISIBILITY_CHANGED);

  if (child_dialogs_.empty())
    return;

  bool visible = *content::Details<bool>(details).ptr();
  if (visible)
    native_manager_->ShowDialog(child_dialogs_.front());
  else
    native_manager_->HideDialog(child_dialogs_.front());
}

WebContentsModalDialogManager::WebContentsModalDialogManager(
    content::WebContents* web_contents)
    : content::WebContentsObserver(web_contents),
      delegate_(NULL),
      native_manager_(CreateNativeManager(this)),
      closing_all_dialogs_(false) {
  DCHECK(native_manager_);
  registrar_.Add(this,
                 content::NOTIFICATION_WEB_CONTENTS_VISIBILITY_CHANGED,
                 content::Source<content::WebContents>(web_contents));
}

void WebContentsModalDialogManager::BlockWebContentsInteraction(bool blocked) {
  WebContents* contents = web_contents();
  if (!contents) {
    // The WebContents has already disconnected.
    return;
  }

  // RenderViewHost may be NULL during shutdown.
  content::RenderViewHost* host = contents->GetRenderViewHost();
  if (host)
    host->SetIgnoreInputEvents(blocked);
  if (delegate_)
    delegate_->SetWebContentsBlocked(contents, blocked);
}

void WebContentsModalDialogManager::CloseAllDialogs() {
  closing_all_dialogs_ = true;

  // Clear out any dialogs since we are leaving this page entirely.
  while (!child_dialogs_.empty())
    native_manager_->CloseDialog(child_dialogs_.front());

  closing_all_dialogs_ = false;
}

void WebContentsModalDialogManager::DidNavigateMainFrame(
    const content::LoadCommittedDetails& details,
    const content::FrameNavigateParams& params) {
  // Close constrained windows if necessary.
  if (!net::registry_controlled_domains::SameDomainOrHost(
          details.previous_url, details.entry->GetURL(),
          net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES))
    CloseAllDialogs();
}

void WebContentsModalDialogManager::DidGetIgnoredUIEvent() {
  if (!child_dialogs_.empty())
    native_manager_->FocusDialog(child_dialogs_.front());
}

void WebContentsModalDialogManager::WebContentsDestroyed(WebContents* tab) {
  // First cleanly close all child dialogs.
  // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
  // some of these to close.  CloseAllDialogs is async, so it might get called
  // twice before it runs.
  CloseAllDialogs();
}

}  // namespace web_modal


text:
/*****************************************************************************/
/* LIBC++ - stack.cpp                                                        */
/* Pile                                                                      */
/* Copyright (c) 2004 Guillaume Morin - All rights reserved                  */
/*****************************************************************************/

#include "stack.hpp"

using namespace std;

// push met une donnée au dessus de la pile
int Stack::push(const void *data)
{
  return insert_next(NULL,data);
}

// push extrait une donnée de la pile
int Stack::pop(void **data)
{
  return remove_next(NULL,data);
}

// push extrait une donnée de la pile sans la supprimer
void *Stack::peek()
{
  return (Head == NULL) ? NULL : Head->Data;
}

// Affichage sur stdout du contenu de la pile
void Stack::display()
{
  List_Element* element;
  int count=0;

  // On affiche les données générales de la pile
  cout << "Stack::display - Size " << Size << " | Dest " << (void*)Destroy << " | Head " << (void*)Head << " | Tail " << (void*)Tail << endl;

  // On affiche un à un les éléments de la pile
  element=Head;
  while(count<Size)
    {
      cout << "Elmt " << ++count << " | ";
      element->display();
      element=element->Next;
    }
}


text:
package io.gatling.charts.stats.buffers

import scala.collection.mutable

import io.gatling.commons.util.Maps._
import io.gatling.charts.stats.UserRecord
import io.gatling.core.stats.IntVsTimePlot
import io.gatling.core.stats.message.{ End, Start }

private[stats] object SessionDeltas {
  val Empty = SessionDeltas(0, 0)
}

private[stats] case class SessionDeltas(starts: Int, ends: Int) {

  def addStart() = copy(starts = starts + 1)
  def addEnd() = copy(ends = ends + 1)
}

private[stats] class SessionDeltaBuffer(minTimestamp: Long, maxTimestamp: Long, buckets: Array[Int], runDurationInSeconds: Int) {

  private val startCounts: Array[Int] = Array.fill(runDurationInSeconds)(0)
  private val endCounts: Array[Int] = Array.fill(runDurationInSeconds)(0)

  def addStart(second: Int): Unit = startCounts(second) += 1

  def addEnd(second: Int): Unit = endCounts(second) += 1

  def endOrphan(): Unit = addEnd(runDurationInSeconds - 1)

  private val bucketWidthInMillis = ((maxTimestamp - minTimestamp) / buckets.length).toInt
  private def secondToBucket(second: Int): Int = math.min(second * 1000 / bucketWidthInMillis, buckets.length - 1)

  def distribution: List[IntVsTimePlot] = {

    val eachSecondActiveSessions = Array.fill(runDurationInSeconds)(0)

    for (second <- 0 until runDurationInSeconds) {
      val previousSessions = if (second == 0) 0 else eachSecondActiveSessions(second - 1)
      val previousEnds = if (second == 0) 0 else endCounts(second - 1)
      val bucketSessions = previousSessions - previousEnds + startCounts(second)
      eachSecondActiveSessions.update(second, bucketSessions)
    }

    eachSecondActiveSessions.zipWithIndex.iterator
      .map { case (sessions, second) => second -> sessions }
      .groupByKey(secondToBucket)
      .map {
        case (bucket, sessionCounts) =>
          val averageSessionCount = sessionCounts.sum / sessionCounts.size
          val time = buckets(bucket)
          IntVsTimePlot(time, averageSessionCount)
      }.toList.sortBy(_.time)
  }
}

private[stats] trait SessionDeltaPerSecBuffers {
  this: Buckets with RunTimes =>

  private val sessionDeltaPerSecBuffers = mutable.Map.empty[Option[String], SessionDeltaBuffer]
  private val orphanStartRecords = mutable.Map.empty[String, UserRecord]
  private val runDurationInSeconds = math.ceil((maxTimestamp - minTimestamp) / 1000.0).toInt

  def getSessionDeltaPerSecBuffers(scenarioName: Option[String]): SessionDeltaBuffer =
    sessionDeltaPerSecBuffers.getOrElseUpdate(scenarioName, new SessionDeltaBuffer(minTimestamp, maxTimestamp, buckets, runDurationInSeconds))

  private def timestamp2SecondOffset(timestamp: Long) = {
    val millisOffset = timestamp - minTimestamp
    val includeRightBorderCorrection =
      if (millisOffset > 0 && millisOffset % 1000 == 0) {
        1
      } else {
        0
      }

    (millisOffset / 1000).toInt - includeRightBorderCorrection
  }

  def addSessionBuffers(record: UserRecord): Unit = {
    record.event match {
      case Start =>
        val startSecond = timestamp2SecondOffset(record.start)
        getSessionDeltaPerSecBuffers(None).addStart(startSecond)
        getSessionDeltaPerSecBuffers(Some(record.scenario)).addStart(startSecond)
        orphanStartRecords += record.userId -> record

      case End =>
        val endSecond = timestamp2SecondOffset(record.end)
        getSessionDeltaPerSecBuffers(None).addEnd(endSecond)
        getSessionDeltaPerSecBuffers(Some(record.scenario)).addEnd(endSecond)
        orphanStartRecords -= record.userId
    }
  }

  def endOrphanUserRecords(): Unit =
    orphanStartRecords.values.foreach { start =>
      getSessionDeltaPerSecBuffers(None).endOrphan()
      getSessionDeltaPerSecBuffers(Some(start.scenario)).endOrphan()
    }
}


text:
"""
The ``astc_test_image_dl`` utility provides a means to programatically download
test images that are available online, avoiding the need to duplicate them in
the git repository.
"""

import os
import sys
import urllib.request

from PIL import Image

TEST_IMAGE_DIR = os.path.join("Test", "Images")

def download(testSet, index, srcUrl, dstPath):
    """
    Download a single image.

    Args:
        testSet (str): The test set name.
        index (int): The download index.
        srcUrl (str): The download URL.
        dstPath (str): The destination path.
    """
    dirName = os.path.dirname(dstPath)
    if not os.path.exists(dirName):
        os.makedirs(dirName)

    # Skip downloads if the file already exists
    if not os.path.exists(dstPath):
        print("%s image %u: Downloading" % (testSet, index))
        urllib.request.urlretrieve(srcUrl, dstPath)
    else:
        print("%s image %u: Skipping" % (testSet, index))

def make_landscape(imgPath):
    """
    Make an image on disk landscape aspect (edit in place)

    Args:
        imgPath: The pth of the image on disk.
    """
    img = Image.open(imgPath)
    if img.size[0] < img.size[1]:
        img = img.rotate(90, expand=True)
        img.save(imgPath)

def make_mixed_image(imgPathA, imgPathB, dstPath):
    """
    Make image consisting of RGB from A's RGB, and alpha from B's luminance.

    Args:
        imgPathA: The path of input A on disk.
        imgPathB: The path of input B on disk.
        dstPath: The path of the destination.
    """
    imgA = Image.open(imgPathA)
    imgB = Image.open(imgPathB).convert("L")

    imgA.putalpha(imgB)

    dirs = os.path.dirname(dstPath)
    if not os.path.exists(dirs):
        os.makedirs(dirs)

    imgA.save(dstPath)

def make_montage(imageDir, dstPath):
    """
    Make a single mosaic montage consisting of all of the Kodak images.

    Args:
        imgDir: The directory path of the Kodak images on disk.
        dstPth: The file path of the resulting montage.
    """
    cols = 6
    rows = 4

    width = 768
    height = 512

    images = os.listdir(imageDir)
    images.sort()

    montage = Image.new('RGB', (width * cols, height * rows))

    for i, src in enumerate(images):
        im = Image.open(os.path.join(imageDir, src))
        col = i % cols
        row = i // cols
        montage.paste(im, (width * col, height * row))

    dirs = os.path.dirname(dstPath)
    if not os.path.exists(dirs):
        os.makedirs(dirs)

    montage.save(dstPath)

def retrieve_kodak_set():
    """
    Download the public domain Kodak image set.

    To make test set mosaics easier to build we rotate images to make
    everything landscape.
    """
    testSet = "Kodak"

    # Download the original RGB images
    for i in range(1, 25):
        fle = "ldr-rgb-kodak%02u.png" % i
        dst = os.path.join(TEST_IMAGE_DIR, "Kodak", "LDR-RGB", fle)
        src = "http://r0k.us/graphics/kodak/kodak/kodim%02u.png" % i
        download(testSet, i, src, dst)

        # Canonicalize image aspect
        make_landscape(dst)

    # Make some correlated alpha RGBA images
    fle = "ldr-rgb-kodak%02u.png"  # Expand later
    pattern = os.path.join(TEST_IMAGE_DIR, "Kodak", "LDR-RGB", fle)

    for i in (22, 23):
        imgA = pattern % i
        fle = "ldr-rgba-kodak%02u+ca.png" % i
        dst = os.path.join(TEST_IMAGE_DIR, "KodakSim", "LDR-RGBA", fle)
        make_mixed_image(imgA, imgA, dst)

    # Make some non-correlated alpha RGBA images
    for i, j in ((22, 24), (23, 20)):
        imgA = pattern % i
        imgB = pattern % j
        fle = "ldr-rgba-kodak%02u+%02u+nca.png" % (i, j)
        dst = os.path.join(TEST_IMAGE_DIR, "KodakSim", "LDR-RGBA", fle)
        make_mixed_image(imgA, imgB, dst)

    # Make a large montage
    srcDir = os.path.join(TEST_IMAGE_DIR, "Kodak", "LDR-RGB")
    fle = "ldr-rgb-montage.png"
    dst = os.path.join(TEST_IMAGE_DIR, "KodakMnt", "LDR-RGB", fle)
    make_montage(srcDir, dst)

def main():
    """
    The main function.

    Returns:
        int: The process return code.
    """
    retrieve_kodak_set()
    return 0

if __name__ == "__main__":
    sys.exit(main())


text:
% DEMROBOTWIRELESSMEU3 Model the stick man with MEU using 7 neighbors.

% MEU

% Fix seeds
randn('seed', 1e5);
rand('seed', 1e5);

dataSetName = 'robotWireless';
experimentNo = 3;

% load data
[Y, lbls] = lvmLoadData(dataSetName);
meanY = mean(Y);
Y = Y - repmat(meanY, size(Y, 1), 1);

% Set up model
latentDim = 2;
options = meuOptions(7, 0, true);
options.gammaOptimize = false;
d = size(Y, 2);
model = meuCreate(latentDim, d, Y, options);
model.gamma = 1e4;
% Optimise the model.
iters = 100;
display = 3;

model = meuOptimise(model, display, iters);

if exist('printDiagram') & printDiagram
  lvmPrintPlot(model, lbls, dataSetName, experimentNo);
else
  clf;
  lvmScatterPlot(model, lbls);
end
fprintf('Scoring model.\n');
model.lambda = eig(model.K)/trace(model.K);
model.score = lvmScoreModel(model);
fprintf('Model score %2.4f\n', model.score);

% Save the results.
modelWriteResult(model, dataSetName, experimentNo);


text:
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

import Page = require('../../../../../base/Page');
import Response = require('../../../../../http/response');
import V2010 = require('../../../V2010');
import serialize = require('../../../../../base/serialize');
import { SerializableClass } from '../../../../../interfaces';

/**
 * @description Initialize the VoipList
 *
 * @param version - Version of the resource
 * @param accountSid - The 34 character string that uniquely identifies your account.
 * @param countryCode - The ISO Country code to lookup phone numbers for.
 */
declare function VoipList(version: V2010, accountSid: string, countryCode: string): VoipListInstance;

interface VoipListInstance {
  /**
   * Streams VoipInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param opts - Options for request
   * @param callback - Function to process each record
   */
  each(opts?: VoipListInstanceEachOptions, callback?: (item: VoipInstance, done: (err?: Error) => void) => void): void;
  /**
   * Retrieve a single target page of VoipInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param targetUrl - API-generated URL for the requested results page
   * @param callback - Callback to handle list of records
   */
  getPage(targetUrl?: string, callback?: (error: Error | null, items: VoipPage) => any): Promise<VoipPage>;
  /**
   * Lists VoipInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  list(opts?: VoipListInstanceOptions, callback?: (error: Error | null, items: VoipInstance[]) => any): Promise<VoipInstance[]>;
  /**
   * Retrieve a single page of VoipInstance records from the API.
   * Request is executed immediately
   *
   * If a function is passed as the first argument, it will be used as the callback function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  page(opts?: VoipListInstancePageOptions, callback?: (error: Error | null, items: VoipPage) => any): Promise<VoipPage>;
}

/**
 * Options to pass to each
 *
 * @property areaCode - The area_code
 * @property beta - The beta
 * @property callback -
 *                         Function to process each record. If this and a positional
 *                         callback are passed, this one will be used
 * @property contains - The contains
 * @property distance - The distance
 * @property done - Function to be called upon completion of streaming
 * @property excludeAllAddressRequired - The exclude_all_address_required
 * @property excludeForeignAddressRequired - The exclude_foreign_address_required
 * @property excludeLocalAddressRequired - The exclude_local_address_required
 * @property faxEnabled - The fax_enabled
 * @property inLata - The in_lata
 * @property inLocality - The in_locality
 * @property inPostalCode - The in_postal_code
 * @property inRateCenter - The in_rate_center
 * @property inRegion - The in_region
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         each() guarantees never to return more than limit.
 *                         Default is no limit
 * @property mmsEnabled - The mms_enabled
 * @property nearLatLong - The near_lat_long
 * @property nearNumber - The near_number
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no pageSize is defined but a limit is defined,
 *                         each() will attempt to read the limit with the most efficient
 *                         page size, i.e. min(limit, 1000)
 * @property smsEnabled - The sms_enabled
 * @property voiceEnabled - The voice_enabled
 */
interface VoipListInstanceEachOptions {
  areaCode?: number;
  beta?: boolean;
  callback?: (item: VoipInstance, done: (err?: Error) => void) => void;
  contains?: string;
  distance?: number;
  done?: Function;
  excludeAllAddressRequired?: boolean;
  excludeForeignAddressRequired?: boolean;
  excludeLocalAddressRequired?: boolean;
  faxEnabled?: boolean;
  inLata?: string;
  inLocality?: string;
  inPostalCode?: string;
  inRateCenter?: string;
  inRegion?: string;
  limit?: number;
  mmsEnabled?: boolean;
  nearLatLong?: string;
  nearNumber?: string;
  pageSize?: number;
  smsEnabled?: boolean;
  voiceEnabled?: boolean;
}

/**
 * Options to pass to list
 *
 * @property areaCode - The area_code
 * @property beta - The beta
 * @property contains - The contains
 * @property distance - The distance
 * @property excludeAllAddressRequired - The exclude_all_address_required
 * @property excludeForeignAddressRequired - The exclude_foreign_address_required
 * @property excludeLocalAddressRequired - The exclude_local_address_required
 * @property faxEnabled - The fax_enabled
 * @property inLata - The in_lata
 * @property inLocality - The in_locality
 * @property inPostalCode - The in_postal_code
 * @property inRateCenter - The in_rate_center
 * @property inRegion - The in_region
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         list() guarantees never to return more than limit.
 *                         Default is no limit
 * @property mmsEnabled - The mms_enabled
 * @property nearLatLong - The near_lat_long
 * @property nearNumber - The near_number
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no page_size is defined but a limit is defined,
 *                         list() will attempt to read the limit with the most
 *                         efficient page size, i.e. min(limit, 1000)
 * @property smsEnabled - The sms_enabled
 * @property voiceEnabled - The voice_enabled
 */
interface VoipListInstanceOptions {
  areaCode?: number;
  beta?: boolean;
  contains?: string;
  distance?: number;
  excludeAllAddressRequired?: boolean;
  excludeForeignAddressRequired?: boolean;
  excludeLocalAddressRequired?: boolean;
  faxEnabled?: boolean;
  inLata?: string;
  inLocality?: string;
  inPostalCode?: string;
  inRateCenter?: string;
  inRegion?: string;
  limit?: number;
  mmsEnabled?: boolean;
  nearLatLong?: string;
  nearNumber?: string;
  pageSize?: number;
  smsEnabled?: boolean;
  voiceEnabled?: boolean;
}

/**
 * Options to pass to page
 *
 * @property areaCode - The area_code
 * @property beta - The beta
 * @property contains - The contains
 * @property distance - The distance
 * @property excludeAllAddressRequired - The exclude_all_address_required
 * @property excludeForeignAddressRequired - The exclude_foreign_address_required
 * @property excludeLocalAddressRequired - The exclude_local_address_required
 * @property faxEnabled - The fax_enabled
 * @property inLata - The in_lata
 * @property inLocality - The in_locality
 * @property inPostalCode - The in_postal_code
 * @property inRateCenter - The in_rate_center
 * @property inRegion - The in_region
 * @property mmsEnabled - The mms_enabled
 * @property nearLatLong - The near_lat_long
 * @property nearNumber - The near_number
 * @property pageNumber - Page Number, this value is simply for client state
 * @property pageSize - Number of records to return, defaults to 50
 * @property pageToken - PageToken provided by the API
 * @property smsEnabled - The sms_enabled
 * @property voiceEnabled - The voice_enabled
 */
interface VoipListInstancePageOptions {
  areaCode?: number;
  beta?: boolean;
  contains?: string;
  distance?: number;
  excludeAllAddressRequired?: boolean;
  excludeForeignAddressRequired?: boolean;
  excludeLocalAddressRequired?: boolean;
  faxEnabled?: boolean;
  inLata?: string;
  inLocality?: string;
  inPostalCode?: string;
  inRateCenter?: string;
  inRegion?: string;
  mmsEnabled?: boolean;
  nearLatLong?: string;
  nearNumber?: string;
  pageNumber?: number;
  pageSize?: number;
  pageToken?: string;
  smsEnabled?: boolean;
  voiceEnabled?: boolean;
}

interface VoipPayload extends VoipResource, Page.TwilioResponsePayload {
}

interface VoipResource {
  address_requirements: string;
  beta: boolean;
  capabilities: string;
  friendly_name: string;
  iso_country: string;
  lata: string;
  latitude: number;
  locality: string;
  longitude: number;
  phone_number: string;
  postal_code: string;
  rate_center: string;
  region: string;
}

interface VoipSolution {
  accountSid?: string;
  countryCode?: string;
}

declare class VoipInstance extends SerializableClass {
  /**
   * Initialize the VoipContext
   *
   * @property friendlyName - The friendly_name
   * @property phoneNumber - The phone_number
   * @property lata - The lata
   * @property locality - The locality
   * @property rateCenter - The rate_center
   * @property latitude - The latitude
   * @property longitude - The longitude
   * @property region - The region
   * @property postalCode - The postal_code
   * @property isoCountry - The iso_country
   * @property addressRequirements - The address_requirements
   * @property beta - The beta
   * @property capabilities - The capabilities
   *
   * @param version - Version of the resource
   * @param payload - The instance payload
   * @param accountSid - The 34 character string that uniquely identifies your account.
   * @param countryCode - The ISO Country code to lookup phone numbers for.
   */
  constructor(version: V2010, payload: VoipPayload, accountSid: string, countryCode: string);

  addressRequirements: string;
  beta: boolean;
  capabilities: string;
  friendlyName: string;
  isoCountry: string;
  lata: string;
  latitude: number;
  locality: string;
  longitude: number;
  phoneNumber: string;
  postalCode: string;
  rateCenter: string;
  region: string;
  /**
   * Produce a plain JSON object version of the VoipInstance for serialization.
   * Removes any circular references in the object.
   */
  toJSON(): any;
}

declare class VoipPage extends Page<V2010, VoipPayload, VoipResource, VoipInstance> {
  /**
   * Initialize the VoipPage
   *
   * @param version - Version of the resource
   * @param response - Response from the API
   * @param solution - Path solution
   */
  constructor(version: V2010, response: Response<string>, solution: VoipSolution);

  /**
   * Build an instance of VoipInstance
   *
   * @param payload - Payload response from the API
   */
  getInstance(payload: VoipPayload): VoipInstance;
}

export { VoipInstance, VoipList, VoipListInstance, VoipListInstanceEachOptions, VoipListInstanceOptions, VoipListInstancePageOptions, VoipPage, VoipPayload, VoipResource, VoipSolution }


text:
                    <?php echo $this->session->flashdata('success_profile_update');?>
                    <?php echo $this->session->flashdata('success');?>
                    <?php echo $this->session->flashdata('error');?>

                            <?php echo strtoupper($panel_title); ?>

                            <?php echo $about->description;?>

                            <a href="<?php echo base_url().'admin/admin-company-edit/'.$about->id;?>" class="btn btn-primary"> Update
                            <?php $btn_text = ($about->status == 0) ? 'Enable' : 'Disable'; ?>
                            <?php $btn_type = ($about->status == 0) ? 'success' : 'warning'; ?>
                            <?php $status_icon = ($about->status == 0) ? 'ok-sign' : 'remove-sign'; ?>
                            <a onclick="change_status(<?php echo $about->id;?>, <?php echo $about->status;?>)"  class="btn btn-<?php echo $btn_type;?>">
                                <span class="glyphicon glyphicon-<?php echo $status_icon;?>">
                                <?php echo $btn_text;?>


text:
package com.amazonaws.services.cognitosync.model;

import java.io.Serializable;

/**
 *

 * Response to a RegisterDevice request.
 *

 */
public class RegisterDeviceResult implements Serializable, Cloneable {

    /**
     *

     * The unique ID generated for this device by Cognito.
     *

     */
    private String deviceId;

    /**
     *

     * The unique ID generated for this device by Cognito.
     *

     *
     * @param deviceId
     *        The unique ID generated for this device by Cognito.
     */
    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }

    /**
     *

     * The unique ID generated for this device by Cognito.
     *

     *
     * @return The unique ID generated for this device by Cognito.
     */
    public String getDeviceId() {
        return this.deviceId;
    }

    /**
     *

     * The unique ID generated for this device by Cognito.
     *

     *
     * @param deviceId
     *        The unique ID generated for this device by Cognito.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public RegisterDeviceResult withDeviceId(String deviceId) {
        setDeviceId(deviceId);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDeviceId() != null)
            sb.append("DeviceId: " + getDeviceId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof RegisterDeviceResult == false)
            return false;
        RegisterDeviceResult other = (RegisterDeviceResult) obj;
        if (other.getDeviceId() == null ^ this.getDeviceId() == null)
            return false;
        if (other.getDeviceId() != null
                && other.getDeviceId().equals(this.getDeviceId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getDeviceId() == null) ? 0 : getDeviceId().hashCode());
        return hashCode;
    }

    @Override
    public RegisterDeviceResult clone() {
        try {
            return (RegisterDeviceResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request as Request;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\EncryptedFile;
use Auth;
use File;
use Response;
use Storage;

class ApiController extends Controller
{
	public function signin(Request $request)
    {
        $user = User::where('email', $request->input('email'))->first();
        if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
            $user->api_token = str_random(60); // On génére un nouveau token aléatoire
            $user->save();
            return Response::make(
                    json_encode(array('result' => 'ok', 'api_token' => $user->api_token, 'key' => File::get('D39B74E6.asc'), 'key_id' => "D39B74E6")),
                    200,
                    array('Content-Type' => 'application/json; charset=utf-8')
                );
        }
        return Response::make(
            json_encode(array('error' => "Bad credentials")),
            401,
            array('Content-Type' => 'application/json; charset=utf-8')
        );
    }

    public function upload(Request $request)
    {
        $u = Auth::guard('api')->user();

        // var_dump($request->all());
        // var_dump($request->file("Stegano1.jpg"));

        $res = "upload error";
        if ($request->hasFile('document')) {
            $res = "document uploaded";
            $doc_file = $request->file('document');
            $filename = $doc_file->getClientOriginalName();
            // fonctionne
            $doc_file->move(public_path('files'), $doc_file->getClientOriginalName());
            // dans le file bucket peut être ?
            // $doc_file->move(public_path('safezone_fb'), $filename);
            // var_dump($doc_file);
            $file = new EncryptedFile;
            $file->content = $filename;
            // var_dump($file->content);
            $file->user_id = $u->id;
            $file->save();
        }

        return Response::make(
            json_encode(array('result' => $res)),
            200,
            array('Content-Type' => 'application/json; charset=utf-8')
        );
    }

    public function testUpload(Request $request)
    {
        return view('safezone.testupload');
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

namespace AuditCdUse
{
    class MySqlConn
    {
        private MySqlConnection connection;
        private string server;
        private string database;
        private string uid;
        private string password;
        private string connectionString;

        private void Init()
        {
            server = "CDDB.grove.ad.uconn.edu";
            database = "cddb";
            uid = "cddbUser";
            password = "uwmbtlpup4ldHt7nzA76";
            //string connectionString;

            connectionString = "SERVER=" + server + ";" + "DATABASE=" +
                                database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

            connection = new MySqlConnection(connectionString);

        }

        public MySqlConn()
        {
            Init();
        }

        private bool OpenConnection()
        {
            try
            {
                connection.Open();

                if(connection.State != System.Data.ConnectionState.Open)
                {
                    connection = new MySqlConnection(connectionString);
                    connection.Open();
                }

                return true;
            }
            catch (MySqlException ex)
            {
                //When handling errors, you can your application's response based
                //on the error number.
                //The two most common error numbers when connecting are as follows:
                //0: Cannot connect to server.
                //1045: Invalid user name and/or password.
                switch (ex.Number)
                {
                    case 0:
                        Debug.WriteLine("Cannot connect to server.  Contact administrator");
                        break;

                    case 1045:
                        Debug.WriteLine("Invalid username/password, please try again");
                        break;
                    case 1042:
                        Debug.WriteLine("Cannot contact the MySQL host");
                        break;
                }
                return false;
            }
        }

        private bool CloseConnection()
        {
            try
            {
                connection.Close();
                return true;
            }
            catch (MySqlException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return false;
            }
        }

        public int InsertCdEvent(string machineName, string userName, string cdTitle)
        {
            DateTime dateValue = DateTime.Now;
            string sqlDateString = dateValue.ToString("yyyy-MM-dd HH:mm:ss");
            string insert = String.Format("INSERT INTO cddb.cd_events(MachineName, EventDateTime, UserName, CdTitle) VALUES('{0}','{1}','{2}','{3}')", machineName, sqlDateString, userName, cdTitle);
            //string insert = String.Format("INSERT INTO cddb.cd_events(MachineName, EventDateTime, UserName) VALUES('{0}','{1}','{2}')", machineName, sqlDateString, userName, cdTitle);
            if (this.OpenConnection() == true)
            {
                MySqlCommand cmd = new MySqlCommand(insert, connection);
                cmd.ExecuteNonQuery();
                this.CloseConnection();
                Debug.WriteLine("INSERT SENT");
                return 1;
            }
            else
            {
                return 0;
            }
        }

    }
}


text:
**Color Segmentation**
========================
*This is a blog entry from [License Plate Object Identification Blogs](http://chenyumin.com/p/license-plate-object-detection-4-color-segmentation).*

This week, color segmentation is introduced in this project to separate the blue vertical band to the left of the license plate containing the 12 stars of the Flag of Europe.

```matlab
% Convert to HSV color space
imageHsv = rgb2hsv(image);
h = imageHsv(:, :, 1);
s = imageHsv(:, :, 2);
v = imageHsv(:, :, 3);

% Segment using color
roi = ((h > 0.5) & (h < 0.833)) & (s > 0.5) & (v > 0.5);

% Restore to RGB colored image
output = image;
for i = 1:3
    output(:, :, i) = roi .* image(:, :, i);
end
```

------------------------
Previous: [Week 3: Edge Detection](./week3.md)
Next: [Week 5: Finishing Up](./week5.md)


text:
package org.gradle.internal.nativeintegration.filesystem;

import org.gradle.internal.file.FileMetadataSnapshot;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

public interface FileMetadataAccessor {
    FileMetadataSnapshot stat(File f);
    FileMetadataSnapshot stat(Path path) throws IOException;
}


text:
boardApp.factory('teamService', function() {

    var team = {
        name: 'Stellarwinds',
        image: 'http://stellarwinds.io/images/seo.png',
        city: 'Oklahoma City',
        tagLine: 'At the space bar...',
        github: 'https://github.com/AmbitiousOkie',
        facebook: false,
        twitter: 'https://twitter.com/ambitiousokie',
        email: 'kris@urbanscouter.com'
    };

    //  ---- Getters--------------------
    function getTeam() {
        return team;
    }

    // Setters ---------------------------

    // Factory returns -----------------------
    return {
        getTeam: getTeam
    }
});

boardApp.controller('teamController', function teamController($scope, teamService, navService, stateService) {
    stateService.setTabState('Main');

    $scope.$watch(function() {
        return stateService.getTabState();
    }, function(value) {
        $scope.state = value;

    });

    $scope.getTeamTabs = navService.getTeamTabs;
    $scope.tabs = $scope.getTeamTabs();
    $scope.team = teamService.getTeam();

});


text:
'use strict';

module.exports = function(app) {
	// Root routing
	var core = require('../../app/controllers/core.server.controller');
	app.route('/').get(core.index);
	app.route('/jquerytest').get(core.jquerytest);
	app.route('/getdseData').get(core.dseprocess );
    app.route('/getdseDaily').get(core.dsedaily);

};


text:
namespace mx
{
    namespace core
    {

        MX_FORWARD_DECLARE_ELEMENT( EndLine )

        inline EndLinePtr makeEndLine() { return std::make_shared<EndLine>(); }

        class EndLine : public ElementInterface
        {
        public:
            EndLine();

            virtual bool hasAttributes() const;
            virtual bool hasContents() const;
            virtual std::ostream& streamAttributes( std::ostream& os ) const;
            virtual std::ostream& streamName( std::ostream& os ) const;
            virtual std::ostream& streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const;

            private:
            virtual bool fromXElementImpl( std::ostream& message, ::ezxml::XElement& xelement );
        };
    }
}


text:
from typing import List
from discord import Message, Embed
from discord.ext.commands import command, Context, Cog

from .youtube_result import YoutubeResult
from ..bunkbot import BunkBot
from ..core.bunk_exception import BunkException
from ..core.functions import get_cmd_params
from ..core.registry import CHANNEL_SERVICE
from ..channel.channel_service import ChannelService

MORE_TITLE = "Type !ytl 1-5 to link another video\nType !link or !link 0 to relink the original result\n"

YOUTUBE_DESCRIPTION = """
    Search for a youtube video with a given query. Display related videos with !more and re-link a related video with !ytl

    Example: !yt heroes of the storm
    Example: !more
    Example: !ytl 2
"""
class Youtube(Cog):
    def __init__(self, bot: BunkBot, channels: ChannelService):
        """
        Description
        ------------
        A cog that enables the ability to search and embed youtube videos

        Parameters
        -----------
        bot: Bunkbot
            Super class instance of the bot

        database: DatabaseService
            Super class instance of the database service

        channels: ChannelService
            Access to the server channels and other channel functions
        """
        self.bot: BunkBot = bot
        self.message: Message = None
        self.channels: ChannelService = channels
        self.yt_result: YoutubeResult = YoutubeResult()
        self.yt_link: str = ""

    @command(help=YOUTUBE_DESCRIPTION, aliases=["youtube"])
    async def yt(self, ctx: Context) -> None:
        """
        Description
        ------------
        Perform a basic youtube search with a given keyword

        Parameters
        -----------
        ctx: Context
            Discord request context
        """
        try:
            params: List[str] = get_cmd_params(ctx)

            if len(params) == 0:
                await ctx.send("No youtube query given")
                return

            await ctx.trigger_typing()

            self.yt_link = self.yt_result.query(params)

            self.message = await ctx.send(self.yt_link)
        except BunkException as be:
            await ctx.send(be.message)
        except Exception as e:
            msg = "Oops, I messed up. Here is your search: {0}".format(self.yt_result.qualified_query)
            await ctx.send(msg)
            await self.channels.log_error(e, "yt")

    @command(help="Link another youtube result from the last search", aliases=["ytl"])
    async def link(self, ctx: Context) -> None:
        """
        Description
        ------------
        Replace the video from the previous search based on the value entered (1-5)

        Parameters
        -----------
        ctx: Context
            Discord request context
        """
        try:
            params: List[str] = get_cmd_params(ctx)

            if len(params) < 1 or not params[0].isdigit() or int(params[0]) > len(self.yt_result.ids):
                await ctx.send("Please enter a valid video number from 0 to 5")
                return

            self.yt_link = await self.message.edit(content=self.yt_result.get_link(int(params[0])))
            await ctx.message.delete()
        except Exception as e:
            await self.channels.log_error(e, "ytl")

    @command(help="Get a list of related videos from the last youtube search")
    async def more(self, ctx: Context) -> None:
        """
        Description
        ------------
        Get a list of related videos from the last youtube search

        Parameters
        -----------
        ctx: Context
        Discord request context
        """
        e_title: str = MORE_TITLE
        e_message: str = "\n".join(self.yt_result.titles)
        embed: Embed = Embed(title=e_title, description=e_message, color=int("CC181E", 16))

        await ctx.send(embed=embed)
        await ctx.message.delete()

def setup(bot: BunkBot) -> None:
    bot.add_cog(Youtube(bot, CHANNEL_SERVICE))


text:
<?php

namespace rapidweb\googlecontacts\objects;

class Contact
{
    public function __construct($contactDetails)
    {
        foreach ($contactDetails as $key => $value) {
            $this->$key = $value;
        }
    }
}


text:
```bash
sudo apt update
sudo apt install mariadb-server
sudo mysql_secure_installation
```

## Access Database from outside
Open `/etc/mysql/mariadb.conf.d/50-server.cnf` and change the `bind-address` to:
```
...

bind-address = 0.0.0.0

...
```
## Create Administrative User
1. Create a new user `newuser` for the host `localhost` with a new `password`:
```mysql
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
```

2. Grant all permissions to the new user
```mysql
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
```

3. Update permissions
```mysql
FLUSH PRIVILEGES;
```


text:
<?php

/**
 * Exception thrown by the lexer.
 */

namespace PhpMyAdmin\SqlParser\Exceptions;

/**
 * Exception thrown by the lexer.
 *
 * @category   Exceptions
 *
 * @license    https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
 */
class LoaderException extends \Exception
{
    /**
     * The failed load name.
     *
     * @var string
     */
    public $name;

    /**
     * Constructor.
     *
     * @param string $msg  the message of this exception
     * @param string $ch   the character that produced this exception
     * @param int    $pos  the position of the character
     * @param int    $code the code of this error
     */
    public function __construct($msg = '', $name = '', $code = 0)
    {
        parent::__construct($msg, $code);
        $this->name = $name;
    }
}