text:
from TEMPy.StructureBlurrer import StructureBlurrer
from TEMPy.ScoringFunctions import ScoringFunctions
from TEMPy.Cluster import  Cluster
from numpy import zeros,mean,median,asarray
from scipy.stats import mode
import sys
from collections import defaultdict

class Consensus:
    """A class to clustering an ensemble of structure instance"""

    def __init__(self):
        pass

    def _makedict_value(self,rankCCC):
        """
        private function used in Consensus Module.
        """
        #print rankCCC
        rank_dict={}
        for r in rankCCC:
            rank_dict[r[0]]=r[2]
        return rank_dict

    def _makedict(self,rank_score):
        """
        private function used in Consensus Module.
        """

        namerank_score=[mod[0] for mod in rank_score]
        d_rank={i:j for i,j in enumerate(namerank_score,start=1)}
        return d_rank

    def _makedict_list(self,list_score):
        """
        private function used in Consensus Module.
        """
        #print enumerate(rankCCC)
        d_rank={i:j for i,j in list_score}
        return d_rank

    def _printdict(self,dict_score):
        """
        private function used in Consensus Module.
        """
        for k,v in list(dict_score.items()):
            print(k,v)

    def _modes(self,values):
        """
        private function used in Consensus Module.
        """
        count = defaultdict(int)
        for v in values:
            count[v] +=1
        best = max(count.values())
        print([k for k,v in list(count.items()) if v == best])

    def _mode_here(self,arr):
        """
        private function used in Consensus Module.
        """
        m = max([arr.count(a) for a in arr])
        print([x for x in arr if arr.count(x) == m][0] if m>1 else None)

    def vote_mode(self,ensemble_list,score_list,res_target_map,sigma_coeff,number_top_mod=0,write=False,targetMap=False):
        """

             Mode consensus scoring calculation between multiple "fits" using a user defined set of scores.

                Arguments:
                    *ensemble_list*
                        Input list of Structure Instances.
                    *score_list*
                    	Input list of scoring function to use.

                        See ScoringFunctions class for a list of the available Scoring Function.
                        E.g. set score='CCC' to use the Cross-correlation coefficient.

                        Score option are:

                        i    'CCC' - Cross-correlation coefficient;

                        ii    'LAP' - Laplacian-filtered cross-correlation coefficient:  useful for maps with resolutions worse than 10-15 A;

                        iii   'MI' - Mutual information score: a good and robust score but relatively slow to calculate;

                        iv    'ENV' - Envelope score: the fastest score to calculate due to binarisation of the map.

                        v-vii  'NV','NV_Sobel','NV_Laplace'- Normal vector score: a vector-based surface superimposition score with or without Sobel/Laplace filter.

                        viii 'CD' - Chamfer Distance: a score used in computer vision algorithms as a fast similarity metric
                    *res_target_map*
                        the resolution, in Angstroms, of the target Map.
                    *sigma_coeff*
                        the sigma value (multiplied by the resolution) that controls the width of the Gaussian.
                        Default values is 0.356.

                        Other values used :

                            0.187R corresponding with the Gaussian width of the Fourier transform falling to half the maximum at 1/resolution, as used in Situs (Wriggers et al, 1999);

                            0.225R which makes the Fourier transform of the distribution fall to 1/e of its maximum value at wavenumber 1/resolution, the default in Chimera (Petterson et al, 2004)

                            0.356R corresponding to the Gaussian width at 1/e maximum height equaling the resolution, an option in Chimera (Petterson et al, 2004);

                            0.425R the fullwidth half maximum being equal to the resolution, as used by FlexEM (Topf et al, 2008);

                            0.5R the distance between the two inflection points being the same length as the resolution, an option in Chimera (Petterson et al, 2004);

                            1R where the sigma value simply equal to the resolution, as used by NMFF (Tama et al, 2004).
                    *number_top_mod*
                        Number of Fits to cluster. Default is all.
                    *write*
                        True will write out a file that contains the list of the structure instances representing different fits scored and clustered.
                        note the lrms column is the Calpha RMSD of each fit from the first fit in its class
                    *targetMap*
                        Target Map Instance.

        """

        cluster=Cluster()
        list_dict=[]
        if targetMap==False:
            #targetMap = self.protMap(prot, min(resolution/4., 3.5), resolution)
            print("WARNING:Need target map")
            sys.exit()
        score_select=[]
        for score in score_list:
            #check if score chosen are correct
            if score not in ['CCC','LAP','MI','NV','NV_Sobel','NV_Laplace','ENV','CD']:
                print('Incorrect Scoring Function: %s' % score)
                print('Please select from one of the following scoring functions: %s' % ', '.join(['CCC','LAP','MI','NV','NV_Sobel','NV_Laplace','ENV','CD']))
                sys.exit()
            if score not in score_select:
                score_select.append(score)
            else:
                print('Chose the %s twice' % score)
                sys.exit()
        for score in score_list:
            print("******",score)
            if score=='CCC':
                rankCCC=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictCCC=Consensus()._makedict(rankCCC)
                list_dict.append(dictCCC)
                Consensus()._printdict(dictCCC)
            elif score=='LAP':
                rankLAP=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictLAP=Consensus()._makedict(rankLAP)
                list_dict.append(dictLAP)
                Consensus()._printdict(dictLAP)
            elif score=='MI':
                rankMI=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictMI=Consensus()._makedict(rankMI)
                list_dict.append(dictMI)
                Consensus()._printdict(dictMI)

            elif score=='NV':
                rankNV=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictNV=Consensus()._makedict(rankNV)
                list_dict.append(dictNV)
                Consensus()._printdict(dictNV)

            elif score=='NV_Sobel':
                rankNVS=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictNVS=Consensus()._makedict(rankNVS)
                list_dict.append(dictNVS)
                Consensus()._printdict(dictNVS)
            elif score=='NV_Laplace':
                rankNVL=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictNVL=Consensus()._makedict(rankNVL)
                list_dict.append(dictNVL)
                Consensus()._printdict(dictNVL)
            elif score=='ENV':
                rankENV=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictENV=Consensus()._makedict(rankENV)
                list_dict.append(dictENV)
                Consensus()._printdict(dictENV)
            if score=='CD':
                rankCD=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictCD=Consensus()._makedict(rankCD)
                list_dict.append(dictCD)
                Consensus()._printdict(dictCD)
        dict_count={}
        mxcinsensus = zeros(shape=(7,number_top_mod))
        for k,v in list(list_dict[0].items()):
            dict_count[v]=[]
        for k in dict_count:
            for num in range(len(list_dict)):
                for k2,v2  in list(list_dict[num].items()):
                    if k == v2:
                        dict_count[k].append(k2)
        dict_out={}
        for k,v in list(dict_count.items()):
            median_list=median(v)
            m = max([v.count(a) for a in v])
            if m>1:
                mode_list=[x for x in v if v.count(x) == m][0]
                dict_out[k]=[median_list,mode_list]
            else:
                pass
            mode_list=max(set(v), key=v.count)

        sorted_dict = sorted(list(dict_out.items()), key=lambda x: x[1])
        print("**************")
        print("Consensus rank")
        for fit in sorted_dict:
            print(fit[1],fit[0])
        return sorted_dict

    def _borda_score(self,list_rank,candidate,voters):
        """
        private function used in vote function.
    	It calculates the Borda count is a single-winner election method in which voters rank candidates in order of preference.
        """
        score=0
        for r in list_rank:
            score+=(candidate-r)*voters
        return score

    def vote(self,ensemble_list,score_list,res_target_map,sigma_coeff,number_top_mod=0,write=False,targetMap=False):
        """

             Borda consensus scoring calculation between multiple "fits" using a user defined set of scores.
             The Borda count is a single-winner election method in which voters rank candidates in order of preference.

                Arguments:
                    *ensemble_list*
                        Input list of Structure Instances.
                    *score_list*
                    	Input list of scoring function to use.

                        See ScoringFunctions class for a list of the available Scoring Function.
                        E.g. set score='CCC' to use the Cross-correlation coefficient.

                        Score option are:

                        i    'CCC' - Cross-correlation coefficient;

                        ii    'LAP' - Laplacian-filtered cross-correlation coefficient:  useful for maps with resolutions worse than 10-15 A;

                        iii   'MI' - Mutual information score: a good and robust score but relatively slow to calculate;

                        iv    'ENV' - Envelope score: the fastest score to calculate due to binarisation of the map.

                        v-vii  'NV','NV_Sobel','NV_Laplace'- Normal vector score: a vector-based surface superimposition score with or without Sobel/Laplace filter.

                        viii 'CD' - Chamfer Distance: a score used in computer vision algorithms as a fast similarity metric
                    *res_target_map*
                        the resolution, in Angstroms, of the target Map.
                    *sigma_coeff*
                        the sigma value (multiplied by the resolution) that controls the width of the Gaussian.
                        Default values is 0.356.

                        Other values used :

                            0.187R corresponding with the Gaussian width of the Fourier transform falling to half the maximum at 1/resolution, as used in Situs (Wriggers et al, 1999);

                            0.225R which makes the Fourier transform of the distribution fall to 1/e of its maximum value at wavenumber 1/resolution, the default in Chimera (Petterson et al, 2004)

                            0.356R corresponding to the Gaussian width at 1/e maximum height equaling the resolution, an option in Chimera (Petterson et al, 2004);

                            0.425R the fullwidth half maximum being equal to the resolution, as used by FlexEM (Topf et al, 2008);

                            0.5R the distance between the two inflection points being the same length as the resolution, an option in Chimera (Petterson et al, 2004);

                            1R where the sigma value simply equal to the resolution, as used by NMFF (Tama et al, 2004).
                    *number_top_mod*
                        Number of Fits to cluster. Default is all.
                    *write*
                        True will write out a file that contains the list of the structure instances representing different fits scored and clustered.
                        note the lrms column is the Calpha RMSD of each fit from the first fit in its class
                    *targetMap*
                        Target Map Instance.

        """

        cluster=Cluster()
        list_dict=[]
        candidate=len(ensemble_list)
        voters=len(score_list)
        if targetMap==False:
            #targetMap = self.protMap(prot, min(resolution/4., 3.5), resolution)
            print("WARNING:Need target map")
            sys.exit()
        score_select=[]
        for score in score_list:
            #check if score chosen are correct
            if score not in ['CCC','LAP','MI','NV','NV_Sobel','NV_Laplace','ENV','CD']:
                print('Incorrect Scoring Function: %s' % score)
                print('Please select from one of the following scoring functions: %s' % ', '.join(['CCC','LAP','MI','NV','NV_Sobel','NV_Laplace','ENV','CD']))
                sys.exit()
            if score not in score_select:
                score_select.append(score)
            else:
                print('Chose the %s twice' % score)
                sys.exit()
        for score in score_list:
            print("******",score)
            if score=='CCC':
                rankCCC=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                #print rankCCC
                dictCCC=Consensus()._makedict(rankCCC)
                list_dict.append(dictCCC)
                Consensus()._printdict(dictCCC)
            elif score=='LAP':
                rankLAP=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictLAP=Consensus()._makedict(rankLAP)
                list_dict.append(dictLAP)
                Consensus()._printdict(dictLAP)
            elif score=='MI':
                rankMI=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictMI=Consensus()._makedict(rankMI)
                list_dict.append(dictMI)
                Consensus()._printdict(dictMI)
            elif score=='NV':
                rankNV=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictNV=Consensus()._makedict(rankNV)
                list_dict.append(dictNV)
                Consensus()._printdict(dictNV)
                for i in rankNV:
                	print(i[0],i[2])

            elif score=='NV_Sobel':
                rankNVS=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictNVS=Consensus()._makedict(rankNVS)
                list_dict.append(dictNVS)
                Consensus()._printdict(dictNVS)
            elif score=='NV_Laplace':
                rankNVL=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictNVL=Consensus()._makedict(rankNVL)
                list_dict.append(dictNVL)
                Consensus()._printdict(dictNVL)
            elif score=='ENV':
                rankENV=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictENV=Consensus()._makedict(rankENV)
                list_dict.append(dictENV)
                Consensus()._printdict(dictENV)
            if score=='CD':
                rankCD=cluster.rank_fit_ensemble(ensemble_list,score,res_target_map,sigma_coeff,number_top_mod=number_top_mod,targetMap=targetMap.copy())
                dictCD=Consensus()._makedict(rankCD)
                list_dict.append(dictCD)
                Consensus()._printdict(dictCD)
        dict_count={}
        #dict with [0,0,0,0,0,0,0,score_mod] possibility CCC,MI ... so keep order. add a colum for 'goal done -goal concived'
        #in our case how many time is 1st.
        #for d_rank in list_dict:
                #sorted_dict = sorted(dict.items(), key=lambda x: x[1])
                #print sorted_dict
        mxcinsensus = zeros(shape=(7,number_top_mod))
        for k,v in list(list_dict[0].items()):
            dict_count[v]=[]
        for k in dict_count:
            #print 'k',k
            for num in range(len(list_dict)):
                for k2,v2  in list(list_dict[num].items()):
                    if k == v2:
                        dict_count[k].append(k2)
        dict_out={}
        for k,v in list(dict_count.items()):
           # print k
           # print sum(v)
            #print mean(v)
            median_list=median(v)
            #print mode(v)
            #most_frequent=mode(v)[0][0]
            #print 'mode most freq',most_frequent
            #Consensus().modes(v)
            #Consensus().mode_here(v)
            #print v
            borda_score=Consensus()._borda_score(v,candidate,voters)
            dict_out[k]=[borda_score,v]

        sorted_dict = sorted(list(dict_out.items()), key=lambda x: x[1][0],reverse=True)
        print("**************")
        print("Consensus rank")
        line=''
        line+="Borda_score\t"
        for score in score_list:
            line+='%s\t'%score
        line+="Fit\n"
        count=0
        for fit in sorted_dict:
            count+=1
            line+='%s\t'%count
            b=fit[1][0]
            line+='%s\t'%b
            for s in fit[1][1]:
                line+='%s\t'%s
            m=fit[0]
            line+='%s\n'%m
        print(line)
        return sorted_dict

