text:
<!DOCTYPE html>

            <title>Red Dead Redemption Sequel Confirmed In Development Says Rockstar Insider | Game Golem</title>
            <meta name="keywords" content="Video Game, News, Video Game News, Call of Duty, Bethesda, Valve, Steam, Shadow of Mordor, WWE 2K15, World of Warcraft, Warlords of Draenor, Review, News, Opinions, Red Dead Redemption, Red Dead Redemption 2 "  />
            <meta name="description" content="Red Dead Redemption Sequel is apparently in the works and we have some information about it!" />
            <link href="style.css" rel="stylesheet" type="text/css" />
            <link rel="shortcut icon" href="images/default/favicon.ico" >

            <meta name="viewport" content="width=device-width, initial-scale=1">

Archive

About Us

Join Us

News

Archive

Team

About Us

Join Us

Contact Us

Dylan Graham is a hardcore gamer with full intention on loving every moment of game time he gets. Dylan is also the Game Golem founder and Web Developer. He loves music and his secondary hobby is drumming. For all things ridiculous, follow him on twitter: @Codewow_

'Red Dead Redemption Sequel In Development' Says Rockstar Insider

A member of NeoGAF posted a very small thread rumoring the development of Red Dead Redemption 2, while the thread was originally just a rumor based on a single persons possible troll-attempt, it has since been verified by a NeoGAF Moderator as true.

The information we have so far is that the sequel will be exclusive to Xbox One and PS4, while no information about a PC release is known. There will also be a focus on co-op play. No word on how it will tie into the story or other areas of the game.

Even though the claims of this user have been "verified". We recommend that all information posted be taken with a grain of salt. If it so happens that these claims turn out false, we will update this article. Likewise, we will also update the article if new information emerges.

For all things Gaming, like Game Golem on Facebook and Follow us on Twitter. You can also join our Steam Group.

Excited about this information? Skeptical? What are your thoughts?

    Please enable JavaScript to view the comments powered by Disqus.

                Copyright© 2014 Game Golem


text:
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from browse.models import *
from django.db.models import Q
from browse.browse_view_models import allEHFPI
from news.models import news
from search.models import das
from django.shortcuts import HttpResponseRedirect
from analysis.models import vtpModel
from django.utils.encoding import smart_str,smart_unicode
import csv
from ehf.settings import PAGINATION_DEFAULT_PAGINATION
from ehf.settings import URL_PREFIX
from ehf.commonVar import fieldDic,field,fieldDes
from analysis.models import idNameMap,heatmapModel

def index(request):
    return HttpResponseRedirect(URL_PREFIX)

#given query and searchType, return a result
# we define this function from quick search, because gea analysis use this function too
def getResult(query, searchType):
    result = ""
    if searchType == 'gene':  #exact match
        result = allEHFPI.objects.filter(
            Q(drosophilaGene__iexact=query) |Q(humanHomolog__iexact=query)| Q(entrezId__iexact=query) | Q(uniprotId__iexact=query) | Q(
                previousName__icontains=query) | Q(synonyms__icontains=query) | Q(ensemblGeneId__iexact=query))
    elif searchType == 'pathogen':
        result = allEHFPI.objects.filter(
            Q(fullName__iexact=query) | Q(abbreviation__iexact=query) | Q(aliases__iexact=query) | Q(
                strain__iexact=query) | Q(genus__iexact=query)| Q(species__iexact=query) | Q(family__iexact=query) | Q(
                group__iexact=query) | Q(kingdom__iexact=query))
    elif searchType == 'publication':
        result = allEHFPI.objects.filter(
            Q(pubmedId__iexact=query) | Q(title__iexact=query) | Q(author__iexact=query) | Q(
                journal__iexact=query) | Q(year__iexact=query))
    elif searchType == 'ehfpiacc':
        result = allEHFPI.objects.filter(Q(ehfpiAcc__iexact=query))
    else:
        result = allEHFPI.objects.filter(
            Q(drosophilaGene__iexact=query) |Q(humanHomolog__iexact=query) | Q(entrezId__iexact=query) | Q(uniprotId__iexact=query) | Q(
                previousName__icontains=query) | Q(synonyms__icontains=query) |Q(ensemblGeneId__iexact=query)|
                Q(fullName__iexact=query) | Q(
                abbreviation__iexact=query) | Q(aliases__iexact=query) | Q(strain__iexact=query) | Q(
                species__iexact=query) | Q(genus__iexact=query)| Q(family__iexact=query) | Q(group__iexact=query) | Q(
                kingdom__iexact=query) | Q(pubmedId__iexact=query) | Q(title__iexact=query) | Q(
                author__iexact=query) | Q(journal__iexact=query) | Q(year__iexact=query) | Q(
                ehfpiAcc__iexact=query))
    return result

# Create your views here.
# code for quick search
def quickSearch(request):

    if request.method == 'GET':  # If the form has been submitted...
        searchType = request.GET['searchType']
        query = request.GET['query']

        #change columns?
        if 'columns' in request.GET:
            selectedColumns_tmp = request.GET['columns']
            selectedColumns = selectedColumns_tmp.split(',')
            request.session['has_changed'] = True  # set the session, not change
            request.session['selectedColumns'] = selectedColumns  #store the columns

        if 'has_changed' not in request.session:
            defaultColumns = ['ehfpiAcc', 'geneSymbol', 'targetOrganism', 'strain', 'title']
            request.session['selectedColumns'] = defaultColumns  #store the columns

        if request.GET['query']:  #not empty search
            result = getResult(query.strip(), searchType)

            if (len(result)):
                #sort the column
                order = request.GET.get('order_by', 'ehfpiAcc')
                result = result.order_by(order)

            #custom display columns start!
            columns = []
            for i in range(0, len(field), 1):
                columns.append([field[i], fieldDes[i]])
            #custom display columns end

            #columns to display start!

            displayColumns = request.session['selectedColumns']
            if displayColumns == '':
                displayColumns = ['ehfpiAcc', 'geneSymbol', 'targetOrganism', 'strain', 'title']
            displayColumnsDic = []
            for item in displayColumns:
                displayColumnsDic.append([item, fieldDic[item]])
            #columns to display end

            #get publication number and EHF gene number
            publicationNum = len(set(result.values_list('title')))
            geneList = []
            for item in result.values_list('humanHomolog'):
                geneList.append(item[0].strip().upper())
            geneList = list(set(geneList))
            if '' in geneList:
                geneList.remove('')
            ehfNum = len(geneList)
            #end
            return render_to_response('search/searchResult.html',
                                      {'searchType': searchType, 'query': query, 'publicationNum': publicationNum,
                                       'ehfNum': ehfNum, 'result': result, 'columns': columns,
                                       'displayColumnsDic': displayColumnsDic},
                                      context_instance=RequestContext(request))
        else:
            all_news = news.objects.all()[0:4]
            mark = 0
            if len(news.objects.all()) > 4:
                mark = 1
            return render_to_response('index.html', {'news': all_news, 'mark': mark})
    else:
        return render_to_response('index.html')

