text:
"""
Created on Fri Jul 27 10:08:25 2018

@author: cdeline

Using pytest to create unit tests for bifacial_radiance.

to run unit tests, run pytest from the command line in the bifacial_radiance directory
to run coverage tests, run py.test --cov-report term-missing --cov=bifacial_radiance

"""

#from bifacial_radiance import RadianceObj, SceneObj, AnalysisObj
import bifacial_radiance
import numpy as np
import pytest
import os
import pandas as pd

# try navigating to tests directory so tests run from here.
try:
    os.chdir('tests')
except:
    pass

#TESTDIR = os.path.dirname(__file__)  # this folder

cellParams = {'xcell':0.156, 'ycell':0.156, 'numcellsx':6, 'numcellsy':10,
               'xcellgap':0.02, 'ycellgap':0.02}

frameParams = {'frame_material' : 'Metal_Grey',
               'frame_thickness' : 0.003,
               'frame_z' : 0.03,
               'nSides_frame' : 4,
               'frame_width' : 0.05}

omegaParams = {'omega_material': 'litesoil',
                'x_omega1' : 0.10,
                'mod_overlap' : 0.5,
                'y_omega' : 1.5,
                'x_omega3' : 0.05,
                'omega_thickness' : 0.01,
                'inverted' : False}

def test_CellLevelModule():
    # test the cell-level module generation
    name = "_test_CellLevelModule"
    demo = bifacial_radiance.RadianceObj(name)  # Create a RadianceObj 'object'

    module = demo.makeModule(name='test-module', rewriteModulefile=True, cellModule=cellParams, customtext=' | xform -t 0 0.181 0')
    assert module.x == 1.036
    assert module.y == 1.74
    assert module.scenex == 1.046
    assert module.sceney == 1.74
    assert module.text == '! genbox black cellPVmodule 0.156 0.156 0.02 | xform -t -0.44 -0.87 0 -a 6 -t 0.176 0 0 -a 10 -t 0 0.176 0 -a 1 -t 0 1.74 0 | xform -t 0 0.181 0'

    module.addCellModule(**cellParams, centerJB=0.01)  #centerJB simulations still under development.
#    assert module.text == '! genbox black cellPVmodule 0.156 0.156 0.02 | xform -t -0.44 -0.87 0 -a 6 -t 0.176 0 0 -a 5.0 -t 0 0.176 0 -a 2 -t 0 0.772 0 | xform -t 0 0.181 0 -a 1 -t 0 1.73 0'

def test_TorqueTubes_Module():
    name = "_test_TorqueTubes"
    demo = bifacial_radiance.RadianceObj(name)  # Create a RadianceObj 'object'
    module = demo.makeModule(name='square', y=0.95,x=1.59, tubeParams={'tubetype':'square', 'axisofrotation':False}, hpc=True) #suppress saving .json
    assert module.x == 1.59
    assert module.text == '! genbox black square 1.59 0.95 0.02 | xform -t -0.795 -0.475 0 -a 1 -t 0 0.95 0\r\n! genbox Metal_Grey tube1 1.6 0.1 0.1 | xform -t -0.8 -0.05 -0.2'
    module = demo.makeModule(name='round', y=0.95,x=1.59, tubeParams={'tubetype':'round', 'axisofrotation':False}, hpc=True)
    assert module.text[0:30] == '! genbox black round 1.59 0.95'
    module = demo.makeModule(name='hex', y=0.95,x=1.59,  tubeParams={'tubetype':'hex', 'axisofrotation':False}, hpc=True)
    assert module.text[0:30] == '! genbox black hex 1.59 0.95 0'
    module = demo.makeModule(name='oct', y=0.95,x=1.59, hpc=True)
    module.addTorquetube(tubetype='oct', axisofrotation=False, recompile=False)
    module.compileText(rewriteModulefile=False, json=False)
    assert module.text[0:30] == '! genbox black oct 1.59 0.95 0'

def test_moduleFrameandOmegas():
    # test moduleFrameandOmegas. Requires metdata for boulder.

    name = "_test_moduleFrameandOmegas"
    demo = bifacial_radiance.RadianceObj(name)
    #demo.setGround(0.2)
    zgap = 0.10

    loopaxisofRotation = [True, True, True, True, True, True, True, True]
    loopTorquetube = [True, True, True, True, False, False, False, False ]
    loopOmega = [omegaParams, omegaParams, None, None, omegaParams, omegaParams, None, None]
    loopFrame = [frameParams, None, frameParams, None, frameParams,  None, frameParams, None]
    expectedModuleZ = [3.179, 3.149, 3.179, 3.149, 3.129, 3.099, 3.129, 3.099]

    # test inverted=True on the first test
    loopOmega[0]['inverted'] = True
    sceneDict = {'tilt':0, 'pitch':3, 'clearance_height':3,'azimuth':90,
                 'nMods': 1, 'nRows': 1}

    for ii in range (0, len(loopOmega)):

        if loopTorquetube[ii] is False:
            diam = 0.0
        else:  diam = 0.1

        module = bifacial_radiance.ModuleObj(name='test-module',x=2, y=1, zgap = zgap,
                                             )
        module.addTorquetube(diameter=diam, axisofrotation=loopaxisofRotation[ii],
                             visible = loopTorquetube[ii])
        if loopFrame[ii]:
            module.addFrame(**loopFrame[ii])

        if loopOmega[ii]:
            module.addOmega(**loopOmega[ii])  #another way to add omega parameters
        scene = demo.makeScene(module,sceneDict)
        analysis = bifacial_radiance.AnalysisObj()  # return an analysis object including the scan dimensions for back irradiance
        frontscan, backscan = analysis.moduleAnalysis(scene, sensorsy=1) # Gives us the dictionaries with coordinates
        assert backscan['zstart'] == expectedModuleZ[ii]

        # read the data back from module.json and check again
        module = demo.makeModule(name='test-module')
        scene = demo.makeScene('test-module',sceneDict)
        analysis = bifacial_radiance.AnalysisObj()  # return an analysis object including the scan dimensions for back irradiance
        frontscan, backscan = analysis.moduleAnalysis(scene, sensorsy=1)
        assert backscan['zstart'] == expectedModuleZ[ii]
    # do it again by passing everying at once
    module = bifacial_radiance.ModuleObj(name='test-module',x=2, y=1, zgap = zgap,
                                          frameParams=frameParams, omegaParams=omegaParams,
                                          tubeParams={'diameter':0.1,
                                                      'axisofrotation':True})
    scene = demo.makeScene(module, sceneDict)
    analysis = bifacial_radiance.AnalysisObj()  # return an analysis object including the scan dimensions for back irradiance
    frontscan, backscan = analysis.moduleAnalysis(scene, sensorsy=1) # Gives us the dictionaries with coordinates
    assert backscan['zstart'] == expectedModuleZ[0]

    # omega default values
    module.addOmega()
    assert module.omega.x_omega1==0.003; assert module.omega.y_omega==0.5; assert module.omega.x_omega3==0.005;
    module.addOmega(inverted=True)
    assert module.omega.x_omega1==0.005; assert module.omega.y_omega==0.5; assert module.omega.x_omega3==0.0015;

    # test cellModulescan (sensorsy = numellsy)
    module.glass=True
    module.addCellModule(**cellParams)
    scene = demo.makeScene(module, sceneDict)
    analysis = bifacial_radiance.AnalysisObj()  # return an analysis object including the scan dimensions for back irradiance
    frontscan, backscan = analysis.moduleAnalysis(scene, sensorsy=10) # Gives us the dictionaries with coordinates
    assert backscan['xstart'] == pytest.approx(0.792)


text:
import os.path
import re
import unittest
from glob import glob

from streamlink import Streamlink