#need to make it more elegant this come from private scripting.
    def vote_list(self,score_lists):
        """

             Borda consensus scoring calculation between multiple "fits" using a user defined set of scores.
             The Borda count is a single-winner election method in which voters rank candidates in order of preference.

                Arguments:
                    *ensemble_list*
                        Input list of Structure Instances.
                    *score_list*
                    	Input list of list. Each list is a list of Structure Instances associated with a score.
        """

        dict_count={}
        list_dict=[]
        candidate=[]
        voters=len(score_lists)
        for i in score_lists:
        	candidate.append(len(i))
        for list_score in  score_lists:
            dictScore=Consensus()._makedict(list_score)
            list_dict.append(dictScore)
        for k,v in list(list_dict[0].items()):
            dict_count[v]=[]
        for k in dict_count:
            #print 'k',k
            for num in range(len(list_dict)):
                for k2,v2  in list(list_dict[num].items()):
                    if k == v2:
                        dict_count[k].append(k2)
        dict_out={}
        for k,v in list(dict_count.items()):
            #print v
            #v = asarray(v)
            #print v
            #median_list=median(v)
            borda_score=Consensus()._borda_score(v,candidate[0],voters)
            dict_out[k]=[borda_score]

        sorted_dict = sorted(list(dict_out.items()), key=lambda x: x[1][0],reverse=True)
        print("**************")
        print("Consensus rank")
        line=''
        line+="Borda_score\t"
        count=0
        for score in score_lists:
        	count+=1
        	line+='%s\t'%count
        line+="Fit\n"
        count=0
        for fit in sorted_dict:
            count+=1
            line+='%s\t'%count
            b=fit[1][0]
            line+='%s\t'%b
            for s in fit[1][1]:
                line+='%s\t'%s
            m=fit[0]
            line+='%s\n'%m
        print(line)
        return sorted_dict

#     def vote_list(self,score_lists):
#
#         dict_count={}
#         list_dict=[]
#         for list_score in  score_lists:
#             dictScore=Consensus()._makedict_list(list_score)
#             list_dict.append(dictScore)
#         for k,v in list_dict[0].items():
#             dict_count[v]=[]
#         for k in dict_count:
#             for num in range(len(list_dict)):
#                 for k2,v2  in list_dict[num].items():
#                     if k == v2:
#                         dict_count[k].append(k2)
#         dict_out={}
#         for k,v in dict_count.items():
#            # print k
#            # print sum(v)
#             #print mean(v)
#             #print median(v)
#             most_frequent=mode(v)[0][0]
#             dict_out[k]=most_frequent
#         sorted_dict = sorted(dict_out.items(), key=lambda x: x[1])
#         print "**************"
#         print "Consensus rank"
#         for fit in sorted_dict:
#             print fit[1],fit[0]
#         return sorted_dict
#


text:
import {
  GraphQLString,
  GraphQLObjectType,
  GraphQLID,
  GraphQLNonNull,
} from 'graphql';
import GraphQLDate from './GraphQLDateType';
import User from '../models/User';
/* eslint-disable import/no-cycle */
import UserType from './UserType';
import ObjectType from './ObjectType';
/* eslint-enable import/no-cycle */

import Message from '../models/Message';
import Proposal from '../models/Proposal';
import Statement from '../models/Statement';
import Vote from '../models/Vote';
import Discussion from '../models/Discussion';
import Comment from '../models/Comment';
import WorkTeam from '../models/WorkTeam';
import Request from '../models/Request';
import { ActivityType as AType } from '../models/Activity';

const addProposalInfo = async (viewer, loaders, pollId, data = {}) => {
  if (!pollId) {
    return JSON.stringify({});
  }
  const proposalData = await Proposal.genByPoll(viewer, pollId, loaders);

  return JSON.stringify(
    proposalData
      ? {
          proposalId: proposalData.id,
          proposalTitle: proposalData.title,
          ...data,
        }
      : data,
  );
};

const addWorkTeamInfo = async (viewer, loaders, workTeamId) => {
  if (!workTeamId) {
    return JSON.stringify({});
  }
  const data = await WorkTeam.gen(viewer, workTeamId, loaders);

  return JSON.stringify(
    data
      ? {
          workTeamId: data.id,
          name: data.name,
          logo: data.logo,
          itName: data.itName,
          deName: data.deName,
          lldName: data.lldName,
        }
      : {},
  );
};

// TODO store this in activity - would not be a problem
const addDiscussionInfo = async (viewer, loaders, discussionId) => {
  if (!discussionId) {
    return JSON.stringify({});
  }
  const data = await Discussion.gen(viewer, discussionId, loaders);
  return JSON.stringify(
    data
      ? {
          workTeamId: data.workTeamId,
          title: data.title,
        }
      : {},
  );
};

const getVote = (viewer, parent, loaders) => {
  let vote;
  if (parent.verb === 'delete') {
    vote = new Vote({
      id: parent.content.id,
      user_id: parent.content.userId,
      positions: parent.content.positions,
      poll_id: parent.content.pollId,
    });
  } else {
    if (parent.verb === 'update') {
      loaders.votes.clear(parent.objectId);
    }
    vote = new Vote({
      id: parent.content.id,
      user_id: parent.content.userId,
      positions: parent.content.positions,
      poll_id: parent.content.pollId,
    }); // await Vote.gen(viewer, parent.objectId, loaders);
  }
  return vote;
};

const getStatement = async (viewer, parent, loaders) => {
  let statement;
  if (parent.verb === 'delete') {
    statement = new Statement({
      id: parent.content.id,
      poll_id: parent.content.pollId,
    });
  } else {
    if (parent.verb === 'update') {
      loaders.statements.clear(parent.objectId);
    }
    // clear votes loader, bc if user changed vote, it will return wrong values
    loaders.votes.clear(parent.content.voteId);

    statement = await Statement.gen(viewer, parent.objectId, loaders);
  }
  return statement;
};

const ActivityType = new GraphQLObjectType({
  name: 'Activity',

  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLID),
    },

    // not sure if this is the right way as we have to make a system user
    actor: {
      type: UserType,
      resolve: (parent, args, { viewer, loaders }) =>
        User.gen(viewer, parent.actorId, loaders),
    },
    type: {
      type: GraphQLString, // or enum?
    },
    verb: {
      type: GraphQLString, // or enum?
    },
    objectId: {
      type: GraphQLID,
    },
    object: {
      type: ObjectType,
      resolve: async (parent, args, { viewer, loaders }) => {
        let result;
        if (parent.type === AType.PROPOSAL) {
          if (parent.verb === 'update') {
            loaders.proposals.clear(parent.objectId);
            loaders.polls.clearAll(); // or specify
          }
          result = await Proposal.gen(viewer, parent.objectId, loaders);
          if (result && result.deletedAt) {
            return new Proposal({
              id: result.id,
              deleted_at: result.deletedAt,
              work_team_id: result.workTeamId,
            });
          }

          return result;
        }
        if (parent.type === AType.STATEMENT) {
          return getStatement(viewer, parent, loaders);
        }
        if (parent.type === AType.VOTE) {
          return getVote(viewer, parent, loaders);
        }
        if (parent.type === AType.MESSAGE) {
          return Message.gen(viewer, parent.objectId, loaders);
        }
        if (parent.type === AType.DISCUSSION) {
          result = await Discussion.gen(viewer, parent.objectId, loaders);
          if (result && result.deletedAt) {
            return new Discussion({
              id: result.id,
              deleted_at: result.deletedAt,
              work_team_id: result.workTeamId,
            });
          }

          return result;
        }
        if (parent.type === AType.COMMENT) {
          return Comment.gen(viewer, parent.objectId, loaders);
        }
        if (parent.type === AType.USER) {
          return User.gen(viewer, parent.objectId, loaders);
        }
        if (parent.type === AType.REQUEST) {
          return Request.gen(viewer, parent.objectId, loaders);
        }
        return null;
      },
    },
    createdAt: {
      type: GraphQLDate,
    },
    info: {
      type: GraphQLString,
      resolve: async (parent, args, { viewer, loaders }) => {
        switch (parent.type) {
          case AType.STATEMENT: {
            const statement = await getStatement(viewer, parent, loaders);
            return addProposalInfo(
              viewer,
              loaders,
              statement && statement.pollId,
            );
          }
          case AType.VOTE: {
            const vote = getVote(viewer, parent, loaders);
            return addProposalInfo(viewer, loaders, vote && vote.pollId, {
              extended: parent.content.extended,
            });
          }
          case AType.PROPOSAL: {
            return addWorkTeamInfo(viewer, loaders, parent.content.workTeamId);
          }

          case AType.DISCUSSION: {
            return addWorkTeamInfo(viewer, loaders, parent.content.workTeamId);
          }
          case AType.COMMENT: {
            return addDiscussionInfo(
              viewer,
              loaders,
              parent.content.discussionId,
            );
          }

          case AType.USER: {
            return JSON.stringify({
              added: parent.content.added,
              changedField: parent.content.changedField,
              diff: parent.content.diff,
            });
          }

          default: {
            return JSON.stringify({});
          }
        }
      },
    },
  }),
});
export default ActivityType;

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Core42\Form\Service;