# code for advanced search
def advancedSearch(request):
    if request.method == 'GET':  # If the form has been submitted...
        if len(request.GET):
            #change columns?
            if 'columns' in request.GET:
                selectedColumns_tmp = request.GET['columns']
                selectedColumns = selectedColumns_tmp.split(',')
                request.session['has_changed'] = True  # set the session, not change
                request.session['selectedColumns'] = selectedColumns  #store the columns

            if 'has_changed' not in request.session:
                defaultColumns = ['ehfpiAcc', 'geneSymbol', 'targetOrganism', 'strain', 'title']
                request.session['selectedColumns'] = defaultColumns  #store the columns

            conditionNum = 0  # search condition number, based on smartSearchSubtype number in POST
            condition = {}  #map to store the condition
            type = {}  #store the search type of each condition
            for key, value in request.GET.iteritems():
                if key.startswith("smartSearchSubtype"):
                    conditionNum = conditionNum + 1
                    conKey = key[key.rfind("_") + 1:]
                    condition[conKey] = ""  #initialize the map
                    type[conKey] = value

            #parse condition
            for conditionKey, conditionValue in type.items():
                if conditionValue == "publication":  #AND phrase
                    pubList = {}
                if conditionValue == "pathogen":  #AND phrase
                    pathogenList = {}

                for key, value in request.GET.iteritems():
                    if key.find("_") != -1:
                        if key[key.rfind("_") + 1:] == conditionKey:  #parse it
                            if conditionValue == "gene":
                                if key.startswith("geneList"):  #get gene list
                                    condition[conditionKey] = value
                            elif conditionValue == "pathogen":
                                if key.startswith("pathogen_species"):
                                    pathogenList["species"] = request.GET.getlist(key)
                                if key.startswith("pathogen_kingdom"):
                                    pathogenList["kingdom"] = request.GET.getlist(key)

                            elif conditionValue == "publication":
                                if key.startswith("publication_title"):
                                    pubList["title"] = request.GET.getlist(key)
                                elif key.startswith("publication_journal"):
                                    pubList["journal"] = request.GET.getlist(key)
                                elif key.startswith("publication_year"):
                                    pubList["year"] = request.GET.getlist(key)
                                else:
                                    print ""

                            elif conditionValue == "scope":
                                if key.startswith("scope"):
                                    condition[conditionKey] = request.GET.getlist(key)
                            elif conditionValue == "function":
                                if key.startswith("function"):
                                    condition[conditionKey] = request.GET.getlist(key)
                            else:
                                print "It is impossible"

                if conditionValue == "publication":  #AND phrase
                    condition[conditionKey] = pubList

                if conditionValue == "pathogen":  #AND phrase
                    condition[conditionKey] = pathogenList

            # combine the search condition
            # we can combine the query condition with Q object
            qDict = {}
            for key, value in condition.items():
                if type[key] == "gene":
                    if value.find(",") > 0:
                        geneList_temp = value.split(",")  #use comma ,
                    else:
                        geneList_temp = value.split("\r\n")  #use return
                    geneList = []
                    for i in geneList_temp:
                        geneList.append(i.strip())
                    geneList = list(set(geneList))
                    qDict[key] = Q(drosophilaGene__in=geneList) | Q(humanHomolog__in=geneList) |Q(entrezId__in=geneList) | Q(uniprotId__in=geneList) \

                    #since previous name and synonyms may have multiple, so we use icontains
                    for aa in geneList:
                        qDict[key] = qDict[key] | Q(synonyms__icontains=aa) | Q(previousName__icontains=aa)

                elif type[key] == 'pathogen':
                    speciesList = value["species"]
                    kingdomList = value["kingdom"]

                    if "all" in speciesList:  #all species
                        if "all" in kingdomList:  #check the kingdom
                            qDict[key] = ""
                        else:
                            qDict[key] = Q(kingdom__in=kingdomList)
                    else:  # not all species
                        qDict[key] = Q(species__in=speciesList)

                elif type[key] == 'publication':
                    titleList = value["title"]
                    journalList = value["journal"]
                    yearList = value["year"]
                    q_title = Q(title__in=titleList)
                    q_journal = Q(journal__in=journalList)
                    q_year = Q(year__in=yearList)

                    if "all" in titleList:
                        if "all" in journalList:
                            if "all" in yearList:
                                qDict[key] = ""
                            else:
                                qDict[key] = q_year
                        else:
                            if "all" in yearList:
                                qDict[key] = q_journal
                            else:
                                qDict[key] = q_journal & q_year
                    else:
                        if "all" in journalList:
                            if "all" in yearList:
                                qDict[key] = q_title
                            else:
                                qDict[key] = q_title & q_year
                        else:
                            if "all" in yearList:
                                qDict[key] = q_title & q_journal
                            else:
                                qDict[key] = q_title & q_journal & q_year

                elif type[key] == 'scope':
                    scopeList = value
                    if "all" in scopeList:
                        qDict[key] = ""
                    else:
                        qDict[key] = Q(scope__in=scopeList)

                elif type[key] == 'function':
                    functionList = value
                    if "all" in functionList:
                        qDict[key] = ""
                    else:
                        qDict[key] = Q(phenotype__in=functionList)
                else:
                    print "It is impossible!"

            result = ""
            if conditionNum > 1:
                qTotal = Q()
                comp = request.GET.get("smartComparator")
                #print comp
                containAll = False
                for key, value in qDict.items():
                    if value == "":
                        containAll = True

                if containAll and comp == "or":  # if contains all and smartComparator = OR, we return all list
                    result = allEHFPI.objects.all()
                else:  # condition doesn't contains all or smartComparator = "AND"
                    for key, value in qDict.items():
                        if value:
                            if comp == "and":
                                qTotal = qTotal & value
                            else:
                                qTotal = qTotal | value
                result = allEHFPI.objects.filter(qTotal)
            else:
                for key, value in qDict.items():
                    if value:
                        result = allEHFPI.objects.filter(value)
                    else:
                        result = allEHFPI.objects.all()

            if (len(result)):
                #sort the column
                order = request.GET.get('order_by', 'ehfpiAcc')
                result = result.order_by(order)

                # else:   #only one condition, complicated!!!
            #     for key,value in condition.items():
            #         if type[key]=="gene":
            #             geneList_temp = value.split("\r\n")
            #             geneList = []
            #             for i in geneList_temp:
            #                 geneList.append(i.strip())
            #             geneList = list(set(geneList))
            #             q = Q(geneSymbol__in = geneList) | Q(entrezId__in = geneList) | Q(uniprotId__in = geneList) | Q(previousName__in = geneList) | Q(synonyms__in = geneList)
            #             result = allEHFPI.objects.filter(q)
            #
            #         elif type[key] == 'pathogen':
            #             speciesList = value["species"]
            #             kingdomList = value["kingdom"]
            #
            #             if "all" in speciesList:  #all species
            #                 if "all" in kingdomList:  #check the kingdom
            #                     result = allEHFPI.objects.all()
            #                 else:
            #                     result = allEHFPI.objects.filter(Q(kingdom__in = kingdomList))
            #             else:   # not all species
            #                 result = allEHFPI.objects.filter(Q(species__in = speciesList))
            #
            #         elif type[key] == 'publication':
            #             authorList = value["author"]
            #             journalList = value["journal"]
            #             yearList = value["year"]
            #             q_author = Q(author__in=authorList)
            #             q_journal = Q(journal__in=journalList)
            #             q_year = Q(year__in=yearList)
            #
            #             if "all" in authorList:
            #                 if "all" in journalList:
            #                     if "all" in yearList:
            #                         q = ""
            #                     else:
            #                         q = q_year
            #                 else:
            #                     if "all" in yearList:
            #                         q = q_journal
            #                     else:
            #                         q = q_journal & q_year
            #             else:
            #                 if "all" in journalList:
            #                     if "all" in yearList:
            #                         q = q_author
            #                     else:
            #                         q = q_author & q_year
            #                 else:
            #                     if "all" in yearList:
            #                         q = q_author & q_journal
            #                     else:
            #                         q = q_author & q_journal & q_year
            #
            #             if q:
            #                 result = allEHFPI.objects.filter(q)
            #             else:
            #                 result = allEHFPI.objects.all()
            #
            #         elif type[key] == 'scope':
            #             scopeList = value
            #             if "all" in scopeList:
            #                 result = allEHFPI.objects.all()
            #             else:
            #                 result = allEHFPI.objects.filter(Q(scope__in = scopeList))
            #
            #         elif type[key] == 'function':
            #             functionList = value
            #             if "all" in functionList:
            #                 result = allEHFPI.objects.all()
            #             else:
            #                 result = allEHFPI.objects.filter(Q(phenotype__in=functionList))
            #
            #         else:
            #             print "It is impossible!"
            #custom display columns start!

            columns = []
            for i in range(0, len(field), 1):
                columns.append([field[i], fieldDes[i]])
            #custom display columns end

            #columns to display start!

            displayColumns = request.session['selectedColumns']
            displayColumnsDic = []
            for item in displayColumns:
                displayColumnsDic.append([item, fieldDic[item]])
            #columns to display end

            # 20140418, when add analysis function to advanced search result, to avoid the above complex calculation, we send all
            # ehfpiacc of result as a hidden div in the result page
            idsList = []
            for item in result:
                idsList.append(str(item.ehfpiAcc))
            ids = ','.join(idsList)

            #get publication number and EHF gene number
            publicationNum = len(set(result.values_list('title')))
            geneList = []
            for item in result.values_list('humanHomolog'):
                geneList.append(item[0].strip().upper())
            geneList = list(set(geneList))
            if '' in geneList:
                geneList.remove('')
            ehfNum = len(geneList)
            #end

            return render_to_response('search/advancedSearchResult.html',
                                      {'result': result, 'publicationNum': publicationNum, 'ehfNum': ehfNum,
                                       'columns': columns, 'displayColumnsDic': displayColumnsDic, 'ids': ids},
                                      context_instance=RequestContext(request))

    return render_to_response('search/advancedSearch.html', context_instance=RequestContext(request))

# process the ajax get in addParms functions, it passes {'r': row,'st': searchType}
def ajaxParms(request):
    if request.method == 'GET':
        rowId = request.GET['r']
        searchType = request.GET['st']
        if searchType == "gene":  # gene tab
            return render_to_response('search/ajaxGene.do', {'row': rowId})

        elif searchType == "pathogen":
            kingdom_list = pathogen.objects.order_by('kingdom').distinct().values_list("kingdom")
            species_list = pathogen.objects.order_by('species').distinct().values_list("species")
            kingdom = []
            species = []
            for item in kingdom_list:
                kingdom.append(item[0].strip())
            for item in species_list:
                species.append(item[0].strip())
            return render_to_response('search/ajaxPathogen.do', {'kingdom': kingdom, 'species': species, 'row': rowId})

        elif searchType == "publication":
            title_list = publication.objects.order_by('title').distinct().values_list("title")
            journal_list = publication.objects.order_by('journal').distinct().values_list("journal")
            year_list = publication.objects.order_by('year').distinct().values_list("year")
            title = []
            journal = []
            year = []
            for item in title_list:
                title.append(item[0].strip())
            for item in journal_list:
                journal.append(item[0].strip())
            for item in year_list:
                year.append(item[0])
            return render_to_response('search/ajaxPublication.do',
                                      {'title': title, 'journal': journal, 'year': year, 'row': rowId})

        elif searchType == "scope":
            scope_list = screen.objects.order_by('scope').distinct().values_list("scope")
            scope = []
            for item in scope_list:
                scope.append(item[0].strip())
            return render_to_response('search/ajaxScope.do', {'scope': scope, 'row': rowId})

        elif searchType == "function":
            function_list = screen.objects.order_by('phenotype').distinct().values_list("phenotype")  # ehf function == phenotype ?
            function = []
            for item in function_list:
                function.append(item[0].strip())
            return render_to_response('search/ajaxFunction.do', {'function': function, 'row': rowId})

        else:
            return render_to_response('search/advancedSearch.html')
            #return render_to_response('search/advancedSearch.html')
    else:
        return render_to_response('search/advancedSearch.html')

# this function get the corresponding species select form based on kingdom select form
def getSpecies(request):
    if request.method == 'GET':
        rowId = request.GET['r']
        val = request.GET['stv']
        selectVal = val.split(",")
        species_list = []

        if "all" in selectVal:  #all in the list
            species_list = pathogen.objects.distinct().values_list("species")
        else:
            species_list = pathogen.objects.filter(kingdom__in=selectVal).distinct().values_list("species")

        species = []
        for item in species_list:
            species.append(item[0])

        return render_to_response('search/getSpecies.do', {'row': rowId, 'species': species})