class TestPluginMeta(unittest.TestCase):
    """
    Test that each plugin has an entry in the plugin matrix and a test file
    """
    longMessage = False
    built_in_plugins = [
        "akamaihd", "http", "hds", "rtmp", "hls", "dash", "stream"
    ]

    title_re = re.compile(r"\n[= ]+\n")
    plugin_re = re.compile(r"^([\w_]+)\s", re.MULTILINE)

    def setUp(self):
        self.session = Streamlink()
        docs_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                                "../docs"))

        with open(os.path.join(docs_dir, "plugin_matrix.rst")) as plfh:
            parts = self.title_re.split(plfh.read())
            self.plugins_in_docs = list(self.plugin_re.findall(parts[3]))

        tests_plugins_dir = os.path.abspath(os.path.join(
            os.path.dirname(__file__), "plugins"))
        tests_plugin_files = glob(os.path.join(tests_plugins_dir, "test_*.py"))

        self.plugins_with_tests = [
            re.sub(r"^test_([^\.]+)\.py$", r"\1",
                   os.path.split(p)[1]) for p in tests_plugin_files
        ]

    def test_plugin_has_docs_matrix(self):
        for pname in self.session.plugins.keys():
            if pname not in self.built_in_plugins:
                self.assertIn(pname, self.plugins_in_docs,
                              "{0} is not in plugin matrix".format(pname))

    def test_docs_matrix_has_plugin(self):
        for pname in self.plugins_in_docs:
            self.assertIn(pname, self.session.plugins,
                          "{0} plugin does not exist".format(pname))

    def test_plugin_has_tests(self):
        for pname in self.session.plugins.keys():
            if pname not in self.built_in_plugins:
                self.assertIn(pname, self.plugins_with_tests,
                              "{0} has no tests".format(pname))

    def test_unknown_plugin_has_tests(self):
        for pname in self.plugins_with_tests:
            if pname not in self.built_in_plugins:
                self.assertIn(pname, self.session.plugins.keys(),
                              "{0} is not a plugin but has tests".format(pname))

    def test_plugin_not_in_removed_list(self):
        from streamlink import plugins as streamlinkplugins
        with open(os.path.abspath(os.path.join(streamlinkplugins.__path__[0], ".removed"))) as file:
            plugins = {name for name in file.read().split("\n") if name and not name.startswith("#")}
            for pname in self.session.plugins.keys():
                self.assertNotIn(pname, plugins, f"{pname} is not in removed plugins list")

    def test_plugin_has_valid_global_args(self):
        from streamlink_cli.argparser import build_parser
        parser = build_parser()
        global_arg_dests = [action.dest for action in parser._actions]
        for pname, plugin in self.session.plugins.items():
            for parg in plugin.arguments:
                if parg.is_global:
                    self.assertIn(parg.dest, global_arg_dests,
                                  f"{parg.name} from plugins.{pname} is not a valid global argument")

redpajama_set_name: RedPajamaGithub


text:
<#
.SYNOPSIS
    Export mailbox statistics for Exchange Organization
.DESCRIPTION
    This script will export mailbox statistics for desired scope on Exchange servers.
    Script has been tested with Exchange 2010 on Windows Server 2008 R2
.PARAMETER Path
    Folder path without trailing slash, where output CSV should be stored.
    Default value: Working Directory (Get-Location).ProviderPath
.PARAMETER Scope
    Which mailboxes to export information about.
    Accepted values: All, Server and Database
    Default value: All
.PARAMETER Server
    Parameter must be supplied if desired scope is "Server". Servername, with or without DNS Suffix.
.PARAMETER Database
    Parameter must be supplied if desired scope is "Database". Mailbox database name.
.EXAMPLE
    Export information on all mailboxes and store CSV in folder C:\temp
    .\Get-MailboxReport.ps1 -Path "C:\temp"
.EXAMPLE
    Export information on mailboxes in server "HUB001" and store CSV in folder C:\temp
    .\Get-MailboxReport.ps1 -Path "C:\temp" -Scope "Server" -Server "HUB001"
.INPUTS
    Does not accept pipeline input.
.OUTPUTS
    Does not provide pipeline output.
.NOTES
    NAME: Get-MailboxReport.ps1
    VERSION: 1.0
    AUTHOR: Tor Ivar Larsen
    CREATED: 02.02.2017
    LASTEDIT: 02.02.2017
#>
[CMDLetBinding()]
Param(
    [Parameter(Mandatory=$false)]
    [string]$Path,
    [Parameter(Mandatory=$false)]
    [string]$Scope,
    [Parameter(Mandatory=$false)]
    [string]$Database,
    [Parameter(Mandatory=$false)]
    [string]$Server
)

If ($Scope -eq "All") { $mailboxes = Get-Mailbox -ResultSize Unlimited }
ElseIf (($Scope -eq "Server") -and ($Server -ne "")) { Get-Mailbox -ResultSize Unlimited -Server "$Server" }
ElseIf (($Scope -eq "Database") -and ($Database -ne "")) { Get-Mailbox -ResultSize Unlimited -Database "$Database" }
Else { $mailboxes = Get-Mailbox -ResultSize Unlimited }

$Organization = (Get-OrganizationConfig).Name
$Date = Get-Date -Format 'yyyy-MM-dd'
$Info = @()
$count = $mailboxes.Count
$i=0

Foreach ($mbx in $mailboxes)
{
    $i++
    Write-Host "Processing $i of $count"
    $DisplayName = $mbx.DisplayName
    $Alias = $mbx.Alias

    $Addresses = $mbx | Select-Object -ExpandProperty EmailAddresses
    $PrimarySMTP = ""
    $SecondarySMTP = @()

    Foreach ($addr in $Addresses)
    {
        If ($addr.PrefixString -ceq "SMTP") { $PrimarySMTP = $addr.AddressString }
        ElseIf ($addr.PrefixString -ceq "smtp") { $SecondarySMTP += $addr.AddressString }
    }
    $obj = New-Object -TypeName PSObject
    $obj | Add-Member -MemberType NoteProperty -Name "PrimarySMTP" -Value $PrimarySMTP
    $obj | Add-Member -MemberType NoteProperty -Name "SecondarySMTP" -Value ($SecondarySMTP -join ",")
    $obj | Add-Member -MemberType NoteProperty -Name "ProhibitSend" -Value $mbx.ProhibitSendQuota
    $obj | Add-Member -MemberType NoteProperty -Name "ProhibitSendReceive" -Value $mbx.ProhibitSendReceiveQuota
    $obj | Add-Member -MemberType NoteProperty -Name "RecipientTypeDetails" -Value $mbx.RecipientTypeDetails.ToString()
    $obj | Add-Member -MemberType NoteProperty -Name "SamAccountName" -Value $mbx.SamAccountName

    $Statistics = $mbx | Get-MailboxStatistics
    $TotalSize = $Statistics.TotalItemSize.Value.ToBytes()
    $DB = "$($Statistics.ServerName)\$($Statistics.DatabaseName)"

    $obj | Add-Member -MemberType NoteProperty -Name "TotalItemSize" -Value $TotalSize
    $TotalSizeInGB = "{0:N2}" -f ($TotalSize/1GB)
    $obj | Add-Member -MemberType NoteProperty -Name "TotalItemSizeInGB" -Value $TotalSizeInGB

    $TotalSizeInMB = "{0:N2}" -f ($TotalSize/1MB)
    $obj | Add-Member -MemberType NoteProperty -Name "TotalItemSizeInMB" -Value $TotalSizeInMB

    $obj | Add-Member -MemberType NoteProperty -Name "ItemCount" -Value $Statistics.ItemCount
    $obj | Add-Member -MemberType NoteProperty -Name "LastLogonTime" -Value $Statistics.LastLogonTime
    $obj | Add-Member -MemberType NoteProperty -Name "LastLogoffTime" -Value $Statistics.LastLogoffTime
    $obj | Add-Member -MemberType NoteProperty -Name "LastLoggedOnUserAccount" -Value $Statistics.LastLoggedOnUserAccount
    $obj | Add-Member -MemberType NoteProperty -Name "StorageLimitStatus" -Value $Statistics.StorageLimitStatus
    $obj | Add-Member -MemberType NoteProperty -Name "MailboxDatabase" -Value $DB

    $Info += $obj
    $obj = $null
}

If (!$Path) { $Path = (Get-Location).ProviderPath }

$Info | Export-Csv -Path "$Path\MailboxReport - $Organization - $Date.csv" -Delimiter ";" -Encoding UTF8 -NoTypeInformation


text:
package org.cf.smalivm.opcode;

import gnu.trove.map.TIntObjectMap;

import org.cf.smalivm.VirtualMachine;
import org.cf.util.Utils;
import org.jf.dexlib2.builder.MethodLocation;

public class NopOpFactory implements OpFactory {

    @Override
    public Op create(MethodLocation location, TIntObjectMap<MethodLocation> addressToLocation, VirtualMachine vm) {
        MethodLocation child = Utils.getNextLocation(location, addressToLocation);

        return new NopOp(location, child);
    }

}


text:
import json
import math

PLUGIN_VERSION=1
HEARTBEAT=True