use Zend\Form\FormInterface;
use Zend\ServiceManager\AbstractPluginManager;

class FormPluginManager extends AbstractPluginManager
{
    /**
     * @var string
     */
    protected $instanceOf = FormInterface::class;

    /**
     * @var FormElementManager
     */
    protected $formElementManager;

    /**
     * FormPluginManager constructor.
     * @param FormElementManager $formElementManager
     */
    public function __construct(FormElementManager $formElementManager)
    {
        $this->formElementManager = $formElementManager;
    }

    /**
     * @param string $name
     * @param array|null $options
     * @return object
     */
    public function get($name, array $options = null)
    {
        return $this->formElementManager->get($name, $options);
    }

    /**
     * @param string $name
     * @return bool
     */
    public function has($name)
    {
        return $this->formElementManager->has($name);
    }

    /**
     * @param string $name
     * @param array|null $options
     * @return mixed
     */
    public function build($name, array $options = null)
    {
        return parent::build($name, $options);
    }

    /**
     * @param string|\Zend\ServiceManager\Factory\AbstractFactoryInterface $factory
     * @throws \Exception
     */
    public function addAbstractFactory($factory)
    {
        throw new \Exception(
            'This is a proxy class for FormElementManager - please use FormElementManager to set services'
        );
    }

    /**
     * @param callable|string|\Zend\ServiceManager\Initializer\InitializerInterface $initializer
     * @throws \Exception
     */
    public function addInitializer($initializer)
    {
        throw new \Exception(
            'This is a proxy class for FormElementManager - please use FormElementManager to set services'
        );
    }

    /**
     * @param string $name
     * @param callable|string|\Zend\ServiceManager\Factory\DelegatorFactoryInterface $factory
     * @throws \Exception
     */
    public function addDelegator($name, $factory)
    {
        throw new \Exception(
            'This is a proxy class for FormElementManager - please use FormElementManager to set services'
        );
    }

    /**
     * @param string $name
     * @param bool $flag
     * @throws \Exception
     */
    public function setShared($name, $flag)
    {
        throw new \Exception(
            'This is a proxy class for FormElementManager - please use FormElementManager to set services'
        );
    }

    /**
     * @param string $name
     * @param null $class
     * @throws \Exception
     */
    public function setInvokableClass($name, $class = null)
    {
        throw new \Exception(
            'This is a proxy class for FormElementManager - please use FormElementManager to set services'
        );
    }

    /**
     * @param string $alias
     * @param string $target
     * @throws \Exception
     */
    public function setAlias($alias, $target)
    {
        throw new \Exception(
            'This is a proxy class for FormElementManager - please use FormElementManager to set services'
        );
    }

    /**
     * @param string $name
     * @param callable|string|\Zend\ServiceManager\Factory\FactoryInterface $factory
     * @throws \Exception
     */
    public function setFactory($name, $factory)
    {
        throw new \Exception(
            'This is a proxy class for FormElementManager - please use FormElementManager to set services'
        );
    }

    /**
     * @param string $name
     * @param array|object $service
     * @throws \Exception
     */
    public function setService($name, $service)
    {
        throw new \Exception(
            'This is a proxy class for FormElementManager - please use FormElementManager to set services'
        );
    }

    /**
     * @param bool $flag
     * @throws \Exception
     */
    public function setAllowOverride($flag)
    {
        throw new \Exception(
            'This is a proxy class for FormElementManager - please use FormElementManager to set services'
        );
    }
}


text:
=begin
#Swaggy Jenkins

#Jenkins API clients generated from Swagger / Open API specification

The version of the OpenAPI document: 1.5.1-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 6.0.0

=end

require 'spec_helper'
require 'json'
require 'date'

# Unit tests for SwaggyJenkinsClient::HudsonMasterComputerexecutors
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe SwaggyJenkinsClient::HudsonMasterComputerexecutors do
  let(:instance) { SwaggyJenkinsClient::HudsonMasterComputerexecutors.new }

  describe 'test an instance of HudsonMasterComputerexecutors' do
    it 'should create an instance of HudsonMasterComputerexecutors' do
      expect(instance).to be_instance_of(SwaggyJenkinsClient::HudsonMasterComputerexecutors)
    end
  end
  describe 'test attribute "current_executable"' do
    it 'should work' do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  describe 'test attribute "idle"' do
    it 'should work' do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  describe 'test attribute "likely_stuck"' do
    it 'should work' do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  describe 'test attribute "number"' do
    it 'should work' do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  describe 'test attribute "progress"' do
    it 'should work' do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  describe 'test attribute "_class"' do
    it 'should work' do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

end


text:
/**
 *task-view-ccontroller
 */