#this is test case
def searchDetail(request, id):
    result = allEHFPI.objects.filter(ehfpiAcc__iexact=id)
    geneSymbol = ''
    for item in result:
        geneSymbol = item.humanHomolog
    dasRes = das.objects.filter(geneSymbol__iexact=geneSymbol)

    return render_to_response('search/searchDetail.html', {'id': id, 'result': result, 'das': dasRes})

#download function for browse, this function can be implemented in download application,
# but we want to remove couple.
def download(request):
    if request.method == 'GET':
        if 'selectcolumn' in request.GET and 'type' in request.GET:
            selectcolumn_temp = request.GET['selectcolumn']
            selectcolumn = selectcolumn_temp.split(',')
            type = request.GET['type']
            selected_temp = request.GET['selected']
            selected = selected_temp.split(',')

            if type == 'allPage':  # a bit complicated

                query = selected[0]
                searchType = selected[1]
                data = getResult(query,searchType).values()

            else:  #type == 'currentPage'
                data = allEHFPI.objects.filter(ehfpiAcc__in=selected).values()

            # code from download app

            response = HttpResponse(content_type="text/csv")
            response.write('\xEF\xBB\xBF')
            response['Content-Disposition'] = 'attachment; filename=ehfpi.csv'
            writer = csv.writer(response)

            # store row title description
            rowTitle = []
            for item in selectcolumn:
                rowTitle.append(fieldDic[item])
            writer.writerow(rowTitle)

            #get data from database
            #data = allEHFPI.objects.values()
            for item in data:
                res = []
                for i in selectcolumn:
                    # if type(item[i]) is types.UnicodeType:
                    #     res.append(item[i].encode('utf-8'))
                    # else:   #long type
                    #     res.append(item[i])
                    res.append(smart_str(item[i]))
                writer.writerow(res)
            return response

    return HttpResponseRedirect(URL_PREFIX)

def downloadAdvanced(request):
    print request
    if request.method == 'POST':
        if 'selectcolumn[]' in request.POST and 'selected[]' in request.POST:
            selectcolumn = request.POST.getlist('selectcolumn[]')
            selected = request.POST.getlist('selected[]')

            data = allEHFPI.objects.filter(ehfpiAcc__in=selected).values()

            # code from download app

            response = HttpResponse(content_type="text/csv")
            response.write('\xEF\xBB\xBF')
            response['Content-Disposition'] = 'attachment; filename=ehfpi.csv'
            writer = csv.writer(response)

            # store row title description
            rowTitle = []
            for item in selectcolumn:
                rowTitle.append(fieldDic[item])
            writer.writerow(rowTitle)

            #get data from database
            #data = allEHFPI.objects.values()
            for item in data:
                res = []
                for i in selectcolumn:
                    # if type(item[i]) is types.UnicodeType:
                    #     res.append(item[i].encode('utf-8'))
                    # else:   #long type
                    #     res.append(item[i])
                    res.append(smart_str(item[i]))
                writer.writerow(res)
            return response

    return HttpResponseRedirect(URL_PREFIX)

#gea analysis in search
def gea(request):
    if request.method == 'GET':
        if request.GET['type']:
            type = request.GET['type']
            selected = request.GET.getlist('selected[]')

            if type == 'allPage':  # a bit complicated
                query = selected[0]
                searchType = selected[1]
                result = getResult(query.strip(), searchType)

            else:  #type == 'currentPage'
                result = allEHFPI.objects.filter(ehfpiAcc__in=selected)

            geneList = []
            for item in result:
                geneList.append(item.humanHomolog)
            geneList = list(set(geneList))
            return render_to_response('analysis/getGeneList.html', {'geneList': ','.join(geneList)})

    return HttpResponseRedirect(URL_PREFIX)

#network analysis in search
#first same as vtp, and in the specified template call ajax
def network(request):
    if request.method == 'GET':
        if 'type' in request.GET and 'selected' in request.GET:
            type = request.GET['type']
            selected = request.GET['selected'].split(',')
            print type,selected

            if type == 'allPage':  # a bit complicated
                query = selected[0]
                searchType = selected[1]
                result = getResult(query.strip(), searchType)

            else:  #type == 'currentPage'
                result = allEHFPI.objects.filter(ehfpiAcc__in=selected)

            geneList = []
            for item in result:
                geneList.append(item.humanHomolog)
            geneList = list(set(geneList))
            return render_to_response('analysis/overlapNetworkOthers.html', {'geneList': ','.join(geneList)},context_instance=RequestContext(request))

    return HttpResponseRedirect(URL_PREFIX)

def networkAdvanced(request):
    if request.method == 'POST':
        if 'selected' in request.POST:
            selected = request.POST['selected']
            selected = selected.split(',')

            result = allEHFPI.objects.filter(ehfpiAcc__in=selected)

            geneList = []
            for item in result:
                geneList.append(item.humanHomolog)
            geneList = list(set(geneList))

            return render_to_response('analysis/overlapNetworkOthers.html', {'geneList': ','.join(geneList)},context_instance=RequestContext(request))

    return HttpResponseRedirect(URL_PREFIX)

#gea analysis in advanced search
def geaAdvanced(request):
    if request.method == 'POST':
        if 'selected[]' in request.POST:
            selected = request.POST.getlist('selected[]')
            result = allEHFPI.objects.filter(ehfpiAcc__in=selected)

            geneList = []
            for item in result:
                geneList.append(item.humanHomolog)
            geneList = list(set(geneList))
            return render_to_response('analysis/getGeneList.html', {'geneList': ','.join(geneList)})

    return HttpResponseRedirect(URL_PREFIX)

#pip analysis in browse
def pip(request):
    if request.method == 'GET':
        if 'type' in request.GET and 'selected' in request.GET:
            type = request.GET['type']
            selected = request.GET['selected'].split(',')

            if type == 'allPage':  # a bit complicated
                query = selected[0]
                searchType = selected[1]
                result = getResult(query.strip(), searchType)

            else:  #type == 'currentPage'
                result = allEHFPI.objects.filter(ehfpiAcc__in=selected)

            geneList = []
            for item in result:
                geneList.append(item.humanHomolog)
            geneList = list(set(geneList))
            if '' in geneList:
                geneList.remove('')

            #get the geneSymbol-VTP model
            result = vtpModel.objects.filter(geneSymbol__in=geneList)
            GeneNumberSubmit = len(geneList)  # number of gene submitted
            GeneNumberIn = GeneNumberSubmit  #number of genes in EHFPI
            interactions = len(result)  #interactions number
            GeneNumberVTP = 0  # number of genes that are also VTP
            vtpList = []
            for item in result:
                if item.geneSymbol not in vtpList:
                    vtpList.append(item.geneSymbol)
                    GeneNumberVTP += 1

            if (len(result)):
                order = request.GET.get('order_by', 'geneSymbol')
                result = result.order_by(order)

            return render_to_response('analysis/getVTPList.html',
                                      {'GeneNumberSubmit': GeneNumberSubmit, 'GeneNumberIn': GeneNumberIn,'interactions':interactions,
                                       'GeneNumberVTP': GeneNumberVTP, 'ids':','.join(vtpList),'result': result},
                                      context_instance=RequestContext(request))

    return HttpResponseRedirect(URL_PREFIX)