METRICS_UNITS={
    "Response Rate":"/sec",
    "Request Rate":"/sec",
    "Request Latency Avg":"/sec",
    "Outgoing Byte Rate":"Bytes",
    "IO Wait Time NS Avg":"ns",
    "Batch Size Avg":"Bytes"}

class appname:

    def __init__(self,args):

        self.maindata={}
        self.maindata['plugin_version'] = PLUGIN_VERSION
        self.maindata['heartbeat_required']=HEARTBEAT
        self.maindata['units']=METRICS_UNITS

        self.kafka_producer_host=args.kafka_producer_host
        self.kafka_producer_jmx_port=args.kafka_producer_jmx_port

        self.kafka_producer_client_id=args.kafka_producer_client_id

        self.logsenabled=args.logs_enabled
        self.logtypename=args.log_type_name
        self.logfilepath=args.log_file_path

    def metriccollector(self):

        try:
            global jmx
            import jmxquery as jmx
            jmxConnection = jmx.JMXConnection(f"service:jmx:rmi:///jndi/rmi://{self.kafka_producer_host}:{self.kafka_producer_jmx_port}/jmxrmi")

            metric_queries={
                "Compression Rate Avg":f"kafka.producer:type=producer-metrics,client-id={self.kafka_producer_client_id}/compression-rate-avg",
                "Response Rate":f"kafka.producer:type=producer-metrics,client-id={self.kafka_producer_client_id}/response-rate",
                "Request Rate":f"kafka.producer:type=producer-metrics,client-id={self.kafka_producer_client_id}/request-rate",
                "Request Latency Avg":f"kafka.producer:type=producer-metrics,client-id={self.kafka_producer_client_id}/request-latency-avg",
                "Outgoing Byte Rate":f"kafka.producer:type=producer-metrics,client-id={self.kafka_producer_client_id}/outgoing-byte-rate",
                "IO Wait Time NS Avg":f"kafka.producer:type=producer-metrics,client-id={self.kafka_producer_client_id}/io-wait-time-ns-avg",
                "Batch Size Avg":f"kafka.producer:type=producer-metrics,client-id={self.kafka_producer_client_id}/batch-size-avg"
        }

            for metric in metric_queries:

                jmxQuery = [jmx.JMXQuery(metric_queries[metric])]
                metric_result = jmxConnection.query(jmxQuery)
                data=metric_result[0].value
                if math.isnan(data):
                    self.maindata[metric]=-1
                else:
                    self.maindata[metric]=data

            self.maindata["Client ID"]=self.kafka_producer_client_id

            applog={}
            if(self.logsenabled in ['True', 'true', '1']):
                    applog["logs_enabled"]=True
                    applog["log_type_name"]=self.logtypename
                    applog["log_file_path"]=self.logfilepath
            else:
                    applog["logs_enabled"]=False
            self.maindata['applog'] = applog

        except Exception as e:
            self.maindata['msg']=str(e)
            self.maindata['status']=0
            return self.maindata

        return self.maindata

if __name__=="__main__":

    kafka_producer_host="localhost"
    kafka_producer_jmx_port=9982
    kafka_producer_client_id="console-producer"

    import argparse
    parser=argparse.ArgumentParser()
    parser.add_argument('--kafka_producer_host', help='host name to access the kafka consumer metrics',default=kafka_producer_host)
    parser.add_argument('--kafka_producer_jmx_port', help='jmx port to access the kafka consumer metrics',default=kafka_producer_jmx_port)
    parser.add_argument('--kafka_producer_client_id', help='kafka consumer client id',default=kafka_producer_client_id)

    parser.add_argument('--logs_enabled', help='enable log collection for this plugin application',default="False")
    parser.add_argument('--log_type_name', help='Display name of the log type', nargs='?', default=None)
    parser.add_argument('--log_file_path', help='list of comma separated log file paths', nargs='?', default=None)
    args=parser.parse_args()

    obj=appname(args)

    result=obj.metriccollector()
    print(json.dumps(result,indent=True))


text:
package com.navercorp.pinpoint.common.server.bo.codec.stat;

import com.navercorp.pinpoint.common.server.bo.stat.ActiveTraceBo;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * @author HyunGil Jeong
 */
@Component
public class ActiveTraceEncoder extends AgentStatEncoder<ActiveTraceBo> {

    public ActiveTraceEncoder(@Qualifier("activeTraceCodecV2") AgentStatCodec<ActiveTraceBo> activeTraceCodec) {
        super(activeTraceCodec);
    }
}


text:
package org.mapfish.print;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.CharStreams;
import com.google.common.io.Closer;
import org.mapfish.print.http.MfClientHttpRequestFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

/**
 * Utility methods for editing and analyzing uris.
 */
public final class URIUtils {
    private URIUtils() {
        // intentionally empty
    }

    /**
     * Parse the URI and get all the parameters in map form.  Query name -> List of Query values.
     *
     * @param uri uri to analyze
     */
    public static Multimap<String, String> getParameters(final URI uri) {
        return getParameters(uri.getRawQuery());
    }

