text:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class ucPatientPortalAccount : System.Web.UI.UserControl
{
    public long lUsrRightMode { get; set; }
    bool bControlsEnabled;
    CSec usrsec = new CSec();

    public BaseMaster BaseMstr { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        CheckUserRightsMode();
    }

    protected void EnablePasswordFields()
    {
        txtPassword.Enabled = true;
        txtVerifyPassword.Enabled = true;
    }

    protected void DisablePasswordFields()
    {
        txtPassword.Enabled = false;
        txtVerifyPassword.Enabled = false;
    }

    protected void btnResetPassword_click(object sender, EventArgs e)
    {
        if (txtPassword.Enabled)
        {
            txtPassword.Text = "";
            txtVerifyPassword.Text = "";
            DisablePasswordFields();
        }
        else
        {
            EnablePasswordFields();
            txtPassword.Focus();
        }
    }

    public void loadPatientPortalAccount()
    {
        txtPassword.Enabled = false;
        txtVerifyPassword.Enabled = false;

        BaseMstr.SetVSValue("NewPatientPortalAcct", false);

        BaseMstr.SetVSValue("PatientFXUserIDExists", false);

        BaseMstr.SetVSValue("PatientFXUserIDExists", CheckIfPatientFXUserRecExists());

        bool bFXUserIDExists = BaseMstr.GetVSBoolValue("PatientFXUserIDExists");

        if (!bFXUserIDExists)
        {
            txtPassword.Enabled = true;
            txtVerifyPassword.Enabled = true;
            txtUserId.Enabled = true;
            chkResetPassword.Enabled = false;

            BaseMstr.SetVSValue("NewPatientPortalAcct", true);
        }
        else
        {
            CDataUtils utils = new CDataUtils();
            CSec sec = new CSec();

            DataSet dsSecData = new DataSet();

            //attempt to grab the user's profile
            dsSecData = sec.GetPatientFXUsernamePasswordDS(BaseMstr);

            //load FXUser Username and Password fields
            if (dsSecData != null)
            {
                txtUserId.Text = sec.dec(utils.GetStringValueFromDS(dsSecData, "USER_NAME"),"");
                chkbxAccountLocked.Checked = Convert.ToBoolean(utils.GetLongValueFromDS(dsSecData, "IS_LOCKED"));
                chkbxAccountInactive.Checked = Convert.ToBoolean(utils.GetLongValueFromDS(dsSecData, "IS_INACTIVE"));

                txtUserId.Enabled = false;
                divResetPWDButton.Visible = true;
                chkResetPassword.Enabled = true;
                txtPassword.Enabled = false;
                txtVerifyPassword.Enabled = false;
            }
        }

        Page_Load(null, EventArgs.Empty);
    }

    protected bool CheckIfPatientFXUserRecExists()
    {
        CSec sec = new CSec();
        DataSet secDataChk = sec.CheckPatientFXUserRecDS(BaseMstr);

        //load all of the patient's available fields
        if (secDataChk != null)
        {
            foreach (DataTable secTable in secDataChk.Tables)
            {
                foreach (DataRow secRow in secTable.Rows)
                {
                    if (!secRow.IsNull("FXUSERCOUNT"))
                    {
                        long lFXUserCount = Convert.ToInt32(secRow["FXUSERCOUNT"]);
                        if (lFXUserCount > 0)
                        {
                            return true;
                        }
                    }
                }
            }
        }

        return false;

    }

    protected long getPatientFXUserID()
    {
        long Value = 0;

        CSec fxSec = new CSec();

        DataSet SecSet = new DataSet();
        SecSet = fxSec.GetPatientFXUserIdDS(BaseMstr);

        //load all of the user's available fields
        if (SecSet != null)
        {
            foreach (DataTable secTable in SecSet.Tables)
            {
                foreach (DataRow secRow in secTable.Rows)
                {
                    if (!secRow.IsNull("FX_USER_ID"))
                    {
                        Value = Convert.ToInt64(secRow["FX_USER_ID"]);
                    }
                }
            }
        }

        return Value;
    }

    public bool SavePatientPortalAccount()
    {
        bool bSaved = false;

        CheckUserRightsMode();
        bool bIsReadOnly = (
            ((BaseMstr.APPMaster.UserType != (long)SUATUserType.ADMINISTRATOR) && lUsrRightMode < (long)RightMode.ReadWrite)
            || ((BaseMstr.APPMaster.UserType == (long)SUATUserType.ADMINISTRATOR) && usrsec.GetRightMode(BaseMstr, (long)SUATUserRight.AdministratorUR) < (long)RightMode.ReadWrite)
            );

        if (bIsReadOnly)
        {
            return false;
        }
        else
        {
            //fx sec Patient helper
            CSec sec = new CSec();
            long lFXUserID = 0;

            bool bUserExists = CheckIfPatientFXUserRecExists();
            bool bChkInsPatPortalAccount = CheckPatientFXUser(sec, !bUserExists);

            if (bChkInsPatPortalAccount)
            {
                bool m_bFXUserIDExists = bUserExists;

                if (!m_bFXUserIDExists)
                {
                    bSaved = sec.InsertPatientFXUser(BaseMstr,
                                             BaseMstr.SelectedPatientID,
                                             txtUserId.Text,
                                             txtPassword.Text,
                                             chkbxAccountLocked.Checked,
                                             chkbxAccountInactive.Checked,
                                             out lFXUserID);

                    if (BaseMstr.StatusCode == 0)
                    {
                        txtUserId.Enabled = false;
                        divPassword.Visible = true;
                        divResetPWDButton.Visible = true;
                    }
                }
                else
                {
                    //update a record into the fx_user table and update
                    //the fx_user_id in the patient table
                    lFXUserID = getPatientFXUserID();
                }

                //ONLY if we changed the users account info, update the
                //record in the FX_USER table
                if (txtPassword.Enabled)
                {
                    bSaved = sec.UpdatePatientFXUserPWD(BaseMstr,
                                                lFXUserID,
                                                txtUserId.Text,
                                                txtPassword.Text,
                                                chkbxAccountLocked.Checked,
                                                chkbxAccountInactive.Checked
                                                 );

                    if (BaseMstr.StatusCode == 0)
                    {
                        txtPassword.Enabled = false;
                        txtVerifyPassword.Enabled = false;
                    }
                }
                else
                {
                    bSaved = sec.UpdatePatientFXUserOptions(BaseMstr,
                                                    lFXUserID,
                                                    chkbxAccountLocked.Checked,
                                                    chkbxAccountInactive.Checked
                                                   );
                }

            }
            loadPatientPortalAccount();
            return bSaved;
        }
    }

    protected bool CheckPatientFXUser(CSec secx, bool bIsNewPatPortalAcct)
    {
        if (txtPassword.Enabled)
        {
            //make sure pwd and verify pwd match
            if (txtPassword.Text != txtVerifyPassword.Text)
            {
                BaseMstr.StatusCode = 501;
                BaseMstr.StatusComment = "Password and verify password must match!";
                return false;
            }

            //check all the account rules for the account...
            if (!secx.ValidateUserAccountRules(BaseMstr,
                                               txtUserId.Text,
                                               txtPassword.Text))
            {
                //Note: ValidateUserAccountRules will set StatusCode/StatusComment info
                return false;
            }
        }

        //make sure user name does not already exist since
        //we are doing an insert
        if (bIsNewPatPortalAcct)
        {
            if (secx.UserNameExists(BaseMstr, txtUserId.Text))
            {
                BaseMstr.StatusCode = 500;
                BaseMstr.StatusComment = "Please choose a different user name!";
                return false;
            }
        }
        return true;
    }

    //chkResetPassword_click
    protected void chkResetPassword_click(object sender, EventArgs e)
    {
        CheckBox chk = (CheckBox)sender;
        if (chk.Checked)
        {
            btnResetPassword_click(null, EventArgs.Empty);
        }
        else
        {
            txtPassword.Text = String.Empty;
            txtVerifyPassword.Text = String.Empty;
            DisablePasswordFields();
        }
    }

    //Check user right mode
    protected void CheckUserRightsMode() {

        bool bRecLocked = BaseMstr.IsPatientLocked;

        if (BaseMstr.APPMaster.UserType != (long)SUATUserType.ADMINISTRATOR)
        {
            lUsrRightMode = usrsec.GetRightMode(BaseMstr, (long)SUATUserRight.ProcessNewPatientsUR);
        }
        else
        {
            lUsrRightMode = usrsec.GetRightMode(BaseMstr, (long)SUATUserRight.AdministratorUR);
        }

        bControlsEnabled = ((lUsrRightMode > (long)RightMode.ReadOnly) && !bRecLocked);

        if (!bControlsEnabled)
        {
            chkbxAccountLocked.Enabled = false;
            chkbxAccountInactive.Enabled = false;
            txtUserId.Enabled = false;
            chkResetPassword.Enabled = false;
            txtPassword.Enabled = false;
            txtVerifyPassword.Enabled = false;
        }
    }

    //show save confirmation
    public void showSaveConfirmation()
    {
        divStatus.InnerHtml = " User's data was saved!";
        ScriptManager.RegisterClientScriptBlock(upPortalAccount, typeof(string), "saved", "clearStatusDiv(4);", true);
    }
}


text:
title: 'MemphisPHP February Meetup w/ Juliette Reinders Folmer'
date: '2015-02-18 09:45:19'
layout: post
slug: memphisphp-february-meetup-w-juliette-reinders-folmer
categories:
    - 'Meet Ups'
tags: {  }
---

            {{ page.title }}

            This month we will have a very special guest: Juliette Reinders Folmer:

            So you think you know PHP ? But do you really ?

            We all compare and test data on nearly every other line in our code, be it input validation, an if-statement, a switch or determining what to display and how. So of course we are all experts on how to do these tests and comparisons…. Or are we?

            No matter whether you are a beginner or an expert, come and join in the fun for the Big "Why equal doesn't equal" Quiz, test your knowledge and learn about defensive programming and the quirks of a loose type programming language along the way.

            About Juliette:

            Juliette Reinders Folmer is an all round consultant and web-developer who tries not be a geek. Juliette is a long-standing member of PHPWomen which helped her immensely to find her feet in the PHP world. She is ZCE, actively contributes to a number of open source projects, has published several articles and speaks at conferences when given the chance.

            Juliette is self-employed and based in the Netherlands. When not working for customers or on open source projects, she is the project manager of the worldwide 'Remember me when I'm gone' non-profit project or out raising funds for Stop AIDS Now!

    {% if post.meta.tags %}

        Tags:
        {% for tag in post.meta.tags %}
        {{ tag }}{% if not loop.last %}, {% endif %}
        {% endfor %}

    {% endif %}

redpajama_set_name: RedPajamaGithub


text:
package P03_GraphicEditor;

public interface Drawable {
    String draw();
}


text:
namespace HaloOnline.Server.Model.User
{
    public class UserState
    {
        public int OwnType { get; set; }
        public int Value { get; set; }
        public string StateName { get; set; }
        public int StateType { get; set; }
    }
}


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

namespace TreeApplication
{
    class Program
    {