(function(){
  var taskViewStyle, taskView, getTime, getDateStr;
  taskViewStyle = require('styles/taskViewStyle');
  taskView = YTI.View["taskView"] || YTI.View.create();
  taskView.Els = {
    taskTextAreaView: null,
    taskInfoView: null,
    bottomBarView: null
  };
  taskView.Data = {
    record: null,
    startedCount: false,
    lastTime: null,
    t: 0
  };
  taskView.Style = taskViewStyle;
  taskView.addedToWindow = false;
  /**
   *@private
   */
  getTime = function(delta){
    var time;
    return time = {
      hours: Math.floor(delta / (1000 * 60 * 60)),
      minutes: Math.floor((delta / (1000 * 60)) % 60),
      seconds: Math.floor((delta / 1000) % 60)
    };
  };
  getDateStr = function(date){
    var str;
    str = "";
    str += date.getFullYear() + "-";
    str += (date.getMonth() - 0 + 1) + "-";
    str += date.getDate() + "\n";
    str += date.getHours() + ":";
    str += date.getMinutes();
    return str;
  };
  /**
   *@method get-task-view
   */
  taskView.getPageView = function(){
    var view;
    log('create-task-view');
    if (this.Els["pageView"]) {
      return this.Els["pageView"];
    } else {
      view = this.createTaskView();
      return view;
    }
  };
  /**
   *@create create-task-view
   */
  taskView.createTaskView = function(){
    var view;
    view = this.Els["pageView"] = TUI.createView(this.Style.page);
    view.add(this.Els["taskTextAreaView"] = this.createTaskTextAreaView());
    view.add(this.Els["taskInfoView"] = this.createTaskInfoView());
    view.add(this.Els["bottomBarView"] = this.createBottomBarView());
    return view;
  };
  /**
   *@create create-task-text-area-view
   */
  taskView.createTaskTextAreaView = function(){
    var view, taskTextLabel;
    log('create-text-area-view');
    view = TUI.createView(this.Style.taskTextAreaView);
    taskTextLabel = this.Els["taskTextLabel"] = TUI.createLabel(this.Style.taskTextLabel);
    taskTextLabel.text = "什么都没有!";
    view.add(taskTextLabel);
    return view;
  };
  /**
   *@create create-task-info-view
   */
  taskView.createTaskInfoView = function(){
    var that, view, restTimeView, restTimeLabel, startCountBtn;
    log('create-task-info-view');
    that = this;
    view = TUI.createView(this.Style.taskInfoView);
    /*******************************
     *task 任务执行时间视图
     *******************************/
    restTimeView = TUI.createView(that.Style.restTimeView);
    restTimeLabel = this.Els["restTimeLabel"] = TUI.createLabel(that.Style.restTimeLabel);
    restTimeLabel.text = "888";
    restTimeView.add(restTimeLabel);
    restTimeView.add(this.createTimeToolsNavView());
    view.add(restTimeView);
    view.add(this.createTaskAdvicesView());
    /*******************************
     *count-btn
     *******************************/
    startCountBtn = this.Els["startCountBtn"] = TUI.createLabel(this.Style.startCountBtn);
    startCountBtn.addEventListener('click', function(){
      that.trigger('start-count');
    });
    view.add(startCountBtn);
    return view;
  };
  /**
   *@create create-task-list-view
   */
  taskView.createTaskAdvicesView = function(){
    var _this, advicesView, advicesLabel, createItem;
    _this = this;
    advicesView = TUI.createView(this.Style.advicesView);
    advicesLabel = TUI.createLabel(this.Style.advicesLabel);
    advicesLabel.text = "建议: \n 1:haha! \n 2: hehe! \n 3: 好了!";
    createItem = function(imgSrc, attrs, ev){
      var itemContainer, itemImg, itemContent, itemLabel;
      itemContainer = TUI.createView({
        height: "120px",
        width: "50%",
        backgroundColor: "white"
      });
      import$(itemContainer, attrs);
      itemImg = TUI.createView({
        backgroundImage: "/assets/" + imgSrc,
        height: "100%",
        width: "120px",
        top: "0px",
        left: "0px"
      });
      itemImg.addEventListener('click', function(){
        _this.trigger(ev);
      });
      itemContainer.add(itemImg);
      itemContent = TUI.createView({
        height: "100%",
        left: "120px",
        top: "0px",
        right: "0px"
      });
      itemLabel = TUI.createLabel({
        font: {
          fontSize: "30px"
        },
        color: "gray",
        text: "2011-11-13 14:23"
      });
      itemContent.add(itemLabel);
      itemContainer.add(itemContent);
      itemContainer.setContent = function(str){
        itemLabel.text = str;
      };
      return itemContainer;
    };
    advicesView.add(this.Els.startTimeView = createItem("tool1.png", {
      left: "0px",
      top: "20px"
    }, "set-start-time"));
    advicesView.add(this.Els.endTimeView = createItem("tool2.png", {
      left: "50%",
      top: "20px"
    }, "set-finish-time"));
    advicesView.add(this.Els.deadLineView = createItem("tool3.png", {
      left: "0px",
      top: "140px"
    }, "set-dead-line"));
    advicesView.add(this.Els.lastTimeView = createItem("tool4.png", {
      left: "50%",
      top: "140px"
    }, "set-last-time"));
    return advicesView;
  };
  /**
   *@create create times-tool-nav-view
   */
  taskView.createTimeToolsNavView = function(it){
    var _this, wrapperView, toolNavView, toggle, tools, posX, width, marginX, i$, len$, toolBtn, closure;
    _this = this;
    wrapperView = TUI.createView(this.Style.restTimeToolWrapperView);
    toolNavView = TUI.createScrollView(this.Style.restTimeToolNavView);
    toggle = TUI.createView(this.Style.restTimeToolToggle);
    wrapperView.add(toggle);
    wrapperView.add(toolNavView);
    tools = [
      {
        title: "重置",
        name: "resetTimeBtn",
        ev: "resetTime"
      }, {
        title: "减少",
        name: "minusTimeBtn",
        ev: "minusTime"
      }, {
        title: "减5分钟",
        name: "minusFiveBtn",
        ev: "minusFiveTime"
      }, {
        title: "减10分钟",
        name: "minusTenBtn",
        ev: "minusTenTime"
      }, {
        title: "减30分钟",
        name: "minusThirtyBtn",
        ev: "minusThiryTime"
      }
    ];
    posX = 30;
    width = 160;
    marginX = 20;
    for (i$ = 0, len$ = tools.length; i$ < len$; ++i$) {
      it = tools[i$];
      toolBtn = TUI.createLabel(this.Style.restTimeToolBtn);
      toolBtn.left = posX + "";
      toolBtn.width = width;
      toolBtn.text = it.title;
      closure = fn$;
      closure(toolBtn, it);
      posX += width + marginX;
      toolNavView.add(toolBtn);
    }
    wrapperView.toggle = "off";
    toggle.addEventListener('click', function(){
      var animation;
      animation = TUI.createAnimation();
      animation.duration = 300;
      if (wrapperView.toggle === "off") {
        wrapperView.toggle = "on";
        animation.left = "0%";
        wrapperView.animate(animation);
      } else {
        wrapperView.toggle = "off";
        animation.left = "90%";
        wrapperView.animate(animation);
      }
    });
    return wrapperView;
    function fn$(btn, item){
      btn.addEventListener('click', function(){
        log('clicked' + item.title);
        _this.trigger(item.ev);
      });
    }
  };
  /**
   *@create create bottom-bar-view
   */
  taskView.createBottomBarView = function(){
    var that, view, barView, toolNavView;
    log('create-bottom-bar-view');
    that = this;
    view = TUI.createView(this.Style.bottomBarView);
    barView = TUI.createView(this.Style.bottomBarBar);
    toolNavView = TUI.createView(this.Style.bottomBarToolNavView);
    view.add(barView);
    view.add(toolNavView);
    /**********************************
     *create bottom bar view elements
     **********************************/
    (function(){
      var posX, width, backBtn, editBtn, detailBtn, deleteBtn, toggleBtn;
      posX = 0;
      width = 140;
      backBtn = that.Els.backBtn = TUI.createLabel(that.Style.navBtn);
      backBtn.text = "返回";
      backBtn.left = posX + "px";
      backBtn.width = width + "px";
      barView.add(backBtn);
      backBtn.addEventListener('click', function(){
        that.trigger('go-to-home');
      });
      posX += width;
      editBtn = that.Els.detailBtn = TUI.createLabel(that.Style.navBtn);
      editBtn.text = "编辑";
      editBtn.left = posX + "px";
      editBtn.width = width + "px";
      barView.add(editBtn);
      editBtn.addEventListener('click', function(){
        that.trigger('edit-task');
      });
      posX += width;
      detailBtn = that.Els.editBtn = TUI.createLabel(that.Style.navBtn);
      detailBtn.text = "详情";
      detailBtn.left = posX + "px";
      detailBtn.width = width + "px";
      barView.add(detailBtn);
      detailBtn.addEventListener('click', function(){
        that.trigger('task-detail');
      });
      posX += width;
      deleteBtn = that.Els.deleteBtn = TUI.createLabel(that.Style.navBtn);
      deleteBtn.text = "删除";
      deleteBtn.left = posX + "px";
      deleteBtn.width = width + "px";
      barView.add(deleteBtn);
      deleteBtn.addEventListener('click', function(){
        that.trigger('delete-task');
      });
      toggleBtn = TUI.createLabel(that.Style.navBtn);
      toggleBtn.text = "设置";
      toggleBtn.right = "0px";
      toggleBtn.width = width;
      toggleBtn.toggle = "off";
      toggleBtn.addEventListener('click', function(){
        var animation;
        animation = TUI.createAnimation();
        animation.duration = 300;
        if (this.toggle === "off") {
          this.toggle = "on";
          animation.bottom = "0px";
          view.animate(animation);
        } else {
          this.toggle = "off";
          animation.bottom = "-400px";
          view.animate(animation);
        }
      });
      barView.add(toggleBtn);
    })();
    /**********************************
     *add tools elements to tool-nav-view
     **********************************/
    view.add(this.createSettingToolsView());
    return view;
  };
  /**
   *@create setting tools-view
   */
  taskView.createSettingToolsView = function(it){
    var _this, container, tools, posX, posY, marginX, marginY, width, height, i$, len$, info, view, closure;
    _this = this;
    container = TUI.createScrollView(this.Style.settingToolsView);
    tools = [
      {
        title: "开始时间",
        ev: "set-start-time"
      }, {
        title: "结束时间",
        ev: "set-finish-time"
      }, {
        title: "完成时间",
        ev: "set-dead-line"
      }, {
        title: "持续时间",
        ev: "set-last-time"
      }, {
        title: "重复",
        ev: "set-repeatment"
      }, {
        title: "分类",
        ev: "set-class"
      }, {
        title: "重要性",
        ev: "set-importance"
      }, {
        title: "提醒",
        ev: "set-remind-time"
      }
    ];
    posX = 40;
    posY = 40;
    marginX = 150;
    marginY = 100;
    width = 240;
    height = 120;
    for (i$ = 0, len$ = tools.length; i$ < len$; ++i$) {
      it = tools[i$];
      info = posX + ", " + posY;
      view = TUI.createButton({
        top: posY + "px",
        left: posX + "px",
        width: width + "px",
        height: height + "px",
        title: it.title
      });
      closure = fn$;
      closure(view, it);
      if (posY > 40) {
        posY = 40;
        posX += width + marginX;
      } else {
        posY += height + marginY;
      }
      container.add(view);
    }
    return container;
    function fn$(btn, item){
      btn.addEventListener('click', function(){
        log('clicked' + item.title + item.ev);
        return _this.trigger(item.ev);
      });
    }
  };
  /**
   *@render render
   */
  taskView.renderByRecord = function(record){
    var time;
    this.Els.taskTextLabel.text = record.data.content;
    if (record.data.lastTime !== 0) {
      time = getTime(record.data.lastTime);
      this.Els["restTimeLabel"].text = time.hours + "小时 " + time.minutes + "分钟 " + time.seconds + "秒";
    } else {
      this.Els["restTimeLabel"].text = "任务艰巨, 赶紧完成啊少年!";
    }
    this.renderAdvicesView(record);
    if (record.meta.started) {
      return this.trigger('start-count');
    }
  };
  /**
   *@render render the time rules
   */
  taskView.renderAdvicesView = function(record){
    var startTime, endTime, deadLine;
    startTime = getDateStr(new Date(record.rules.startTime));
    endTime = getDateStr(new Date(record.rules.endTime));
    deadLine = getDateStr(new Date(record.rules.deadLine));
    this.Els.startTimeView.setContent(startTime);
    this.Els.endTimeView.setContent(endTime);
    this.Els.deadLineView.setContent(deadLine);
  };
  /************************************************
   *event handlers binding
   ************************************************/
  /**
   *@bind show-task
   */
  taskView.bind('show-task', function(record){
    var pageView;
    pageView = this.getPageView();
    if (!this.addedToWindow) {
      this.addedToWindow = true;
      YTI.APP.mainWindow.add(pageView);
    }
    pageView.show();
    this.record = record;
    this.Data = {};
    return this.renderByRecord(record);
  });
  /**
   *@bind delete-task
   */
  taskView.bind('delete-task', function(){
    var id, taskModel, homeView;
    id = this.record.id;
    taskModel = YTI.Model.taskModel;
    homeView = YTI.View.homeView;
    taskModel.deleteRecordById(id);
    homeView.updateTaskView();
    this.trigger('go-to-home');
  });
  /*
   *@bind start-count 开始计时
   */
  taskView.bind('start-count', function(){
    var _this, Data, taskModel, startCount, endTime, startTime;
    log("start-count");
    _this = this;
    Data = this.Data;
    taskModel = YTI.Model.taskModel;
    startCount = function(){
      var startedTime, delta, time;
      startedTime = _this.Data.startedTime;
      delta = _this.record.data.lastTime + (new Date() - startedTime);
      time = getTime(delta);
      _this.Els["restTimeLabel"].text = time.hours + "小时 " + time.minutes + "分钟 " + time.seconds + "秒";
    };
    if (!_this.Data.startedCount || _this.Data.startedCount === false) {
      _this.Data.startedCount = true;
      if (_this.record.meta.started) {
        _this.Data.startedTime = _this.record.meta.startedTime;
      } else {
        _this.Data.startedTime = new Date() - 0;
      }
      _this.record.meta.started = true;
      _this.record.meta.startedTime = _this.Data.startedTime;
      taskModel.save();
      _this.Els["startCountBtn"].text = "停止计时";
      _this.Data.t = setInterval(startCount, 1000);
    } else {
      _this.Data.startedCount = false;
      endTime = new Date() - 0;
      startTime = _this.Data.startedTime - 0;
      _this.Els["startCountBtn"].text = "开始计时";
      _this.record.meta.started = false;
      _this.record.meta.updateTime = endTime;
      _this.record.tracks.push([startTime, endTime]);
      _this.record.data.lastTime += endTime - startTime;
      taskModel.save();
      clearTimeout(_this.Data.t);
    }
  });
  /**
   *@bind go-to-home 返回到主界面
   */
  taskView.bind('go-to-home', function(){
    YTI.View.homeView.getPageView().show();
    if (this.Data.startedCount === true) {
      this.trigger('start-count');
    }
    return this.Els.pageView.hide();
  });
  taskView.bind('task-detail', function(){
    return alert('task-detal');
  });
  taskView.bind('resetTime', function(){
    alert('reset-time-clicked');
    this.trigger('set-finish-time');
  });
  /**
   *@bind 设置开始时间
   */
  taskView.bind('set-start-time', function(){
    var _this;
    _this = this;
    YTI.View.datePickerView.getDate(this, function(date){
      _this.record.rules.startTime = date;
      YTI.Model.taskModel.save();
      return _this.renderAdvicesView(_this.record);
    });
  });
  /**
   *@bind 设置完成时间
   */
  taskView.bind('set-finish-time', function(){
    var _this;
    _this = this;
    YTI.View.datePickerView.getDate(this, function(date){
      log('I-am-call-back-and-I-was-called');
      _this.record.rules.endTime = date;
      YTI.Model.taskModel.save();
      _this.renderAdvicesView(_this.record);
    });
  });
  /**
   *@bind 设置dead-line
   */
  taskView.bind('set-dead-line', function(){
    var _this;
    _this = this;
    YTI.View.datePickerView.getDate(this, function(date){
      _this.record.rules.deadLine = date;
      YTI.Model.taskModel.save();
      return _this.renderAdvicesView(_this.record);
    });
  });
  module.exports = taskView;
  function import$(obj, src){
    var own = {}.hasOwnProperty;
    for (var key in src) if (own.call(src, key)) obj[key] = src[key];
    return obj;
  }
}).call(this);