#pip analysis in advanced search
def pipAdvanced(request):
    if request.method == 'GET':
        if 'queryType' in request.GET:
            queryType = request.GET['queryType']
            if queryType == 'currentPage':
                selected = request.GET['selected'].split(',')
                result = allEHFPI.objects.filter(ehfpiAcc__in=selected)
            else:
                conditionNum = 0  # search condition number, based on smartSearchSubtype number in POST
                condition = {}  #map to store the condition
                type = {}  #store the search type of each condition
                for key, value in request.GET.iteritems():
                    if key.startswith("smartSearchSubtype"):
                        conditionNum = conditionNum + 1
                        conKey = key[key.rfind("_") + 1:]
                        condition[conKey] = ""  #initialize the map
                        type[conKey] = value

                #parse condition
                for conditionKey, conditionValue in type.items():
                    if conditionValue == "publication":  #AND phrase
                        pubList = {}
                    if conditionValue == "pathogen":  #AND phrase
                        pathogenList = {}

                    for key, value in request.GET.iteritems():
                        if key.find("_") != -1:
                            if key[key.rfind("_") + 1:] == conditionKey:  #parse it
                                if conditionValue == "gene":
                                    if key.startswith("geneList"):  #get gene list
                                        condition[conditionKey] = value
                                elif conditionValue == "pathogen":
                                    if key.startswith("pathogen_species"):
                                        pathogenList["species"] = request.GET.getlist(key)
                                    if key.startswith("pathogen_kingdom"):
                                        pathogenList["kingdom"] = request.GET.getlist(key)

                                elif conditionValue == "publication":
                                    if key.startswith("publication_title"):
                                        pubList["title"] = request.GET.getlist(key)
                                    elif key.startswith("publication_journal"):
                                        pubList["journal"] = request.GET.getlist(key)
                                    elif key.startswith("publication_year"):
                                        pubList["year"] = request.GET.getlist(key)
                                    else:
                                        print ""

                                elif conditionValue == "scope":
                                    if key.startswith("scope"):
                                        condition[conditionKey] = request.GET.getlist(key)
                                elif conditionValue == "function":
                                    if key.startswith("function"):
                                        condition[conditionKey] = request.GET.getlist(key)
                                else:
                                    print "It is impossible"

                    if conditionValue == "publication":  #AND phrase
                        condition[conditionKey] = pubList

                    if conditionValue == "pathogen":  #AND phrase
                        condition[conditionKey] = pathogenList

                # combine the search condition
                # we can combine the query condition with Q object
                qDict = {}
                for key, value in condition.items():
                    if type[key] == "gene":
                        if value.find(",") > 0:
                            geneList_temp = value.split(",")  #use comma ,
                        else:
                            geneList_temp = value.split("\r\n")  #use return
                        geneList = []
                        for i in geneList_temp:
                            geneList.append(i.strip())
                        geneList = list(set(geneList))
                        qDict[key] = Q(drosophilaGene__in=geneList) | Q(humanHomolog__in=geneList) |Q(entrezId__in=geneList) | Q(uniprotId__in=geneList) \

                        #since previous name and synonyms may have multiple, so we use icontains
                        for aa in geneList:
                            qDict[key] = qDict[key] | Q(synonyms__icontains=aa) | Q(previousName__icontains=aa)

                    elif type[key] == 'pathogen':
                        speciesList = value["species"]
                        kingdomList = value["kingdom"]

                        if "all" in speciesList:  #all species
                            if "all" in kingdomList:  #check the kingdom
                                qDict[key] = ""
                            else:
                                qDict[key] = Q(kingdom__in=kingdomList)
                        else:  # not all species
                            qDict[key] = Q(species__in=speciesList)

                    elif type[key] == 'publication':
                        titleList = value["title"]
                        journalList = value["journal"]
                        yearList = value["year"]
                        q_title = Q(title__in=titleList)
                        q_journal = Q(journal__in=journalList)
                        q_year = Q(year__in=yearList)

                        if "all" in titleList:
                            if "all" in journalList:
                                if "all" in yearList:
                                    qDict[key] = ""
                                else:
                                    qDict[key] = q_year
                            else:
                                if "all" in yearList:
                                    qDict[key] = q_journal
                                else:
                                    qDict[key] = q_journal & q_year
                        else:
                            if "all" in journalList:
                                if "all" in yearList:
                                    qDict[key] = q_title
                                else:
                                    qDict[key] = q_title & q_year
                            else:
                                if "all" in yearList:
                                    qDict[key] = q_title & q_journal
                                else:
                                    qDict[key] = q_title & q_journal & q_year

                    elif type[key] == 'scope':
                        scopeList = value
                        if "all" in scopeList:
                            qDict[key] = ""
                        else:
                            qDict[key] = Q(scope__in=scopeList)

                    elif type[key] == 'function':
                        functionList = value
                        if "all" in functionList:
                            qDict[key] = ""
                        else:
                            qDict[key] = Q(phenotype__in=functionList)
                    else:
                        print "It is impossible!"

                result = ""
                if conditionNum > 1:
                    qTotal = Q()
                    comp = request.GET.get("smartComparator")
                    #print comp
                    containAll = False
                    for key, value in qDict.items():
                        if value == "":
                            containAll = True

                    if containAll and comp == "or":  # if contains all and smartComparator = OR, we return all list
                        result = allEHFPI.objects.all()
                    else:  # condition doesn't contains all or smartComparator = "AND"
                        for key, value in qDict.items():
                            if value:
                                if comp == "and":
                                    qTotal = qTotal & value
                                else:
                                    qTotal = qTotal | value
                    result = allEHFPI.objects.filter(qTotal)
                else:
                    for key, value in qDict.items():
                        if value:
                            result = allEHFPI.objects.filter(value)
                        else:
                            result = allEHFPI.objects.all()

            geneList = []
            for item in result:
                geneList.append(item.humanHomolog)
            geneList = list(set(geneList))
            if '' in geneList:
                geneList.remove('')

            #get the geneSymbol-VTP model
            result = vtpModel.objects.filter(geneSymbol__in=geneList)
            GeneNumberSubmit = len(geneList)  # number of gene submitted
            GeneNumberIn = GeneNumberSubmit  #number of genes in EHFPI
            interactions = len(result)  #interactions number
            GeneNumberVTP = 0  # number of genes that are also VTP
            vtpList = []
            for item in result:
                if item.geneSymbol not in vtpList:
                    vtpList.append(item.geneSymbol)
                    GeneNumberVTP += 1

            if (len(result)):
                order = request.GET.get('order_by', 'geneSymbol')
                result = result.order_by(order)

            return render_to_response('analysis/getVTPList.html',
                                      {'GeneNumberSubmit': GeneNumberSubmit, 'GeneNumberIn': GeneNumberIn,'interactions':interactions,
                                       'GeneNumberVTP': GeneNumberVTP, 'ids':','.join(vtpList),'result': result},
                                      context_instance=RequestContext(request))

    return HttpResponseRedirect(URL_PREFIX)

#pip analysis in heatmap search
def pipHeatmap(request):
    if request.method == 'GET':
        if 'queryType' in request.GET:
            queryType = request.GET['queryType']
            if queryType == 'currentPage':
                selected = request.GET['selected'].split(',')
                result = allEHFPI.objects.filter(ehfpiAcc__in=selected)
            else:
                a = request.GET['a']
                b = request.GET['b']
                type = request.GET['type']
                searchList = []
                searchList.append(a)
                searchList.append(b)
                searchList = list(set(searchList))
                searchName = []

                if type == 'article':  #for article, species_taxonomy, pubmed id
                    speciesList = []
                    articleList = []
                    for item in searchList:
                        speciesTemp = item[0:item.find('_')]
                        articleTemp = item[item.find('_')+1:]
                        if speciesTemp not in speciesList:
                            speciesList.append(speciesTemp)
                        if articleTemp not in articleList:
                            articleList.append(articleTemp)

                elif type == 'group':
                    idMap = idNameMap.objects.filter(acc__in=searchList)
                    for item in idMap:
                        if item.acc in searchList:
                            searchName.append(item.name)
                else:
                    searchName = searchList

                res = heatmapModel.objects.filter((Q(a=a) & Q(b=b)) | (Q(a=b) & Q(b=a)))
                geneList_temp = ''
                for item in res:
                    geneList_temp = smart_unicode(item.commonGeneList)
                geneList = geneList_temp.split(';')

                result = ''
                if type == 'kingdom':
                    result = allEHFPI.objects.filter(kingdomTaxonomy__in=searchName, humanHomolog__in=geneList)
                    # print result
                elif type == 'group':
                    result = allEHFPI.objects.filter(group__in=searchName, humanHomolog__in=geneList)
                elif type == 'family':
                    result = allEHFPI.objects.filter(familyTaxonomy__in=searchName, humanHomolog__in=geneList)
                elif type == 'genus':
                    result = allEHFPI.objects.filter(genusTaxonomy__in=searchName, humanHomolog__in=geneList)
                elif type == 'species':
                    result = allEHFPI.objects.filter(speciesTaxonomy__in=searchName, humanHomolog__in=geneList)
                elif type == 'article':
                    result = allEHFPI.objects.filter(speciesTaxonomy__in=speciesList, pubmedId__in=articleList, humanHomolog__in=geneList)
                    #print result
                else:
                    result = ''

            geneList = []
            for item in result:
                geneList.append(item.humanHomolog)
            geneList = list(set(geneList))
            if '' in geneList:
                geneList.remove('')

            #get the geneSymbol-VTP model
            result = vtpModel.objects.filter(geneSymbol__in=geneList)
            GeneNumberSubmit = len(geneList)  # number of gene submitted
            GeneNumberIn = GeneNumberSubmit  #number of genes in EHFPI
            interactions = len(result)  #interactions number
            GeneNumberVTP = 0  # number of genes that are also VTP
            vtpList = []
            for item in result:
                if item.geneSymbol not in vtpList:
                    vtpList.append(item.geneSymbol)
                    GeneNumberVTP += 1

            if (len(result)):
                order = request.GET.get('order_by', 'geneSymbol')
                result = result.order_by(order)

            return render_to_response('analysis/getVTPList.html',
                                      {'GeneNumberSubmit': GeneNumberSubmit, 'GeneNumberIn': GeneNumberIn,'interactions':interactions,
                                       'GeneNumberVTP': GeneNumberVTP, 'ids':','.join(vtpList),'result': result},
                                      context_instance=RequestContext(request))

    return HttpResponseRedirect(URL_PREFIX)

#pip analysis in preview search
def pipPreview(request):
    if request.method == 'GET':
        if 'queryType' in request.GET:
            queryType = request.GET['queryType']
            if queryType == 'currentPage':
                selected = request.GET['selected'].split(',')
                result = allEHFPI.objects.filter(ehfpiAcc__in=selected)
            else:
                pubmedId = request.GET['pubmedId']
                if 'species' in request.GET:
                    speciesTaxonomy = request.GET['species']
                    result = allEHFPI.objects.filter(pubmedId=pubmedId,speciesTaxonomy=speciesTaxonomy)

                if 'strain' in request.GET:
                    strain= request.GET['strain']
                    result = allEHFPI.objects.filter(pubmedId=pubmedId,strain=strain)

            geneList = []
            for item in result:
                geneList.append(item.humanHomolog)
            geneList = list(set(geneList))
            if '' in geneList:
                geneList.remove('')

            #get the geneSymbol-VTP model
            result = vtpModel.objects.filter(geneSymbol__in=geneList)
            GeneNumberSubmit = len(geneList)  # number of gene submitted
            GeneNumberIn = GeneNumberSubmit  #number of genes in EHFPI
            interactions = len(result)  #interactions number
            GeneNumberVTP = 0  # number of genes that are also VTP
            vtpList = []
            for item in result:
                if item.geneSymbol not in vtpList:
                    vtpList.append(item.geneSymbol)
                    GeneNumberVTP += 1

            if (len(result)):
                order = request.GET.get('order_by', 'geneSymbol')
                result = result.order_by(order)

            return render_to_response('analysis/getVTPList.html',
                                      {'GeneNumberSubmit': GeneNumberSubmit, 'GeneNumberIn': GeneNumberIn,'interactions':interactions,
                                       'GeneNumberVTP': GeneNumberVTP, 'ids':','.join(vtpList),'result': result},
                                      context_instance=RequestContext(request))

    return HttpResponseRedirect(URL_PREFIX)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Collejo\Foundation\Testing;