        static void Main(string[] args)
        {
        }
    }
}


text:
#include "jtorch/spatial_convolution.h"

#include <cstring>

#include "jcl/threading/callback.h"
#include "jcl/threading/thread.h"
#include "jcl/threading/thread_pool.h"
#include "jtorch/tensor.h"
#include "jtorch/jtorch.h"

using namespace jcl::threading;
using namespace jcl::math;
using namespace jcl;

namespace jtorch {

static const char* kSpatialConvolutionKernel =
"    __kernel void SpatialConvolution(\n"
"      const __global  float* input,  /* 0 */\n"
"      __global  float* output,       /* 1 */\n"
"      const __global float* weights, /* 2 */\n"
"      const __global float* biases,  /* 3 */\n"
"      const int input_nfeats,        /* 4 */\n"
"      const int input_height,        /* 5 */\n"
"      const int input_width,         /* 6 */\n"
"      const int filt_height,         /* 7 */\n"
"      const int filt_width) {        /* 8 */\n"
"\n"
"      const int width = get_global_size(0);\n"
"      const int height = get_global_size(1);\n"
"      const int feats = get_global_size(2);\n"
"\n"
"      const int x_out = get_global_id(0);\n"
"      const int y_out = get_global_id(1);\n"
"      const int f_out = get_global_id(2);\n"
"      const int xInTopLeft = x_out;\n"
"      const int yInTopLeft = y_out;\n"
"\n"
"      /* Initilize the output to the bias */\n"
"      float sum = biases[f_out];\n"
"\n"
"      const int filt_size = filt_height * filt_width;\n"
"      const int filt_size_per_fout = input_nfeats * filt_size;\n"
"      const int in_size = input_width * input_height;\n"
"      for (int f = 0; f < input_nfeats; f++) {\n"
"        /* Get a pointer to the current weight matrix and input feature */\n"
"        /* THIS COULD BE FASTER --> STRIPE WEIGHTS MATRIX FOR BETTER DATA ACCESS! */\n"
"        const __global  float* pkernel = &weights[f_out * filt_size_per_fout + f * filt_size];\n"
"        const __global  float* pinput = &input[f * in_size];\n"
"\n"
"        /* Perform the convolution on this input feature */\n"
"        for (int r = 0; r < filt_height; r++) {\n"
"          const int idxFtmp = r * filt_width;\n"
"          const int yIn = yInTopLeft + r;\n"
"          const int idxIntmp = yIn * input_width + xInTopLeft;\n"
"          for (int c = 0; c < filt_width; c++) {\n"
"            const int idxF  = idxFtmp  + c;\n"
"            const int idxIn = idxIntmp + c;\n"
"            sum += pkernel[idxF] * pinput[idxIn];\n"
"          }\n"
"        }\n"
"      }\n"
"      const int iout = x_out + width * (y_out + height * f_out);\n"
"      output[iout] = sum;\n"
"    }\n"
"\n"
"    __kernel void SpatialConvolutionPadding(\n"
"      const __global  float* input,   /* 0 */\n"
"      __global  float* output,        /* 1 */\n"
"      const __global float* weights,  /* 2 */\n"
"      const __global float* biases,   /* 3 */\n"
"      const int input_nfeats,         /* 4 */\n"
"      const int input_height,         /* 5 */\n"
"      const int input_width,          /* 6 */\n"
"      const int filt_height,          /* 7 */\n"
"      const int filt_width,           /* 8 */\n"
"      const int padding) {            /* 9 */\n"
"\n"
"      const int width = get_global_size(0);\n"
"      const int height = get_global_size(1);\n"
"      const int feats = get_global_size(2);\n"
"\n"
"      const int x_out = get_global_id(0);\n"
"      const int y_out = get_global_id(1);\n"
"      const int f_out = get_global_id(2);\n"
"      const int xInTopLeft = x_out;\n"
"      const int yInTopLeft = y_out;\n"
"\n"
"      const int pad_left_top = padding;\n"
"\n"
"      /* Initilize the output to the bias */\n"
"      float sum = biases[f_out];\n"
"\n"
"      const int filt_size = filt_height * filt_width;\n"
"      const int filt_size_per_fout = input_nfeats * filt_size;\n"
"      const int in_size = input_width * input_height;\n"
"      for (int f = 0; f < input_nfeats; f++) {\n"
"        /* Get a pointer to the current weight matrix and input feature */\n"
"        /* THIS COULD BE FASTER --> STRIPE WEIGHTS MATRIX FOR BETTER DATA ACCESS! */\n"
"        const __global  float* pkernel = &weights[f_out * filt_size_per_fout + f * filt_size];\n"
"        const __global  float* pinput = &input[f * in_size];\n"
"\n"
"        /* Perform the convolution on this input feature */\n"
"        for (int r = 0; r < filt_height; r++) {\n"
"          const int idxFtmp = r * filt_width;\n"
"          const int yIn = yInTopLeft + r - pad_left_top;\n"
"          const int idxIntmp = yIn * input_width;\n"
"\n"
"          if (yIn >= 0 && yIn < input_height) {\n"
"            for (int c = 0; c < filt_width; c++) {\n"
"              const int idxF  = idxFtmp  + c;\n"
"              const int xIn = xInTopLeft + c - pad_left_top;\n"
"              if (xIn >= 0 && xIn < input_width) {\n"
"                const int idxIn = idxIntmp + xIn;\n"
"                sum += pkernel[idxF] * pinput[idxIn];\n"
"              }\n"
"            }\n"
"          }\n"
"        }\n"
"      }\n"
"      const int iout = x_out + width * (y_out + height * f_out);\n"
"      output[iout] = sum;\n"
"    }";

SpatialConvolution::SpatialConvolution(const uint32_t feats_in,
                                       const uint32_t feats_out,
                                       const uint32_t filt_height,
                                       const uint32_t filt_width,
                                       const uint32_t padding)
    : TorchStage() {
  filt_width_ = filt_width;
  filt_height_ = filt_height;
  feats_in_ = feats_in;
  feats_out_ = feats_out;
  padding_ = padding;

  output = nullptr;

  uint32_t dim = 4;
  uint32_t size[4] = {filt_width_, filt_height_, feats_in_, feats_out_};
  weights_.reset(new Tensor<float>(dim, size));
  biases_.reset(new Tensor<float>(1, &feats_out_));
}

SpatialConvolution::~SpatialConvolution() {}

void SpatialConvolution::setWeights(const float* weights) {
  weights_->setData(weights);
}

void SpatialConvolution::setBiases(const float* biases) {
  biases_->setData(biases);
}

void SpatialConvolution::init(std::shared_ptr<TorchData> input) {
  RASSERT(input->type() == TorchDataType::TENSOR_DATA);

  Tensor<float>* in = TO_TENSOR_PTR(input.get());
  RASSERT(in->dim() == 3);
  RASSERT(in->size()[2] == feats_in_);

  if (output != nullptr) {
    uint32_t owidth = in->size()[0] - filt_width_ + 1 + 2 * padding_;
    uint32_t oheight = in->size()[1] - filt_height_ + 1 + 2 * padding_;
    const uint32_t* out_size = TO_TENSOR_PTR(output.get())->size();
    if (out_size[0] != owidth || out_size[1] != oheight ||
        out_size[2] != feats_out_) {
      output = nullptr;
    }
  }
  if (output == nullptr) {
    uint32_t out_dim[3];
    out_dim[0] = in->size()[0] - filt_width_ + 1 + 2 * padding_;
    out_dim[1] = in->size()[1] - filt_height_ + 1 + 2 * padding_;
    out_dim[2] = feats_out_;
    output.reset(new Tensor<float>(3, out_dim));
  }
}

void SpatialConvolution::forwardProp(std::shared_ptr<TorchData> input) {
  init(input);
  Tensor<float>* in = TO_TENSOR_PTR(input.get());
  if (padding_ > 0) {
    cl_context->useKernelCStr(kSpatialConvolutionKernel, "SpatialConvolutionPadding");
  } else {
    cl_context->useKernelCStr(kSpatialConvolutionKernel, "SpatialConvolution");
  }
  cl_context->setArg(0, in->storage());
  cl_context->setArg(1, TO_TENSOR_PTR(output.get())->storage());
  cl_context->setArg(2, weights_->storage());
  cl_context->setArg(3, biases_->storage());
  cl_context->setArg(4, (int)in->size()[2]);
  cl_context->setArg(5, (int)in->size()[1]);
  cl_context->setArg(6, (int)in->size()[0]);
  cl_context->setArg(7, (int)filt_height_);
  cl_context->setArg(8, (int)filt_width_);
  if (padding_ > 0) {
    cl_context->setArg(9, (int)padding_);
  }
  uint32_t dim = 3;
  cl_context->runKernel(jtorch::deviceid, dim,
                        TO_TENSOR_PTR(output.get())->size(), false);
}

std::unique_ptr<TorchStage> SpatialConvolution::loadFromFile(
    std::ifstream& file) {
  int32_t filt_width, filt_height, n_input_features, n_output_features, padding;
  file.read((char*)(&filt_width), sizeof(filt_width));
  file.read((char*)(&filt_height), sizeof(filt_height));
  file.read((char*)(&n_input_features), sizeof(n_input_features));
  file.read((char*)(&n_output_features), sizeof(n_output_features));
  file.read((char*)(&padding), sizeof(padding));

#if defined(DEBUG) || defined(_DEBUG)
  std::cout << "\t\t(fout,fin,kh,kw,pad)=(" << n_output_features << ","
            << n_input_features << "," << filt_height << "," << filt_width
            << "," << padding << ")" << std::endl;
#endif

  std::unique_ptr<SpatialConvolution> ret(new SpatialConvolution(
      n_input_features, n_output_features, filt_height, filt_width, padding));

  int32_t filt_dim = filt_width * filt_height;
  std::unique_ptr<float[]> weights(
      new float[n_output_features * n_input_features * filt_dim]);
  for (int32_t i = 0; i < n_output_features * n_input_features; i++) {
    float* bank = &weights[i * filt_dim];
    file.read((char*)(bank), sizeof(bank[0]) * filt_dim);
  }
  ret->setWeights(weights.get());

  std::unique_ptr<float[]> biases(new float[n_output_features]);
  file.read((char*)(biases.get()), sizeof(biases[0]) * n_output_features);
  ret->setBiases(biases.get());

  return std::unique_ptr<TorchStage>(std::move(ret));
}

}  // namespace jtorch


text:
import uuid = require("node-uuid");
'use strict';
import ICharacter = require("./interfaces/ICharacter");
import _ = require('lodash');
import IItem = require("./interfaces/IItem");
import IItemOpts = require("./interfaces/IItemOpts");
import Tier = require("./enums/Tier");
import Slot = require("./enums/Slot");
import randopeep = require("randopeep");
import Dice = require('./Dice');

class Item{
  private id: string;
  private name: string;
  private statAffinity: string;
  private statModifier: number;
  private requiredTier: Tier;
  private slot: Slot;
  private value: number;
  private createdBy: ICharacter;
  private createdWhen: number;