    /**
     * Parse the URI and get all the parameters in map form.  Query name -> List of Query values.
     *
     * @param rawQuery query portion of the uri to analyze.
     */
    public static Multimap<String, String> getParameters(final String rawQuery) {
        Multimap<String, String> result = HashMultimap.create();
        if (rawQuery == null) {
            return result;
        }

        StringTokenizer tokens = new StringTokenizer(rawQuery, "&");
        while (tokens.hasMoreTokens()) {
            String pair = tokens.nextToken();
            int pos = pair.indexOf('=');
            String key;
            String value;
            if (pos == -1) {
                key = pair;
                value = "";
            } else {

                try {
                    key = URLDecoder.decode(pair.substring(0, pos), "UTF-8");
                    value = URLDecoder.decode(pair.substring(pos + 1, pair.length()), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw ExceptionUtils.getRuntimeException(e);
                }
            }

            result.put(key, value);
        }
        return result;
    }

    /**
     * Add the given params to the query.
     *
     * @param url            The query
     * @param params         The params to add
     * @param overrideParams A set of parameter names that must be overridden and not added
     * @return The new query
     * @throws URISyntaxException
     */
    public static String addParams(final String url, final Multimap<String, String> params, final Set<String> overrideParams)
            throws URISyntaxException {
        return addParams(new URI(url), params, overrideParams).toString();
    }

    /**
     * Add the given params to the query.
     *
     * @param uri            The query
     * @param params         The params to add
     * @param overrideParams A set of parameter names that must be overridden and not added
     * @return The new query
     */
    public static URI addParams(final URI uri, final Multimap<String, String> params, final Set<String> overrideParams) {
        if (params == null || params.isEmpty()) {
            return uri;
        }
        final String origTxt = uri.toString();
        int queryStart = origTxt.indexOf('?');
        final StringBuilder result = new StringBuilder();
        if (queryStart < 0) {
            int fragmentStart = origTxt.indexOf('#');
            if (fragmentStart < 0) {
                result.append(origTxt);
            } else {
                result.append(origTxt.substring(0, fragmentStart));
            }
        } else {
            result.append(origTxt.substring(0, queryStart));
        }

        Map<String, Collection<String>> origParams = getParameters(uri).asMap();
        boolean first = true;
        for (Map.Entry<String, Collection<String>> param : params.asMap().entrySet()) {
            final String key = param.getKey();
            Collection<String> origList = origParams.remove(key);
            if (origList != null && (overrideParams == null || !overrideParams.contains(key))) {
                first = addParams(result, first, key, origList);
            }
            Collection<String> list = param.getValue();
            first = addParams(result, first, key, list);
        }

        for (Map.Entry<String, Collection<String>> param : origParams.entrySet()) {
            final String key = param.getKey();
            Collection<String> list = param.getValue();
            first = addParams(result, first, key, list);
        }

        if (uri.getFragment() != null) {
            result.append('#').append(uri.getRawFragment());
        }

        try {
            return new URI(result.toString());
        } catch (URISyntaxException e) {
            throw ExceptionUtils.getRuntimeException(e);
        }
    }

    private static boolean addParams(final StringBuilder result, final boolean isFirstParam, final String key,
                                     final Collection<String> list) {
        boolean first = isFirstParam;
        for (String val : list) {
            if (first) {
                result.append('?');
                first = false;
            } else {
                result.append('&');
            }
            try {
                result.append(URLEncoder.encode(key, Constants.DEFAULT_ENCODING));
                result.append("=");
                result.append(URLEncoder.encode(val, Constants.DEFAULT_ENCODING));
            } catch (UnsupportedEncodingException e) {
                throw ExceptionUtils.getRuntimeException(e);
            }
        }
        return first;
    }

    /**
     * Add a parameter to the query params (the params map) replacing any parameter that might be there.
     *
     * @param params the query parameters
     * @param key    the key/param name
     * @param value  the value to insert
     */
    public static void addParamOverride(final Multimap<String, String> params, final String key, final String value) {
        params.removeAll(key);
        params.put(key, value);
    }

    /**
     * Add a parameter to the query params (the params map) if there is not existing value for that key.
     *
     * @param params the query parameters
     * @param key    the key/param name
     * @param value  the value to insert
     */
    public static void setParamDefault(final Multimap<String, String> params, final String key, final String value) {
        if (!params.containsKey(key)) {
            params.put(key, value);
        }
    }

    /**
     * Construct a new uri by replacing query parameters in initialUri with the query parameters provided.
     *
     * @param initialUri  the initial/template URI
     * @param queryParams the new query parameters.
     */
    public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {
        StringBuilder queryString = new StringBuilder();
        for (Map.Entry<String, String> entry : queryParams.entries()) {
            if (queryString.length() > 0) {
                queryString.append("&");
            }
            queryString.append(entry.getKey()).append("=").append(entry.getValue());
        }
        try {
            if (initialUri.getHost() == null && initialUri.getAuthority() != null) {
                return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(), queryString.toString(),
                        initialUri.getFragment());
            } else {
                return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(), initialUri.getPort(),
                        initialUri.getPath(),
                        queryString.toString(), initialUri.getFragment());
            }
        } catch (URISyntaxException e) {
            throw ExceptionUtils.getRuntimeException(e);
        }
    }

    /**
     * Read all the data from the provided URI and return the data as a string.
     *
     * @param requestFactory Request factory for making the request.
     * @param uri            the uri to load data from.
     * @return the data in string form.
     */
    public static String toString(final MfClientHttpRequestFactory requestFactory, final URI uri) throws IOException {
        Closer closer = Closer.create();
        try {
            ClientHttpResponse response = closer.register(requestFactory.createRequest(uri, HttpMethod.GET).execute());

            InputStream input = closer.register(response.getBody());
            InputStreamReader reader = closer.register(new InputStreamReader(input, Constants.DEFAULT_ENCODING));
            BufferedReader bufferedReader = closer.register(new BufferedReader(reader));

            return CharStreams.toString(bufferedReader);
        } finally {
            closer.close();
        }
    }

    /**
     * Read all the data from the provided URI and return the data as a string.
     *
     * @param requestFactory Request factory for making the request.
     * @param url            the uri to load data from.
     * @return the data in string form.
     */
    public static String toString(final MfClientHttpRequestFactory requestFactory, final URL url) throws IOException {
        try {
            return toString(requestFactory, url.toURI());
        } catch (URISyntaxException e) {
            throw ExceptionUtils.getRuntimeException(e);
        }
    }

    /**
     * Set the replace of the uri and return the new URI.
     *
     * @param initialUri the starting URI, the URI to update
     * @param path    the path to set on the baeURI
     */
    public static URI setPath(final URI initialUri, final String path) {
        String finalPath = path;
        if (!finalPath.startsWith("/")) {
            finalPath = '/' + path;
        }
        try {
            if (initialUri.getHost() == null && initialUri.getAuthority() != null) {
                return new URI(initialUri.getScheme(), initialUri.getAuthority(), finalPath, initialUri.getQuery(),
                        initialUri.getFragment());
            } else {
                return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(), initialUri.getPort(),
                        finalPath, initialUri.getQuery(), initialUri.getFragment());
            }
        } catch (URISyntaxException e) {
            throw ExceptionUtils.getRuntimeException(e);
        }
    }
}


text:
package com.intellij.ide.ui.laf.darcula.ui;

import com.intellij.ide.ui.laf.darcula.DarculaUIUtil;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.ui.Gray;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;

import javax.swing.border.Border;
import javax.swing.plaf.UIResource;
import javax.swing.text.JTextComponent;
import java.awt.*;

/**
 * @author Konstantin Bulenkov
 */
public class DarculaTextBorder implements Border, UIResource {
  @Override
  public Insets getBorderInsets(Component c) {
    int vOffset = TextFieldWithPopupHandlerUI.isSearchField(c) ? 6 : 4;
    if (TextFieldWithPopupHandlerUI.isSearchFieldWithHistoryPopup(c)) {
      return JBUI.insets(vOffset, 7 + 16 + 3, vOffset, 7 + 16).asUIResource();
    }
    else if (TextFieldWithPopupHandlerUI.isSearchField(c)) {
      return JBUI.insets(vOffset, 4 + 16 + 3, vOffset, 7 + 16).asUIResource();
    }
    else {
      return JBUI.insets(vOffset, 7, vOffset, 7).asUIResource();
    }
  }

  @Override
  public boolean isBorderOpaque() {
    return false;
  }

  @Override
  public void paintBorder(Component c, Graphics g2, int x, int y, int width, int height) {
    if (DarculaTextFieldUI.isSearchField(c)) return;
    Graphics2D g = (Graphics2D)g2;
    final GraphicsConfig config = new GraphicsConfig(g);
    g.translate(x, y);

    if (c.hasFocus()) {
      DarculaUIUtil.paintFocusRing(g, 2, 2, width - 4, height - 4);
    }
    else {
      boolean editable = !(c instanceof JTextComponent) || ((JTextComponent)c).isEditable();
      g.setColor(getBorderColor(c.isEnabled() && editable));
      g.drawRect(1, 1, width - 2, height - 2);
    }
    g.translate(-x, -y);
    config.restore();
  }

  private static Color getBorderColor(boolean enabled) {
    // in sync with ComboBox's border color
    if (UIUtil.isUnderDarcula()) {
      return enabled ? Gray._100 : Gray._83;
    }
    return Gray._150;
  }
}


text:
package org.telegram.telegrambots.meta.api.methods.send;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Tolerate;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethodMessage;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author Ruben Bermudez
 * @version 4.7
 * Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.
 */
@EqualsAndHashCode(callSuper = false)
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SendDice extends BotApiMethodMessage {
    private static final List<String> VALIDEMOJIS = Collections.unmodifiableList(Arrays.asList("🎲", "🎯", "🏀", "⚽", "🎳", "🎰"));

    public static final String PATH = "sendDice";

    private static final String CHATID_FIELD = "chat_id";
    private static final String MESSAGETHREADID_FIELD = "message_thread_id";
    private static final String EMOJI_FIELD = "emoji";
    private static final String DISABLENOTIFICATION_FIELD = "disable_notification";
    private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id";
    private static final String REPLYMARKUP_FIELD = "reply_markup";
    private static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply";
    private static final String PROTECTCONTENT_FIELD = "protect_content";

    /**
     * Unique identifier for the target chat or username of the target channel (in the format @channelusername)
     */
    @JsonProperty(CHATID_FIELD)
    @NonNull
    private String chatId;
    /**
     * Unique identifier for the target message thread (topic) of the forum;
     * for forum supergroups only
     */
    @JsonProperty(MESSAGETHREADID_FIELD)
    private Integer messageThreadId;
    /**
     * Optional.
     *
     * Emoji on which the dice throw animation is based.
     *
     * Currently, must be one of "🎲", "🎯", "🏀", "⚽", "🎳", or "🎰".
     *
     * Dice can have values 1-6 for "🎲", "🎯" and "🎳", values 1-5 for "🏀" and "⚽", and values 1-64 for "🎰".
     *
     * Defaults to "🎲"
     */
    @JsonProperty(EMOJI_FIELD)
    private String emoji;
    @JsonProperty(DISABLENOTIFICATION_FIELD)
    private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound.
    @JsonProperty(REPLYTOMESSAGEID_FIELD)
    private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message
    @JsonProperty(REPLYMARKUP_FIELD)
    private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard
    @JsonProperty(ALLOWSENDINGWITHOUTREPLY_FIELD)
    private Boolean allowSendingWithoutReply; ///< Optional. Pass True, if the message should be sent even if the specified replied-to message is not found
    @JsonProperty(PROTECTCONTENT_FIELD)
    private Boolean protectContent; ///< Optional. Protects the contents of sent messages from forwarding and saving

    @Tolerate
    public void setChatId(@NonNull Long chatId) {
        this.chatId = chatId.toString();
    }

    public void enableNotification() {
        this.disableNotification = false;
    }

    public void disableNotification() {
        this.disableNotification = true;
    }

    @Override
    public String getMethod() {
        return PATH;
    }

    @Override
    public void validate() throws TelegramApiValidationException {
        if (chatId.isEmpty()) {
            throw new TelegramApiValidationException("ChatId parameter can't be empty", this);
        }
        if (emoji != null && !VALIDEMOJIS.contains(emoji)) {
            throw new TelegramApiValidationException("Only \"\uD83C\uDFB2\", \"\uD83C\uDFAF\", \"\uD83C\uDFC0\", \"⚽\", \"\uD83C\uDFB0\" are allowed in Emoji field ", this);
        }
        if (replyMarkup != null) {
            replyMarkup.validate();
        }
    }

    public static class SendDiceBuilder {

        @Tolerate
        public SendDiceBuilder chatId(@NonNull Long chatId) {
            this.chatId = chatId.toString();
            return this;
        }
    }
}