text:
require 'flexmock'
require 'rspec'

require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'transcode_producer'))

RSpec.configure do |c|
  c.mock_with(:flexmock)
end


text:
import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable }     from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';

import { User }           from './user';

@Injectable()
export class UserService  {
    private userUrl = 'app/users.json';

    constructor(private http: Http){ }

    getUsers(): Observable<User[]> {
        return this.http.get(this.userUrl)
            .map(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body.data || { };
    }

    private handleError (error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}


text:
package org.apache.lucene.search.similarities;

import java.util.List;
import java.util.Locale;

import org.apache.lucene.search.Explanation;

/**
 * Bayesian smoothing using Dirichlet priors. From Chengxiang Zhai and John
 * Lafferty. 2001. A study of smoothing methods for language models applied to
 * Ad Hoc information retrieval. In Proceedings of the 24th annual international
 * ACM SIGIR conference on Research and development in information retrieval
 * (SIGIR '01). ACM, New York, NY, USA, 334-342.
 * <p>
 * The formula as defined the paper assigns a negative score to documents that
 * contain the term, but with fewer occurrences than predicted by the collection
 * language model. The Lucene implementation returns {@code 0} for such
 * documents.
 * </p>
 *
 * @lucene.experimental
 */
public class LMDirichletSimilarity extends LMSimilarity {
  /** The μ parameter. */
  private final float mu;

  /** Instantiates the similarity with the provided μ parameter. */
  public LMDirichletSimilarity(CollectionModel collectionModel, float mu) {
    super(collectionModel);
    this.mu = mu;
  }

  /** Instantiates the similarity with the provided μ parameter. */
  public LMDirichletSimilarity(float mu) {
    this.mu = mu;
  }

  /** Instantiates the similarity with the default μ value of 2000. */
  public LMDirichletSimilarity(CollectionModel collectionModel) {
    this(collectionModel, 2000);
  }

  /** Instantiates the similarity with the default μ value of 2000. */
  public LMDirichletSimilarity() {
    this(2000);
  }

  @Override
  protected float score(BasicStats stats, float freq, float docLen) {
    float score = stats.getBoost() * (float)(Math.log(1 + freq /
        (mu * ((LMStats)stats).getCollectionProbability())) +
        Math.log(mu / (docLen + mu)));
    return score > 0.0f ? score : 0.0f;
  }

  @Override
  protected void explain(List<Explanation> subs, BasicStats stats, int doc,
      float freq, float docLen) {
    if (stats.getBoost() != 1.0f) {
      subs.add(Explanation.match(stats.getBoost(), "boost"));
    }

    subs.add(Explanation.match(mu, "mu"));
    Explanation weightExpl = Explanation.match(
        (float)Math.log(1 + freq /
        (mu * ((LMStats)stats).getCollectionProbability())),
        "term weight");
    subs.add(weightExpl);
    subs.add(Explanation.match(
        (float)Math.log(mu / (docLen + mu)), "document norm"));
    super.explain(subs, stats, doc, freq, docLen);
  }

  /** Returns the μ parameter. */
  public float getMu() {
    return mu;
  }

  @Override
  public String getName() {
    return String.format(Locale.ROOT, "Dirichlet(%f)", getMu());
  }
}


text:
<!DOCTYPE html>

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

    <title>Gulchekhra Inoyatova: Pianist, Professor, Honored Artist </title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet">

    <link href="css/creative.min.css" rel="stylesheet">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Gulchekhra Inoyatova

                        About

                        Peer Reviews

                        Portfolio

                        Contact

Pianist, Professor, Honored Artist

Played with the best orchestras of Russia and the CIS countries and performed numerous concerts around the world.

                Find Out More

Biography

Gulchekhra Inoyatova was raised in the best traditions of the Russian piano school. She is a

creative, pianist and acquired fame as a gifted interpreter of the music of contemporary

composers. Having received an excellent musical education, she graduated from the Central

Music School (CMS), the Moscow Tchaikovsky State Conservatory with DMA in Piano

Performance and Pedagogy, where her supervisor was a world famous musician, Tatiana

Nikolaeva. Inoyatova's extensive repertoire includes both contemporary music and works of

classical composers. Her playing is characterized by deep musicality, wonderful sense of form,

bright colorful expression and rich range of sound.

Gulchekhra Inoyatova played with the best orchestras of Russia, Latvia and the CIS

countries and performed numerous concerts in Germany, Latvia, Moldova, Czech Republic,

China, Hungary and other countries in Asia and Europe.

Ms. Inoyatova was often the first performer and interpreter of the brightest and most

important works of Tajik composers, written for piano during the period of 1980 to the 2000s.

Her ability to appreciate the author's idea, very deep understanding of the individual style of

each piece, clarity of articulation, total mastery of the keyboard are often an integral

component of the success of the composition.

For her artistic achievements, creative and teaching services to the development of Tajik

art and education of creative youth, she was honored with a title of Honored Artist of Republic

of Tajikistan in 1996.

Gulchekhra Inoyatova is a successful educator with over 30 years experience in higher

educational institutions of music in Russia, China and Tajikistan. She headed the piano

departments in both the universities of Tajikistan and Russia. During the past 11 years, she has

been a foreign expert in Xi'an Conservatoty of Music and South China Normal University, China.

More than a hundred students and young teachers have had a chance to improve their skills in

her class. Almost all of them are winners and laureates of piano competitions at various levels,

including international ones, and now successfully continue their musical activities and work in

Europe and Asia.

Ms. Inoyatova regularly holds master classes and gets invited to work as the jury

member of various piano competitions in China, America, Russia, Hong Kong and Central Asian

countries.

                    Download CV

Quotes

Prof. Boris Lvov, Higher School of Music (Trossingen, Germany) and the Boston Conservatory, America.

"Her erudition and outstanding memory, including the information in various fields of art, are used during her teaching work, and the intensity and persistence of her character infect students with desire to achieve success in the acquisition of skills."

Prof. V. K. Merzhanov, People's Artist of the USSR

"A talented, bright pianist, and has successfully performed many concerts. Her playing is

distinguished by fine musicianship, virtuosity and emotional content. Inoyatova Gulchekhra

repeatedly demonstrated her pedagogical skills in the master classes and courses of higher art

of pianistic skill in Russia, Hungary, Czech Republic, Kyrgyzstan and Tajikistan. Her experience

can be used for the successful development of the piano performing arts in any country.

Prof. Tatyana Nikolaeva, People's Artist of the USSR

"Inoyatova Gulchekhra is a talented pianist, very purposeful and effective in working in her

country and abroad. Her performance is characterized a big emotional musicality and good

taste."

                                    Category

                                    Project Name

                                    Category

                                    Project Name

                                    Category

                                    Project Name

                                    Category

                                    Project Name

                                    Category

                                    Project Name

                                    Category

                                    Project Name

Let's Get In Touch!

You are welcome to contact me for additional information!

Gulchekhra Inoyatova

gulchekhra57@gmail.com


text:
<?php
    header("Location: https://events.dancemarathon.com/index.cfm?fuseaction=donorDrive.event&eventID=5233");
?>


text:
/*
 * @(#)B.java	1.3 06/02/11
 */

package com.sun.ts.tests.ejb30.persistence.entitytest.persist.oneXone;

import java.io.Serializable;
import com.sun.ts.tests.ejb30.common.helper.TLogger;

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Basic;
import javax.persistence.OneToOne;
import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;

@Entity
@Table(name="BEJB_1X1_BI_BTOB")
public class B implements java.io.Serializable {

    // ===========================================================
    // instance variables
    @Id
    protected String id;

    @Basic
    protected String name;

    @Basic
    protected int value;

    // ===========================================================
    // relationship fields

    @OneToOne(targetEntity=com.sun.ts.tests.ejb30.persistence.entitytest.persist.oneXone.A.class, cascade=CascadeType.PERSIST)
    @JoinColumn(name="FK_FOR_AEJB_1X1_BI_BTOB")
    protected A a1;

    // ===========================================================
    // constructors

    public B() {
        TLogger.log("Entity B no arg constructor");
    }

    public B(String id, String name, int value)
    {
      this.id = id;
      this.name = name;
      this.value = value;
    }

    public B(String id, String name, int value, A a1)
    {
      this.id = id;
      this.name = name;
      this.value = value;
      this.a1 = a1;
    }

    // ==========================================================
    // Business Methods for Test Cases

    public A getA1() {
	return a1;
    }

    public void setA1(A a1) {
	this.a1 = a1;
    }

    public boolean isA()
    {
        TLogger.log("isA");
        if (getA1() != null)
            TLogger.log("Relationship for A is not null...");
        else
            TLogger.log("Relationship for A is null...");
        return getA1() != null;
    }

    public A getA1Info()
    {
        TLogger.log("getA1Info");
          if (isA()) {
            A a1 = getA1();
            return a1;
          }
          else
            return null;
    }

    public String getBId()
    {
	return id;
    }

    public String getBName()
    {
	return name;
    }

    public void setBName(String name)
    {
	this.name = name;
    }

    public int getBValue()
    {
	return value;
    }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once

// Auxiliary tests for juniper - based on Juniper 1.x proximitytest.cpp

#include "testenv.h"
#include "test.h"
#include <map>

class AuxTest : public Test
{
private:
    AuxTest(const AuxTest&);
    AuxTest& operator=(const AuxTest&);
public:
    AuxTest();
    virtual ~AuxTest();

    typedef void(AuxTest::* tst_method_ptr) ();
    typedef std::map<std::string, tst_method_ptr> MethodContainer;
    MethodContainer test_methods_;
    void init();

    void Run(MethodContainer::iterator &itr);
    void Run(const char* method);
    void Run(int argc, char* argv[]);
    void Run() override;
protected:
    /**
     * Since we are running within Emacs, the default behavior of
     * print_progress which includes backspace does not work.
     * We'll use a single '.' instead.
     */
    void print_progress() override { *m_osptr << '.' << std::flush; }
private:
    // tests:
    void TestPropertyMap();
    void TestRerase();
    void TestExample();
    void TestUTF8context();
    void TestJapanese();
    void TestStartHits();
    void TestEndHit();
    void TestJuniperStack();
    void TestUTF811();
    void TestUTF812();
    void TestDoubleWidth();
    void TestPartialUTF8();
    void TestLargeBlockChinese();
    void TestSpecialTokenRegistry();
    void TestWhiteSpacePreserved();

    bool assertChar(ucs4_t act, char exp);

    // Utilities
    char* IsoToUtf8 (const char* iso, size_t size);
    char* Utf8ToIso (const char* iso, size_t size);
    void test_summary(Matcher& m, const char* input, size_t input_len,
                      int size, int matches, int surround, size_t& charsize);
    void TestUTF8(unsigned int size);

    bool _split_char;
    SummaryConfig* _sumconf;
};


text:
include_attribute "composer"

normal['composer']['link_type'] = :hard


text:
#include <grpc/support/port_platform.h>

#include "src/core/lib/transport/status_metadata.h"

#include "src/core/lib/slice/slice_string_helpers.h"
#include "src/core/lib/transport/static_metadata.h"

/* we offset status by a small amount when storing it into transport metadata
   as metadata cannot store a 0 value (which is used as OK for grpc_status_codes
   */
#define STATUS_OFFSET 1

static void destroy_status(void* ignored) {}

grpc_status_code grpc_get_status_code_from_metadata(grpc_mdelem md) {
  if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_0)) {
    return GRPC_STATUS_OK;
  }
  if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_1)) {
    return GRPC_STATUS_CANCELLED;
  }
  if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_2)) {
    return GRPC_STATUS_UNKNOWN;
  }
  void* user_data = grpc_mdelem_get_user_data(md, destroy_status);
  if (user_data != nullptr) {
    return static_cast<grpc_status_code>((intptr_t)user_data - STATUS_OFFSET);
  }
  uint32_t status;
  if (!grpc_parse_slice_to_uint32(GRPC_MDVALUE(md), &status)) {
    status = GRPC_STATUS_UNKNOWN; /* could not parse status code */
  }
  grpc_mdelem_set_user_data(
      md, destroy_status, (void*)static_cast<intptr_t>(status + STATUS_OFFSET));
  return static_cast<grpc_status_code>(status);
}