  constructor(opts: IItemOpts){
    this.id = uuid.v4();
    this.name = opts.name;
    this.statAffinity = opts.statAffinity;
    this.statModifier = opts.statModifier;
    this.requiredTier = opts.requiredTier;
    this.slot = opts.slot;
    this.value = opts.value;
    this.createdBy = opts.createdBy;
    this.createdWhen = opts.createdWhen;
  }

  static RandomItem():Item{
    var stats = [
      'mind',
      'body',
      'soul',
      'conviction',
      'insight',
      'spirit',
      'heart',
      'resilience',
      'agility',
      'might',
      'vigor',
      'willpower',
      'wits',
      'intellect',
      'heart'
    ];
    return new Item({
      name:randopeep.invention(),
      statAffinity: _.first(_.shuffle(stats)),
      statModifier: 1,
      requiredTier: Tier.amatuer,
      slot:Slot[Slot[Dice.roll(1,5)-1]],
      value:Dice.roll(1,100),
      createdBy:{
        id:uuid.v4(),
        name:randopeep.name()
      },
      createdWhen: new Date().getTime()
    });
  }
}

export = Item;


text:
package graphics.Doctor;

import graphics.BackGroundImage;
import graphics.Layout;
import graphics.LoginUI;
import graphics.DocAdminCommons.PatientSearch;
import graphics.DocAdminCommons.PatientsSearchResault;
import graphics.Report.DrugReport;
import graphics.Report.Health;
import graphics.Report.Illness;
import graphics.Report.IllnessReport;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

@SuppressWarnings("serial")
public class DoctorUI extends Layout {

	public DoctorUI() {
		setTitle("\u0645\u062F\u06CC\u0631\u06CC\u062A \u0628\u06CC\u0645\u0627\u0631");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		DoctorPatientSearch searchPanel = new DoctorPatientSearch();
		IllnessReport illReportPanel = new IllnessReport();
		DrugReport drugReportPanel = new DrugReport();
		DoctorConsultationsInbox consultInbox = new DoctorConsultationsInbox();

		content.add(new BackGroundImage("img/doctor.jpg"), "default");
		content.add(new DoctorProfile(), "profile");
		content.add(new DoctorInbox(), "patientsInbox");
		content.add(consultInbox, "consultationsInbox");
		content.add(searchPanel, "psearch");
		DoctorPatientSearchResult search_res = new DoctorPatientSearchResult(this.notice);
		content.add(search_res, "showall");
		content.add(new DoctorToPatient(this.notice), "messageToPatient");
		content.add(new DoctorToDoctor(this.notice), "sendPatient");
		content.add(illReportPanel, "illnessReport");
		content.add(drugReportPanel, "drugReport");
		content.add(new EditPrescription(this.notice), "editPrescription");

		// Making Patient menu
		JMenuBar menuBar = new JMenuBar();
		menuBar.setBounds(0, 0, 490, 30);
		menu.add(menuBar);

		JMenu menu_1 = new JMenu("\u06AF\u0632\u0627\u0631\u0634 \u06AF\u06CC\u0631\u06CC");
		menuBar.add(menu_1);

		JMenuItem illnessReport = new JMenuItem("\u0628\u06CC\u0645\u0627\u0631\u06CC \u0647\u0627");
		illnessReport.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					illReportPanel.notice.call();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				cl.show(content, "illnessReport");
			}
		});
		menu_1.add(illnessReport);

		JMenuItem drugsReport = new JMenuItem("\u062F\u0627\u0631\u0648 \u0647\u0627");
		drugsReport.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					drugReportPanel.notice.call();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				cl.show(content, "drugReport");
			}
		});
		menu_1.add(drugsReport);

		JMenu menu = new JMenu("\u0628\u06CC\u0645\u0627\u0631\u0627\u0646");
		menuBar.add(menu);

		JMenuItem search = new JMenuItem("\u062C\u0633\u062A\u062C\u0648");
		search.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					searchPanel.notice.call();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				cl.show(content, "psearch");
			}
		});
		menu.add(search);

		JMenuItem showAll = new JMenuItem("\u062A\u0645\u0627\u0645 \u0628\u06CC\u0645\u0627\u0631\u0627\u0646");
		showAll.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				search_res.setQuery("");
				cl.show(content, "showall");
			}
		});
		menu.add(showAll);

		JMenu mnNewMenu = new JMenu("\u0648\u06CC\u0631\u0627\u06CC\u0634");
		menuBar.add(mnNewMenu);

		JMenuItem editPrescroption = new JMenuItem("\u0648\u06CC\u0631\u0627\u06CC\u0634 \u0646\u0633\u062E\u0647");
		editPrescroption.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				cl.show(content, "editPrescription");
			}
		});
		mnNewMenu.add(editPrescroption);

		JMenu manage = new JMenu("\u0645\u062F\u06CC\u0631\u06CC\u062A");
		menuBar.add(manage);

		JMenuItem profile = new JMenuItem("\u067E\u0631\u0648\u0641\u0627\u06CC\u0644");
		profile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cl.show(content, "profile");
			}
		});
		manage.add(profile);

		JMenuItem logout = new JMenuItem("\u062E\u0631\u0648\u062C");
		logout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DoctorUI.this.dispose();
				try {
					LoginUI frame = new LoginUI();
					frame.setVisible(true);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});

		JMenu inbox = new JMenu("\u0635\u0646\u062F\u0648\u0642");
		manage.add(inbox);

		JMenuItem consultationMessages = new JMenuItem("\u062F\u0631\u062E\u0648\u0627\u0633\u062A \u067E\u0630\u06CC\u0631\u0634");
		consultationMessages.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				consultInbox.fill();
				cl.show(content, "consultationsInbox");
			}
		});
		inbox.add(consultationMessages);

		JMenuItem patientsMessage = new JMenuItem("\u062F\u0631\u062E\u0648\u0627\u0633\u062A \u0645\u0634\u0627\u0648\u0631\u0647");
		patientsMessage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cl.show(content, "patientsInbox");
			}
		});
		inbox.add(patientsMessage);
		manage.add(logout);
	}

}


text:
package io.vertigo.orchestra.services.execution;

/**
 * Enumération des états d'execution.
 * @author mlaroche.
 * @version $Id$
 */
public enum ExecutionState {

	WAITING,

	SUBMITTED,

	RUNNING,

	DONE,

	ERROR,

	ABORTED,

	PENDING;

}


text:
package org.apache.airavata.xbaya.util;

import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.Collection;
import java.util.List;