text:
(function($CQ, _, Backbone, SCF) {
    "use strict";
    var Idea = SCF.Topic.extend({
        modelName: "IdeaModel",
        setTech: function(tech) {
            var error = _.bind(function(jqxhr, text, error) {
                this.log.error("error setting status " + error);
                this.trigger('idea:statuserror', {
                    'error': error
                });
            }, this);
            var success = _.bind(function(response) {
                this.set(response.response);
                this.trigger('idea:statusset', {
                    model: this
                });
                this.trigger(this.events.UPDATED, {
                    model: this
                });
            }, this);
            var postData = {
                'tech': tech,
                ':operation': 'social:setTechnology'
            };
            $CQ.ajax(SCF.config.urlRoot + this.get('id') + SCF.constants.URL_EXT, {
                dataType: 'json',
                type: 'POST',
                xhrFields: {
                    withCredentials: true
                },
                data: this.addEncoding(postData),
                'success': success,
                'error': error
            });
        },
        addLike:function(likeValue){

            var error = _.bind(function(jqxhr, text, error) {
                this.log.error("error setting status " + error);
                this.trigger('idea:statuserror', {
                    'error': error
                });
            }, this);
            var success = _.bind(function(response) {
                this.set(response.response);
            }, this);

            var postData = {
                'likes' :likeValue,
                ':operation': 'social:addLike'
            };
            $CQ.ajax(SCF.config.urlRoot + this.get('id') + SCF.constants.URL_EXT, {
                async:false,
                dataType: 'json',
                type: 'POST',
                xhrFields: {
                    withCredentials: true
                },
                data: this.addEncoding(postData),
                'success': success,
                'error': error
            });

        }

    });

    var IdeaView = SCF.TopicView.extend({
        viewName: "Idea",
        setTech: function(e){
            var tech = this.getField("tech");
            this.model.setTech(tech.join("-"));
            e.preventDefault();
        },
        addLike:function(event){
             event.preventDefault();
            var likeValue = $(event.target).data('likes');
         	this.model.addLike(likeValue);
            this.render();
        }

    });

    SCF.Idea = Idea;
    SCF.IdeaView = IdeaView;
    SCF.registerComponent('scf/components/ideation/post', SCF.Post, SCF.PostView);
    SCF.registerComponent('scf/components/ideation/topic', SCF.Idea, SCF.IdeaView);
    SCF.registerComponent('scf/components/ideation/forum', SCF.Forum, SCF.ForumView);
})($CQ, _, Backbone, SCF);


text:
#ifndef JSAPIValueWrapper_h
#define JSAPIValueWrapper_h

#include "JSCell.h"
#include "CallFrame.h"
#include "Structure.h"

namespace JSC {

    class JSAPIValueWrapper : public JSCell {
        friend JSValue jsAPIValueWrapper(ExecState*, JSValue);
    public:
        JSValue value() const { return m_value.get(); }

        virtual bool isAPIValueWrapper() const { return true; }

        static Structure* createStructure(JSGlobalData& globalData, JSValue prototype)
        {
            return Structure::create(globalData, prototype, TypeInfo(CompoundType, OverridesVisitChildren | OverridesGetPropertyNames), AnonymousSlotCount, &s_info);
        }

    private:
        JSAPIValueWrapper(ExecState* exec, JSValue value)
            : JSCell(exec->globalData(), exec->globalData().apiWrapperStructure.get())
        {
            m_value.set(exec->globalData(), this, value);
            ASSERT(!value.isCell());
        }
        static const ClassInfo s_info;

        WriteBarrier<Unknown> m_value;
    };

    inline JSValue jsAPIValueWrapper(ExecState* exec, JSValue value)
    {
        return new (exec) JSAPIValueWrapper(exec, value);
    }

} // namespace JSC

#endif // JSAPIValueWrapper_h


text:
function solve() {
    function isValidName(str) {
        if (!/^[A-Z][a-z]*$/.test(str)) {
            throw new Error('error');
        }
    }
    function isValidTitle(str) {
        if (typeof str !== 'string' ||
            str.trim() == '' ||
            /^\s+/.test(str) ||
            /\s+$/.test(str) ||
            /\s{2,}/.test(str)) {
            throw new Error('error');
        }
    }
    function isValidPres(pres) {
        if (pres.length == 0) {
            throw new Error('error');
        }
        pres.forEach(function (title) {
            isValidTitle(title);
        });
    }
    function validScore(results) {
        results.forEach(function (item) {
            if (isNaN(item.score)) {
                throw new Error('error');
            }
        });
    }
    function validId(id, max) {
        if (id != Number(id) || id < 1 || id > max) {
            throw new Error('error');
        }

    }
    var Course = {

        init: function (title, presentations) {
            isValidTitle(title);
            this.title = title;
            isValidPres(presentations);
            this.presentations = presentations;
            this.students = [];
            return this;
        },
        addStudent: function (name) {

            var student,
                names = name.split(' ').trim(),
                id = (this.students.length + 1);
            if (names.length !== 2) {
                throw new Error('error');
            }
            isValidName(names[0]);
            isValidName(names[1]);
            student.firstname = names[0];
            student.lastname = names[1];
            student.id = id;
            student.score = 0;
            this.students.push(student);
            return id;
        },
        getAllStudents: function () {
            return this.students.slice(0);
        },
        submitHomework: function (studentID, homeworkID) {
            this.students.forEach(function (student) {
                validId(homeworkID, this.presentations.length);
                validId(studentID, this.students.length);
                if (student.id === studentID) {
                    student.homeworks++;
                }
            });
            return this;
        },
        pushExamResults: function (results) {
            var i, j, lenR = results.length, lenS = students.length;
            validScore(results);
            for (i = 0; i < lenR; i += 1) {
                for (j = 0; j < lenS; j++) {
                    validId(results[i].StudentID, this.students.length);
                    if (results[i].StudentID == this.students[j].id) {
                        if (this.students[j].score != 0) {
                            throw new Error('error');
                        }
                        else {
                            this.students[j].score = +results[i].score;
                        }
                    }
                    else {
                        throw new Error('error');
                    }

                }
            }
            //results.forEach(function (item) {
            //    if (item.StudentID == this.students[id]) {
            //        if (this.students[id].result!=0) {
            //            throw new Error('error');
            //        }
            //        else {
            //            this.students[id].score = item.score;
            //        }
            //    }
            //    else {
            //        throw new Error('error');
            //    }
            //});
            return this;
        },
        getTopStudents: function () {
            this.students.forEach(function (student) {
                student.totalScore = (25 * (student.homeworks / this.presentations.length)) + (0.75 * student.score);
            });
            var sorted = this.students.slice(0);
            sorted.sort(function (a, b) {
                return a.totalScore - b.totalScore;
            });
            return sorted.slice(0, 10);
        }
    };

    return Course;
}

module.exports = solve;


text:
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Options;
using static Microsoft.AspNetCore.Internal.LinkerFlags;

namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication;

internal sealed class DefaultRemoteApplicationPathsProvider<[DynamicallyAccessedMembers(JsonSerialized)] TProviderOptions> : IRemoteAuthenticationPathsProvider where TProviderOptions : class, new()
{
    private readonly IOptions<RemoteAuthenticationOptions<TProviderOptions>> _options;