use Collejo\Foundation\Database\Eloquent\LoadFactories;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Laravel\Dusk\TestCase as BaseTestCase;

abstract class DuskTestCase extends BaseTestCase
{
    use CreatesApplication, DatabaseMigrations, LoadFactories, DatabaseTransactions;

    /**
     * Prepare for Dusk test execution.
     *
     * @beforeClass
     *
     * @return void
     */
    public static function prepare()
    {
        static::startChromeDriver();
    }

    /**
     * Create the RemoteWebDriver instance.
     *
     * @return \Facebook\WebDriver\Remote\RemoteWebDriver
     */
    protected function driver()
    {
        $options = (new ChromeOptions())->addArguments([
            '--disable-gpu',
            '--headless',
        ]);

        return RemoteWebDriver::create(
            'http://localhost:9515', DesiredCapabilities::chrome()->setCapability(
                ChromeOptions::CAPABILITY, $options
            )
        );
    }

    /**
     * Setup.
     */
    public function setup()
    {
        parent::setup();

        $this->loadFactories();

        $this->runDatabaseMigrations();
    }
}


text:
layout: post
status: publish
published: true
title: Must Be A Slow Music News Day
author:
  display_name: Trott
  login: admin
  email: rtrott@gmail.com
  url: http://musicroutes.com/
author_login: admin
author_email: rtrott@gmail.com
author_url: http://musicroutes.com/
wordpress_id: 169
wordpress_url: http://blog.musicroutes.com/?p=169
date: '2008-11-08 21:26:04 -0800'
date_gmt: '2008-11-09 04:26:04 -0800'
tags:
- sia furler
- christina aguilera
- rolling stones
- zero 7
comments: []
---

Must have been a slow music news day.  Billboard reported that Christina Aguilera's next record may have electro elements. They particularly cited the involvement of Sia Furler.

How much of a stretch is this, really?  Well, one crude, inaccurate, but fun measurement is the distance from Aguilera to Furler in a Six Degrees Of Kevin Bacon sort of route.

I especially like that the particular route starts with two versions of "Live With Me" by The Rolling Stones.  (Or at least it did as of this writing.)

As always, if you know how to make the route shorter, get in touch.

If your suggestion removes "Live With Me" from the route, I will only be slightly saddened, and mostly grateful.


text:
export {
  Page,
  PageProps,
  PageHeader,
  PageHeaderProps,
  PageSidebar,
  PageSidebarProps,
  PageSectionVariants,
} from '@patternfly/react-core';
export * from './PageSection';
export { default as PageSection } from './PageSection';


text:
export interface IInputResourceStrings {
    igx_input_upload_button?: string;
    igx_input_clear_button?: string;
    igx_input_file_placeholder?: string;
}

export const InputResourceStringsEN: IInputResourceStrings = {
    igx_input_upload_button: 'Upload File',
    igx_input_clear_button: 'clear',
    igx_input_file_placeholder: 'No file chosen',
};


text:
function [skel, expmapchannels] = bvh2expmap(skel,eulerchannels)

% This is a function for converting from Euler BVH data to exponential maps
% It assumes that Neil Lawrence's MOCAP toolbox has been used to create a
% skeleton structure "skel" and matrix of channels "eulerchannels".
% This function proceeds through the skeleton, replacing the Euler angles
% for rotational dimensions with the expmap dof
%
% Usage: [skel, expmapchannels] = bvh2expmap(skel,eulerchannels)

for ii=1:length(skel.tree)
  if ~isempty(skel.tree(ii).posInd)
    %don't touch translational dimensions
    expmapchannels(skel.tree(ii).posInd) = eulerchannels(skel.tree(ii).posInd);
  end

  if ~isempty(skel.tree(ii).rotInd)
    xangle = deg2rad(eulerchannels(skel.tree(ii).rotInd(1)));
    yangle = deg2rad(eulerchannels(skel.tree(ii).rotInd(2)));
    zangle = deg2rad(eulerchannels(skel.tree(ii).rotInd(3)));

    %3x3 Rotation Matrix
    thisRotation = rotationMatrix(xangle, yangle, zangle, skel.tree(ii).order);

    r = rotmat2expmap(thisRotation);

    %Conversion to Exponential Map
    %Overwriting roational channels
    expmapchannels(:,skel.tree(ii).rotInd) = r;

  end
end


text:
import Subscriber from './Subscriber';
import Observer from './Observer';
import OuterSubscriber from './OuterSubscriber';
import tryCatch from './util/tryCatch';
import { errorObject } from './util/errorObject';

export default class InnerSubscriber<T, R> extends Subscriber<R> {
  index: number = 0;

  constructor(private parent: OuterSubscriber<T, R>, private outerValue: T, private outerIndex: number) {
    super();
  }

  _next(value: R) {
    const index = this.index++;
    this.parent.notifyNext(this.outerValue, value, this.outerIndex, index);
  }

  _error(error: any) {
    this.parent.notifyError(error, this);
  }

  _complete() {
    this.parent.notifyComplete(this);
  }
}


text:
// coding: utf-8

// ----------------------------------------------------------------------------

#ifndef XPCC_HOSTED_CAN_USB_HPP
#define XPCC_HOSTED_CAN_USB_HPP

#include <queue>
#include <string>

// FIXME: remove this dependency!
#include "../../uart/hosted/serial_interface.hpp"
#include <xpcc/architecture/interface/can.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>

namespace xpcc
{

namespace hosted
{

/**
 * Driver for a CAN232 or CANUSB adapter
 *
 * @see		http://www.canusb.com/
 * @see		http://www.can232.com/
 * @ingroup	hosted
 */
class CanUsb : public ::xpcc::Can
{
public:
	CanUsb();

	~CanUsb();

	bool
	open(std::string deviceName, unsigned int serialBaudRate, xpcc::Can::Bitrate canBitrate = xpcc::Can::kBps125);

	void
	close();

	inline bool
	isMessageAvailable()
	{
		return (!this->readBuffer.empty());
	}

	bool
	getMessage(can::Message& message);

	inline bool
	isReadyToSend()
	{
		// TODO
		return true;
	}

	BusState
	getBusState();

	/*
	 * Send a message over the CAN.
	 *
	 * @return `true` if the message was send, `false` otherwise
	 */
	bool
	sendMessage(const can::Message& message);

	bool
	isOpen()
	{
		return this->serialPort.isOpen();
	}

private:
	// updated by boost thread
	void
	update();

private:
	typedef boost::mutex				Mutex;
	typedef boost::mutex::scoped_lock	MutexGuard;

	Mutex stateLock;
	Mutex readBufferLock;
	bool active;

	BusState busState;

	xpcc::hosted::SerialInterface serialPort;

	std::string tmpRead;
	std::queue<can::Message> readBuffer;

	boost::thread* thread;
};

}	// namespace hosted

}	// namespace xpcc

#endif // XPCC_HOSTED_CAN_USB_HPP


text:
"""
Cell Scheduler weights
"""

from jacket.compute import weights

class WeightedCell(weights.WeighedObject):
    def __repr__(self):
        return "WeightedCell [cell: %s, weight: %s]" % (
                self.obj.name, self.weight)

class BaseCellWeigher(weights.BaseWeigher):
    """Base class for cell weights."""
    pass

class CellWeightHandler(weights.BaseWeightHandler):
    object_class = WeightedCell

    def __init__(self):
        super(CellWeightHandler, self).__init__(BaseCellWeigher)

def all_weighers():
    """Return a list of weight plugin classes found in this directory."""
    return CellWeightHandler().get_all_classes()


text:
import tensorflow as tf
# from mlperf_compliance import mlperf_log
# from mlperf_compliance import resnet_log_helper
# from configs.res50.res50_config import res50_config

_BATCH_NORM_EPSILON = 1e-4
_BATCH_NORM_DECAY = 0.9

ML_PERF_LOG=False