import org.apache.airavata.api.Airavata;
import org.apache.airavata.api.Airavata.Client;
import org.apache.airavata.api.client.AiravataClientFactory;
import org.apache.airavata.common.utils.StringUtil;
import org.apache.airavata.model.error.AiravataClientConnectException;
import org.apache.airavata.workflow.model.exceptions.WorkflowRuntimeException;
import org.apache.airavata.workflow.model.graph.DataPort;
import org.apache.airavata.workflow.model.graph.Node;
import org.apache.airavata.workflow.model.graph.system.EndForEachNode;
import org.apache.airavata.workflow.model.graph.system.ForEachNode;
import org.apache.airavata.xbaya.ThriftClientData;
import org.apache.airavata.xbaya.ThriftServiceType;
import org.apache.airavata.xbaya.XBayaEngine;
import org.apache.airavata.xbaya.ui.dialogs.registry.RegistryWindow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class XBayaUtil {

    private static final Logger logger = LoggerFactory.getLogger(XBayaUtil.class);
    public static final String JCR_USER = "jcr.username";
    public static final String JCR_PASS = "jcr.password";
    public static final String JCR_URL = "jcr.url";

    public static boolean isURLExists(String URLName) {
        try {
            if (!URLName.toUpperCase().contains("HTTP"))
                URLName = "http://" + URLName;
            URL url = new URL(URLName);
            System.setProperty("java.net.useSystemProxies", "true");
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setConnectTimeout(9000);
            urlConn.setReadTimeout(9000);
            urlConn.connect();
            if (HttpURLConnection.HTTP_OK == urlConn.getResponseCode())
                return true;
            else
                return false;
        } catch (SocketTimeoutException e) {
            return false;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

//    public static boolean acquireJCRRegistry(XBayaEngine engine) {
//        XBayaConfiguration configuration = engine.getConfiguration();
//        if (configuration.getAiravataAPI() == null) {
//        	updateJCRRegistryInfo(engine);
//        }
//        return engine.getConfiguration().getAiravataAPI() != null;
//    }

    public static void updateJCRRegistryInfo(XBayaEngine xbayaEngine) {
    	RegistryWindow window = new RegistryWindow(xbayaEngine, ThriftServiceType.API_SERVICE);
        window.show();
	}

	/**
	 * @param node
	 * @return
	 */
	public static Node findEndForEachFor(ForEachNode node) {

		Collection<Node> toNodes = node.getOutputPort(0).getToNodes();
		if(toNodes.size() != 1){
			throw new WorkflowRuntimeException("ForEach output does not contain single out-edge");
		}
		Node middleNode = toNodes.iterator().next();
		List<DataPort> outputPorts = middleNode.getOutputPorts();
		for (DataPort dataPort : outputPorts) {
			if(dataPort.getToNodes().size() == 1){
				Node possibleEndForEachNode = dataPort.getToNodes().get(0);
				if(possibleEndForEachNode instanceof EndForEachNode){
					return possibleEndForEachNode;
				}
			}
		}
		throw new WorkflowRuntimeException("EndForEachNode not found");
	}

//	public static List<NameValue> getIOParameterData(String xml) throws ParserConfigurationException, SAXException, IOException{
//		List<NameValue> parameters=new ArrayList<NameValue>();
//		Document parameterDocument = XMLUtils.newDocument(new ByteArrayInputStream(xml.getBytes()));
//		org.w3c.dom.NodeList childNodes = parameterDocument.getDocumentElement().getChildNodes();
//		for(int i=0;i<childNodes.getLength();i++){
//			org.w3c.dom.Node parameterNode = childNodes.item(i);
//			NameValue pair = new NameValue();
//			pair.setName(parameterNode.getLocalName());
//			pair.setValue(parameterNode.getTextContent());
//			parameters.add(pair);
//		}
//		return parameters;
//	}

	public static Airavata.Client getAiravataClient(ThriftClientData data) throws AiravataClientConnectException{
		return AiravataClientFactory.createAiravataClient(data.getServerAddress(),data.getServerPort());
	}

	public static Client getWorkflowClient(ThriftClientData data) throws AiravataClientConnectException{
		return AiravataClientFactory.createAiravataClient(data.getServerAddress(),data.getServerPort());
	}

//    public static AiravataRegistry2 getExperimentCatalog(URL url) throws IOException, RepositoryException, URISyntaxException {
//        Properties properties = new Properties();
//        properties.load(url.openStream());
//        JCRComponentRegistry jcrComponentRegistry = new JCRComponentRegistry(new URI((String) properties.get(JCR_URL)),
//                (String) properties.get(JCR_USER),(String) properties.get(JCR_PASS));
//        return jcrComponentRegistry.getExperimentCatalog();
//    }

}


text:
var fs = require('fs');

var filePath = null;
var lines = [];
var lineSwapOptionSet = false;
var numberSwapOptionSet = false;
var crudOptionSet = false;

console.log("File path:");
process.stdin.on('readable', function() {
  var chunk = process.stdin.read();
  if (chunk !== null) {
    var input = chunk.toString().trim();
    if(filePath == null){
      filePath = input;
      processFile(filePath);
    }else if(input == 'a'){
      try{
        validateData();
      }catch(e){
        console.error(e.message);
        process.exit(1);
      }
    }else if(lineSwapOptionSet){
      var indices = input.trim().split(/\s+/gmi);
      if(indices.length < 2){
        throw new Error('Missing '+(2-indices.length)+' or more parameters');
      }
      for (var i = 0; i < indices.length; i++) {
        var index = indices[i];
        if(isNaN(index)){
          throw new Error('"'+index+'" is not a number');
        }
      };
      var firstLineIndex = indices[0];
      var secondLineIndex = indices[1];
      lines.swap(firstLineIndex, secondLineIndex);
      lineSwapOptionSet = false;
    }else if(numberSwapOptionSet){
      var indices = input.trim().split(/\s+/gmi);
      if(indices.length < 4){
        throw new Error('Missing '+(4-indices.length)+' or more parameters');
      }
      for (var i = 0; i < indices.length; i++) {
        var index = indices[i];
        if(isNaN(index)){
          throw new Error('"'+index+'" is not a number');
        }
      };
      var firstLineIndex = indices[0];
      var firstNumberIndex = indices[1];
      var secondLineIndex = indices[2];
      var secondNumberIndex = indices[3];
      lines.swap2d(firstLineIndex, firstNumberIndex,
            secondLineIndex, secondNumberIndex);

      numberSwapOptionSet = false;
    }else if(crudOptionSet){
      var indices = input.trim().split(/\s+/gmi);
      var operation = indices.shift();
      for (var i = 0; i < indices.length; i++) {
        var index = indices[i];
        if(isNaN(index)){
          throw new Error('"'+index+'" is not a number');
        }
      };
      if(operation == 'create'){
        if(indices.length < 3){
          throw new Error('Missing '+(3-indices.length)+' or more parameters');
        }
        if(typeof lines[indices[0]] !='undefined'){
          lines[indices[0]].splice(indices[1], 0, indices[2]);
        }else{
          throw new Error('Index out of bounds');
        }
      }else if(operation == 'read'){
        if(indices.length < 2){
          throw new Error('Missing '+(2-indices.length)+' or more parameters');
        }
        if(typeof lines[indices[0]][indices[1]] !='undefined'){
          console.log(lines[indices[0]][indices[1]]);
        }else{
          throw new Error('Index out of bounds');
        }
      }else if(operation == 'update'){
        if(indices.length < 3){
          throw new Error('Missing '+(3-indices.length)+' or more parameters');
        }
        if(typeof lines[indices[0]][indices[1]] !='undefined'){
          lines[indices[0]][indices[1]] = indices[2];
        }else{
          throw new Error('Index out of bounds');
        }
      }else if(operation == 'delete'){
        if(indices.length < 2){
          throw new Error('Missing '+(2-indices.length)+' or more parameters');
        }
        if(typeof lines[indices[0]][indices[1]] !='undefined'){
          lines[indices[0]].splice(indices[1], 1);
        }else{
          throw new Error('Index out of bounds');
        }
      }else{
        console.error('Invalid operation');
      }
      crudOptionSet = false;
    }else if(input == 'b'){
      lineSwapOptionSet = true;
      console.log("Enter line indices:");
    }else if(input == 'c'){
      numberSwapOptionSet = true;
      console.log("Enter line and number indices:");
    }else if(input == 'd'){
      saveToFile(filePath);
    }else if(input == 'e'){
      crudOptionSet = true;
      console.log('Enter operation("create", "read", "update" or "delete") '+
        'followed by the appropriate parameters');
    }else if(input == 'exit'){
        process.exit(0);
    }else{
      console.error('Unknown action: "%s", please try again', input);
    }

    if(!lineSwapOptionSet && !numberSwapOptionSet && !crudOptionSet){
      console.log('Choose action:\n\t"a" - Validate the file contents\n\t'+
        '"b" - Switch entire line from the file with an entire other line\n\t'+
        '"c" - Switch number at specific index in one line with a number with '+
        'specific index from another line\n\t'+
        '"d" - Validate and save the result\n\t'+
        '"e" - Apply \'CRUD\' operations on a selected position of a number\n\t'+
        '"exit" - Exit the application\n\t'
      );
    }
  }
});

/**
 * Reads and parses data from the given file name resource
 * @param  {String} filePath Path to the file resource to be read
 * @return {void}
 */
function processFile(filePath) {
  fs.readFile(filePath, function(e, data){
      if (e){
        throw e;
      }
    var fileContents = data.toString();
    if(fileContents[0] == ' ' || fileContents[0] == '\t'){
      throw new Error('A line cannot start with a space or a tab');
    }
    var rawLines = fileContents.trim().split(/\n+/gmi);
    for (var i = 0; i < rawLines.length; i++) {
      if(rawLines[i][0] == ' ' || rawLines[i][0] == '\t'){
        throw new Error('A line cannot start with a space or a tab');
      }
      var line = rawLines[i].trim().split(/\s+/gmi);
      for (var j = 0; j < line.length; j++) {
        if(line[j] == ''){
          line.splice(j, 1);
        }
      };
      lines.push(line);
    };
  });
}

/**
 * Validates and persists the lines global object content state
 * to the given file resource
 * @param  {String} filePath  Path to the file resource the data will be saved to
 * @return {void}
 */
function saveToFile(filePath) {
  try{
    validateData();
  }catch(e){
   console.error(e.message);
   process.exit(1);
  }
  var data = '';
  for (var i = 0; i < lines.length; i++) {
    var l = lines[i];
    for (var j = 0; j < l.length; j++) {
      data += (l[j]);
      if(j!=(l.length-1)){
        data +=' ';
      }
    };
    if(i!=(lines.length-1)){
      data +='\n';
    }
  };
  fs.writeFile(filePath, data, function (e) {
    if(e){
      throw e;
    }
    console.log('File "%s" saved!', filePath);
  });
}

/**
 * Swaps the values of the array at the given indices
 * @param  {Integer} a The first index
 * @param  {Integer} b The second index
 * @return {Array}   The Array object
 */
Array.prototype.swap = function (a,b) {
  if(typeof this[a] != 'undefined' && typeof this[b] != 'undefined'){
    var t = this[a];
    this[a] = this[b];
    this[b] = t;
  }else{
    throw new Error('Index out of bounds');
  }
  return this;
}

/**
 * Swaps the values of two cells in a 2d matrix
 * @param  {Integer} a First column index
 * @param  {Integer} b First row index
 * @param  {Integer} c Second column index
 * @param  {Integer} d Second row index
 * @return {Array}   The Array object
 */
Array.prototype.swap2d = function (a,b,c,d) {
  if(typeof this[a][b] != 'undefined' && typeof this[c][d] != 'undefined'){
    var t = this[a][b];
    this[a][b] = this[c][d];
    this[c][d] = t;
  }else{
    throw new Error('Index out of bounds');
  }
  return this;
}

/**
 * Validates the the contents of the global lines object state
 *
 * @return {void}
 */
function validateData() {
  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    for (var j = 0; j < line.length; j++) {
      var number = line[j];
      var numCharMatched = number.match(/\d+/gmi);
      if(numCharMatched.length > 1){
        var errorMessage = 'line '+(i+1) +', number '+(j+1)+', '+
          'character "'+number[numCharMatched[0].length]+'"('+(numCharMatched[0].length)+') is not allowed';
        throw new Error(errorMessage);
      }
      if(number[0]==0){
        var errorMessage = 'line '+(i+1) +', number '+(j+1)+', '+
        'starts with 0';
        throw new Error(errorMessage);
      }
    };
  };
}


text:
package us.rader.dinodocs;

/**
 * {@link DocBuilder} for Git-based SCM hosting services.
 */
public abstract class GitBuilder extends DocBuilder {

    /**
     * Serialization version number.
     */
    private static final long serialVersionUID = 1L;

    /**
     * @param parameters
     *            Parameters
     *
     * @return Concrete {@link Puller}
     */
    @Override
    protected final Puller getPuller(Parameters parameters) {

        return new GitPuller(parameters);

    }

}


text:
"""Path tracking utilities, representing mapper graph traversals.

"""

from __future__ import annotations

from functools import reduce
from itertools import chain
import logging
import operator
from typing import Any
from typing import cast
from typing import Dict
from typing import Iterator
from typing import List
from typing import Optional
from typing import overload
from typing import Sequence
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Union

from . import base as orm_base
from ._typing import insp_is_mapper_property
from .. import exc
from .. import util
from ..sql import visitors
from ..sql.cache_key import HasCacheKey

if TYPE_CHECKING:
    from ._typing import _InternalEntityType
    from .interfaces import MapperProperty
    from .mapper import Mapper
    from .relationships import RelationshipProperty
    from .util import AliasedInsp
    from ..sql.cache_key import _CacheKeyTraversalType
    from ..sql.elements import BindParameter
    from ..sql.visitors import anon_map
    from ..util.typing import _LiteralStar
    from ..util.typing import TypeGuard

    def is_root(path: PathRegistry) -> TypeGuard[RootRegistry]:
        ...

    def is_entity(path: PathRegistry) -> TypeGuard[AbstractEntityRegistry]:
        ...

else:
    is_root = operator.attrgetter("is_root")
    is_entity = operator.attrgetter("is_entity")

_SerializedPath = List[Any]

_PathElementType = Union[
    str, "_InternalEntityType[Any]", "MapperProperty[Any]"
]

# the representation is in fact
# a tuple with alternating:
# [_InternalEntityType[Any], Union[str, MapperProperty[Any]],
# _InternalEntityType[Any], Union[str, MapperProperty[Any]], ...]
# this might someday be a tuple of 2-tuples instead, but paths can be
# chopped at odd intervals as well so this is less flexible
_PathRepresentation = Tuple[_PathElementType, ...]

_OddPathRepresentation = Sequence["_InternalEntityType[Any]"]
_EvenPathRepresentation = Sequence[Union["MapperProperty[Any]", str]]

log = logging.getLogger(__name__)

def _unreduce_path(path: _SerializedPath) -> PathRegistry:
    return PathRegistry.deserialize(path)

_WILDCARD_TOKEN: _LiteralStar = "*"
_DEFAULT_TOKEN = "_sa_default"

class PathRegistry(HasCacheKey):
    """Represent query load paths and registry functions.

    Basically represents structures like:

    (<User mapper>, "orders", <Order mapper>, "items", <Item mapper>)

    These structures are generated by things like
    query options (joinedload(), subqueryload(), etc.) and are
    used to compose keys stored in the query._attributes dictionary
    for various options.

    They are then re-composed at query compile/result row time as
    the query is formed and as rows are fetched, where they again
    serve to compose keys to look up options in the context.attributes
    dictionary, which is copied from query._attributes.

    The path structure has a limited amount of caching, where each
    "root" ultimately pulls from a fixed registry associated with
    the first mapper, that also contains elements for each of its
    property keys.  However paths longer than two elements, which
    are the exception rather than the rule, are generated on an
    as-needed basis.

    """

    __slots__ = ()

    is_token = False
    is_root = False
    has_entity = False
    is_property = False
    is_entity = False

    path: _PathRepresentation
    natural_path: _PathRepresentation
    parent: Optional[PathRegistry]
    root: RootRegistry

    _cache_key_traversal: _CacheKeyTraversalType = [
        ("path", visitors.ExtendedInternalTraversal.dp_has_cache_key_list)
    ]

    def __eq__(self, other: Any) -> bool:
        try:
            return other is not None and self.path == other._path_for_compare
        except AttributeError:
            util.warn(
                "Comparison of PathRegistry to %r is not supported"
                % (type(other))
            )
            return False

    def __ne__(self, other: Any) -> bool:
        try:
            return other is None or self.path != other._path_for_compare
        except AttributeError:
            util.warn(
                "Comparison of PathRegistry to %r is not supported"
                % (type(other))
            )
            return True

    @property
    def _path_for_compare(self) -> Optional[_PathRepresentation]:
        return self.path

    def set(self, attributes: Dict[Any, Any], key: Any, value: Any) -> None:
        log.debug("set '%s' on path '%s' to '%s'", key, self, value)
        attributes[(key, self.natural_path)] = value

    def setdefault(
        self, attributes: Dict[Any, Any], key: Any, value: Any
    ) -> None:
        log.debug("setdefault '%s' on path '%s' to '%s'", key, self, value)
        attributes.setdefault((key, self.natural_path), value)

    def get(
        self, attributes: Dict[Any, Any], key: Any, value: Optional[Any] = None
    ) -> Any:
        key = (key, self.natural_path)
        if key in attributes:
            return attributes[key]
        else:
            return value

    def __len__(self) -> int:
        return len(self.path)

    def __hash__(self) -> int:
        return id(self)

    @overload
    def __getitem__(self, entity: str) -> TokenRegistry:
        ...

    @overload
    def __getitem__(self, entity: int) -> _PathElementType:
        ...

    @overload
    def __getitem__(self, entity: slice) -> _PathRepresentation:
        ...

    @overload
    def __getitem__(
        self, entity: _InternalEntityType[Any]
    ) -> AbstractEntityRegistry:
        ...

    @overload
    def __getitem__(self, entity: MapperProperty[Any]) -> PropRegistry:
        ...

    def __getitem__(
        self,
        entity: Union[
            str, int, slice, _InternalEntityType[Any], MapperProperty[Any]
        ],
    ) -> Union[
        TokenRegistry,
        _PathElementType,
        _PathRepresentation,
        PropRegistry,
        AbstractEntityRegistry,
    ]:
        raise NotImplementedError()

    # TODO: what are we using this for?
    @property
    def length(self) -> int:
        return len(self.path)

    def pairs(
        self,
    ) -> Iterator[
        Tuple[_InternalEntityType[Any], Union[str, MapperProperty[Any]]]
    ]:
        odd_path = cast(_OddPathRepresentation, self.path)
        even_path = cast(_EvenPathRepresentation, odd_path)
        for i in range(0, len(odd_path), 2):
            yield odd_path[i], even_path[i + 1]

    def contains_mapper(self, mapper: Mapper[Any]) -> bool:
        _m_path = cast(_OddPathRepresentation, self.path)
        for path_mapper in [_m_path[i] for i in range(0, len(_m_path), 2)]:
            if path_mapper.is_mapper and path_mapper.isa(mapper):
                return True
        else:
            return False

    def contains(self, attributes: Dict[Any, Any], key: Any) -> bool:
        return (key, self.path) in attributes

    def __reduce__(self) -> Any:
        return _unreduce_path, (self.serialize(),)

    @classmethod
    def _serialize_path(cls, path: _PathRepresentation) -> _SerializedPath:
        _m_path = cast(_OddPathRepresentation, path)
        _p_path = cast(_EvenPathRepresentation, path)

        return list(
            zip(
                tuple(
                    m.class_ if (m.is_mapper or m.is_aliased_class) else str(m)
                    for m in [_m_path[i] for i in range(0, len(_m_path), 2)]
                ),
                tuple(
                    p.key if insp_is_mapper_property(p) else str(p)
                    for p in [_p_path[i] for i in range(1, len(_p_path), 2)]
                )
                + (None,),
            )
        )

    @classmethod
    def _deserialize_path(cls, path: _SerializedPath) -> _PathRepresentation:
        def _deserialize_mapper_token(mcls: Any) -> Any:
            return (
                # note: we likely dont want configure=True here however
                # this is maintained at the moment for backwards compatibility
                orm_base._inspect_mapped_class(mcls, configure=True)
                if mcls not in PathToken._intern
                else PathToken._intern[mcls]
            )

        def _deserialize_key_token(mcls: Any, key: Any) -> Any:
            if key is None:
                return None
            elif key in PathToken._intern:
                return PathToken._intern[key]
            else:
                mp = orm_base._inspect_mapped_class(mcls, configure=True)
                assert mp is not None
                return mp.attrs[key]

        p = tuple(
            chain(
                *[
                    (
                        _deserialize_mapper_token(mcls),
                        _deserialize_key_token(mcls, key),
                    )
                    for mcls, key in path
                ]
            )
        )
        if p and p[-1] is None:
            p = p[0:-1]
        return p

    def serialize(self) -> _SerializedPath:
        path = self.path
        return self._serialize_path(path)

    @classmethod
    def deserialize(cls, path: _SerializedPath) -> PathRegistry:
        assert path is not None
        p = cls._deserialize_path(path)
        return cls.coerce(p)

    @overload
    @classmethod
    def per_mapper(cls, mapper: Mapper[Any]) -> CachingEntityRegistry:
        ...

    @overload
    @classmethod
    def per_mapper(cls, mapper: AliasedInsp[Any]) -> SlotsEntityRegistry:
        ...

    @classmethod
    def per_mapper(
        cls, mapper: _InternalEntityType[Any]
    ) -> AbstractEntityRegistry:
        if mapper.is_mapper:
            return CachingEntityRegistry(cls.root, mapper)
        else:
            return SlotsEntityRegistry(cls.root, mapper)

    @classmethod
    def coerce(cls, raw: _PathRepresentation) -> PathRegistry:
        def _red(prev: PathRegistry, next_: _PathElementType) -> PathRegistry:
            return prev[next_]

        # can't quite get mypy to appreciate this one :)
        return reduce(_red, raw, cls.root)  # type: ignore

    def __add__(self, other: PathRegistry) -> PathRegistry:
        def _red(prev: PathRegistry, next_: _PathElementType) -> PathRegistry:
            return prev[next_]

        return reduce(_red, other.path, self)

    def __str__(self) -> str:
        return f"ORM Path[{' -> '.join(str(elem) for elem in self.path)}]"

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}({self.path!r})"