    public DefaultRemoteApplicationPathsProvider(IOptionsSnapshot<RemoteAuthenticationOptions<TProviderOptions>> options)
    {
        _options = options;
    }

    public RemoteAuthenticationApplicationPathsOptions ApplicationPaths => _options.Value.AuthenticationPaths;
}


text:
from weakref import ref

class GcWeakrefs(object):
    def __init__(self, ffi):
        self.ffi = ffi
        self.data = {}

    def build(self, cdata, destructor):
        # make a new cdata of the same type as the original one
        new_cdata = self.ffi.cast(self.ffi._backend.typeof(cdata), cdata)
        #
        def remove(key):
            # careful, this function is not protected by any lock
            old_key = self.data.pop(index)
            assert old_key is key
            destructor(cdata)
        #
        key = ref(new_cdata, remove)
        index = object()
        self.data[index] = key
        return new_cdata


text:
import os
import json
import urllib.request
import mimetypes
from pathlib import Path
from distutils.dir_util import copy_tree

HTML_PAGE_HEADER = '<!DOCTYPE html> \n  \n  \
<title> Physical Web Exhibit </title>\
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/shoelace-css/1.0.0-beta13/shoelace.css"> \
 \
 '
HTML_PAGE_FOOTER = ' \
 \n '

def _decorate_h1(text):
    return "
" + text + "
"

def _decorate_subtitle(text):
    return "
 " + text + "
"

def _decorate_p(text):
    return "
" + text + "
"