class LayerBuilder(object):
    def __init__(self, activation=None, data_format='channels_last',
                 training=False, use_batch_norm=False, batch_norm_config=None,
                 conv_initializer=None, bn_init_mode='adv_bn_init', bn_gamma_initial_value=1.0 ):
        self.activation = activation
        self.data_format = data_format
        self.training = training
        self.use_batch_norm = use_batch_norm
        self.batch_norm_config = batch_norm_config
        self.conv_initializer = conv_initializer
        self.bn_init_mode = bn_init_mode
        self.bn_gamma_initial_value = bn_gamma_initial_value
        if self.batch_norm_config is None:
            self.batch_norm_config = {
                'decay': _BATCH_NORM_DECAY,
                'epsilon': _BATCH_NORM_EPSILON,
                'scale': True,
                'zero_debias_moving_mean': False,
            }

    def _conv2d(self, inputs, activation, *args, **kwargs):
        x = tf.layers.conv2d(
            inputs, data_format=self.data_format,
            use_bias=not self.use_batch_norm,
            kernel_initializer=self.conv_initializer,
            activation=None if self.use_batch_norm else activation,
            *args, **kwargs)
        if self.use_batch_norm:
            param_initializers = {
                'moving_mean': tf.zeros_initializer(),
                'moving_variance': tf.ones_initializer(),
                'beta': tf.zeros_initializer(),
            }
            if self.bn_init_mode == 'adv_bn_init':
                param_initializers['gamma'] = tf.ones_initializer()
            elif self.bn_init_mode == 'conv_bn_init':
                param_initializers['gamma'] = tf.constant_initializer(self.bn_gamma_initial_value)
            else:
                raise ValueError("--bn_init_mode must be 'conv_bn_init' or 'adv_bn_init' ")

            x = self.batch_norm(x)
            x = activation(x) if activation is not None else x
        return x

    def conv2d_linear_last_bn(self, inputs, *args, **kwargs):
        x = tf.layers.conv2d(
            inputs, data_format=self.data_format,
            use_bias=False,
            kernel_initializer=self.conv_initializer,
            activation=None, *args, **kwargs)
        param_initializers = {
            'moving_mean': tf.zeros_initializer(),
            'moving_variance': tf.ones_initializer(),
            'beta': tf.zeros_initializer(),
        }
        if self.bn_init_mode == 'adv_bn_init':
            param_initializers['gamma'] = tf.zeros_initializer()
        elif self.bn_init_mode == 'conv_bn_init':
            param_initializers['gamma'] = tf.constant_initializer(self.bn_gamma_initial_value)
        else:
            raise ValueError("--bn_init_mode must be 'conv_bn_init' or 'adv_bn_init' ")

        x = self.batch_norm(x, param_initializers=param_initializers)
        return x

    def conv2d_linear(self, inputs, *args, **kwargs):
        return self._conv2d(inputs, None, *args, **kwargs)

    def conv2d(self, inputs, *args, **kwargs):
        return self._conv2d(inputs, self.activation, *args, **kwargs)

    def pad2d(self, inputs, begin, end=None):
        if end is None:
            end = begin
        try:
            _ = begin[1]
        except TypeError:
            begin = [begin, begin]
        try:
            _ = end[1]
        except TypeError:
            end = [end, end]
        if self.data_format == 'channels_last':
            padding = [[0, 0], [begin[0], end[0]], [begin[1], end[1]], [0, 0]]
        else:
            padding = [[0, 0], [0, 0], [begin[0], end[0]], [begin[1], end[1]]]
        return tf.pad(inputs, padding)

    def max_pooling2d(self, inputs, *args, **kwargs):
        return tf.layers.max_pooling2d(
            inputs, data_format=self.data_format, *args, **kwargs)

    def average_pooling2d(self, inputs, *args, **kwargs):
        return tf.layers.average_pooling2d(
            inputs, data_format=self.data_format, *args, **kwargs)

    def dense_linear(self, inputs, units, **kwargs):
        return tf.layers.dense(inputs, units, activation=None)

    def dense(self, inputs, units, **kwargs):
        return tf.layers.dense(inputs, units, activation=self.activation)

    def activate(self, inputs, activation=None):
        activation = activation or self.activation
        return activation(inputs) if activation is not None else inputs

    def batch_norm(self, inputs, **kwargs):
        all_kwargs = dict(self.batch_norm_config)
        all_kwargs.update(kwargs)
        data_format = 'NHWC' if self.data_format == 'channels_last' else 'NCHW'
        bn_inputs = inputs
        outputs = tf.contrib.layers.batch_norm(
            inputs, is_training=self.training, data_format=data_format,
            fused=True, **all_kwargs)

        if ML_PERF_LOG:
            resnet_log_helper.log_batch_norm(
                input_tensor=bn_inputs, output_tensor=outputs, momentum=_BATCH_NORM_DECAY,
                epsilon=_BATCH_NORM_EPSILON, center=True, scale=True, training=self.training)
        return outputs

    def spatial_average2d(self, inputs):
        shape = inputs.get_shape().as_list()
        if self.data_format == 'channels_last':
            n, h, w, c = shape
        else:
            n, c, h, w = shape
        n = -1 if n is None else n
        x = tf.layers.average_pooling2d(inputs, (h, w), (1, 1),
                                        data_format=self.data_format)
        return tf.reshape(x, [n, c])

    def flatten2d(self, inputs):
        x = inputs
        if self.data_format != 'channels_last':
            # Note: This ensures the output order matches that of NHWC networks
            x = tf.transpose(x, [0, 2, 3, 1])
        input_shape = x.get_shape().as_list()
        num_inputs = 1
        for dim in input_shape[1:]:
            num_inputs *= dim
        return tf.reshape(x, [-1, num_inputs], name='flatten')

    def residual2d(self, inputs, network, units=None, scale=1.0, activate=False):
        outputs = network(inputs)
        c_axis = -1 if self.data_format == 'channels_last' else 1
        h_axis = 1 if self.data_format == 'channels_last' else 2
        w_axis = h_axis + 1
        ishape, oshape = [y.get_shape().as_list() for y in [inputs, outputs]]
        ichans, ochans = ishape[c_axis], oshape[c_axis]
        strides = ((ishape[h_axis] - 1) // oshape[h_axis] + 1,
                   (ishape[w_axis] - 1) // oshape[w_axis] + 1)
        with tf.name_scope('residual'):
            if (ochans != ichans or strides[0] != 1 or strides[1] != 1):
                inputs = self.conv2d_linear(inputs, units, 1, strides, 'SAME')
            x = inputs + scale * outputs
            if activate:
                x = self.activate(x)
        return x

def resnet_bottleneck_v1(builder, inputs, depth, depth_bottleneck, stride, filters,
                         basic=False):
    num_inputs = inputs.get_shape().as_list()[3]
    x = inputs
    with tf.name_scope('resnet_v1'):
        if ML_PERF_LOG:
            resnet_log_helper.log_begin_block(input_tensor=x, block_type=mlperf_log.BOTTLENECK_BLOCK)
        if depth == num_inputs:
            if stride == 1:#v1.5
                shortcut = x
            else:#v1
                shortcut = builder.max_pooling2d(x, 1, stride)
        else:
            shortcut = builder.conv2d_linear(x, depth, 1, stride, 'SAME')
            conv_input = x
            if ML_PERF_LOG:
                resnet_log_helper.log_conv2d(
            	input_tensor=conv_input, output_tensor=shortcut, stride=stride,
            	filters=filters*4, initializer=mlperf_log.TRUNCATED_NORMAL, use_bias=False)
                resnet_log_helper.log_projection(input_tensor=conv_input, output_tensor=shortcut)
        if basic:
            x = builder.pad2d(x, 1)
            x = builder.conv2d(x, depth_bottleneck, 3, stride, 'VALID')
            x = builder.conv2d_linear(x, depth, 3, 1, 'SAME')
        else:
            conv_input = x
            x = builder.conv2d(x, depth_bottleneck, 1, 1, 'SAME')
            if ML_PERF_LOG:
                resnet_log_helper.log_conv2d(
                    input_tensor=conv_input, output_tensor=x, stride=1,
                    filters=filters, initializer=mlperf_log.TRUNCATED_NORMAL, use_bias=False)
                mlperf_log.resnet_print(key=mlperf_log.MODEL_HP_RELU)
            conv_input = x
            x = builder.conv2d(x, depth_bottleneck, 3, stride, 'SAME')

            if ML_PERF_LOG:
                resnet_log_helper.log_conv2d(
                    input_tensor=conv_input, output_tensor=x, stride=stride,
                    filters=filters, initializer=mlperf_log.TRUNCATED_NORMAL, use_bias=False)
                mlperf_log.resnet_print(key=mlperf_log.MODEL_HP_RELU)
            # x = builder.conv2d_linear(x, depth,            1, 1,      'SAME')
            conv_input = x
            x = builder.conv2d_linear_last_bn(x, depth, 1, 1, 'SAME')
            if ML_PERF_LOG:
                resnet_log_helper.log_conv2d(
                    input_tensor=conv_input, output_tensor=x, stride=1,
                    filters=filters*4, initializer=mlperf_log.TRUNCATED_NORMAL, use_bias=False)
                mlperf_log.resnet_print(key=mlperf_log.MODEL_HP_RELU)
                mlperf_log.resnet_print(key=mlperf_log.MODEL_HP_SHORTCUT_ADD)
                mlperf_log.resnet_print(key=mlperf_log.MODEL_HP_RELU)
        x = tf.nn.relu(x + shortcut)
        if ML_PERF_LOG:
            resnet_log_helper.log_end_block(output_tensor=x)
        return x

def inference_resnet_v1_impl(builder, inputs, layer_counts, arch_type='C1+D', resnet_version='v1.5', basic=False):
    x = inputs
    x = builder.conv2d(x, 64, 7, 2, 'SAME')
    num_filters=64

    x, argmax = tf.nn.max_pool_with_argmax( input=x, ksize=(1,3,3,1), strides=(1,2,2,1), padding='SAME' )
    for i in range(layer_counts[0]):
        x = resnet_bottleneck_v1(builder, x, 256, 64, 1, num_filters, basic)
    for i in range(layer_counts[1]):
        num_filters=num_filters*2
        x = resnet_bottleneck_v1(builder, x, 512, 128, 2 if i == 0 else 1, num_filters, basic)
    for i in range(layer_counts[2]):
        num_filters=num_filters*2
        x = resnet_bottleneck_v1(builder, x, 1024, 256, 2 if i == 0 else 1, num_filters, basic)
    for i in range(layer_counts[3]):
        num_filters=num_filters*2
        x = resnet_bottleneck_v1(builder, x, 2048, 512, 2 if i == 0 else 1, num_filters, basic)

   # x = builder.spatial_average2d(x)

    # same function as spatial average
    axis = [1,2]
    x = tf.reduce_mean( x, axis, keepdims=True )
    x = tf.reshape(x, [-1,2048])

    logits = tf.layers.dense(x, 1001,
                            kernel_initializer=tf.random_normal_initializer(stddev=0.01, seed=1))
    return logits

def inference_resnet_v1(config, inputs, nlayer, data_format='channels_last',
                        training=False, conv_initializer=None, bn_init_mode='adv_bn_init', bn_gamma_initial_value=1.0 ):

    """Deep Residual Networks family of models
    https://arxiv.org/abs/1512.03385
    """
    if ML_PERF_LOG:
        mlperf_log.resnet_print(key=mlperf_log.MODEL_HP_INITIAL_SHAPE,
                            value=inputs.shape.as_list()[1:])

    builder = LayerBuilder(tf.nn.relu, data_format, training, use_batch_norm=True,
                           conv_initializer=conv_initializer, bn_init_mode=bn_init_mode, bn_gamma_initial_value=bn_gamma_initial_value)
    if nlayer == 18:
        return inference_resnet_v1_impl(builder, inputs, [2, 2, 2, 2], basic=True)
    elif nlayer == 34:
        return inference_resnet_v1_impl(builder, inputs, [3, 4, 6, 3], basic=True)
    elif nlayer == 50:
        return inference_resnet_v1_impl(builder, inputs, [3, 4, 6, 3])
    elif nlayer == 101:
        return inference_resnet_v1_impl(builder, inputs, [3, 4, 23, 3])
    elif nlayer == 152:
        return inference_resnet_v1_impl(builder, inputs, [3, 8, 36, 3])
    else:
        raise ValueError("Invalid nlayer (%i); must be one of: 18,34,50,101,152" %
                         nlayer)


text:
require 'quickeebooks'
require 'quickeebooks/windows/model/id'
require 'quickeebooks/windows/model/external_key'
require 'quickeebooks/windows/model/custom_field'
require 'quickeebooks/windows/model/meta_data'

module Quickeebooks
  module Windows
    module Model
      class SalesTax < Quickeebooks::Windows::Model::IntuitType

        XML_COLLECTION_NODE = 'SalesTaxes'
        XML_NODE = 'SalesTax'

        # https://services.intuit.com/sb/salestax/v2/<realmID>
        REST_RESOURCE = "salestax"

        xml_convention :camelcase
        xml_accessor :id, :as => Quickeebooks::Windows::Model::Id
        xml_accessor :sync_token
        xml_accessor :meta_data, :from => 'MetaData', :as => Quickeebooks::Windows::Model::MetaData
        xml_accessor :external_key, :as => Quickeebooks::Windows::Model::ExternalKey
        xml_accessor :synchronized
        xml_accessor :custom_fields, :as => [Quickeebooks::Windows::Model::CustomField]
        xml_accessor :name
        xml_accessor :desc
        xml_accessor :tax_rate, :as => Float

      end
    end
  end
end


text:
============
Runners
============

Module: ``polygraphy.backend.onnxrt``

.. automodule:: polygraphy.backend.onnxrt.runner
    :inherited-members:


text:
package org.hisp.dhis.category;

import org.hisp.dhis.common.IdentifiableObjectStore;

import java.util.List;

/**
 * @author Lars Helge Overland
 */
public interface CategoryOptionStore
    extends IdentifiableObjectStore<CategoryOption>
{
    List<CategoryOption> getCategoryOptions( Category category );
}


text:
'use strict';

const twilioRespond = require('./twilioRespond');

const VERIFY = process.env.PASSWORD;

module.exports = function(req, res, next) {
  let textBody = req.query.Body;
  textBody = textBody.split(' ');
  if (textBody[0] !== 'Verification') {
    req.userRole = 'basic';
    return next();
  }
  const verificationToken = textBody[1];
  if (verificationToken !== VERIFY) {
    return twilioRespond('authorization failed', res);
  }
  req.userRole = 'admin';
  req.query.Body = textBody.slice(2).join(' ');
  next();
};


text:
package org.redisson.mapreduce;

import org.redisson.api.RLexSortedSet;
import org.redisson.api.RList;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RSet;
import org.redisson.api.RSetCache;
import org.redisson.api.RSortedSet;
import org.redisson.api.mapreduce.RCollectionMapper;
import org.redisson.api.mapreduce.RCollector;
import org.redisson.client.codec.Codec;
import org.redisson.misc.Injector;

/**
 *
 * @author Nikita Koksharov
 *
 * @param <VIn> input value type
 * @param <KOut> output key type
 * @param <VOut> output value type
 */
public class CollectionMapperTask<VIn, KOut, VOut> extends BaseMapperTask<KOut, VOut> {

    private static final long serialVersionUID = -2634049426877164580L;

    RCollectionMapper<VIn, KOut, VOut> mapper;

    public CollectionMapperTask() {
    }

    public CollectionMapperTask(RCollectionMapper<VIn, KOut, VOut> mapper, Class<?> objectClass, Class<?> objectCodecClass) {
        super(objectClass, objectCodecClass);
        this.mapper = mapper;
    }

    @Override
    public void run()  {
        Codec codec;
        try {
            codec = (Codec) objectCodecClass.getConstructor().newInstance();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }

        Injector.inject(mapper, redisson);

        for (String objectName : objectNames) {
            Iterable<VIn> collection = null;
            if (RSetCache.class.isAssignableFrom(objectClass)) {
                collection = redisson.getSetCache(objectName, codec);
            } else if (RSet.class.isAssignableFrom(objectClass)) {
                collection = redisson.getSet(objectName, codec);
            } else if (RSortedSet.class.isAssignableFrom(objectClass)) {
                collection = redisson.getSortedSet(objectName, codec);
            } else if (RScoredSortedSet.class.isAssignableFrom(objectClass)) {
                collection = redisson.getScoredSortedSet(objectName, codec);
            } else if (RLexSortedSet.class.isAssignableFrom(objectClass)) {
                collection = (Iterable<VIn>) redisson.getLexSortedSet(objectName);
            } else if (RList.class.isAssignableFrom(objectClass)) {
                collection = redisson.getList(objectName, codec);
            } else {
                throw new IllegalStateException("Unable to work with " + objectClass);
            }

            RCollector<KOut, VOut> collector = new Collector<KOut, VOut>(codec, redisson, collectorMapName, workersAmount, timeout);

            for (VIn value : collection) {
                if (Thread.currentThread().isInterrupted()) {
                    return;
                }

                mapper.map(value, collector);
            }
        }
    }

}


text:
/**
 *
 */
package com.stuartwarren.logit.logstash.v1;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.stuartwarren.logit.layout.ILayout;
import com.stuartwarren.logit.layout.LayoutFactory;
import com.stuartwarren.logit.layout.Log;

/**
 * @author Stuart Warren
 * @date 6 Oct 2013
 *
 */
public final class LogstashV1Layout extends LayoutFactory implements ILayout {

    private final static String LOGSTASH_VERSION = "1";

    private ObjectMapper objectMapper = new ObjectMapper();

    /* (non-Javadoc)
     * @see com.stuartwarren.logit.layout.ILayout#configure()
     */
    @Override
    public void configure() {
        // empty
    }

    /* (non-Javadoc)
     * @see com.stuartwarren.logit.layout.ILayout#format(com.stuartwarren.logit.layout.Log)
     */
    public String format(final Log log) {
        final LogstashV1Log l = (LogstashV1Log) log;
        l.setVersion(LOGSTASH_VERSION);
        return l.toString();
    }

    /* (non-Javadoc)
     * @see com.stuartwarren.logit.layout.ILayout#getLog()
     */
    @Override
    public Log getLog() {
        return new LogstashV1Log(objectMapper);
    }

}


text:
// @flow
/* eslint-env mocha */

import assert from 'power-assert'
import isSameYear from '.'

describe('isSameYear', function() {
  it('returns true if the given dates have the same year', function() {
    var result = isSameYear(
      new Date(2014, 8 /* Sep */, 2),
      new Date(2014, 8 /* Sep */, 25)
    )
    assert(result === true)
  })

  it('returns false if the given dates have different years', function() {
    var result = isSameYear(
      new Date(2014, 8 /* Sep */, 2),
      new Date(2013, 8 /* Sep */, 25)
    )
    assert(result === false)
  })

  it('accepts a timestamp', function() {
    var result = isSameYear(
      new Date(2014, 8 /* Sep */, 2).getTime(),
      new Date(2014, 8 /* Sep */, 25).getTime()
    )
    assert(result === true)
  })

  it('returns false if the first date is `Invalid Date`', function() {
    var result = isSameYear(new Date(NaN), new Date(1989, 6 /* Jul */, 10))
    assert(result === false)
  })

  it('returns false if the second date is `Invalid Date`', function() {
    var result = isSameYear(new Date(1987, 1 /* Feb */, 11), new Date(NaN))
    assert(result === false)
  })

  it('returns false if the both dates are `Invalid Date`', function() {
    var result = isSameYear(new Date(NaN), new Date(NaN))
    assert(result === false)
  })

  it('throws TypeError exception if passed less than 2 arguments', function() {
    assert.throws(isSameYear.bind(null), TypeError)
    assert.throws(isSameYear.bind(null, 1), TypeError)
  })
})


text:
.PHONY: asset auto-review cache coverage cs database infection integration it stan test test-env unit

it: cs stan test

asset:
	yarn install
	yarn run production

auto-review: vendor
	SYMFONY_DEPRECATIONS_HELPER=disabled vendor/bin/phpunit --testsuite auto-review

cache: vendor
	bin/console cache:clear --env=testing

coverage: vendor
	if [ $(type) = "html" ]; then SYMFONY_DEPRECATIONS_HELPER=disabled vendor/bin/phpunit --testsuite unit --coverage-html coverage; else vendor/bin/phpunit --testsuite unit --coverage-text; fi;

cs: vendor
	vendor/bin/php-cs-fixer fix --verbose --diff

database: test-env vendor
	bin/console doctrine:database:drop --env=testing --force
	bin/console doctrine:database:create --env=testing
	bin/console doctrine:migrations:migrate --env=testing -n

doctrine:
	bin/console doctrine:schema:update --env=testing --force
	bin/console doctrine:schema:validate --env=testing
	bin/console doctrine:mapping:info --env=testing

infection: vendor database
	SYMFONY_DEPRECATIONS_HELPER=disabled CFP_ENV=testing php -d zend_extension=xdebug.so vendor/bin/infection

integration: test-env vendor database cache
	SYMFONY_DEPRECATIONS_HELPER=disabled CFP_ENV=testing vendor/bin/phpunit --testsuite integration

static: vendor
	vendor/bin/psalm

test: auto-review doctrine integration unit

test-env:
	if [ ! -f "config/testing.yml" ]; then cp config/testing.yml.dist config/testing.yml; fi

unit: vendor
	SYMFONY_DEPRECATIONS_HELPER=disabled CFP_ENV=testing vendor/bin/phpunit --testsuite unit

vendor: composer.json composer.lock
	composer validate
	composer install


text:
module Beekeeper.Pretty where

import Beekeeper.Core.Declaration (Declaration(..))
import Beekeeper.Core.Identifiers (ImportSource, ModuleName(..), PythonTree(..))

import qualified Data.List as List

import Text.PrettyPrint (
  Doc,
  colon,
  empty,
  int,
  nest,
  parens,
  text,
  vcat,
  (<>),
  (<+>),
  ($+$))

class Pretty a where
  pretty :: a -> Doc

instance (Pretty a, Pretty b) => Pretty (PythonTree a b) where
  pretty tree = header <+> countInfo $+$ prettyChildren
    where header = case tree of
            ModuleTree {} -> pretty . moduleNode $ tree
            SourceTree {} -> pretty . sourceNode $ tree
          count = length . children $ tree
          annot | count == 1 = "child"
                | otherwise  = "children"
          countInfo | count > 0 = parens (int count <+> text annot) <> colon
                    | otherwise = empty
          prettyChildren = vcat . map (nest 4 . pretty) . children $ tree

instance Pretty ModuleName where
  pretty m@(ModuleName {}) = text . moduleName $ m
  pretty m@(SourceName {}) = text $ moduleName m ++ ".py"

instance Pretty Declaration where
  pretty dec@(StarImport {}) = text "from" <+> src <+> text "import *"
    where src = text . sourceToName . source $ dec

  pretty dec@(ImportVar {}) = text "import" <+> src <+> text "as" <+> name
    where src = text . sourceToName . source $ dec
          name = text . declarationName $ dec

  pretty dec@(ImportModule {}) = text "import" <+> src <+> text "as" <+> name
    where src = text . sourceToName . source $ dec
          name = text . declarationName $ dec

  pretty (LambdaDec {}) = text "lambda"

  pretty dec = header <+> varName
    where header = text $ case dec of
            ClassDec {}    -> "class"
            FunctionDec {} -> "def"
            LocalVar {}    -> "var"
            GlobalVar {}   -> "global"
            NonlocalVar {} -> "nonlocal"
            Dereference {} -> "load"
            _              -> error "bad declaration pretty print instance"

          varName = text . declarationName $ dec

sourceToName :: ImportSource -> String
sourceToName = List.intercalate "."


text:
package raytracer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Tracer {

    public static final double TOLERANCE = 0.000001;

    private static final int MAX_RECURSION = 4;
    private static final double REFLECTIVITY = 0.10;

    private final ExecutorService executor = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
    private final List<Callable<Object>> todo = new ArrayList<>();
    private final int[] pixels;
    private final int width;
    private final int height;

    public Tracer(int[] pixels, int width, int height) {
        this.pixels = pixels;
        this.width = width;
        this.height = height;
    }

    public void render(Camera camera, Scene scene) {
        int xStart = width >> 1;
        int yStart = height >> 1;

        todo.clear();
        for (int y = 0; y < height; y++) {
            int finalY = y;
            todo.add(Executors.callable(() -> {
                Ray ray = new Ray();
                int offset = finalY * width;
                camera.transform(ray.origin.set(0.0, 0.0, 1.0)).mul(-camera.distance);
                for (int wx = -xStart; wx < xStart; wx++) {
                    camera.transform(ray.direction.set(wx, yStart - finalY, camera.fov)).normalize();
                    pixels[offset++] = traceRay(scene, ray, 0);
                }
            }));
        }

        try {
            executor.invokeAll(todo);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private int traceRay(Scene scene, Ray ray, int level) {
        Ray hitRay = new Ray();
        Geometry intersected = scene.intersect(ray, hitRay);

        if (intersected != null) {
            Material material = intersected.getMaterial();

            Vector kd = new Vector();
            Vector ks = new Vector();
            Vector kr = new Vector();

            for (Light light : scene.lights) {
                Vector toLight = new Vector(light.position).sub(hitRay.origin);
                boolean shadowed = scene.isShadowed(toLight, hitRay.origin);

                if (!shadowed) {
                    toLight.normalize();
                    double intensity = toLight.dot(hitRay.direction);

                    if (intensity > 0.0) {
                        intensity *= 1.0 - REFLECTIVITY;

                        Color diff = material.computeDiffuse(hitRay);
                        kd.add(intensity * diff.red * light.color.red,
                               intensity * diff.grn * light.color.grn,
                               intensity * diff.blu * light.color.blu);

                        double specular = specularity(ray, hitRay, toLight);
                        if (specular > 0.0) {
                            specular = Math.pow(Math.min(specular, 1.0), material.computeGlossiness(hitRay));
                            Color spec = material.computeSpecular(hitRay);
                            ks.add(specular * spec.red * light.color.red,
                                   specular * spec.grn * light.color.grn,
                                   specular * spec.blu * light.color.blu);
                        }
                    }
                }
            }

            if (level <= MAX_RECURSION) {
                Ray result = new Ray();
                result.direction.set(hitRay.direction).mul(-2.0 * ray.direction.dot(hitRay.direction)).add(ray.direction);
                result.origin.set(result.direction).mul(TOLERANCE).add(hitRay.origin);
                Color color = new Color(traceRay(scene, result, level + 1));
                kr.add(REFLECTIVITY * color.red, REFLECTIVITY * color.grn, REFLECTIVITY * color.blu);
            }

            return shade(scene.ambient.red * material.ambient.red + kd.x + ks.x + kr.x, 0x10) |
                   shade(scene.ambient.grn * material.ambient.grn + kd.y + ks.y + kr.y, 0x08) |
                   shade(scene.ambient.blu * material.ambient.blu + kd.z + ks.z + kr.z, 0x00);
        }
        return 0x000000;
    }

    private static double specularity(Ray ray, Ray hitRay, Vector toLight) {
        double vx = ray.origin.x - hitRay.origin.x;
        double vy = ray.origin.y - hitRay.origin.y;
        double vz = ray.origin.z - hitRay.origin.z;
        double ol = Math.sqrt(vx * vx + vy * vy + vz * vz);
        vx += toLight.x * ol;
        vy += toLight.y * ol;
        vz += toLight.z * ol;
        double d = vx * hitRay.direction.x + vy * hitRay.direction.y + vz * hitRay.direction.z;
        return d > 0.0 ? d / Math.sqrt(vx * vx + vy * vy + vz * vz) : 0.0;
    }

    private static int shade(double v, int shift) {
        return (int)(Math.max(0.0, Math.min(v, 1.0)) * 255.0) << shift;
    }
}


text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import { setBreakpoint } from 'ember-responsive/test-support';

module('Integration | Helper | media', function(hooks) {
  setupRenderingTest(hooks);

  test('it proxies to the media service', async function(assert) {
    await render(hbs`{{#if (media 'isDesktop')}}Is desktop{{/if}}`);
    assert.equal(this.element.textContent.trim(), 'Is desktop');

    await render(hbs`{{#if (media 'isTablet')}}Is tablet{{/if}}`);
    assert.equal(this.element.textContent.trim(), '');

    await render(hbs`{{media 'classNames'}}`);
    assert.equal(this.element.textContent.trim(), 'media-desktop');
  });

  test('it proxies to the media service without issers', async function(assert) {
    await render(hbs`{{#if (media 'desktop')}}Is desktop{{/if}}`);
    assert.equal(this.element.textContent.trim(), 'Is desktop');

    await render(hbs`{{#if (media 'tablet')}}Is tablet{{/if}}`);
    assert.equal(this.element.textContent.trim(), '');
  });

  test('it recomputes when breakpoints change', async function(assert) {
    await render(hbs`
      {{#if (media 'isDesktop')}}Is desktop{{/if}}
      {{#if (media 'isTablet')}}Is tablet{{/if}}
      {{#if (media 'isMobile')}}Is mobile{{/if}}
    `);
    assert.equal(this.element.textContent.trim(), 'Is desktop');

    setBreakpoint('tablet');

    assert.equal(this.element.textContent.trim(), 'Is tablet');

    setBreakpoint('mobile');

    assert.equal(this.element.textContent.trim(), 'Is mobile');
  });
});


text:
<?php
namespace tests\application\sitemaps\ProcessorMapTrait;
use mocks\application\sitemaps\MapFixture;
use vsc\application\sitemaps\ProcessorMapTrait;
use vsc\presentation\helpers\ViewHelperA;

/**
 * @covers \vsc\application\sitemaps\ProcessorMapTrait::registerHelper()
 */
class registerHelper extends \BaseUnitTest
{
	public function testBasicRegisterHelper()
	{
		$o = new ProcessorMapT_underTest_registerHelper();

		$o->registerHelper(new ViewHelperA_underTest_registerHelper());

		$helpers = $o->getViewHelpers();
		$this->assertEquals(1, count($helpers));
		foreach ($helpers as $helper) {
			$this->assertInstanceOf(ViewHelperA::class, $helper);
		}
	}
}

class ViewHelperA_underTest_registerHelper extends ViewHelperA {}

class ProcessorMapT_underTest_registerHelper extends MapFixture {
	use ProcessorMapTrait;
	public function __construct ($sPath = null, $sRegex = null) {
		if (is_null($sPath)) {
			$sPath = __FILE__;
		}
		if (is_null($sRegex)) {
			$sRegex = '.*';
		}
		parent::__construct($sPath, $sRegex);
	}
}