class CreatesToken(PathRegistry):
    __slots__ = ()

    is_aliased_class: bool
    is_root: bool

    def token(self, token: str) -> TokenRegistry:
        if token.endswith(f":{_WILDCARD_TOKEN}"):
            return TokenRegistry(self, token)
        elif token.endswith(f":{_DEFAULT_TOKEN}"):
            return TokenRegistry(self.root, token)
        else:
            raise exc.ArgumentError(f"invalid token: {token}")

class RootRegistry(CreatesToken):
    """Root registry, defers to mappers so that
    paths are maintained per-root-mapper.

    """

    __slots__ = ()

    inherit_cache = True

    path = natural_path = ()
    has_entity = False
    is_aliased_class = False
    is_root = True
    is_unnatural = False

    def _getitem(
        self, entity: Any
    ) -> Union[TokenRegistry, AbstractEntityRegistry]:
        if entity in PathToken._intern:
            if TYPE_CHECKING:
                assert isinstance(entity, str)
            return TokenRegistry(self, PathToken._intern[entity])
        else:
            try:
                return entity._path_registry  # type: ignore
            except AttributeError:
                raise IndexError(
                    f"invalid argument for RootRegistry.__getitem__: {entity}"
                )

    def _truncate_recursive(self) -> RootRegistry:
        return self

    if not TYPE_CHECKING:
        __getitem__ = _getitem

PathRegistry.root = RootRegistry()

class PathToken(orm_base.InspectionAttr, HasCacheKey, str):
    """cacheable string token"""

    _intern: Dict[str, PathToken] = {}

    def _gen_cache_key(
        self, anon_map: anon_map, bindparams: List[BindParameter[Any]]
    ) -> Tuple[Any, ...]:
        return (str(self),)

    @property
    def _path_for_compare(self) -> Optional[_PathRepresentation]:
        return None

    @classmethod
    def intern(cls, strvalue: str) -> PathToken:
        if strvalue in cls._intern:
            return cls._intern[strvalue]
        else:
            cls._intern[strvalue] = result = PathToken(strvalue)
            return result

class TokenRegistry(PathRegistry):
    __slots__ = ("token", "parent", "path", "natural_path")

    inherit_cache = True

    token: str
    parent: CreatesToken

    def __init__(self, parent: CreatesToken, token: str):
        token = PathToken.intern(token)

        self.token = token
        self.parent = parent
        self.path = parent.path + (token,)
        self.natural_path = parent.natural_path + (token,)

    has_entity = False

    is_token = True

    def generate_for_superclasses(self) -> Iterator[PathRegistry]:
        parent = self.parent
        if is_root(parent):
            yield self
            return

        if TYPE_CHECKING:
            assert isinstance(parent, AbstractEntityRegistry)
        if not parent.is_aliased_class:
            for mp_ent in parent.mapper.iterate_to_root():
                yield TokenRegistry(parent.parent[mp_ent], self.token)
        elif (
            parent.is_aliased_class
            and cast(
                "AliasedInsp[Any]",
                parent.entity,
            )._is_with_polymorphic
        ):
            yield self
            for ent in cast(
                "AliasedInsp[Any]", parent.entity
            )._with_polymorphic_entities:
                yield TokenRegistry(parent.parent[ent], self.token)
        else:
            yield self

    def _getitem(self, entity: Any) -> Any:
        try:
            return self.path[entity]
        except TypeError as err:
            raise IndexError(f"{entity}") from err

    if not TYPE_CHECKING:
        __getitem__ = _getitem