text:
@font-face {
  font-family: "OpenSans";
  src: url("../../../lib/fonts/OpenSans-Light.ttf");
  font-weight: 300;
  font-style: normal;
}
@font-face {
  font-family: 'OpenSans';
  src: url("../../../lib/fonts/OpenSans-Regular.ttf");
  font-weight: normal;
  font-style: normal;
}
@font-face {
  font-family: 'OpenSans';
  src: url("../../../lib/fonts/OpenSans-Semibold.ttf");
  font-weight: 600;
  font-style: normal;
}
html {
  overflow: visible;
}
/* Preferences Editor Separated Panel styles */
.fl-prefsEditor-separatedPanel {
  background-color: #fff;
  background-image: url("../images/default/separatedpanelbg.png");
  background-repeat: repeat;
  height: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  color: #766d68;
  padding: 1px 0px;
  margin: 0px;
}
.fl-prefsEditor-separatedPanel .fl-prefsEditor {
  font-family: 'OpenSans', "Myriad Pro", Helvetica, Arial, sans-serif;
  line-height: 1.2em !important;
}
.fl-prefsEditor-separatedPanel .fl-prefsEditor-panels {
  white-space: nowrap;
  display: table;
  border-spacing: 20px 0px;
}
.fl-prefsEditor-separatedPanel .fl-prefsEditor-panels .fl-prefsEditor-panel {
  border: 1px solid #615e59;
  border-radius: 5px;
  box-shadow: 2px 2px #7a766d;
  display: inline-block;
  padding: 1em;
  min-width: 25em;
  background-color: #fff;
  white-space: normal;
  display: table-cell;
}
.fl-prefsEditor-separatedPanel h2 {
  color: #766d68;
  padding: 0 0 0.5em 0;
  margin: 0 0 1.5em 0;
  width: 100%;
  border-bottom: solid #ccc 1px;
  box-shadow: 0px 6px 7px -6px rgba(0,0,0,0.3);
  font-size: 1.2em;
  text-transform: lowercase;
  line-height: 1.7em;
  height: 2em;
}
.fl-prefsEditor-separatedPanel .fl-inputs {
  float: none;
  padding: 0;
}
.fl-prefsEditor-separatedPanel label {
  font-size: 1em;
  display: block;
}
.fl-prefsEditor-separatedPanel .fl-links-buttons-options label {
  width: 21em;
  display: inline-block;
}
.fl-prefsEditor-separatedPanel .fl-links-buttons-options li {
  margin-bottom: 0.4em;
}
.fl-prefsEditor-separatedPanel h2 label,
.fl-prefsEditor-separatedPanel h2 .fl-heading-text {
  float: left;
  padding-top: 0.2em;
  font-size: 1.3em;
  font-weight: 600;
}
.fl-prefsEditor-separatedPanel.fl-theme-bw {
  background-image: none;
}
.fl-prefsEditor-separatedPanel.fl-theme-wb {
  background-image: none;
}
.fl-prefsEditor-separatedPanel.fl-theme-yb {
  background-image: none;
}
.fl-prefsEditor-separatedPanel.fl-theme-by {
  background-image: none;
}
.fl-prefsEditor-separatedPanel.fl-theme-lgdg {
  background-image: none;
}


text:
'use strict'
import yo from 'yo-yo'

const backgroundImageHome = yo`

    <picture className="hide-on-med-and-down img-top img-top-left">

        </picture>
        <picture className="hide-on-med-and-down img-top img-top-right">

    </picture>

`

const backgroundImageAcerca = yo`

    <picture className="hide-on-med-and-down img-top img-top-left">

        </picture>
        <picture className="hide-on-med-and-down img-top img-top-right">

    </picture>

`

const backgroundImageCatalogo = yo`

    <picture className="hide-on-med-and-down img-top img-top-left">

        </picture>
        <picture className="hide-on-med-and-down img-top img-top-right">

    </picture>

`

const backgroundImageContacto = yo`

    <picture className="hide-on-med-and-down img-top img-top-left">

        </picture>
        <picture className="hide-on-med-and-down img-top img-top-right">

    </picture>

`
export {backgroundImageHome, backgroundImageAcerca, backgroundImageCatalogo, backgroundImageContacto}


text:
{% extends "base.html" %}
{% load humanize %}

{% block back %}{% include "back.html" with page="frontpage" %}{% endblock %}
{% block content %}
{% spaceless %}