def _decorate_unordered_list(items, item_names):
    result = []
    result.append("Beacons:")
    result.append("
")
    for item in items:
        result.append("
 {name}
"
            .format(address=item,
             name=find_beacon_name(item, item_names)))
    result.append("
")
    result = "".join(result)
    return result

def find_beacon_name(item, item_names):
    # reversed because latest name updates are appended to end
    for beacon in reversed(item_names):
        if beacon["address"] == item:
            return beacon["friendly-name"]
    return None

def _decorate_content(content):
    url = urllib.request.pathname2url(content)
    mimetype = mimetypes.guess_type(url)[0].lower()
    if mimetype.startswith("image/"):
        return _decorate_image_content(content)
    elif mimetype.startswith("audio/"):
        return _decorate_sound_content(content)
    elif mimetype.startswith("video/"):
        return _decorate_video_content(content)
    else:
        raise ValueError("Couldn't determine filetype: " + content)

def _decorate_image_content(image):
    return '\n'.format(image_url=image)

def _decorate_sound_content(sound):
    return '<audio class="margin-medium" controls src="{sound_url}"></audio>\n'.format(sound_url=sound)

def _decorate_video_content(video):
    return '<video class="margin-medium" controls src="{video_url}"></video>\n'.format(video_url=video)

def _build_index_page(website_metadata, beacon_friendly_names,
 public_folder):
    index_filename = "index.html"
    index_file = os.path.join(public_folder, index_filename)
    Path(index_file).touch(exist_ok=True)

    title = website_metadata["name"]
    subtitle = website_metadata["description"]
    beacons = []
    for beacon in website_metadata["beacons"]:
        beacons.append(beacon["address"])

    page = []
    page.append(HTML_PAGE_HEADER)
    page.append(_decorate_h1(title))
    page.append(_decorate_subtitle(subtitle))
    page.append(_decorate_unordered_list(beacons, beacon_friendly_names))
    page.append(HTML_PAGE_FOOTER)
    page = ''.join(page)

    with open(index_file, 'w') as f:
        f.write(page)

def _build_content_page(beacon, beacon_friendly_names, public_folder):
    content_filename = "index.html"
    content_file = os.path.join(public_folder, content_filename)
    Path(content_file).touch(exist_ok=True)

    title = find_beacon_name(beacon["address"], beacon_friendly_names)
    contents_html = []
    for content in beacon["contents"]:
        contents_html.append(_decorate_content(content))
    contents_html = ''.join(contents_html)

    page = []
    page.append(HTML_PAGE_HEADER)
    page.append(_decorate_h1(title))
    page.append(contents_html)
    page.append(HTML_PAGE_FOOTER)
    page = ''.join(page)

    with open(content_file, 'w') as f:
        f.write(page)

def _find_active_exhibit(exhibits_folder):
    metadata_file = os.path.join(exhibits_folder, 'metadata.json')
    with open(metadata_file) as data_file:
        id = json.load(data_file)["active-exhibit"]
    active_exhibit_folder = os.path.join(exhibits_folder, str(id))
    return active_exhibit_folder

def _find_beacon_friendly_names(exhibits_folder):
    metadata_file = os.path.join(exhibits_folder, 'metadata.json')
    with open(metadata_file) as data_file:
        return json.load(data_file)["beacon-names"]

def _fetch_metadata(content_folder):
    metadata_file = os.path.join(content_folder, 'metadata.json')
    with open(metadata_file) as data_file:
        return json.load(data_file)

def build_website(exhibits_folder, public_folder):
    print(" [i] Creating HTML")
    os.makedirs(public_folder, exist_ok=True)
    active_exhibit_folder = _find_active_exhibit(exhibits_folder)
    beacon_friendly_names = _find_beacon_friendly_names(exhibits_folder)
    copy_tree(active_exhibit_folder, public_folder)
    exhibit_metadata = _fetch_metadata(active_exhibit_folder)
    _build_index_page(exhibit_metadata, beacon_friendly_names, \
        public_folder)
    for beacon in exhibit_metadata["beacons"]:
        beacon_folder = os.path.join(public_folder, beacon["address"])
        _build_content_page(beacon, beacon_friendly_names, beacon_folder)
    print(" [✓] Website exported to " + os.path.abspath(public_folder))


text:
using System.Linq;
using System.Collections.Generic;
using AutoTest.TestRunners.Shared;
using AutoTest.TestRunners.Shared.Logging;
using AutoTest.TestRunners.Shared.AssemblyAnalysis;
using AutoTest.TestRunners.Shared.Results;
using AutoTest.TestRunners.Shared.Options;
using AutoTest.TestRunners.MSTest.Extensions;
using AutoTest.TestRunners.Shared.Communication;
using System;

namespace AutoTest.TestRunners.MSTest
{
    public class Runner : IAutoTestNetTestRunner
    {
        private ILogger _logger;
        private Func<string, IReflectionProvider> _reflectionProviderFactory = (assembly) => { return Reflect.On(assembly); };
        private ITestFeedbackProvider _channel = new NullTestFeedbackProvider();

        public string Identifier { get { return "MSTest"; } }

        public void SetLogger(ILogger logger)
        {
            _logger = logger;
        }

        public void SetReflectionProvider(Func<string, IReflectionProvider> reflectionProviderFactory)
        {
            _reflectionProviderFactory = reflectionProviderFactory;
        }

        public void SetLiveFeedbackChannel(ITestFeedbackProvider channel)
        {
            _channel = channel;
        }

        public bool IsTest(string assembly, string member)
        {
            using (var locator = _reflectionProviderFactory(assembly))
            {
                var parentType = locator.GetParentType(member);
                if (parentType == null)
                    return false;
                var parent = locator.LocateClass(parentType);
                if (parent == null)
                    return false;
                var method = locator.LocateMethod(member);
                if (method == null)
                    return false;
                return method.Attributes.Contains("Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute") &&
                    !method.IsAbstract &&
                    !parent.IsAbstract;
            }
        }

        public bool ContainsTestsFor(string assembly, string member)
        {
            using (var locator = _reflectionProviderFactory(assembly))
            {
                var cls = locator.LocateClass(member);
                if (cls == null)
                    return false;
                return !cls.IsAbstract && cls.Attributes.Contains("Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute");
            }
        }

        public bool ContainsTestsFor(string assembly)
        {
            using (var parser = _reflectionProviderFactory(assembly))
            {
                return parser.GetReferences().Count(x =>
                {
                    return
                        x.Name.Equals("Microsoft.VisualStudio.QualityTools.UnitTestFramework") ||
                        x.Name.Equals("Worst.Testing.Framework.Ever");
                }) > 0;
            }
        }

        public bool Handles(string identifier)
        {
            return Identifier.ToLower().Equals(identifier.ToLower());
        }

        public IEnumerable<TestResult> Run(RunSettings settings)
        {
            return new CelerRunner(_logger, _reflectionProviderFactory, _channel).Run(settings);
        }
    }
}


text:
package org.avmframework.variable;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class TestCharacterVariable {

  @Test
  public void testAsChar() {
    CharacterVariable charVar = CharacterVariable.createPrintableAsciiCharacterVariable('a');
    assertEquals(97, charVar.getValue());
    assertEquals('a', charVar.asChar());
  }
}


text:
.class final Lcom/android/server/location/GeofenceManager$GeofenceHandler;
.super Landroid/os/Handler;
.source "GeofenceManager.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/location/GeofenceManager;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x12
    name = "GeofenceHandler"
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/location/GeofenceManager;

# direct methods
.method public constructor <init>(Lcom/android/server/location/GeofenceManager;)V
    .locals 1
    .parameter

    .prologue
    .line 411
    iput-object p1, p0, Lcom/android/server/location/GeofenceManager$GeofenceHandler;->this$0:Lcom/android/server/location/GeofenceManager;

    .line 412
    const/4 v0, 0x1

    invoke-direct {p0, v0}, Landroid/os/Handler;-><init>(Z)V

    .line 413
    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 1
    .parameter "msg"

    .prologue
    .line 417
    iget v0, p1, Landroid/os/Message;->what:I

    packed-switch v0, :pswitch_data_0

    .line 423
    :goto_0
    return-void

    .line 419
    :pswitch_0
    iget-object v0, p0, Lcom/android/server/location/GeofenceManager$GeofenceHandler;->this$0:Lcom/android/server/location/GeofenceManager;

    #calls: Lcom/android/server/location/GeofenceManager;->updateFences()V
    invoke-static {v0}, Lcom/android/server/location/GeofenceManager;->access$000(Lcom/android/server/location/GeofenceManager;)V

    goto :goto_0

    .line 417
    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_0
    .end packed-switch
.end method


text:
<manifest package="jp.co.recruit_lifestyle.android.floatingview"
          xmlns:tools="http://schemas.android.com/tools">
    <uses-sdk tools:overrideLibrary="android.support.dynamicanimation" />
</manifest>


text:
matchingDict = {}

def matches(regex):
    def decorated(f):
        matchingDict[regex] = f
        return f
    return decorated


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Nest.Resolvers;
using Elasticsearch.Net.Serialization;

namespace Nest
{
	internal class IndicesMultiSyntaxJsonConverter : JsonConverter
	{
		public override bool CanConvert(Type objectType) => typeof(Indices) == objectType;

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var marker = value as Indices;
			if (marker == null)
			{
				writer.WriteNull();
				return;
			}
			marker.Match(
				all=> writer.WriteValue("_all"),
				many => writer.WriteValue(((IUrlParameter)marker).GetString(serializer.GetConnectionSettings()))
			);
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			if (reader.TokenType == JsonToken.String)
			{
				string indices = reader.Value.ToString();
				return (Indices)indices;
			}
			return null;
		}

	}
}


text:
import time

from django.test import TestCase
from django.utils import six
import mock
from oauth_tokens.factories import UserCredentialsFactory
import tweepy

from .api import api_call, TwitterApi, TwitterError
from .factories import UserFactory, StatusFactory
from .models import User, Status
from .parser import get_replies

STATUS_ID = 327926550815207424
USER_ID = 813286
USER_SCREEN_NAME = 'BarackObama'
USER1_ID = 18807761
USER1_SCREEN_NAME = 'voronezh'
STATUS_MANY_REPLIES_ID = 538755896063832064
STATUS_MANY_RETWEETS_ID = 329231054282055680

class TwitterApiTest(TestCase):

    def raise_rate_limit(*a, **kw):
        raise tweepy.TweepError([{u'message': u'Rate limit exceeded', u'code': 88}])

    def get_rate_limit_status(*a, **kw):
        return {u'rate_limit_context': {u'access_token': u''},
                u'resources': {
                    u'trends': {u'/trends/available': {u'limit': 15,
                                                       u'remaining': 0,
                                                       u'reset': time.time() + 100}}}}

    @mock.patch('tweepy.API.trends_available', side_effect=raise_rate_limit)
    @mock.patch('tweepy.API.rate_limit_status', side_effect=get_rate_limit_status)
    @mock.patch('twitter_api.api.TwitterApi.sleep_repeat_call')
    def test_rate_limit(self, sleep, rate_limit_status, trends_available):

        api_call('trends_available')

        self.assertTrue(trends_available.called)
        self.assertTrue(rate_limit_status.called)
        self.assertTrue(sleep.called)
        self.assertEqual(sleep.call_count, 1)
        self.assertGreater(sleep.call_args_list[0], 98)

    def test_user_screen_name_unique(self):

        # created user with unexisting pk
        user_wrong = UserFactory(pk=102732226, screen_name=USER_SCREEN_NAME)

        self.assertEqual(User.objects.count(), 1)
        self.assertEqual(User.objects.filter(pk=user_wrong.pk).count(), 1)

        user = User.remote.fetch(USER_SCREEN_NAME)

        self.assertEqual(User.objects.count(), 1)
        self.assertEqual(User.objects.filter(pk=user.pk).count(), 1)

    def test_request_error(self):

        with self.assertRaises(TwitterError):
            response = api_call('get_status')

    def test_api_instance_singleton(self):

        self.assertEqual(id(TwitterApi()), id(TwitterApi()))

    def test_request(self):

        response = api_call('get_status', STATUS_ID)
        self.assertEqual(response.text, '@mrshoranweyhey Thanks for the love! How about a follow for a follow? :) ^LF')
        self.assertEqual(response.source_url, 'http://www.exacttarget.com/social')

        response = api_call('get_user', USER_SCREEN_NAME)
        self.assertEqual(response.id, USER_ID)
        self.assertEqual(response.name, 'Barack Obama')

    def test_tweepy_properties(self):

        instance = User.remote.fetch(USER_ID)

        self.assertEqual(instance.screen_name, USER_SCREEN_NAME)
        self.assertIsInstance(instance.tweepy, tweepy.models.User)
        self.assertEqual(instance.tweepy.id_str, str(USER_ID))

    def test_fetch_negative_friends_count(self):

        user = User.remote.fetch(961050745)
        # problem with saving User id = 2577412818
        user.fetch_statuses(count=100)

    def test_fetch_status(self):

        self.assertEqual(Status.objects.count(), 0)

        instance = Status.remote.fetch(STATUS_ID)

        self.assertEqual(Status.objects.count(), 2)

        self.assertEqual(instance.id, STATUS_ID)
        self.assertEqual(instance.source, 'SocialEngage')
        self.assertEqual(instance.source_url, 'http://www.exacttarget.com/social')
        self.assertEqual(instance.text, '@mrshoranweyhey Thanks for the love! How about a follow for a follow? :) ^LF')
        self.assertEqual(instance.in_reply_to_status_id, 327912852486762497)
        self.assertEqual(instance.in_reply_to_user_id, 1323314442)
        self.assertEqual(instance.in_reply_to_status, Status.objects.get(id=327912852486762497))
        self.assertEqual(instance.in_reply_to_user, User.objects.get(id=1323314442))

    def test_fetch_user(self):

        instance = User.remote.fetch(USER_ID)

        self.assertEqual(instance.screen_name, USER_SCREEN_NAME)
        self.assertEqual(instance.id, USER_ID)
        self.assertEqual(instance.name, 'Barack Obama')
        self.assertEqual(instance.location, 'Washington, DC')
        self.assertEqual(instance.verified, True)
        self.assertEqual(instance.lang, 'en')
        self.assertGreater(instance.followers_count, 30886141)
        self.assertGreater(instance.friends_count, 600000)
        self.assertGreater(instance.listed_count, 192107)

        instance1 = User.remote.fetch(USER_SCREEN_NAME)
        self.assertEqual(instance.name, instance1.name)
        self.assertEqual(User.objects.count(), 1)

    def test_fetch_user_statuses(self):

        instance = UserFactory(id=USER_ID)

        self.assertEqual(Status.objects.count(), 0)

        instances = instance.fetch_statuses(count=30)

        self.assertEqual(len(instances), 30)
        self.assertEqual(len(instances), Status.objects.filter(author=instance).count())

        instances = instance.fetch_statuses(all=True, exclude_replies=True)

        self.assertGreater(len(instances), 3100)
        self.assertLess(len(instances), 4000)
        self.assertEqual(len(instances), Status.objects.filter(author=instance).count())

    def test_fetch_user_followers(self):

        instance = UserFactory(id=USER1_ID)

        self.assertEqual(User.objects.count(), 1)
        instances = instance.fetch_followers(all=True)
        self.assertGreater(len(instances), 870)
        self.assertLess(len(instances), 2000)
        self.assertIsInstance(instances[0], User)
        self.assertEqual(len(instances), User.objects.count() - 1)

    def test_fetch_user_followers_ids(self):

        instance = UserFactory(id=USER1_ID)

        self.assertEqual(User.objects.count(), 1)

        ids = instance.get_followers_ids(all=True)

        self.assertGreater(len(ids), 1000)
        self.assertLess(len(ids), 2000)
        self.assertIsInstance(ids[0], six.integer_types)
        self.assertEqual(User.objects.count(), 1)

    def test_fetch_status_retweets(self):

        instance = StatusFactory(id=STATUS_MANY_RETWEETS_ID)

        self.assertEqual(Status.objects.count(), 1)

        instances = instance.fetch_retweets()

        self.assertGreaterEqual(len(instances), 6)
        self.assertEqual(len(instances), Status.objects.count() - 1)

    def test_get_replies(self):
        """
            Check what ids[0] < ids[1] < ids[2] ...
            this also check what there is no duplicates
        """
        status = Status.remote.fetch(STATUS_MANY_REPLIES_ID)
        ids = get_replies(status)

        self.assertListEqual(ids, sorted(ids))
        self.assertEqual(len(ids), len(set(ids)))

    def test_status_fetch_replies(self):
        status = Status.remote.fetch(STATUS_MANY_REPLIES_ID)

        self.assertEqual(Status.objects.count(), 1)
        self.assertEqual(status.replies_count, None)

        replies = status.fetch_replies()

        self.assertGreater(replies.count(), 50)
        self.assertEqual(replies.count(), status.replies_count)
        self.assertEqual(replies.count(), Status.objects.count() - 1)

        self.assertEqual(replies[0].in_reply_to_status, status)

        status = Status.remote.fetch(STATUS_MANY_REPLIES_ID)
        self.assertEqual(replies.count(), status.replies_count)


text:
Are you looking to build a website that is easily updatable/maintainable? Do you hate Wordpress and other bloated website platforms? Do you understand that simple websites do not require the use of a SPA framework? Do you still want to needlessly optimize your site to the nth degree, and get a 100 on [Google PageSpeed](https://developers.google.com/speed/pagespeed/insights/)? Well this is the project for you.

You can see a working demo of this project [here](https://simple-website-demo.herokuapp.com/).

## Getting Started

So you're ready to build an awesome new website. Good, this is the place to be. This project helps you setup a site using Bootstrap 4, TypeScript, SASS, Handlebars, NodeJS/Express, Markdown, and a few optimizations for serving webp, AMP, bundling js/css, inlining js/css, and helping with SEO/Structured Data.

### Layout

The site has the following directories

-   `build`: Contains some build scripts for running the server
-   `public`: Where all the public assets go. Note that the CSS and JS folders will be created automatically by the build process.
-   `scss`: Where you put all your SASS files.
    -   `includes`: Used for global styles, bootstrap overrides, etc
    -   `layouts`: Used for main layout styles
    -   `partials`: Used for partial layout styles
-   `server`: Contains all the files necessary to run the server
    -   `blogs`: Put all your blog markdown here
    -   `config`: Stores global configuration for the server
    -   `helpers`: Stores handlebars helpers
    -   `log`: A simple logging utility class
    -   `middleware`: Has files for CORS, errors, setting meta context, serving webp, handling redirects, and parsing/compiling Handlebars files
    -   `routes`: Defines all the pages for the site
    -   `typings`: Adds some types to the project
    -   `utils`: Has utility methods and a caching class
-   `ts`: Where you put all your TS files.
    -   `layouts`: Used for TS scripts that can be included in many pages
    -   `partials`: Used for TS scripts that need only be included in specific pages
-   `views`: Where you put all your Handlebars files for your pages.
    -   `layouts`: Used for Handlebars layout pages
    -   `partials`: Used for Handlebars partials

### Features

Here are a few cool things this project is designed to do.

#### Webp

The express server can serve [webp](https://developers.google.com/speed/webp/) assets alongside pngs and jpgs. So in your html you might have `<img src="path/to/image.jpg">`, and if the server finds a file `path/to/image.webp` it will serve it instead.

#### AMP

This project comes with blog scaffolding for you, which includes an AMP template. If you run the project and go to any blog post, you can see the AMP version by visiting the blog `<url>/amp`.

#### Build Process

The build process includes a few custom scripts in the `build` directory. There is a `minify` script that will compile and minify TypeScript files and output to a public JS directory. There is also a `lib` build script that will build 3rd-party libraries for you and output to a `public/js/lib.js`. By default it builds bootstrap and its dependencies (jQuery, popper, etc). The last script is the `scss` script. This will compile your SASS files (in the `scss` directory) per-page. So you don't have to worry about including unnecessary css per page, and you also don't have issues with overriding styles.

#### Inlining Styles and Scripts

When this project was created, the intention was to perform all optimizations to make the site as fast as possible while allowing for ease of deployment. The express server is designed to allow you to declare styles and scripts that you with to inline with your HTML pages. If you put the following in a .hbs page:

```
<!-- Remove Script -->
<script src="/public/lib/lib.js"></script>
<!-- /Remove Script -->

<!-- Remove Style -->
<link rel="stylesheet" href="/public/css/about.css">
<!-- /Remove Style -->
```

There is a method that runs after the Handlebars page is rendered. It pulls out the scripts and styles, concatenates them, and then puts them in 1 style or script tag. After that it caches the pages to save some time with multiple requests. Of course there are times when you don't want to concatenate the styles/scripts. You can do so using an "ignore" attribute like so:

```
<link ignore="true" href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900" rel="stylesheet">
```

#### Read Time

There is a simple reading time calculator for blog posts, which can help entice users to read a post knowing that it should only take 3-5 minutes.

#### SEO

This project has example structured data that you can replace with your own properties. There is structured data for an [Organization](https://developers.google.com/search/docs/guides/intro-structured-data), [Breadscrumbs](https://developers.google.com/search/docs/data-types/breadcrumbs), and [Articles](https://developers.google.com/search/docs/data-types/articles). It's also designed to allow you to specify title, description, image, and video meta information for every page when you add a new route.

#### Markdown Front Matter

You will notice in `server/blogs` there are blog markdown files. They include some front matter that has information about the blog. The server interprets this and sets the right context when rendering a page.

### Prerequisites

The only requirements to build this project are Node and npm.

### Installing

Setting up this project is incredibly simple:

```
npm install
```

```
npm run lib
```

```
npm run dev
```

Then navigate to http://localhost:3000/ and see a sample mini-site built out for you.

**NOTE**: You only need to run `npm run lib` whenever you change the `lib.js` in `/build`, or when one of the libraries updates.

### Adding a Page

When you want to add a page, there are a couple things to do:

1. Create a new Handlebars file in `views`
1. Create a new route in `server/routes`
1. Add the route to the Express router in `server/routes/index.ts`

### Useful NPM Scripts

1. `build`: Builds everything (srver, client, lib, and sass)
1. `clean`: Cleans the compiled files
1. `dev`: Run this in dev mode, watches files and starts a dev server
1. `format`: Runs `prettier` to format all the TS files according to the `prettier.config.js`
1. `lint`: Runs `tslint` using the `tslint.json`, also uses some addons from `tslint-microsoft-contrib`
1. `start`: Starts node server

## Deployment

This site can be deployed on AWS, GCP, Azure, Heroku, etc. I didn't include any deployment instructions, so you will have to figure that part out on your own.

## Built With

-   [Express](http://expressjs.com/) - Used to render pages and serve assets
-   [Bootstrap 4](https://getbootstrap.com/) - Used for the easy layout, duh
-   [Handlebars](http://handlebarsjs.com/) - Used to render pages and apply simple context
-   [Remarkable](https://github.com/jonschlinkert/remarkable) - Used for markdown rendering on blog pages
-   [TypeScript](https://www.typescriptlang.org/) - Used to allow you to write simple scripts in TypeScript that will be included with your pages
-   [SASS](http://sass-lang.com/) - CSS precompiler

## Demo

You can see a working demo of this project [here](https://simple-website-demo.herokuapp.com/).

## Authors

-   **William Johnston** - _Initial work_ - [wjohnsto](https://github.com/wjohnsto)

## Contributors

-   **Jesse Li** - [veggiedefender](https://github.com/veggiedefender)

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details