class PropRegistry(PathRegistry):
    __slots__ = (
        "prop",
        "parent",
        "path",
        "natural_path",
        "has_entity",
        "entity",
        "mapper",
        "_wildcard_path_loader_key",
        "_default_path_loader_key",
        "_loader_key",
        "is_unnatural",
    )
    inherit_cache = True
    is_property = True

    prop: MapperProperty[Any]
    mapper: Optional[Mapper[Any]]
    entity: Optional[_InternalEntityType[Any]]

    def __init__(
        self, parent: AbstractEntityRegistry, prop: MapperProperty[Any]
    ):
        # restate this path in terms of the
        # given MapperProperty's parent.
        insp = cast("_InternalEntityType[Any]", parent[-1])
        natural_parent: AbstractEntityRegistry = parent
        self.is_unnatural = False

        if not insp.is_aliased_class or insp._use_mapper_path:  # type: ignore
            parent = natural_parent = parent.parent[prop.parent]
        elif (
            insp.is_aliased_class
            and insp.with_polymorphic_mappers
            and prop.parent in insp.with_polymorphic_mappers
        ):
            subclass_entity: _InternalEntityType[Any] = parent[-1]._entity_for_mapper(prop.parent)  # type: ignore  # noqa: E501
            parent = parent.parent[subclass_entity]

            # when building a path where with_polymorphic() is in use,
            # special logic to determine the "natural path" when subclass
            # entities are used.
            #
            # here we are trying to distinguish between a path that starts
            # on a the with_polymorhpic entity vs. one that starts on a
            # normal entity that introduces a with_polymorphic() in the
            # middle using of_type():
            #
            #  # as in test_polymorphic_rel->
            #  #    test_subqueryload_on_subclass_uses_path_correctly
            #  wp = with_polymorphic(RegularEntity, "*")
            #  sess.query(wp).options(someload(wp.SomeSubEntity.foos))
            #
            # vs
            #
            #  # as in test_relationship->JoinedloadWPolyOfTypeContinued
            #  wp = with_polymorphic(SomeFoo, "*")
            #  sess.query(RegularEntity).options(
            #       someload(RegularEntity.foos.of_type(wp))
            #       .someload(wp.SubFoo.bar)
            #   )
            #
            # in the former case, the Query as it generates a path that we
            # want to match will be in terms of the with_polymorphic at the
            # beginning.  in the latter case, Query will generate simple
            # paths that don't know about this with_polymorphic, so we must
            # use a separate natural path.
            #
            #
            if parent.parent:
                natural_parent = parent.parent[subclass_entity.mapper]
                self.is_unnatural = True
            else:
                natural_parent = parent
        elif (
            natural_parent.parent
            and insp.is_aliased_class
            and prop.parent  # this should always be the case here
            is not insp.mapper
            and insp.mapper.isa(prop.parent)
        ):
            natural_parent = parent.parent[prop.parent]

        self.prop = prop
        self.parent = parent
        self.path = parent.path + (prop,)
        self.natural_path = natural_parent.natural_path + (prop,)
        self.has_entity = prop._links_to_entity
        if prop._is_relationship:
            if TYPE_CHECKING:
                assert isinstance(prop, RelationshipProperty)
            self.entity = prop.entity
            self.mapper = prop.mapper
        else:
            self.entity = None
            self.mapper = None

        self._wildcard_path_loader_key = (
            "loader",
            parent.path + self.prop._wildcard_token,  # type: ignore
        )
        self._default_path_loader_key = self.prop._default_path_loader_key
        self._loader_key = ("loader", self.natural_path)

    def _truncate_recursive(self) -> PropRegistry:
        earliest = None
        for i, token in enumerate(reversed(self.path[:-1])):
            if token is self.prop:
                earliest = i

        if earliest is None:
            return self
        else:
            return self.coerce(self.path[0 : -(earliest + 1)])  # type: ignore

    @property
    def entity_path(self) -> AbstractEntityRegistry:
        assert self.entity is not None
        return self[self.entity]

    def _getitem(
        self, entity: Union[int, slice, _InternalEntityType[Any]]
    ) -> Union[AbstractEntityRegistry, _PathElementType, _PathRepresentation]:
        if isinstance(entity, (int, slice)):
            return self.path[entity]
        else:
            return SlotsEntityRegistry(self, entity)

    if not TYPE_CHECKING:
        __getitem__ = _getitem

class AbstractEntityRegistry(CreatesToken):
    __slots__ = (
        "key",
        "parent",
        "is_aliased_class",
        "path",
        "entity",
        "natural_path",
    )

    has_entity = True
    is_entity = True

    parent: Union[RootRegistry, PropRegistry]
    key: _InternalEntityType[Any]
    entity: _InternalEntityType[Any]
    is_aliased_class: bool

    def __init__(
        self,
        parent: Union[RootRegistry, PropRegistry],
        entity: _InternalEntityType[Any],
    ):
        self.key = entity
        self.parent = parent
        self.is_aliased_class = entity.is_aliased_class
        self.entity = entity
        self.path = parent.path + (entity,)

        # the "natural path" is the path that we get when Query is traversing
        # from the lead entities into the various relationships; it corresponds
        # to the structure of mappers and relationships. when we are given a
        # path that comes from loader options, as of 1.3 it can have ac-hoc
        # with_polymorphic() and other AliasedInsp objects inside of it, which
        # are usually not present in mappings.  So here we track both the
        # "enhanced" path in self.path and the "natural" path that doesn't
        # include those objects so these two traversals can be matched up.

        # the test here for "(self.is_aliased_class or parent.is_unnatural)"
        # are to avoid the more expensive conditional logic that follows if we
        # know we don't have to do it.   This conditional can just as well be
        # "if parent.path:", it just is more function calls.
        if parent.path and (self.is_aliased_class or parent.is_unnatural):
            # this is an infrequent code path used only for loader strategies
            # that also make use of of_type().
            if entity.mapper.isa(parent.natural_path[-1].entity):  # type: ignore # noqa: E501
                self.natural_path = parent.natural_path + (entity.mapper,)
            else:
                self.natural_path = parent.natural_path + (
                    parent.natural_path[-1].entity,  # type: ignore
                )
        # it seems to make sense that since these paths get mixed up
        # with statements that are cached or not, we should make
        # sure the natural path is cacheable across different occurrences
        # of equivalent AliasedClass objects.  however, so far this
        # does not seem to be needed for whatever reason.
        # elif not parent.path and self.is_aliased_class:
        #     self.natural_path = (self.entity._generate_cache_key()[0], )
        else:
            # self.natural_path = parent.natural_path + (entity, )
            self.natural_path = self.path

    def _truncate_recursive(self) -> AbstractEntityRegistry:
        return self.parent._truncate_recursive()[self.entity]

    @property
    def root_entity(self) -> _InternalEntityType[Any]:
        return cast("_InternalEntityType[Any]", self.path[0])

    @property
    def entity_path(self) -> PathRegistry:
        return self

    @property
    def mapper(self) -> Mapper[Any]:
        return self.entity.mapper

    def __bool__(self) -> bool:
        return True

    def _getitem(
        self, entity: Any
    ) -> Union[_PathElementType, _PathRepresentation, PathRegistry]:
        if isinstance(entity, (int, slice)):
            return self.path[entity]
        elif entity in PathToken._intern:
            return TokenRegistry(self, PathToken._intern[entity])
        else:
            return PropRegistry(self, entity)

    if not TYPE_CHECKING:
        __getitem__ = _getitem

class SlotsEntityRegistry(AbstractEntityRegistry):
    # for aliased class, return lightweight, no-cycles created
    # version
    inherit_cache = True

class _ERDict(Dict[Any, Any]):
    def __init__(self, registry: CachingEntityRegistry):
        self.registry = registry

    def __missing__(self, key: Any) -> PropRegistry:
        self[key] = item = PropRegistry(self.registry, key)

        return item

class CachingEntityRegistry(AbstractEntityRegistry):
    # for long lived mapper, return dict based caching
    # version that creates reference cycles

    __slots__ = ("_cache",)

    inherit_cache = True

    def __init__(
        self,
        parent: Union[RootRegistry, PropRegistry],
        entity: _InternalEntityType[Any],
    ):
        super().__init__(parent, entity)
        self._cache = _ERDict(self)

    def pop(self, key: Any, default: Any) -> Any:
        return self._cache.pop(key, default)

    def _getitem(self, entity: Any) -> Any:
        if isinstance(entity, (int, slice)):
            return self.path[entity]
        elif isinstance(entity, PathToken):
            return TokenRegistry(self, entity)
        else:
            return self._cache[entity]

    if not TYPE_CHECKING:
        __getitem__ = _getitem

if TYPE_CHECKING:

    def path_is_entity(
        path: PathRegistry,
    ) -> TypeGuard[AbstractEntityRegistry]:
        ...

    def path_is_property(path: PathRegistry) -> TypeGuard[PropRegistry]:
        ...

else:
    path_is_entity = operator.attrgetter("is_entity")
    path_is_property = operator.attrgetter("is_property")


text:
require "test_helper"
require "ebisu_connection/replica"

class InitializeConfIsStringTest < Minitest::Test
  test "hostname only" do
    s = EbisuConnection::Replica.new("host_1", "replica")
    assert_equal "host_1", s.hostname
    assert_equal 1, s.weight
  end

  test "hostname and weight" do
    s = EbisuConnection::Replica.new("host_1, 10", "replica")
    assert_equal "host_1", s.hostname
    assert_equal 10, s.weight
  end

  test "hostname, weight and port" do
    s = EbisuConnection::Replica.new("host_1:1975, 10", "replica")
    assert_equal "host_1", s.hostname
    assert_equal 10, s.weight
  end
end


text:
Unique random token generator for ActiveRecord.

## Installation

Add `token_attr` to your Gemfile:

    gem 'token_attr', '~> 0.2.0'

## Usage

```
class User < ActiveRecord::Base
  include TokenAttr::Concern
  token_attr :token
end

user = User.new
user.valid?
user.token # => "b8bd30ff"
```

The token is generated in a `before_validation` callback only if the it's `nil`.

### Options

#### Length

The length of the token to generate.

Default: 8

```
token_attr :token, length: 40
```

#### Alphabet

The alphabet to use to generate the token.

Uses hexadecimal characters by default.

Accepted values:
- `:alphabetic` - any character from a to z (both lower and upper case)
- `:numeric` - any number
- `:alphanumeric` - any character or number
- a string - a string of your choice of the characters you want to use

```
token_attr :token, alphabet: :numeric      # => "82051173"
token_attr :token, alphabet: :alphabetic   # => "xqnInSJa"
token_attr :token, alphabet: :alphanumeric # => "61nD0lUo"
token_attr :token, alphabet: "token"       # => "ktnekoet"
```

## Contributing

1. Fork it ( http://github.com/mbillard/token_attr/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
const settings = require('settings');
const hooks = require('hooks');

hooks.onPage('action:ajaxify.end', () => {
	// note: this is probably deprecated in core soon...
	socket.emit('categories.get', function(err, data) {
		categories = data;
		for (var i = 0; i < categories.length; ++i) {
			$('#postCategories').append('<option value=' + categories[i].cid + '>' + categories[i].name + '</option>');
		}
	});
})

settings.load('discord-notification', $('.discord-notification-settings'));

$('#save').on('click', function() {
	settings.save('discord-notification', $('.discord-notification-settings'), function() {
		app.alert({
			type: 'success',
			alert_id: 'discord-notification-saved',
			title: 'Settings Saved',
			message: 'Please reload your NodeBB to apply these settings',
			clickfn: function() {
				socket.emit('admin.reload');
			}
		});
	});
});


text:
package commands

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"

	"github.com/github/hub/git"
	"github.com/github/hub/github"
	"github.com/github/hub/ui"
	"github.com/github/hub/utils"
)