{#
#}
{#  <map name="logomap">#}
{#    <area shape="rect" coords="20,0,476,150" alt="European Language Resource Coordination" href="http://www.lr-coordination.eu/" target="_blank">#}
{#    <area shape="rect" coords="90,58,3" alt="Metashare" href="http://www.meta-share.eu/">#}
{#      <area shape="rect" coords="15,0,190,175" alt="European Language Resource Coordination" href="http://www.lr-coordination.eu/" target="_blank">#}
{#    <area shape="rect" coords="550,172,400,145" alt="Metashare" href="http://www.meta-share.eu/" target="_blank">#}
{#</map>#}
{#
#}
{#      {% if user.get_profile.has_editor_permission %}#}

{{resources|intcomma}} language resource{{resources|pluralize}} at your disposal (and counting)

  <form method="get" action="{% url metashare.views.frontpage %}repository/search/" class="form_helper">

<input class="big_input span-14" type="text" name="q" defaultText="Type in your keywords, please..." />

<button type="submit" class="big_button button">Search</button>

  </form>

{#{% endif %}#}

{#    #}
{#      #}
{#    	#}

Welcome to the ELRC-SHARE repository!

The ELRC-SHARE repository is used for documenting, storing, browsing and
            accessing Language Resources that
            are collected through the European Language
                Resource Coordination and considered useful for feeding the CEF Automated Translation
            (CEF.AT) platform.

If you want to contribute resources, all you have to do is
            {% if not user.is_authenticated %}
            register (new user)
            or login (returing user)
            {% else %}
            click here
            {% endif %}
             and go on to describe and upload your data with a simple form.

          <map name="registerMap">
                <area shape="circle" coords="47,82,45" alt="Register" href="/accounts/create/">
                <area shape="circle" coords="290,82,45" alt="Contribute data" href="/repository/simple_form">
          </map>
          <map name="contributeMap">
                <area shape="circle" coords="290,82,45" alt="Contribute data" href="/repository/simple_form">
          </map>

All data resources gathered by this initiative will be provided to the European Commission for use in the CEF.AT platform.

{% endspaceless %}
{% endblock %}


text:
Address commentary in manifest.excludedmanifestrevlog.add -
specifically we should improve the collaboration with core so that
add() never gets called on an excluded directory and we can improve
the stand-in to raise a ProgrammingError.

Reason more completely about rename-filtering logic in
narrowfilelog. There could be some surprises lurking there.

Formally document the narrowspec format. For bonus points, unify with the
server-specified narrowspec format.

narrowrepo.setnarrowpats() or narrowspec.save() need to make sure
they're holding the wlock.

The follinwg places do an unrestricted dirstate walk (including files outside the
narrowspec). Some of them should perhaps not do that.

 * debugfileset
 * perfwalk
 * sparse (but restricted to sparse config)
 * largefiles


text:
<!DOCTYPE html>

		<title>pc3sq.github.io</title>
		<link rel="stylesheet" type="text/css" href="../css/main.css">

Test Driven Development

In A Nutshell

					Test driven development - or TDD - proposes to start the development process with tests that defines an improvement or new function to a program. While there are different flavors of TDD, most styles seek ask that the developer write the least amount of code to make the test pass first. Refactoring for readability and scalability is a later (but important) consideration.

Why Use TDD?

					Functions with any sort of complexity will take multiple discrete steps be to built before completion. TDD helps you break down a function into its discrete steps so they can each be tested.

What About BDD?

					Many developers will tell you that BDD is TDD but done right. What they mean is that BDD is TDD but with particular focus on what a user wants and expects out of a system rather than simply testing system outputs. This is very nuanced. You can tell BDD is being used if the tests are phrased more semantically and if you see more integration tests, tests written to test a few functions/features together, being used.

					As a product manager (PM), I cared more about what a user saw and expected from a system so I favored BDD in my work. In fact, if you have technical PM, having the PM write BDD can save you time and miscommunications that result from improperly translated user stories.

					So remember, there is no distinction between BDD or TDD, it's just a matter of keeping best practices in mind while doing test driven development.


text:
FOUNDATION_EXPORT UIDeviceOrientation CT_UIDeviceOrientationFromInterfaceOrientation(UIInterfaceOrientation interfaceOrientation);

FOUNDATION_EXPORT BOOL CT_UIDeviceOrientationIsValid(UIDeviceOrientation deviceOrientation);

@interface UITabBarController (CTInterfaceOrientation)

@property (nonatomic, assign, getter = isCt_shouldAutorotateOrientation) BOOL ct_shouldAutorotateOrientation;

@property (nonatomic, assign) UIInterfaceOrientationMask ct_supportedInterfaceOrientations;

@end

@interface UIDevice (CTInterfaceOrientation)

- (void)ct_setOrientation:(UIDeviceOrientation)orientation;

@end


text:
{% extends "base.html" %}
{% load staticfiles %}

{% load i18n %}
{% load url from future %}

{% block body_class %}home{% endblock %}

{% block body_base %}

		<form class="category-form" method="POST" action="{{ request.path }}">
			{% csrf_token %}
			<input name="category_id" value="{{ category_id }}" type="hidden">

					Category name
					<input type="text" class="form-control" name="category_name" placeholder="Category name..." value="{{ form.category_name.value }}">

					<button id="edit_category" class="btn btn-primary pull-right"> Update</button>
					<button id="delete_category" style="margin-right: 5px" type="button" class="btn btn-danger pull-right"> Delete</button>

					 Back to list

		</form>

{% endblock %}

{% block extra_script %}

{% endblock %}


text:
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

#nullable disable

namespace StyleCop.Analyzers.Lightup
{
    using System;
    using Microsoft.CodeAnalysis.CSharp;
    using Microsoft.CodeAnalysis.CSharp.Syntax;

    internal static class BaseMethodDeclarationSyntaxExtensions
    {
        private static readonly Func<BaseMethodDeclarationSyntax, ArrowExpressionClauseSyntax> ExpressionBodyAccessor;

        static BaseMethodDeclarationSyntaxExtensions()
        {
            ExpressionBodyAccessor = LightupHelpers.CreateSyntaxPropertyAccessor<BaseMethodDeclarationSyntax, ArrowExpressionClauseSyntax>(typeof(BaseMethodDeclarationSyntax), nameof(ExpressionBody));
        }

        public static ArrowExpressionClauseSyntax ExpressionBody(this BaseMethodDeclarationSyntax syntax)
        {
            if (!LightupHelpers.SupportsCSharp7)
            {
                // Prior to C# 7, the ExpressionBody properties did not override a base method.
                switch (syntax.Kind())
                {
                case SyntaxKind.MethodDeclaration:
                    return ((MethodDeclarationSyntax)syntax).ExpressionBody;

                case SyntaxKind.OperatorDeclaration:
                    return ((OperatorDeclarationSyntax)syntax).ExpressionBody;

                case SyntaxKind.ConversionOperatorDeclaration:
                    return ((ConversionOperatorDeclarationSyntax)syntax).ExpressionBody;

                default:
                    break;
                }
            }

            return ExpressionBodyAccessor(syntax);
        }
    }
}


text:
#include "smSocket.h"
#include "vmapiUnDocumented.h"
#include "smapiTableParser.h"
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>

#define PARSER_TABLE_NAME     Virtual_Network_Query_OSA_Layout
#define OUTPUT_STRUCTURE_NAME vmApiVirtualNetworkQueryOsaOutput

/**
 * Virtual_Network_Query_OSA SMAPI interface
 */
int smVirtual_Network_Query_OSA(struct _vmApiInternalContext* vmapiContextP, vmApiVirtualNetworkQueryOsaOutput ** outData) {
    const char * const functionName = "Virtual_Network_Query_OSA";
    tableParserParms parserParms;
    int tempSize;
    char * cursor;
    char * stringCursor;  // Used for outData string area pointer
    int arrayCount;
    int totalStringSize;
    int rc;
    int sockDesc;
    int requestId;

    int inputSize = 4 + 1 + strlen(functionName) + 1;
    char * inputP = 0;
    char * smapiOutputP = 0;
    char line[LINESIZE];
    int i;

    // Build SMAPI input parameter buffer
    if (0 == (inputP = malloc(inputSize))) {
        return MEMORY_ERROR;
    }
    cursor = inputP;
    PUT_INT(inputSize - 4, cursor);

    *cursor = 0xFF;  // Separator
    cursor++;

    tempSize = strlen(functionName);
    strcpy(cursor, functionName);
    cursor += tempSize + 1;

    // This routine will send SMAPI the input, delete the input storage
    // and call the table parser to set the output in outData
    rc = getAndParseSmapiBuffer(vmapiContextP, &inputP, inputSize,
            PARSER_TABLE_NAME,  // Integer table
            TO_STRING(PARSER_TABLE_NAME),  // String name of the table
            (char * *) outData);
    return rc;
}


text:
require 'test_helper' unless eval "begin; Spork.using_spork?; rescue; false; end"

class FeedbacksControllerTest < ActionController::TestCase

  test 'new should display form' do
    user = FactoryGirl.create :user
    sign_in user

    get :new

    assert_response :success
    assert_not_nil assigns[:feedback]
  end

  test 'create feedback should drop every params in text' do
    user = FactoryGirl.create :user
    sign_in user
    some_email = FactoryGirl.generate :email

    assert_difference 'Feedback.count' do
      post :create, :test_1 => 'test 1 value', :test_2 => some_email
    end

    feedback = Feedback.last
    answers = ActiveSupport::JSON.decode(feedback.answers)

    assert_equal 'test 1 value', answers['test_1']
    assert_equal some_email, answers['test_2']
  end

  test 'create feedback should mark feedbacks on user and do accept feedback after that' do
    user = FactoryGirl.create :user
    sign_in user
    some_email = FactoryGirl.generate :email
    assert ! user.reload.feedbacks

    assert_difference 'Feedback.count' do
      post :create, :test_1 => 'test 1 value', :test_2 => some_email
    end

    assert_redirected_to thanks_path
    assert user.reload.feedbacks

    assert_no_difference 'Feedback.count' do
      post :create, :test_1 => 'test 1 value', :test_2 => some_email
    end
    assert_redirected_to thanks_path
  end

end


text:
    qt_script_runtime_LTX_RegisterScriptRuntimeExtension

using ggadget::ScriptRuntimeManager;
using ggadget::qt::JSScriptRuntime;

static JSScriptRuntime *g_script_runtime_ = NULL;

extern "C" {
  bool Initialize() {
    LOGI("Initialize qt_script_runtime extension.");
    return true;
  }

  void Finalize() {
    LOGI("Finalize qt_script_runtime extension.");
    delete g_script_runtime_;
  }

  bool RegisterScriptRuntimeExtension(ScriptRuntimeManager *manager) {
    LOGI("Register qt_script_runtime extension.");
    if (manager) {
      if (!g_script_runtime_)
        g_script_runtime_ = new JSScriptRuntime();

      manager->RegisterScriptRuntime("js", g_script_runtime_);
      return true;
    }
    return false;
  }
}


text:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class BorderDemo extends JFrame {
	public BorderDemo() {
		setTitle("Border Demo");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//		getContentPane().setBackground(Color.white);

		JPanel panel = new JPanel();
		panel.setLayout(new GridLayout(0, 2, 5, 10));
		panel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
		panel.setBackground(Color.white);

		JPanel p1 = new JPanel();
		p1.setBorder(BorderFactory.createLineBorder(Color.red, 3));
		p1.add(new JLabel("Line Border"));
		p1.setBackground(Color.white);
		panel.add(p1);

		JPanel p2 = new JPanel();
		Border pd1 = BorderFactory.createEtchedBorder();
		Border pde = BorderFactory.createTitledBorder(pd1, "Title");
		p2.setBorder(pde);
		p2.add(new JLabel("Etched Titled Border"));
		p2.setBackground(Color.white);
		panel.add(p2);

		JPanel p3 = new JPanel();
		p3.setBorder(BorderFactory.createRaisedBevelBorder());
		p3.add(new JLabel("Raised Bevel Border"));
		p3.setBackground(Color.white);
		panel.add(p3);

		JPanel p4 = new JPanel();
		p4.setBorder(BorderFactory.createLoweredBevelBorder());
		p4.add(new JLabel("Lowered Bevel Border"));
		p4.setBackground(Color.white);
		panel.add(p4);

		JPanel p5 = new JPanel();
		p5.setBorder(BorderFactory.createTitledBorder("Title"));
		p5.add(new JLabel("Titled Border"));
		p5.setBackground(Color.white);
		panel.add(p5);

		JPanel p6 = new JPanel();
		TitledBorder tb = BorderFactory.createTitledBorder("Title");
		tb.setTitleJustification(TitledBorder.RIGHT);
		p6.setBorder(tb);
		p6.add(new JLabel("Titled Border (right)"));
		p6.setBackground(Color.white);
		panel.add(p6);

		JPanel p7 = new JPanel();
		Border b1 = BorderFactory.createLineBorder(Color.blue, 2);
		Border b2 = BorderFactory.createEtchedBorder();
		p7.setBorder(BorderFactory.createCompoundBorder(b1, b2));
		p7.add(new JLabel("Compound Border"));
		p7.setBackground(Color.white);
		panel.add(p7);

		JPanel p8 = new JPanel();
		Border mb = BorderFactory.createMatteBorder(1, 5, 1, 1, Color.red);
		p8.setBorder(mb);
		p8.add(new JLabel("Matte Border"));
		p8.setBackground(Color.white);
		panel.add(p8);

		getContentPane().add(panel);
		pack();
	}

	public static void main(String[] args) {
		BorderDemo BD = new BorderDemo();
		BD.setVisible(true);
	}
}


text:
package metricbatcher_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestMetricBatcher(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "MetricBatcher Suite")
}


text:
package ru.dionisius.model;

import java.sql.Timestamp;

/**
 * Created by Dionisius on 05.08.2017.
 * This class stores user's ru.dionisius.ru.dionisius.data
 * and has getters for this ru.dionisius.ru.dionisius.data.
 */
public class User {
    /**
     * User's name.
     */
    private final String name;
    /**
     * User's login.
     */
    private final String login;
    /**
     * User's email.
     */
    private final String email;
    /**
     * The date of user's entry creation.
     */
    private final Timestamp createDate;

    /**
     * Constructor.
     * @param name user's name.
     * @param login user's login.
     * @param email user's email;
     * @param createDate creation date of user's entry.
     */
    public User(final String name, final String login, final String email,
                final Timestamp createDate) {
        this.name = name;
        this.login = login;
        this.email = email;
        this.createDate = createDate;
    }

    /**
     * Getter for user's name.
     * @return user's name.
     */
    public String getName() {
        return this.name;
    }

    /**
     * Getter for user's login.
     * @return user's login.
     */
    public String getLogin() {
        return this.login;
    }

    /**
     * Getter for user's email.
     * @return user's email.
     */
    public String getEmail() {
        return this.email;
    }

    /**
     * Getter for creation date of user's entry.
     * @return creation date of user's entry.
     */
    public Timestamp getCreateDate() {
        return this.createDate;
    }

    @Override
    public String toString() {
        return "User{"
                + "name='" + name + '\''
                + ", login='" + login + '\''
                + ", email='" + email + '\''
                + ", createDate=" + createDate
                + '}';
    }
}


text:
/*! \file fill.h
 *  \brief Fills a range with a constant value
 */

#pragma once

#include <thrust/detail/config.h>

namespace thrust
{

/*! \addtogroup transformations
 *  \addtogroup filling
 *  \ingroup transformations
 *  \{
 */

/*! \p fill assigns the value \p value to every element in
 *  the range <tt>[first, last)</tt>. That is, for every
 *  iterator \c i in <tt>[first, last)</tt>, it performs
 *  the assignment <tt>*i = value</tt>.
 *
 *  \param first The beginning of the sequence.
 *  \param last The end of the sequence.
 *  \param value The value to be copied.
 *
 *  \tparam ForwardIterator is a model of Forward Iterator,
 *          and \p ForwardIterator is mutable.
 *  \tparam T is a model of Assignable,
 *          and \p T's \c value_type is convertible to \p ForwardIterator's \c value_type.
 *
 *  The following code snippet demonstrates how to use \p fill to set a thrust::device_vector's
 *  elements to a given value.
 *
 *  \code
 *  #include <thrust/fill.h>
 *  #include <thrust/device_vector.h>
 *  ...
 *  thrust::device_vector<int> v(4);
 *  thrust::fill(v.begin(), v.end(), 137);
 *
 *  // v[0] == 137, v[1] == 137, v[2] == 137, v[3] == 137
 *  \endcode
 *
 *  \see http://www.sgi.com/tech/stl/fill.html
 *  \see \c fill_n
 *  \see \c uninitialized_fill
 */
template<typename ForwardIterator, typename T>
  void fill(ForwardIterator first,
            ForwardIterator last,
            const T &value);

/*! \p fill_n assigns the value \p value to every element in
 *  the range <tt>[first, first+n)</tt>. That is, for every
 *  iterator \c i in <tt>[first, first+n)</tt>, it performs
 *  the assignment <tt>*i = value</tt>.
 *
 *  \param first The beginning of the sequence.
 *  \param n The size of the sequence.
 *  \param value The value to be copied.
 *  \return <tt>first + n</tt>
 *
 *  \tparam OutputIterator is a model of Output Iterator.
 *  \tparam T is a model of Assignable,
 *          and \p T's \c value_type is convertible to a type in \p OutputIterator's set of \c value_type.
 *
 *  The following code snippet demonstrates how to use \p fill to set a thrust::device_vector's
 *  elements to a given value.
 *
 *  \code
 *  #include <thrust/fill.h>
 *  #include <thrust/device_vector.h>
 *  ...
 *  thrust::device_vector<int> v(4);
 *  thrust::fill_n(v.begin(), v.size(), 137);
 *
 *  // v[0] == 137, v[1] == 137, v[2] == 137, v[3] == 137
 *  \endcode
 *
 *  \see http://www.sgi.com/tech/stl/fill_n.html
 *  \see \c fill
 *  \see \c uninitialized_fill_n
 */
template<typename OutputIterator, typename Size, typename T>
  OutputIterator fill_n(OutputIterator first,
                        Size n,
                        const T &value);

/*! \} // end filling
 *  \} // transformations
 */

} // end namespace thrust

#include <thrust/detail/fill.inl>


text:
<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yii message/extract' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
return [
    'Enter your password to continue' => '',
    'Are you sure, that you want to delete your account?
All your published content will be removed! ' => 'Segur que vols eliminar el teu compte?
 S\'eliminarà tot el contingut publicat!',
    'Delete account' => 'Elimina el compte',
    'Sorry, as an owner of a workspace you are not able to delete your account!
Please assign another owner or delete them.' => 'Ho sentim, com a propietari d\'un espai no pots eliminar el seu compte!
 Si us plau, assigna l\'espai a un altre propietari o elimina\'l.',
];


text:
using System;
using System.Data.SqlClient;
using System.IO;

namespace Meadow.Database
{
    /// <summary>
    /// Contains information about a SQL command.
    /// </summary>
    public class MeadowSqlDbCommand : MeadowDbCommand
    {
        internal MeadowSqlDbCommand()
        {
            Command = new SqlCommand();
        }

        /// <inheritdoc />
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="InvalidCastException">A <see cref="P:System.Data.SqlClient.SqlParameter.SqlDbType" /> other than Binary or VarBinary was used when <see cref="P:System.Data.SqlClient.SqlParameter.Value" /> was set to <see cref="T:System.IO.Stream" />. For more information about streaming, see SqlClient Streaming Support.A <see cref="P:System.Data.SqlClient.SqlParameter.SqlDbType" /> other than Char, NChar, NVarChar, VarChar, or  Xml was used when <see cref="P:System.Data.SqlClient.SqlParameter.Value" /> was set to <see cref="T:System.IO.TextReader" />.A <see cref="P:System.Data.SqlClient.SqlParameter.SqlDbType" /> other than Xml was used when <see cref="P:System.Data.SqlClient.SqlParameter.Value" /> was set to <see cref="T:System.Xml.XmlReader" />.</exception>
        /// <exception cref="SqlException">An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0.A timeout occurred during a streaming operation. For more information about streaming, see SqlClient Streaming Support.</exception>
        /// <exception cref="IOException">An error occurred in a <see cref="T:System.IO.Stream" />, <see cref="T:System.Xml.XmlReader" /> or <see cref="T:System.IO.TextReader" /> object during a streaming operation.  For more information about streaming, see SqlClient Streaming Support.</exception>
        /// <exception cref="InvalidOperationException">The <see cref="T:System.Data.SqlClient.SqlConnection" /> closed or dropped during a streaming operation. For more information about streaming, see SqlClient Streaming Support.</exception>
        /// <exception cref="ObjectDisposedException">The <see cref="T:System.IO.Stream" />, <see cref="T:System.Xml.XmlReader" /> or <see cref="T:System.IO.TextReader" /> object was closed during a streaming operation.  For more information about streaming, see SqlClient Streaming Support.</exception>
        protected override int ExecuteNonQueryInternal(bool bReturnAutoIncNumber)
        {
            if (bReturnAutoIncNumber)
            {
                throw new NotSupportedException($"{nameof(bReturnAutoIncNumber)} is not supported for this command type.");
            }

            var sqlCommand = Command as SqlCommand;
            return sqlCommand?.ExecuteNonQuery() ?? 0;
        }
    }
}


text:
Table of Contents
=================

* [Parse](#parse)
  * [Features](#features)
  * [Install](#install)
  * [Example](#example)
  * [API](#api)
    * [parse([args], [options])](#parseargs-options)
      * [Options](#options)
      * [Result](#result)
      * [Aliases](#aliases)
      * [Flags](#flags)
      * [Options](#options-1)
      * [Strict](#strict)
      * [Flat](#flat)
      * [Vars](#vars)
  * [Developer](#developer)
    * [Test](#test)
    * [Cover](#cover)
    * [Lint](#lint)
    * [Clean](#clean)
    * [Readme](#readme)
  * [License](#license)

Parse
=====

[](https://travis-ci.org/tmpfs/cli-argparse)
[](https://npmjs.org/package/cli-argparse)
[](https://coveralls.io/github/tmpfs/cli-argparse?branch=master).

Lightweight yet feature rich argument parser.

This module does not define any options or any program requirements it simply parses arguments into an object structure that is easier for other modules to work with.

## Features

* Supports multiple option values as arrays.
* Supports long flag negations, eg: `--no-color`.
* Supports `--option=value`, `--option value` and `option=value`.
* Expands short flags such as `-xvf`.
* Supports multiple flags as numbers: `-ddd`.
* Assignment on last flag expansion `-xvf file.tgz`.
* Treat `-` as special stdin flag.
* Stop argument parsing on `--`.
* Comprehensive test suite.
* 100% code coverage.

## Install

```
npm install cli-argparse
```

## Example

```javascript
var parse = require('./index');
var args = [
  'server',
  'start',
  '-xvd',
  '--port=80',
  '--config',
  '-',
  '--config=config.json',
  '--log',
  'server.log',
  '--no-color'
];
var result = parse(args);
console.log(JSON.stringify(result, undefined, 2));
```

```json
{
  "flags": {
    "x": true,
    "v": true,
    "d": true,
    "color": false
  },
  "options": {
    "port": "80",
    "config": [
      "-",
      "config.json"
    ],
    "log": "server.log"
  },
  "raw": [
    "server",
    "start",
    "-xvd",
    "--port=80",
    "--config",
    "-",
    "--config=config.json",
    "--log",
    "server.log",
    "--no-color"
  ],
  "stdin": true,
  "unparsed": [
    "server",
    "start"
  ],
  "strict": false,
  "vars": {}
}
```

## API

```javascript
var parse = require('cli-argparse');
var result = parse();
console.dir(result);
```

### parse([args], [options])

* `args`: Specific arguments to parse, default is `process.argv.slice(2)`.
* `options`: Parsing configuration options.

Returns a result object.

#### Options

* `alias`: Map of argument names to property names.
* `flags`: Array of argument names to be treated as flags.
* `options`: Array of argument names to be treated as options.
* `short`: Allow short options to have values.
* `strict`: A boolean that indicates only arguments specified as `options` or `flags` should be parsed.
* `flat`: A boolean that creates a flat result structure.
* `stop`: Array of strings or patterns to stop parsing on, the special pattern `--` is always respected first.
* `vars`: A string or regexp used to collect variables into the `vars` object.
* `camelcase`: When `false` do not convert option names to camelcase; when a string or regexp split the option name on the given pattern for conversion to camelcase.

#### Result

The result object contains the fields:

* `flags`: Object containing arguments treated as flags.
* `options`: Object containing arguments treated as options with values.
* `raw`: Array of the raw arguments parsed.
* `stdin`: Boolean indicating whether `-` is present in the argument list.
* `unparsed`: Array of values that were not parsed.
* `skip`: Array of args skipped upon `--` or a custom stop pattern.
* `stop`: If a stop pattern matched this will contain the pattern that matched (string or regexp).
* `empty`: Set to `true` if a stop pattern matched on the first argument.
* `vars`: Variables collected when the `vars` option is configured.

#### Aliases

Aliases allow arguments to map to meaningful property names that will be set on the result object `options` and `flags`.

Aliases are mapped on the raw argument name, to map `-v | --verbose` to a `verbose` property use `{'-v --verbose': 'verbose'}`.

Note that you should **not** use the negated long form (--no-highlight) when specifying these hints, always use the positive form.

#### Flags

Use the flags array when you need to force a long argument to be treated as a flag, for example `['--syntax-highlight']`.

#### Options

Use the options array when you need to treat a short argument as accepting a value, for example `['-f']`.

#### Strict

A `boolean` that indicates that only known arguments (those declared in the options and flags properties) are accepted, all other arguments will be placed in the unparsed array.

#### Flat

Creating a flat result can be useful if you are certain that there are no naming collisions, typically this can be achieved by providing hints using `flags` and `options`.

When this option is specified the result object will not have a `flags` property, instead all flags and options will be in the `options` property of the result.

#### Vars

Sometimes it is useful to collect arguments following a convention, for example `-D` like java or maybe all arguments prefixed with `@`. When the `vars` option is set all arguments that match the convention are collected in to the `vars` result object, see the [vars test spec](https://github.com/cli-kit/cli-argparse/blob/master/test/spec/vars.js) for examples.

## Developer

### Test

To run the test suite:

```
npm test
```

### Cover

To generate code coverage run:

```
npm run cover
```

### Lint

Run the source tree through [jshint](http://jshint.com) and [jscs](http://jscs.info):

```
npm run lint
```

### Clean

Remove generated files:

```
npm run clean
```

### Readme

To build the readme file from the partial definitions (requires [mdp](https://github.com/tmpfs/mdp)):

```
npm run readme
```

## License

Everything is [MIT](http://en.wikipedia.org/wiki/MIT_License). Read the [license](https://github.com/cli-kit/cli-argparse/blob/master/LICENSE) if you feel inclined.

Generated by [mdp(1)](https://github.com/tmpfs/mdp).

[mdp]: https://github.com/tmpfs/mdp
[jshint]: http://jshint.com
[jscs]: http://jscs.info