var cmdPullRequest = &Command{
	Run: pullRequest,
	Usage: `
pull-request [-foc] [-b <BASE>] [-h <HEAD>] [-a <USERS>] [-M <MILESTONE>] [-l <LABELS>]
pull-request -m <MESSAGE>
pull-request -F <FILE> [--edit]
pull-request -i <ISSUE>
`,
	Long: `Create a GitHub pull request.

## Options:
	-f, --force
		Skip the check for unpushed commits.

	-m, --message <MESSAGE>
		Use the first line of <MESSAGE> as pull request title, and the rest as pull
		request description.

	-F, --file <FILE>
		Read the pull request title and description from <FILE>.

	-e, --edit
		Further edit the contents of <FILE> in a text editor before submitting.

	-i, --issue <ISSUE>, <ISSUE-URL>
		(Deprecated) Convert <ISSUE> to a pull request.

	-o, --browse
		Open the new pull request in a web browser.

	-c, --copy
		Put the URL of the new pull request to clipboard instead of printing it.

	-b, --base <BASE>
		The base branch in "[OWNER:]BRANCH" format. Defaults to the default branch
		(usually "master").

	-h, --head <HEAD>
		The head branch in "[OWNER:]BRANCH" format. Defaults to the current branch.

	-a, --assign <USERS>
		A comma-separated list of GitHub handles to assign to this pull request.

	-M, --milestone <ID>
		Add this pull request to a GitHub milestone with id <ID>.

	-l, --labels <LABELS>
		Add a comma-separated list of labels to this pull request.

## See also:

hub(1), hub-merge(1), hub-checkout(1)
`,
}

var (
	flagPullRequestBase,
	flagPullRequestHead,
	flagPullRequestIssue,
	flagPullRequestMessage,
	flagPullRequestFile string

	flagPullRequestBrowse,
	flagPullRequestCopy,
	flagPullRequestEdit,
	flagPullRequestForce bool

	flagPullRequestMilestone uint64

	flagPullRequestAssignees,
	flagPullRequestLabels listFlag
)

func init() {
	cmdPullRequest.Flag.StringVarP(&flagPullRequestBase, "base", "b", "", "BASE")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestHead, "head", "h", "", "HEAD")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestIssue, "issue", "i", "", "ISSUE")
	cmdPullRequest.Flag.BoolVarP(&flagPullRequestBrowse, "browse", "o", false, "BROWSE")
	cmdPullRequest.Flag.BoolVarP(&flagPullRequestCopy, "copy", "c", false, "COPY")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestMessage, "message", "m", "", "MESSAGE")
	cmdPullRequest.Flag.BoolVarP(&flagPullRequestEdit, "edit", "e", false, "EDIT")
	cmdPullRequest.Flag.BoolVarP(&flagPullRequestForce, "force", "f", false, "FORCE")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestFile, "file", "F", "", "FILE")
	cmdPullRequest.Flag.VarP(&flagPullRequestAssignees, "assign", "a", "USERS")
	cmdPullRequest.Flag.Uint64VarP(&flagPullRequestMilestone, "milestone", "M", 0, "MILESTONE")
	cmdPullRequest.Flag.VarP(&flagPullRequestLabels, "labels", "l", "LABELS")

	CmdRunner.Use(cmdPullRequest)
}

func pullRequest(cmd *Command, args *Args) {
	localRepo, err := github.LocalRepo()
	utils.Check(err)

	currentBranch, err := localRepo.CurrentBranch()
	utils.Check(err)

	baseProject, err := localRepo.MainProject()
	utils.Check(err)

	host, err := github.CurrentConfig().PromptForHost(baseProject.Host)
	if err != nil {
		utils.Check(github.FormatError("creating pull request", err))
	}
	client := github.NewClientWithHost(host)

	trackedBranch, headProject, err := localRepo.RemoteBranchAndProject(host.User, false)
	utils.Check(err)

	var (
		base, head string
		force      bool
	)

	force = flagPullRequestForce

	if flagPullRequestBase != "" {
		baseProject, base = parsePullRequestProject(baseProject, flagPullRequestBase)
	}

	if flagPullRequestHead != "" {
		headProject, head = parsePullRequestProject(headProject, flagPullRequestHead)
	}

	if args.ParamsSize() == 1 {
		arg := args.RemoveParam(0)
		flagPullRequestIssue = parsePullRequestIssueNumber(arg)
	}

	if base == "" {
		masterBranch := localRepo.MasterBranch()
		base = masterBranch.ShortName()
	}

	if head == "" && trackedBranch != nil {
		if !trackedBranch.IsRemote() {
			// the current branch tracking another branch
			// pretend there's no upstream at all
			trackedBranch = nil
		} else {
			if baseProject.SameAs(headProject) && base == trackedBranch.ShortName() {
				e := fmt.Errorf(`Aborted: head branch is the same as base ("%s")`, base)
				e = fmt.Errorf("%s\n(use `-h <branch>` to specify an explicit pull request head)", e)
				utils.Check(e)
			}
		}
	}

	if head == "" {
		if trackedBranch == nil {
			head = currentBranch.ShortName()
		} else {
			head = trackedBranch.ShortName()
		}
	}

	if headRepo, err := client.Repository(headProject); err == nil {
		headProject.Owner = headRepo.Owner.Login
		headProject.Name = headRepo.Name
	}

	fullBase := fmt.Sprintf("%s:%s", baseProject.Owner, base)
	fullHead := fmt.Sprintf("%s:%s", headProject.Owner, head)

	if !force && trackedBranch != nil {
		remoteCommits, _ := git.RefList(trackedBranch.LongName(), "")
		if len(remoteCommits) > 0 {
			err = fmt.Errorf("Aborted: %d commits are not yet pushed to %s", len(remoteCommits), trackedBranch.LongName())
			err = fmt.Errorf("%s\n(use `-f` to force submit a pull request anyway)", err)
			utils.Check(err)
		}
	}

	var editor *github.Editor
	var title, body string

	if cmd.FlagPassed("message") {
		title, body = readMsg(flagPullRequestMessage)
	} else if cmd.FlagPassed("file") {
		title, body, editor, err = readMsgFromFile(flagPullRequestFile, flagPullRequestEdit, "PULLREQ", "pull request")
		utils.Check(err)
	} else if flagPullRequestIssue == "" {
		baseTracking := base
		headTracking := head

		remote := gitRemoteForProject(baseProject)
		if remote != nil {
			baseTracking = fmt.Sprintf("%s/%s", remote.Name, base)
		}
		if remote == nil || !baseProject.SameAs(headProject) {
			remote = gitRemoteForProject(headProject)
		}
		if remote != nil {
			headTracking = fmt.Sprintf("%s/%s", remote.Name, head)
		}

		message, err := createPullRequestMessage(baseTracking, headTracking, fullBase, fullHead)
		utils.Check(err)

		editor, err = github.NewEditor("PULLREQ", "pull request", message)
		utils.Check(err)

		title, body, err = editor.EditTitleAndBody()
		utils.Check(err)
	}

	if title == "" && flagPullRequestIssue == "" {
		utils.Check(fmt.Errorf("Aborting due to empty pull request title"))
	}

	var pullRequestURL string
	if args.Noop {
		args.Before(fmt.Sprintf("Would request a pull request to %s from %s", fullBase, fullHead), "")
		pullRequestURL = "PULL_REQUEST_URL"
	} else {
		params := map[string]interface{}{
			"base": base,
			"head": fullHead,
		}

		if title != "" {
			params["title"] = title
			if body != "" {
				params["body"] = body
			}
		} else {
			issueNum, _ := strconv.Atoi(flagPullRequestIssue)
			params["issue"] = issueNum
		}
		pr, err := client.CreatePullRequest(baseProject, params)

		if err == nil && editor != nil {
			defer editor.DeleteFile()
		}

		utils.Check(err)

		pullRequestURL = pr.HtmlUrl

		params = map[string]interface{}{}
		if len(flagPullRequestLabels) > 0 {
			params["labels"] = flagPullRequestLabels
		}
		if len(flagPullRequestAssignees) > 0 {
			params["assignees"] = flagPullRequestAssignees
		}
		if flagPullRequestMilestone > 0 {
			params["milestone"] = flagPullRequestMilestone
		}

		if len(params) > 0 {
			err = client.UpdateIssue(baseProject, pr.Number, params)
			utils.Check(err)
		}
	}

	if flagPullRequestIssue != "" {
		ui.Errorln("Warning: Issue to pull request conversion is deprecated and might not work in the future.")
	}

	args.NoForward()
	printBrowseOrCopy(args, pullRequestURL, flagPullRequestBrowse, flagPullRequestCopy)
}

func createPullRequestMessage(base, head, fullBase, fullHead string) (string, error) {
	var (
		defaultMsg string
		commitLogs string
		err        error
	)

	commits, _ := git.RefList(base, head)
	if len(commits) == 1 {
		defaultMsg, err = git.Show(commits[0])
		if err != nil {
			return "", err
		}
	} else if len(commits) > 1 {
		commitLogs, err = git.Log(base, head)
		if err != nil {
			return "", err
		}
	}

	if template := github.GetPullRequestTemplate(); template != "" {
		if defaultMsg == "" {
			defaultMsg = "\n\n" + template
		} else {
			parts := strings.SplitN(defaultMsg, "\n\n", 2)
			defaultMsg = parts[0] + "\n\n" + template
			if len(parts) > 1 && parts[1] != "" {
				defaultMsg = defaultMsg + "\n\n" + parts[1]
			}
		}
	}

	cs := git.CommentChar()

	return renderPullRequestTpl(defaultMsg, cs, fullBase, fullHead, commitLogs)
}

func parsePullRequestProject(context *github.Project, s string) (p *github.Project, ref string) {
	p = context
	ref = s

	if strings.Contains(s, ":") {
		split := strings.SplitN(s, ":", 2)
		ref = split[1]
		var name string
		if !strings.Contains(split[0], "/") {
			name = context.Name
		}
		p = github.NewProject(split[0], name, context.Host)
	}

	return
}

func parsePullRequestIssueNumber(url string) string {
	u, e := github.ParseURL(url)
	if e != nil {
		return ""
	}

	r := regexp.MustCompile(`^issues\/(\d+)`)
	p := u.ProjectPath()
	if r.MatchString(p) {
		return r.FindStringSubmatch(p)[1]
	}

	return ""
}


text:
<?php namespace Lio\Forum\Threads\Handlers;

use Lio\Core\Handler;
use Lio\Forum\Forum;
use Lio\Forum\EloquentThreadRepository;
use Mitch\EventDispatcher\Dispatcher;

class DeleteThreadHandler implements Handler
{
    /**
     * @var \Lio\Forum\Forum
     */
    private $forum;
    /**
     * @var \Lio\Forum\EloquentThreadRepository
     */
    private $repository;
    /**
     * @var \Mitch\EventDispatcher\Dispatcher
     */
    private $dispatcher;

    public function __construct(Forum $forum, EloquentThreadRepository $repository, Dispatcher $dispatcher)
    {
        $this->forum = $forum;
        $this->repository = $repository;
        $this->dispatcher = $dispatcher;
    }

    public function handle($command)
    {
        $thread = $this->forum->deleteThread($command->thread);
        $this->repository->delete($thread);
        $this->dispatcher->dispatch($this->forum->releaseEvents());
        return $thread;
    }
}


text:
namespace Google.Analytics.Admin.V1Alpha.Snippets
{
    // [START analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAudiences_sync_flattened]
    using Google.Analytics.Admin.V1Alpha;
    using Google.Api.Gax;
    using System;

    public sealed partial class GeneratedAnalyticsAdminServiceClientSnippets
    {
        /// <summary>Snippet for ListAudiences</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void ListAudiences()
        {
            // Create client
            AnalyticsAdminServiceClient analyticsAdminServiceClient = AnalyticsAdminServiceClient.Create();
            // Initialize request argument(s)
            string parent = "properties/[PROPERTY]";
            // Make the request
            PagedEnumerable<ListAudiencesResponse, Audience> response = analyticsAdminServiceClient.ListAudiences(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Audience item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListAudiencesResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Audience item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Audience> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Audience item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAudiences_sync_flattened]
}


text:
import { Container } from "unstated"

interface State {
  excludeArtistIds?: string[]
}

export class FollowArtistPopoverState extends Container<State> {
  state = { excludeArtistIds: [] }

  constructor(props: State) {
    super()

    if (props && props.excludeArtistIds) {
      // @ts-expect-error STRICT_NULL_CHECK
      this.state.excludeArtistIds = props.excludeArtistIds
    }
  }

  addArtist = (artistId: string) => {
    const { excludeArtistIds } = this.state
    // @ts-expect-error STRICT_NULL_CHECK
    this.setState({ excludeArtistIds: excludeArtistIds.concat(artistId) })
  }
}


text:
from runner.koan import *

class AboutNewStyleClasses(Koan):
    class OldStyleClass:
        "An old style class"
        # Original class style have been phased out in Python 3.

    class NewStyleClass(object):
        "A new style class"
        # Introduced in Python 2.2
        #
        # Aside from this set of tests, Python Koans sticks exclusively to this
        # kind of class
        pass

    def test_new_style_classes_inherit_from_object_base_class(self):
        self.assertEqual(True, issubclass(self.NewStyleClass, object))
        self.assertEqual(False, issubclass(self.OldStyleClass, object))

    def test_new_style_classes_have_more_attributes(self):
        self.assertEqual(2, len(dir(self.OldStyleClass)))
        self.assertEqual('An old style class', self.OldStyleClass.__doc__)
        self.assertEqual('koans.about_new_style_classes', self.OldStyleClass.__module__)

        self.assertEqual(18, len(dir(self.NewStyleClass)))
        # To examine the available attributes, run
        # 'dir(<Class name goes here>)'
        # from a python console

    # ------------------------------------------------------------------

    def test_old_style_classes_have_type_but_no_class_attribute(self):
        self.assertEqual(__, type(self.OldStyleClass).__name__)

        try:
            cls = self.OldStyleClass.__class__.__name__
        except Exception as ex:
            pass

        # What was that error message from the exception?
        self.assertMatch(__, ex[0])

    def test_new_style_classes_have_same_class_as_type(self):
        new_style = self.NewStyleClass()
        self.assertEqual(__, self.NewStyleClass.__class__)
        self.assertEqual(
            __,
            type(self.NewStyleClass) == self.NewStyleClass.__class__)

    # ------------------------------------------------------------------

    def test_in_old_style_instances_class_is_different_to_type(self):
        old_style = self.OldStyleClass()
        self.assertEqual(__, old_style.__class__.__name__)
        self.assertEqual(__, type(old_style).__name__)

    def test_new_style_instances_have_same_class_as_type(self):
        new_style = self.NewStyleClass()
        self.assertEqual(__, new_style.__class__.__name__)
        self.assertEqual(__, type(new_style) == new_style.__class__)


text:
package org.apereo.portal.jdbc;

import java.sql.SQLException;

/**
 * The join query interface defines methods for storing and retrieving queries fragments that will
 * be used for performing joins in SQL.
 */
public interface IJoinQueryString {
    /**
     * Gets a query by the specified key.
     *
     * @param key The key to find the query for.
     * @return The query for the key.
     * @throws SQLException Will be thrown if no query exists for the key
     */
    public String getQuery(String key) throws SQLException;

    /**
     * Adds a query for the specified key, overwriting and query that was already associated with
     * the key.
     *
     * @param key The key to store the query under.
     * @param value The query to store under the key.
     * @throws SQLException
     */
    public void addQuery(String key, String value);
}


text:
#include <aws/amplifybackend/model/ImportBackendAuthRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::AmplifyBackend::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

ImportBackendAuthRequest::ImportBackendAuthRequest() :
    m_appIdHasBeenSet(false),
    m_backendEnvironmentNameHasBeenSet(false),
    m_identityPoolIdHasBeenSet(false),
    m_nativeClientIdHasBeenSet(false),
    m_userPoolIdHasBeenSet(false),
    m_webClientIdHasBeenSet(false)
{
}

Aws::String ImportBackendAuthRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_identityPoolIdHasBeenSet)
  {
   payload.WithString("identityPoolId", m_identityPoolId);

  }

  if(m_nativeClientIdHasBeenSet)
  {
   payload.WithString("nativeClientId", m_nativeClientId);

  }

  if(m_userPoolIdHasBeenSet)
  {
   payload.WithString("userPoolId", m_userPoolId);

  }

  if(m_webClientIdHasBeenSet)
  {
   payload.WithString("webClientId", m_webClientId);

  }

  return payload.View().WriteReadable();
}


text:
<!DOCTYPE html>

		<title>fcc-amazing-voting | home</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
		<link rel="stylesheet" href="public/css/bootstrap.min.css" type = "text/css">
		<link href="/public/css/main.css" rel="stylesheet" type="text/css">

fcc-amazing-voting

My Polls

New Poll

Logout

Login with Twitter

			Oops, there was an error!


text:
%%
%% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
%%
%% Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
%%

$project=Qt5xHb
$module=QtWidgets

$header

$includes

$beginSlotsClass
$slot=|closeEditor( QWidget * editor, QAbstractItemDelegate::EndEditHint hint )
$slot=|commitData( QWidget * editor )
$slot=|sizeHintChanged( const QModelIndex & index )
$endSlotsClass


text:
var CardValue;
(function (CardValue) {
    CardValue[CardValue["Ace"] = 1] = "Ace";
    CardValue[CardValue["Two"] = 2] = "Two";
    CardValue[CardValue["Three"] = 3] = "Three";
    CardValue[CardValue["Four"] = 4] = "Four";
    CardValue[CardValue["Five"] = 5] = "Five";
    CardValue[CardValue["Six"] = 6] = "Six";
    CardValue[CardValue["Seven"] = 7] = "Seven";
    CardValue[CardValue["Eight"] = 8] = "Eight";
    CardValue[CardValue["Nine"] = 9] = "Nine";
    CardValue[CardValue["Ten"] = 10] = "Ten";
    CardValue[CardValue["Jack"] = 11] = "Jack";
    CardValue[CardValue["Queen"] = 12] = "Queen";
    CardValue[CardValue["King"] = 13] = "King";
    CardValue[CardValue["BlackJoker"] = 14] = "BlackJoker";
    CardValue[CardValue["RedJoker"] = 15] = "RedJoker";
})(CardValue || (CardValue = {}));
module.exports = CardValue;
//# sourceMappingURL=CardValue.js.map


text:
//
//  LDKIndexedMapArrays.h
//  LDCore
//
//  Created by Marshall Hayden on 6/25/14.
//  Copyright (c) 2014 Liquid Analytics. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 A map from String to Array. Each element in each array has an index. new elements are added to the end of the array for their key, which will shift down in index the elements in later keys.
 */
@interface LDKIndexedMapArrays : NSObject

@property (readonly) NSInteger count;

+ (LDKIndexedMapArrays *)indexedMapArrays;

/** returns the absolute index of the new value. Returns NSNotFound if the value is already in the array. */
- (NSInteger)addValue:(id)value forKey:(NSString *)key;

/** returns the absolute index of the first occurrence of this value if distinct = NO. Else same behavior as the method not specifying distinct param. */
- (NSInteger)addValue:(id)value forKey:(NSString *)key distinct:(BOOL)distinct;

/** returns the index of the first element of the new values */
- (NSInteger)setValues:(NSArray *)values forKey:(NSString *)key;

/** returns the values for the specified key. Modifying this array will put the datastructure in an inconsistent state! copy first. */
- (NSMutableArray *)valuesForKey:(NSString *)key;

/** Returns @[value, key] */
- (NSArray *)valueAndKeyAtIndex:(NSInteger)index;

- (void)removeValuesForKey:(NSString *)key;
- (void)removeValueAtIndex:(NSInteger)index;
- (NSInteger)removeValue:(id)value forKey:(NSString*) key;

- (void)clear;

- (NSArray *)allKeys;

@end


text:
PACKAGES=$(shell go list ./...)
LINTER_VERSION=1.46.2

lint:
	goimports -w .
	go mod verify
	golangci-lint run --fix
.PHONY: lint

test:
	GORACE="halt_on_error=1" go test -race ./...
.PHONY: test

test-integration:
	GORACE="halt_on_error=1" go test -tags=integration -race ./...
.PHONY: test-integration

ci-lint:
	fgt goimports -l .
	go mod verify
	golangci-lint run
.PHONY: ci-lint

ci-test:
	echo "mode: count" > coverage-all.out
	$(foreach pkg,$(PACKAGES),\
		GORACE="halt_on_error=1" go test -race -cover -coverprofile=coverage.out $(pkg) || exit 1;\
		tail -n +2 coverage.out >> coverage-all.out;)
.PHONY: ci-test

ci-check: ci-lint ci-test
.PHONY: ci-check

install-tools:
	go install github.com/GeertJohan/fgt@latest
	go install golang.org/x/tools/cmd/cover@latest
	go install golang.org/x/tools/cmd/goimports@latest
	curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin v$(LINTER_VERSION)
.PHONY: install-tools

install-tools-ci:
	go install github.com/GeertJohan/fgt@latest
	go install golang.org/x/tools/cmd/cover@latest
	go install golang.org/x/tools/cmd/goimports@latest
.PHONY: install-tools-ci

### Docker ###
up:
	docker-compose up --remove-orphans
.PHONY: up

up-build:
	docker-compose up --remove-orphans --build
.PHONY: up-build

up-daemon:
	docker-compose up --remove-orphans -d
.PHONY: up-daemon

down:
	docker-compose down -v
.PHONY: down

ps:
	docker-compose ps
.PHONY: ps

logs:
	docker-compose logs -f bsk
.PHONY: logs

restart:
	docker-compose restart bsk
.PHONY: restart

bash:
	docker-compose exec bsk bash
.PHONY: bash

docker-check:
	docker-compose exec bsk bash -c "make check"
.PHONY: docker-check

docker-ci-test:
	docker-compose exec -T bsk bash -c "make ci-test"
.PHONY: docker-ci-test