text:
#ifndef HARP_INTERNAL_H
#define HARP_INTERNAL_H

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#define HARP_INTERNAL

#include "harp.h"
#include "harp-chemistry.h"
#include "harp-dimension-mask.h"
#include "harp-vertical-profiles.h"

#include "coda.h"

#include <stdarg.h>

/* make sure that math.h on Windows also includes the defines for e.g. M_PI */
#define _USE_MATH_DEFINES

/* This defines the amount of items that will be allocated per block for an auto-growing array (using realloc) */
#define BLOCK_SIZE 16

/* Maximum number of source variables that can be used to create derived variables */
#define MAX_NUM_SOURCE_VARIABLES 10

/* floating point precision */
#define EPSILON 1e-10

/* maximum length for file paths */
#define HARP_MAX_PATH_LENGTH 4096

/* clamp function */
#define HARP_CLAMP(var, min, max) if (var < min) var = min; if (var > max) var = max;

extern int harp_option_enable_aux_afgl86;
extern int harp_option_enable_aux_usstd76;

typedef int (*harp_conversion_function)(harp_variable *variable, const harp_variable **source_variable);
typedef int (*harp_conversion_enabled_function)(void);

typedef enum harp_collocation_filter_type_enum
{
    harp_collocation_left,
    harp_collocation_right
} harp_collocation_filter_type;

/* dimsvar_name is the variable name prefixed with HARP_MAX_NUM_DIMS characters defining the dimension types
 * dimsvar_name is thus the unique name for the combination of variable name + dimension types
 * the character code for a dimension type is:
 * 'I' = independent, 'T' = time, 'A' = latitude, 'O' = longitude, 'V' = vertical, 'S' = spectral
 * unused dimensions use a space character.
 */
typedef struct harp_source_variable_struct
{
    char *dimsvar_name;
    const char *variable_name;
    harp_data_type data_type;
    char *unit;
    int num_dimensions;
    harp_dimension_type dimension_type[HARP_MAX_NUM_DIMS];
    long independent_dimension_length;
} harp_source_variable_definition;

typedef struct harp_variable_conversion_struct
{
    char *dimsvar_name;
    const char *variable_name;
    harp_data_type data_type;
    char *unit;
    int num_dimensions;
    harp_dimension_type dimension_type[HARP_MAX_NUM_DIMS];
    long independent_dimension_length;
    int num_source_variables;
    harp_source_variable_definition *source_definition;
    char *source_description;
    harp_conversion_function set_variable_data;
    harp_conversion_enabled_function enabled;
} harp_variable_conversion;

typedef struct harp_variable_conversion_list_struct
{
    int num_conversions;
    harp_variable_conversion **conversion;
} harp_variable_conversion_list;

typedef struct harp_derived_variable_list_struct
{
    int num_variables;
    struct hashtable_struct *hash_data;
    harp_variable_conversion_list **conversions_for_variable;
} harp_derived_variable_list;

extern harp_derived_variable_list *harp_derived_variable_conversions;

/* Utility functions */
int harp_path_find_file(const char *searchpath, const char *filename, char **location);
int harp_path_from_path(const char *initialpath, int is_filepath, const char *appendpath, char **resultpath);
int harp_path_for_program(const char *argv0, char **location);
int harp_is_identifier(const char *name);
int harp_match_wildcard(const char *pattern, const char *name);
long harp_parse_double(const char *buffer, long buffer_length, double *dst, int ignore_trailing_bytes);
long harp_get_max_string_length(long num_strings, char **string_data);
int harp_get_char_array_from_string_array(long num_strings, char **string_data, long min_string_length,
                                          long *string_length, char **char_data);
long harp_get_num_elements(int num_dimensions, const long *dimension);
void harp_array_null(harp_data_type data_type, long num_elements, harp_array data);
void harp_array_replace_fill_value(harp_data_type data_type, long num_elements, harp_array data,
                                   harp_scalar fill_value);
int harp_array_invert(harp_data_type data_type, int dim_id, int num_dimensions, const long *dimension, harp_array data);
int harp_array_transpose(harp_data_type data_type, int num_dimensions, const long *dimension, const int *order,
                         harp_array data);

/* Auxiliary data sources */
int harp_aux_afgl86_get_profile(const char *name, double datetime, double latitude, int *num_vertical,
                                const double **values);
int harp_aux_usstd76_get_profile(const char *name, int *num_vertical, const double **values);

/* Error messaging */
#ifdef HAVE_HDF4
void harp_hdf4_add_error_message(void);
#endif
#ifdef HAVE_HDF5
void harp_hdf5_add_error_message(void);
#endif
void harp_add_coda_cursor_path_to_error_message(const coda_cursor *cursor);

/* Variables */
int harp_variable_get_flag_values_string(const harp_variable *variable, char **flag_values);
int harp_variable_get_flag_meanings_string(const harp_variable *variable, char **flag_meanings);
int harp_variable_set_enumeration_values_using_flag_meanings(harp_variable *variable, const char *flag_meanings);
int harp_variable_add_dimension(harp_variable *variable, int dim_index, harp_dimension_type dimension_type,
                                long length);
int harp_variable_rearrange_dimension(harp_variable *variable, int dim_index, long num_dim_elements,
                                      const long *dim_element_ids);
int harp_variable_filter_dimension(harp_variable *variable, int dim_index, const uint8_t *mask);
int harp_variable_resize_dimension(harp_variable *variable, int dim_index, long length);
int harp_variable_remove_dimension(harp_variable *variable, int dim_index, long index);
int harp_variable_squash_dimension(harp_variable *variable, int dim_index);

/* Products */
int harp_product_rearrange_dimension(harp_product *product, harp_dimension_type dimension_type, long num_dim_elements,
                                     const long *dim_element_ids);
int harp_product_filter_by_index(harp_product *product, const char *index_variable, long num_elements, int32_t *index);
int harp_product_filter_dimension(harp_product *product, harp_dimension_type dimension_type, const uint8_t *mask);
int harp_product_remove_dimension(harp_product *product, harp_dimension_type dimension_type);
void harp_product_remove_all_variables(harp_product *product);
int harp_product_get_datetime_range(const harp_product *product, double *datetime_start, double *datetime_stop);
int harp_product_get_derived_bounds_for_grid(harp_product *product, harp_variable *grid, harp_variable **bounds);
int harp_product_get_storage_size(const harp_product *product, int with_attributes, int64_t *size);
int harp_product_bin_full(harp_product *product);
int harp_product_bin_spatial_full(harp_product *product, long num_latitude_edges, double *latitude_edges,
                                  long num_longitude_edges, double *longitude_edges);
int harp_product_bin_with_collocated_dataset(harp_product *product, harp_collocation_result *collocation_result);
int harp_product_bin_with_variable(harp_product *product, int num_variables, const char **variable_name);
int harp_product_clamp_dimension(harp_product *product, harp_dimension_type dimension_type,
                                 const char *grid_variable_name, const char *unit, double lower_bound,
                                 double upper_bound);

/* Import */
#ifdef HAVE_HDF4
int harp_import_hdf4(const char *filename, harp_product **product);
#endif
#ifdef HAVE_HDF5
int harp_import_hdf5(const char *filename, harp_product **product);
#endif
int harp_import_netcdf(const char *filename, harp_product **product);

#ifdef HAVE_HDF4
int harp_export_hdf4(const char *filename, const harp_product *product);
#endif
#ifdef HAVE_HDF5
int harp_export_hdf5(const char *filename, const harp_product *product);
#endif
int harp_export_netcdf(const char *filename, const harp_product *product);

#ifdef HAVE_HDF4
int harp_import_metadata_hdf4(const char *filename, harp_product_metadata *metadata);
#endif
#ifdef HAVE_HDF5
int harp_import_metadata_hdf5(const char *filename, harp_product_metadata *metadata);
#endif
int harp_import_metadata_netcdf(const char *filename, harp_product_metadata *metadata);
int harp_parse_file_convention(const char *str, int *major, int *minor);

/* Ingest */
int harp_ingest(const char *filename, const char *operations, const char *options, harp_product **product);
int harp_ingest_test(const char *filename, int (*print)(const char *, ...));
int harp_ingest_metadata(const char *filename, const char *options, harp_product_metadata *metadata);
void harp_ingestion_done(void);

/* Units */
typedef struct harp_unit_converter_struct harp_unit_converter;
int harp_unit_converter_new(const char *from_unit, const char *to_unit, harp_unit_converter **new_unit_converter);
void harp_unit_converter_delete(harp_unit_converter *unit_converter);
double harp_unit_converter_convert(const harp_unit_converter *unit_converter, double value);
int harp_unit_compare(const char *unit_a, const char *unit_b);
int harp_unit_is_valid(const char *str);
void harp_unit_done(void);

/* Variable conversions */
int harp_variable_conversion_new(const char *variable_name, harp_data_type data_type, const char *unit,
                                 int num_dimensions, harp_dimension_type *dimension_type,
                                 long independent_dimension_length, harp_conversion_function get_variable,
                                 harp_variable_conversion **new_conversion);
int harp_variable_conversion_add_source(harp_variable_conversion *conversion, const char *variable_name,
                                        harp_data_type data_type, const char *unit, int num_dimensions,
                                        harp_dimension_type *dimension_type, long independent_dimension_length);
int harp_variable_conversion_set_enabled_function(harp_variable_conversion *conversion,
                                                  harp_conversion_enabled_function enabled);
int harp_variable_conversion_set_source_description(harp_variable_conversion *conversion, const char *description);
void harp_variable_conversion_delete(harp_variable_conversion *conversion);

/* Derived variables */
int harp_derived_variable_list_init(void);
int harp_derived_variable_list_add_conversion(harp_variable_conversion *conversion);
void harp_derived_variable_list_done(void);

/* Analysis functions */
double harp_angstrom_exponent_from_aod(long num_wavelengths, const double *wavelength, const double *aod);

double harp_fraction_of_day_from_datetime(double datetime);
double harp_fraction_of_year_from_datetime(double datetime);

double harp_frequency_from_wavelength(double wavelength);
double harp_frequency_from_wavenumber(double wavenumber);
double harp_gravity_from_latitude_and_altitude(double latitude, double altitude);
double harp_local_curvature_radius_at_surface_from_latitude(double latitude);
double harp_normal_gravity_from_latitude(double latitude);
double harp_normalized_radiance_from_radiance_and_solar_irradiance(double radiance, double solar_irradiance);
double harp_normalized_radiance_from_reflectance_and_solar_zenith_angle(double reflectance, double solar_zenith_angle);

double harp_ocean_frequency_from_ocean_period(double ocean_period);
double harp_ocean_frequency_from_ocean_wavelength(double ocean_wavelength);
double harp_ocean_frequency_from_ocean_wavenumber(double ocean_wavenumber);
double harp_ocean_period_from_ocean_frequency(double ocean_frequency);
double harp_ocean_period_from_ocean_wavelength(double ocean_wavelength);
double harp_ocean_period_from_ocean_wavenumber(double ocean_wavenumber);
double harp_ocean_wavelength_from_ocean_frequency(double ocean_frequency);
double harp_ocean_wavelength_from_ocean_period(double ocean_period);
double harp_ocean_wavelength_from_ocean_wavenumber(double ocean_wavenumber);
double harp_ocean_wavenumber_from_ocean_frequency(double ocean_frequency);
double harp_ocean_wavenumber_from_ocean_period(double ocean_period);
double harp_ocean_wavenumber_from_ocean_wavelength(double ocean_wavelength);

double harp_radiance_from_normalized_radiance_and_solar_irradiance(double normalized_radiance, double solar_irradiance);
double harp_radiance_from_reflectance_solar_irradiance_and_solar_zenith_angle(double reflectance,
                                                                              double solar_irradiance,
                                                                              double solar_zenith_angle);
double harp_reflectance_from_radiance_solar_irradiance_and_solar_zenith_angle(double radiance, double solar_irradiance,
                                                                              double solar_zenith_angle);
double harp_reflectance_from_normalized_radiance_and_solar_zenith_angle(double normalized_radiance,
                                                                        double solar_zenith_angle);
double harp_scattering_angle_from_sensor_and_solar_angles(double sensor_zenith_angle, double solar_zenith_angle,
                                                          double relative_azimuth_angle);
double harp_sea_surface_temperature_skin_from_subskin_wind_speed_and_solar_zenith_angle(double sst_skin,
                                                                                double wind_speed,
                                                                                double solar_zenith_angle);
double harp_sea_surface_temperature_subskin_from_skin_wind_speed_and_solar_zenith_angle(double sst_skin,
                                                                                double wind_speed,
                                                                                double solar_zenith_angle);
double harp_solar_azimuth_angle_from_latitude_and_solar_angles(double latitude, double solar_declination_angle,
                                                               double solar_hour_angle, double solar_zenith_angle);
double harp_solar_declination_angle_from_datetime(double datetime);
double harp_solar_hour_angle_from_datetime_and_longitude(double datetime, double longitude);
double harp_solar_zenith_angle_from_latitude_and_solar_angles(double latitude, double solar_declination_angle,
                                                              double solar_hour_angle);
double harp_relative_azimuth_angle_from_sensor_and_solar_azimuth_angles(double sensor_azimuth_angle,
                                                                        double solar_azimuth_angle);
double harp_elevation_angle_from_zenith_angle(double zenith_angle);
double harp_zenith_angle_from_elevation_angle(double elevation_angle);
double harp_sensor_angle_from_viewing_angle(double viewing_angle);
double harp_viewing_angle_from_sensor_angle(double sensor_angle);
int harp_sensor_geometry_angles_at_altitude_from_other_altitude(double source_altitude,
                                                                double source_solar_zenith_angle,
                                                                double source_sensor_zenith_angle,
                                                                double source_relative_azimuth_angle,
                                                                double target_altitude,
                                                                double *new_target_solar_zenith_angle,
                                                                double *new_target_sensor_zenith_angle,
                                                                double *new_target_relative_azimuth_angle);
int harp_sensor_geometry_angle_profiles_from_sensor_geometry_angles(double altitude,
                                                                    double solar_zenith_angle,
                                                                    double sensor_zenith_angle,
                                                                    double relative_azimuth_angle,
                                                                    long num_levels,
                                                                    const double *altitude_profile,
                                                                    double *solar_zenith_angle_profile,
                                                                    double *sensor_zenith_angle_profile,
                                                                    double *relative_azimuth_angle_profile);
double harp_wavelength_from_frequency(double frequency);
double harp_wavelength_from_wavenumber(double wavenumber);
double harp_wavenumber_from_frequency(double frequency);
double harp_wavenumber_from_wavelength(double wavelength);
double harp_wrap(double value, double min, double max);

/* Interpolation */
void harp_interpolate_find_index(long source_length, const double *source_grid, double target_grid_point, long *index);
int harp_cubic_spline_interpolation(const double *xx, const double *yy, long n, const double xp, double *new_yp);
int harp_bicubic_spline_interpolation(const double *xx, const double *yy, const double **zz, long m, long n,
                                      double xp, double yp, double *new_zp);
void harp_interpolate_value_linear(long source_length, const double *source_grid, const double *source_array,
                                   double target_grid_point, int out_of_bound_flag, double *target_value);
void harp_interpolate_array_linear(long source_length, const double *source_grid, const double *source_array,
                                   long target_length, const double *target_grid, int out_of_bound_flag,
                                   double *target_array);
void harp_interpolate_value_loglinear(long source_length, const double *source_grid, const double *source_array,
                                      double target_grid_point, int out_of_bound_flag, double *target_value);
void harp_interpolate_array_loglinear(long source_length, const double *source_grid, const double *source_array,
                                      long target_length, const double *target_grid, int out_of_bound_flag,
                                      double *target_array);
void harp_interpolate_value_logloglinear(long source_length, const double *source_grid, const double *source_array,
                                         double target_grid_point, int out_of_bound_flag, double *target_value);
void harp_interpolate_array_logloglinear(long source_length, const double *source_grid, const double *source_array,
                                         long target_length, const double *target_grid, int out_of_bound_flag,
                                         double *target_array);
void harp_interval_interpolate_array_linear(long source_length, const double *source_grid_boundaries,
                                            const double *source_array, long target_length,
                                            const double *target_grid_boundaries, double *target_array);
void harp_bounds_from_midpoints_linear(long num_midpoints, const double *midpoints, int extrapolate, double *intervals);
void harp_bounds_from_midpoints_loglinear(long num_midpoints, const double *midpoints, int extrapolate,
                                          double *intervals);

/* Collocation */
int harp_collocation_result_read_range(const char *collocation_result_filename, long min_collocation_index,
                                       long max_collocation_index, const char *source_product_a,
                                       const char *source_product_b, harp_collocation_result **new_collocation_result);
int harp_collocation_result_shallow_copy(const harp_collocation_result *collocation_result,
                                         harp_collocation_result **new_result);
void harp_collocation_result_shallow_delete(harp_collocation_result *collocation_result);

int harp_collocation_result_get_filtered_product_b(harp_collocation_result *collocation_result,
                                                   const char *source_product, harp_product **product);

#endif


text:
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>

/**
 * Create NS_ENUM macro if it does not exist on the targeted version of iOS or OS X.
 *
 * @see http://nshipster.com/ns_enum-ns_options/
 **/
#ifndef NS_ENUM
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#endif

extern NSString *const kReachabilityUtilChangedNotification;

typedef NS_ENUM(NSInteger, NetworkStatus) {
    // Apple NetworkStatus Compatible Names.
    NotReachable = 0,
    ReachableViaWiFi = 2,
    ReachableViaWWAN = 1
};

@class ReachabilityUtil;

typedef void (^NetworkReachable)(ReachabilityUtil * reachability);
typedef void (^NetworkUnreachable)(ReachabilityUtil * reachability);

@interface ReachabilityUtil : NSObject

@property (nonatomic, copy) NetworkReachable    reachableBlock;
@property (nonatomic, copy) NetworkUnreachable  unreachableBlock;

@property (nonatomic, assign) BOOL reachableOnWWAN;

+(ReachabilityUtil*)reachabilityUtilWithHostname:(NSString*)hostname;
// This is identical to the function above, but is here to maintain
//compatibility with Apples original code. (see .m)
+(ReachabilityUtil*)reachabilityUtilWithHostName:(NSString*)hostname;
+(ReachabilityUtil*)reachabilityUtilForInternetConnection;
+(ReachabilityUtil*)reachabilityUtilWithAddress:(void *)hostAddress;
+(ReachabilityUtil*)reachabilityUtilForLocalWiFi;

-(ReachabilityUtil *)initWithReachabilityRef:(SCNetworkReachabilityRef)ref;

-(BOOL)startNotifier;
-(void)stopNotifier;

-(BOOL)isReachable;
-(BOOL)isReachableViaWWAN;
-(BOOL)isReachableViaWiFi;

// WWAN may be available, but not active until a connection has been established.
// WiFi may require a connection for VPN on Demand.
-(BOOL)isConnectionRequired; // Identical DDG variant.
-(BOOL)connectionRequired; // Apple's routine.
// Dynamic, on demand connection?
-(BOOL)isConnectionOnDemand;
// Is user intervention required?
-(BOOL)isInterventionRequired;

-(NetworkStatus)currentReachabilityStatus;
-(SCNetworkReachabilityFlags)reachabilityFlags;
-(NSString*)currentReachabilityString;
-(NSString*)currentReachabilityFlags;

@end

redpajama_set_name: RedPajamaGithub


text:
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license

<https://opensource.org/licenses/BSD-3-Clause>
"""
import os
import datetime
import re
import json
import logging
import urllib
from scrapy import Selector
from cameo.utility import Utility
from crawlermaster.cmparser import CmParser
from cameo.cmConverter.converterFor36KR import ConverterFor36KR
"""
從 source_html 的 HTML 檔案解析資料
結果放置於 parsed_result 下
"""
class ParserFor36KR:
    #建構子
    def __init__(self):
        self.utility = Utility()
        self.dicSubCommandHandler = {
            "json":[self.parseNewsPageThenCreateNewsJson]
        }
        self.strWebsiteDomain = u"http://36kr.com/"
        self.SOURCE_HTML_BASE_FOLDER_PATH = u"cameo_res\\source_html"
        self.PARSED_RESULT_BASE_FOLDER_PATH = u"cameo_res\\parsed_result"
        self.intNewsJsonNum = 0 #news.json 檔案編號
        self.intMaxNewsPerNewsJsonFile = 1000 #每個 news.json 儲存的 news 之最大數量
        self.dicParsedResultOfNews = [] #news.json 資料

    #取得 parser 使用資訊
    def getUseageMessage(self):
        return (
            "- 36KR -\n"
            "useage:\n"
            "json - parse news.html then create json \n"
        )

    #執行 parser
    def runParser(self, lstSubcommand=None):
        strSubcommand = lstSubcommand[0]
        strArg1 = None
        if len(lstSubcommand) == 2:
            strArg1 = lstSubcommand[1]
        for handler in self.dicSubCommandHandler[strSubcommand]:
            handler(strArg1)

    #解析 news.html 產生 news.json (TODO 使用 crawlermaster 進行 parse)
    def parseNewsPageThenCreateNewsJson(self, uselessArg1=None):
        strNewsResultFolderPath = self.PARSED_RESULT_BASE_FOLDER_PATH + u"\\36KR\\news"
        if not os.path.exists(strNewsResultFolderPath):
            os.mkdir(strNewsResultFolderPath) #mkdir parsed_result/36KR/news/
        strNewsHtmlFolderPath = self.SOURCE_HTML_BASE_FOLDER_PATH + u"\\36KR\\news"
        strCssJsonFilePath = "cameo_res\\selector_rule\\36kr_csslist.json"
        cmParser = CmParser(strCssJsonFilePath=strCssJsonFilePath)
        rawDataConverter = ConverterFor36KR()
        intNewsJsonIndex = 1
        lstDicNewsRawData = cmParser.localHtmlFileParse(isIterable=True, isResetIteration=True)
        while len(lstDicNewsRawData)>0:
            strNewsJsonFilePath = strNewsResultFolderPath + u"\\%d_news.json"%(intNewsJsonIndex*1000)
            rawDataConverter.convert(lstDicNewsRawData=lstDicNewsRawData, strNewsJsonFilePath=strNewsJsonFilePath)
            intNewsJsonIndex = intNewsJsonIndex+1
            lstDicNewsRawData = cmParser.localHtmlFileParse(isIterable=True)


text:
{% extends "common/base.html" %}
{% load tags %}

{% block styles %}
<link rel="stylesheet" href="{% static_url "css/static.css" %}">
<link rel="stylesheet" href="{% static_url "css/forms.css" %}">
<link rel="stylesheet" href="{% static_url "css/error.css" %}">
{% endblock %}

{% block meta %}
{% include "common/meta.html" %}
{% endblock %}

{% block content %}
{% include "util/form_header.html" %}

Sorry, an error has occured

            <input type="text" id="errorsearchbar" name="text" class="placeholder" placeholder="Find Projects, Issues and Supporters" />
            <input type="submit" class="button" value="Go" />

    « go back to the previous page
    go to your homepage »

            If you reached this page because of a problem, please report a bug.

            Thanks,

            The Jumo Team

{% endblock %}


text:
module Spree::Chimpy
  module Interface
    class Orders
      delegate :log, to: Spree::Chimpy

      def initialize
        @api = Spree::Chimpy.api
      end

      def add(order)
        log "Adding order #{order.number}"
        order_hash = hash(order)
        if order_hash[:items].present?

          response = safe_add(order, order_hash)

          if !response.nil? and response["complete"]
            log "Order #{order.number} added successfully!"
            true
          else
            Rails.logger.error "Order #{order.number} not added!"
            false
          end

        else
          log "Order #{order.number} did not have any valid lines!"
        end
      end

      def remove(order)
        log "Attempting to remove order #{order.number}"

        response = @api.ecomm.order_del(Spree::Chimpy::Config.store_id, order.number)
        log "Order #{order.number} removed successfully!" if response["complete"]
        response["complete"]
      end

      def sync(order)
        remove(order) rescue nil
        add(order)
      end

    private

      def safe_add(order, order_hash)
        response = nil
        begin
          response = @api.ecomm.order_add(order_hash)
        rescue Mailchimp::InvalidEcommOrderError => e
          if e.message.match(/Order Id \"#{order.number}\" has already been recorded/)
            Rails.logger.error "Order #{order.number} was not added as it has already been recorded!"
          else
            raise e
          end
        end
        response
      end

      def hash(order)
        source = order.source

        items = order.line_items.map do |line|
          variant = line.variant
          product = variant.product

          {
             product_id:    variant.id,
             sku:           variant.sku,
             product_name:  variant.name,
             category_id:   product.marketing_type.id,
             category_name: product.marketing_type.name,
             cost:          to_usd(line.base_price.to_f, line.currency),
             qty:           line.quantity
           }
        end

        data = {
          id:          order.number,
          email:       order.email,
          total:       to_usd(order.total.to_f, order.currency),
          order_date:  order.completed_at.strftime('%Y-%m-%d'),
          shipping:    to_usd(order.ship_total.to_f, order.currency),
          tax:         to_usd(order.display_tax_total.money.to_f, order.currency),
          store_name:  Spree::Chimpy::Config.store_id.titleize,
          store_id:    Spree::Chimpy::Config.store_id,
          items:       items
        }

        if source
          data[:email_id]    = source.email_id
          data[:campaign_id] = source.campaign_id
        end

        data
      end

      def to_usd(price, currency, quantity = 1)
        return 0 unless price
        rates = Spree::Chimpy::Config.to_usd_rates
        (quantity * price  * rates[currency]).to_f
      end
    end
  end
end


text:
from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI
from pySDC.implementations.problem_classes.HeatEquation_1D_FEniCS_weak_forced import fenics_heat_weak_imex
from pySDC.implementations.sweeper_classes.imex_1st_order import imex_1st_order
from pySDC.implementations.transfer_classes.TransferFenicsMesh import mesh_to_mesh_fenics

if __name__ == "__main__":
    num_procs = 1

    t0 = 0
    dt = 0.2
    Tend = 1.0

    # initialize level parameters
    level_params = dict()
    level_params['restol'] = 5e-12
    level_params['dt'] = dt

    # initialize step parameters
    step_params = dict()
    step_params['maxiter'] = 50

    # initialize sweeper parameters
    sweeper_params = dict()
    sweeper_params['quad_type'] = 'RADAU-RIGHT'
    sweeper_params['num_nodes'] = [3]

    problem_params = dict()
    problem_params['nu'] = 0.1
    problem_params['t0'] = t0  # ugly, but necessary to set up ProblemClass
    problem_params['c_nvars'] = [128]
    problem_params['family'] = 'CG'
    problem_params['order'] = [4]
    problem_params['refinements'] = [0]

    # initialize controller parameters
    controller_params = dict()
    controller_params['logger_level'] = 20

    base_transfer_params = dict()
    base_transfer_params['finter'] = True

    # Fill description dictionary for easy hierarchy creation
    description = dict()
    description['problem_class'] = fenics_heat_weak_imex
    description['problem_params'] = problem_params
    description['sweeper_class'] = imex_1st_order  # pass sweeper (see part B)
    description['sweeper_params'] = sweeper_params  # pass sweeper parameters
    description['level_params'] = level_params  # pass level parameters
    description['step_params'] = step_params  # pass step parameters
    description['space_transfer_class'] = mesh_to_mesh_fenics  # pass spatial transfer class
    description['base_transfer_params'] = base_transfer_params  # pass paramters for spatial transfer

    # quickly generate block of steps
    controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description)

    # get initial values on finest level
    P = controller.MS[0].levels[0].prob
    uinit = P.u_exact(t0)

    # call main function to get things done...
    uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend)

    # compute exact solution and compare
    uex = P.u_exact(Tend)

    print('(classical) error at time %s: %s' % (Tend, abs(uex - uend) / abs(uex)))


text:
<?php

/**
 * @author   Chuck Hagenbuch <chuck@horde.org>
 * @license  http://opensource.org/licenses/bsd-license.php BSD
 * @category Horde
 * @package  Horde_Http_Client
 */
class Horde_Http_Client_Response
{
    /**
     * Fetched URI
     * @var string
     */
    public $uri;

    /**
     * HTTP protocol version that was used
     * @var float
     */
    public $httpVersion;

    /**
     * HTTP response code
     * @var integer
     */
    public $code;

    /**
     * Response headers
     * @var array
     */
    public $headers;

    /**
     * Response body
     * @var stream
     */
    protected $_stream;

    /**
     * Constructor
     */
    public function __construct($uri, $stream, $headers = array())
    {
        $this->uri = $uri;
        $this->_stream = $stream;
        $this->_parseHeaders($headers);
    }

    /**
     * Parse an array of response headers, mindful of line
     * continuations, etc.
     *
     * @param array $headers
     * @return array
     */
    protected function _parseHeaders($headers)
    {
        $lastHeader = null;
        foreach ($headers as $headerLine) {
            // stream_get_meta returns all headers generated while processing a
            // request, including ones for redirects before an eventually successful
            // request. We just want the last one, so whenever we hit a new HTTP
            // header, throw out anything parsed previously and start over.
            if (preg_match('/^HTTP\/(\d.\d) (\d{3})/', $headerLine, $httpMatches)) {
                $this->httpVersion = $httpMatches[1];
                $this->code = (int)$httpMatches[2];
                $this->headers = array();
                $lastHeader = null;
            }

            $headerLine = trim($headerLine, "\r\n");
            if ($headerLine == '') {
                break;
            }
            if (preg_match('|^([\w-]+):\s+(.+)|', $headerLine, $m)) {
                unset($lastHeader);
                $headerName = strtolower($m[1]);
                $headerValue = $m[2];

                if (isset($this->headers[$headerName])) {
                    if (!is_array($this->headers[$headerName])) {
                        $this->headers[$headerName] = array($this->headers[$headerName]);
                    }

                    $this->headers[$headerName][] = $headerValue;
                } else {
                    $this->headers[$headerName] = $headerValue;
                }
                $lastHeader = $headerName;
            } elseif (preg_match("|^\s+(.+)$|", $headerLine, $m) && !is_null($lastHeader)) {
                if (is_array($this->headers[$lastHeader])) {
                    end($this->headers[$lastHeader]);
                    $this->headers[$lastHeader][key($this->headers[$lastHeader])] .= $m[1];
                } else {
                    $this->headers[$lastHeader] .= $m[1];
                }
            }
        }
    }

    /**
     * Return the body of the HTTP response.
     *
     * @return string HTTP response body.
     */
    public function getBody()
    {
        $content = @stream_get_contents($this->_stream);
        if ($content === false) {
            throw new Horde_Http_Client_Exception('Problem reading data from ' . $this->uri . ': ' . $php_errormsg);
        }
        return $content;
    }

    /**
     * Return a stream pointing to the response body that can be used
     * with all standard PHP stream functions.
     */
    public function getStream()
    {
        return $this->_stream;
    }

    /**
     * Get the value of a single response header.
     *
     * @param string $header Header name to get ('Content-Type', 'Content-Length', etc.). This is case sensitive.
     *
     * @return string HTTP header value.
     */
    public function getHeader($header)
    {
        return isset($this->headers[$header]) ? $this->headers[$header] : null;
    }

}


text:
In a lot of cases people will run Fabric8 inside an environment with limited or no access at all to the internet.
The fabric-agent will still need to download artifacts from somewhere. Forcing the users to use a 3rd party maven repository manager doesn't seem like a good idea.
So Fabric8 provides a lightweight maven repository manager that provides the ability of uploading & downloading maven artifacts inside a fabric.

### Installation

When creating a new fabric using commands like:

      fabric:create

the container will automatically install the fabric-maven-proxy feature on the current container. Additionally, the user can have a fabric-maven-proxy run on additional containers by adding the fabric-maven-porxy feature in one of their profiles. By default this feature is part of the fabric profile.

### Discovery

To avoid having the fabric-maven-proxy as a single point of failure fabric can discover & use any fabric-maven-proxy that is running inside the fabric cluster. Each container running the fabric-maven-proxy will register it in the runtime registry and the fabric-agent will be able to discover it from there.
When having multiple fabric-maven-proxies running, the fabric-agent will use them in the same order that were added in the runtime registry.

### Configuration
Out of the box any fabric-maven-proxy will make use of a default set of remote and local repositories.

#### Local repository
Local repository is a read-write repository, which takes priority over the remote repositories. Any artifact lookup, will first use the local repository and if the target artifact is not found the remote repositories will be used.
Moreover, any artifact that was found in the remote repositories it will be also copied to the local repository.

The default local repository is the users maven repository is data/maven/proxy/downloads under the installation directory.

#### Remote repositories
Any read-only repository can be configured as remote repository.

#### Configuring repositories
Both remote and local repositories can be configured using the io.fabric8.maven pid. That configuration accepts two properties:

*localRepository*  The path to the local repository, defaults to data/maven/proxy/downloads

*remoteRepositories* The remote repositories as a comma separated list.

Here is an example of how you can change the local repository for a single fabric-maven-proxy.

      config:propset --pid io.fabric8.maven localRepository /path/to/my/repo myprofile

Fabric maven proxies that are running on managed containers, are configured via fabric profiles. So this would look like:

      fabric:profile-edit --pid io.fabric8.maven/localRepository=/path/to/my/repo myprofile

In the last example there are two things that you need to take into consideration. The firs thing is that not necessarily all containers are managed.
The second is that not all containers running the fabric-maven-proxy use necessarily the same profiles, so its best to make the change in the profile that is the least common denominator *(e.g the default profile)*.

### Deploying artifacts to a fabric-maven-proxy

As already mentioned above, the fabric-maven-proxy allows you to deploy artifacts to it, so that it can be used for provisioning.
Assuming that the fabric-maven-proxy is running on *exampleHost*, the http url for uploading will be *http://username:password@exampleHost:8181/maven/upload*.
The username and password are the credentials of any user with the admin role. Note that the role is also configurable inside the io.fabric8.maven pid.

#### Use the fabric-maven-proxy with mvn from the shell

You can specify the url to the fabric-maven-proxy directly from the shell for deploying any maven project to the project.

      mvn deploy -DaltDeploymentRepository=http://username:password@exampleHost:8181/maven/upload

an alternative for deploying a single file as a maven artifact:

      mvn deploy:deploy-file -Dfile=/path/to/target/file.jar -DartifactId=myartifactId -DgroupId=mygroupId -Dversion=1.0.0 -Dtype=jar  -Durl=http://username:password@exampleHost:8181/maven/upload

#### Configure the fabric-maven-proxy in the user maven settings.xml

To avoid using the fabric-maven-proxy url each time you want to deploy an artifact to fabric, you can configure the fabric-maven-proxy inside the maven ```settings.xml``` file.

The first step is to add inside the maven project a distribution management element that will point to the fabric-maven-proxy.

    <distributionManagement>
     <repository>
        <id>my-fabric-maven-proxy</id>
        <name>Fabric Maven Proxy</name>
        <url>http://exampleHost:8181/maven/upload</url>
      </repository>
    </distributionManagement>

The second step is to configure maven by with the credentials for the maven proxy, by adding a new server element in the settings.xml

    <server>
        <id>my-fabric-maven-proxy-id</id>
        <username>username</username>
        <password>username</password>
    </server>

### Integrating with 3rd party maven repository managers

If it hasn't been clear yet, you can integrate with a 3rd party maven repository manager either by adding them to the list of repositories in the fabric-agent configuration, or by adding them in the list of remote repositories of the fabric-maven-proxy.

The question is when to do go by the first approach and when to go by the second approach.

The actual difference in the two approaches is that the fabric-maven-proxy will store any artifact it fetches from remote repos to its local repository. Future requests for that such artifacts will be served using the local repository.
If retrieving artifacts from the 3rd party repository manager is an expensive operation, then you definitely need to use the fabric-maven-proxy, as it will limit requests to the 3rd party repository manager.

### Using a HTTP proxy with the Maven Proxy

Using the built-in Maven Proxy in fabric will communicate directly between the nodes over HTTP. If a HTTP proxy is required for communication, then you can configure the maven proxy in fabric by configuring the ```MavenProxyRegistrationHandler```.

From the CLI type:

    fabric:profile-edit --pid io.fabric8.maven/proxyHost=servername fabric
    fabric:profile-edit --pid io.fabric8.maven/proxyPort=portNumber fabric

Notice you must specify both a hostname and port to use.

And you can optionally specify a proxy username/password if the HTTP proxy requires that.

    fabric:profile-edit --pid io.fabric8.maven/proxyUsername=someone fabric
    fabric:profile-edit --pid io.fabric8.maven/proxyPassword=secret fabric

It is also possible to specify a nonProxyHost to allow some nodes to not use the HTTP proxy. Multiple hosts is separated using the ```|``` charachter. Remember to qoute the pid value using ```'``` quotes when you use the ```|``` charachter, as the ```|``` is used for chaining commands.

    fabric:profile-edit --pid 'io.fabric8.maven/nonProxyHosts=someServer|somerOtherServer' fabric

Noptice that by default nonProxyHosts will not proxy any URIs that is localhost as access to itself, does not require to use the HTTP proxy.
But if you configure this option, then remember to add ```localhost|127.*``` to still not proxy any localhost addresses.

You can also configure the ```MavenProxyRegistrationHandler``` from the web console, by selecting the fabric profile, and click the ```Configuration``` button.


text:
'use strict';

var chai = require('chai'),
  pp = require('../lib/preprocess');

chai.should();

describe('shall support multiple call signatures', function () {
  var input;

  describe('and support legacy mode', function () {
    it('with only the source param in which case context shall be extracted from process.env', function () {
      process.env.TEST = 'a';
      input = "a<!-- @ifdef TEST -->b<!-- @endif -->c";
      pp.preprocess(input).should.equal("abc");
    });

    it('with the source and context params and take srcDir property from context if available', function () {
      input = "a<!--@include static.txt-->c";
      pp.preprocess(input, {srcDir: 'test/fixtures/include'}).should.equal("a!bazqux!c");
    });

    it('with the source, context and type params', function () {
      input = "a/*@include static.txt*/c";
      pp.preprocess(input, {srcDir: 'test/fixtures/include'}, 'js').should.equal("a!bazqux!c");
    });
  });

  it('shall use process.cwd() if srcDir is not specified', function () {
    input = "a<!--@include test/fixtures/include/static.txt-->c";
    pp.preprocess(input).should.equal("a!bazqux!c");
  });

  describe('and support options object instead of type', function () {
    it('and use srcDir option', function () {
      input = "a<!--@include static.txt-->c";
      pp.preprocess(input, {}, {srcDir: "test/fixtures/include"}).should.equal("a!bazqux!c");
    });

    describe('and use fileNotFoundSilentFail option', function () {
      it('that should default to throwing an error when a file could not be found', function () {
        input = "a<!--@include static.txt-->c";
        (function () {
          pp.preprocess(input);
        }).should.throw(Error, /static.txt not found!/);

        input = "a<!--@extend static.txt-->b<!--@endextend-->c";
        (function () {
          pp.preprocess(input);
        }).should.throw(Error, /static.txt not found!/);
      });

      it('that should fall back to old behavior if it is set to true', function () {
        input = "a<!--@include static.txt-->c";
        pp.preprocess(input, {}, {fileNotFoundSilentFail: true}).should.match(/^a.*static.txt not found!c$/);

        input = "a<!--@extend static.txt-->b<!--@endextend-->c";
        pp.preprocess(input, {}, {fileNotFoundSilentFail: true}).should.match(/^a.*static.txt not found!c$/);
      });
    });

    it('and override automatic EOL detection with srcEol option', function () {
      input = "a\n<!--@include static.txt-->\nc";
      pp.preprocess(input, {}, {srcEol: '\r\n', srcDir: 'test/fixtures/include'}).should.equal("a\r\n!bazqux!\r\nc");
    });
  });
});


text:
using Chip8Sharp.Core;
using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Chip8Sharp.Forms
{
    public partial class Form1 : Form, IInputDevice, IOutputDevice
    {
        Chip8 _chip8;
        private const int DisplayScale = 5;
        public Form1()
        {
            InitializeComponent();

            _chip8 = new Chip8("./game_file_here.c8", this, this);

            KeyDown += OnKeyDown;
            KeyUp += OnKeyUp;

            Task.Run(() =>
            {
                _chip8.Run();
            });
        }

        void OnKeyUp(object sender, KeyEventArgs e)
        {
            InputKey inputKey;
            if (!TryGetInputKeyForKey(e.KeyCode, out inputKey)) return;

            if (PressedKey == inputKey)
            {
                PressedKey = null;
            }

            var handler = KeyReleased;

            if (handler != null)
            {
                handler(this, inputKey);
            }
        }

        void OnKeyDown(object sender, KeyEventArgs e)
        {
            InputKey inputKey;
            if (!TryGetInputKeyForKey(e.KeyCode, out inputKey)) return;

            if (PressedKey == null)
            {
                PressedKey = inputKey;
            }

            var handler = KeyPressed;

            if (handler != null)
            {
                handler(this, inputKey);
            }
        }

        public event EventHandler<InputKey> KeyPressed;

        public event EventHandler<InputKey> KeyReleased;

        public InputKey? PressedKey
        {
            get;
            private set;
        }

        private bool TryGetInputKeyForKey(Keys key, out InputKey inputKey)
        {
            switch (key)
            {
                case Keys.A:
                    inputKey = InputKey.A;
                    return true;
                case Keys.B:
                    inputKey = InputKey.B;
                    return true;
                case Keys.C:
                    inputKey = InputKey.C;
                    return true;
                case Keys.D:
                    inputKey = InputKey.D;
                    return true;
                case Keys.D0:
                    inputKey = InputKey.Zero;
                    return true;
                case Keys.D1:
                    inputKey = InputKey.One;
                    return true;
                case Keys.D2:
                    inputKey = InputKey.Two;
                    return true;
                case Keys.D3:
                    inputKey = InputKey.Three;
                    return true;
                case Keys.D4:
                    inputKey = InputKey.Four;
                    return true;
                case Keys.D5:
                    inputKey = InputKey.Five;
                    return true;
                case Keys.D6:
                    inputKey = InputKey.Six;
                    return true;
                case Keys.D7:
                    inputKey = InputKey.Seven;
                    return true;
                case Keys.D8:
                    inputKey = InputKey.Eight;
                    return true;
                case Keys.D9:
                    inputKey = InputKey.Nine;
                    return true;
                case Keys.E:
                    inputKey = InputKey.E;
                    return true;
                case Keys.F:
                    inputKey = InputKey.F;
                    return true;
                default:
                    inputKey = InputKey.A;
                    return false;
            }
        }

        public void Draw(byte[] displayBuffer)
        {
            using (var graphics = CreateGraphics())
            {
                using (var blackBrush = new SolidBrush(Color.Black))
                {
                    using (var whiteBrush = new SolidBrush(Color.White))
                    {
                        for (int i = 0; i < displayBuffer.Length; i++)
                        {
                            int x = i % 64;
                            int y = (int)Math.Floor(i / 64.0);
                            if(displayBuffer[i] == 255)
                            {
                                graphics.FillRectangle(whiteBrush, new Rectangle(x * DisplayScale, y * DisplayScale, 1 * DisplayScale, 1 * DisplayScale));
                            }
                            else
                            {
                                graphics.FillRectangle(blackBrush, new Rectangle(x * DisplayScale, y * DisplayScale, 1 * DisplayScale, 1 * DisplayScale));
                            }
                        }
                    }
                }
            }
        }

        public void Beep()
        {
        }
    }
}


text:
select c1.cohort_definition_id,
  411 as analysis_id,
  cast( '' as varchar(1) ) as stratum_1, cast( '' as varchar(1) ) as stratum_2, cast( '' as varchar(1) ) as stratum_3, cast( '' as varchar(1) ) as stratum_4,
  COUNT_BIG(co1.condition_occurrence_id) as count_value
into #results_411
from
@CDM_schema.condition_occurrence co1
inner join #HERACLES_cohort_subject c1
on co1.person_id = c1.subject_id
where co1.condition_end_date < co1.condition_start_date
group by c1.cohort_definition_id
;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Machine.Specifications;
using Quarks.FluentNHibernate;

namespace Quarks.Tests.FluentNHibernate
{
	[Subject(typeof(FilterableTypeSource))]
	class When_creating_a_type_filter_and_then_filtering_further
	{
		It should_apply_both_predicates = () =>
			types.Single().ShouldEqual(typeof(Foo));

		Because of = () =>
			types = FilterableTypeSource.CreateTypeFilter(x => typeof(Foo).IsAssignableFrom(x))
				.FromAssemblies(Assembly.GetExecutingAssembly()).Where(x => x.BaseType == typeof(object)).GetTypes();

		static IEnumerable<Type> types;

		class Foo { }
		class Bar : Foo { }
		class Baz : Bar { }
	}
}


text:
//
// Copyright (c) Microsoft.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Search.Models;

namespace Microsoft.Azure.Search
{
    internal partial class DocumentOperations
    {
        public Task<DocumentSearchResponse> ContinueSearchAsync(
            SearchContinuationToken continuationToken,
            CancellationToken cancellationToken)
        {
            string invocationId;
            bool shouldTrace = ValidateAndTraceContinueSearch(continuationToken, out invocationId);

            return DoContinueSearchAsync<DocumentSearchResponse, SearchResult, Document>(
                continuationToken.NextLink,
                shouldTrace,
                invocationId,
                cancellationToken,
                DeserializeForSearch);
        }

        public Task<DocumentSearchResponse<T>> ContinueSearchAsync<T>(
            SearchContinuationToken continuationToken,
            CancellationToken cancellationToken) where T : class
        {
            string invocationId;
            bool shouldTrace = ValidateAndTraceContinueSearch(continuationToken, out invocationId);

            return DoContinueSearchAsync<DocumentSearchResponse<T>, SearchResult<T>, T>(
                continuationToken.NextLink,
                shouldTrace,
                invocationId,
                cancellationToken,
                DeserializeForSearch<T>);
        }

        private bool ValidateAndTraceContinueSearch(
            SearchContinuationToken continuationToken,
            out string invocationId)
        {
            // Validate
            if (continuationToken == null)
            {
                throw new ArgumentNullException("continuationToken");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("continuationToken", continuationToken);

                TracingAdapter.Enter(invocationId, this, "ContinueSearchAsync", tracingParameters);
            }

            return shouldTrace;
        }
    }
}


text:
/**
 * Helper functions shared across all the tasks
 */

var spawn = require('child_process').spawn,
    fs = require('fs'),
    path = require('path'),
    os = require('os'),
    utils = {
        /**
         * Convert an options object into a valid arguments array for the child_process.spawn method
         * from:
         *   var options = {
     *     foo: 'hello',
     *     baz: 'world'
     *   }
         * to:
         *   ['--foo=', 'hello', '--baz=','world']
         *
         * @param   { Object }  obj - object we need to convert
         * @param   { Array }   optionsPrefix - use a prefix for the new array created
         * @param   { Boolean } hasEquals - set the options commands using the equal
         * @returns { Array } - options array
         */
        optionsToArray(obj, optionsPrefix, hasEquals) {
            optionsPrefix = optionsPrefix || '--'
            var ret = []
            Object.keys(obj).forEach((key) => {
                ret.push(optionsPrefix + key + (hasEquals ? '=' : ''))
                if (obj[key]) {
                    ret.push(obj[key])
                }
            })
            return ret
        },
        /**
         * Simple object extend function
         * @param   { Object } obj1 - destination
         * @param   { Object } obj2 - source
         * @returns { Object } - destination object
         */
        extend(obj1, obj2) {
            for (var i in obj2) {
                if (obj2.hasOwnProperty(i)) {
                    obj1[i] = obj2[i]
                }
            }
            return obj1
        },
        /**
         * Run any system command
         * @param  { String } command - command to execute
         * @param  { Array } args - command arguments
         * @param  { Object } envVariables - command environment variables
         * @returns { Promise } chainable promise object
         */
        exec(command, args, envVariables) {

            return new Promise(function(resolve, reject) {

                if (os.platform() == 'win32' || os.platform() == 'win64') command += '.cmd'

                // extend the env variables with some other custom options
                utils.extend(process.env, envVariables)
                utils.print('Executing: ' + command + ' ' + args.join(' ') + '\n', 'confirm')

                var cmd = spawn(path.normalize(command), args, {
                    stdio: 'inherit',
                    cwd: process.cwd()
                })

                cmd.on('exit', function(code) {
                    if (code === 1)
                        reject()
                    else
                        resolve()
                })

            })

        },
        /**
         * Read all the files crawling starting from a certain folder path
         * @param  { String } path directory path
         * @param  { bool } mustDelete delete the files found
         * @returns { Array } files path list
         */
        listFiles(thisPath, mustDelete) {
            utils.print('Listing all the files in the folder: ' + thisPath , 'confirm')
            var files = []
            if (fs.existsSync(thisPath)) {
                var tmpFiles = fs.readdirSync(thisPath)
                tmpFiles.forEach((file) => {
                    var curPath = thisPath + path.sep + file
                    files.push(curPath)
                    if (fs.lstatSync(curPath).isDirectory()) { // recurse
                        utils.listFiles(curPath, mustDelete)
                    } else if (mustDelete) { // delete file
                        fs.unlinkSync(curPath)
                    }
                })
                if (mustDelete) {
                    fs.rmdirSync(thisPath)
                }
            }

            return files
        },
        /**
         * Delete synchronously any folder or file
         * @param  { String } path - path to clean
         */
        clean(path) {
            var files = utils.listFiles(path, true)
            utils.print('Deleting the following files: \n '  + files.join('\n   '), 'cool')
        },
        /**
         * Log messages in the terminal using custom colors
         * @param  { String } msg - message to output
         * @param  { String } type - message type to handle the right color
         */
        print(msg, type) {
            var color
            switch (type) {
                case 'error':
                    color = '\x1B[31m'
                    break
                case 'warning':
                    color = '\x1B[33m'
                    break
                case 'confirm':
                    color = '\x1B[32m'
                    break
                case 'cool':
                    color = '\x1B[36m'
                    break
                default:
                    color = ''
            }
            console.log(color + msg + ' \x1B[39m')
        },
        resolve(projectPath, esskOptions) {
            esskOptions.jsBasePath = projectPath + path.sep + esskOptions.jsBasePath.replace('/', path.sep)
            esskOptions.scssBasePath = projectPath + path.sep + esskOptions.scssBasePath.replace('/', path.sep)
            esskOptions.jsDest = projectPath + path.sep + esskOptions.jsDest.replace('/', path.sep)
            esskOptions.cssDest = projectPath + path.sep + esskOptions.cssDest.replace('/', path.sep)
            esskOptions.projetPath = projectPath;
            return esskOptions
        },
        getDependencies() {
            var content = fs.readFileSync(__dirname + '/../package.json', 'utf8')
            return JSON.parse(content).dependencies
        }
    }

module.exports = utils


text:
struct mlr_paras
{
  int dim_feat;//feature dimension
  int num_classes;//number of classes
  int epochs;//number of epochs of stochastic gradient descent (SGD)
  float init_lr;//init learning rate
  float lr_red;//learning rate reduction ratio
  int lr_red_freq;//learning rate reduction frequency
  float pct_smps_evaluate;//percentage of samples to evaluate
  int num_iters_evaluate;//every <num_iters_evaluate> iterations, evaluate the objective function
  char data_file_list[512];
  char eval_data_meta[512];

};

void load_mlr_paras(mlr_paras & para, const char * file_mlr_para);

void print_mlr_paras(mlr_paras para);

#endif


text:
import os
import sys
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.abspath(os.path.join(parent, '../')))

import cv2
import unittest
import yaml
import argparse

from ppcv.core.workspace import global_config
from ppcv.core.config import ConfigParser

class TestSegmentation(unittest.TestCase):
    def setUp(self):
        self.config = 'configs/unittest/test_segmentation.yml'
        self.input = 'demo/segmentation_cityscapes_img.png'
        self.cfg_dict = dict(config=self.config, input=self.input)
        cfg = argparse.Namespace(**self.cfg_dict)
        config = ConfigParser(cfg)
        config.print_cfg()
        self.model_cfg, self.env_cfg = config.parse()

    def test_segmentation(self):
        img = cv2.imread(self.input)[:, :, ::-1]
        inputs = [
            {
                "input.image": [img]
            },
            {
                "input.image": [img, img]
            },
        ]

        op_name = list(self.model_cfg[0].keys())[0]
        cls_op = global_config[op_name](self.model_cfg[0][op_name],
                                        self.env_cfg)
        result = cls_op(inputs)

class TestPPHumanSegV2(unittest.TestCase):
    def setUp(self):
        self.config = 'configs/unittest/test_seg_pphumansegv2.yml'
        self.input = 'demo/pp_humansegv2_demo.jpg'
        self.cfg_dict = dict(config=self.config, input=self.input)
        cfg = argparse.Namespace(**self.cfg_dict)
        config = ConfigParser(cfg)
        config.print_cfg()
        self.model_cfg, self.env_cfg = config.parse()

    def test_segmentation(self):
        img = cv2.imread(self.input)[:, :, ::-1]
        inputs = [
            {
                "input.image": [img]
            },
            {
                "input.image": [img, img]
            },
        ]

        op_name = list(self.model_cfg[0].keys())[0]
        cls_op = global_config[op_name](self.model_cfg[0][op_name],
                                        self.env_cfg)
        result = cls_op(inputs)

class TestPPMattingV1(unittest.TestCase):
    def setUp(self):
        self.config = 'configs/unittest/test_seg_ppmattingv1.yml'
        self.input = 'demo/pp_mattingv1_demo.jpg'
        self.cfg_dict = dict(config=self.config, input=self.input)
        cfg = argparse.Namespace(**self.cfg_dict)
        config = ConfigParser(cfg)
        config.print_cfg()
        self.model_cfg, self.env_cfg = config.parse()

    def test_segmentation(self):
        img = cv2.imread(self.input)[:, :, ::-1]
        inputs = [
            {
                "input.image": [img]
            },
            {
                "input.image": [img, img]
            },
        ]

        op_name = list(self.model_cfg[0].keys())[0]
        cls_op = global_config[op_name](self.model_cfg[0][op_name],
                                        self.env_cfg)
        result = cls_op(inputs)

if __name__ == '__main__':
    unittest.main()


text:
namespace anki {

/// @addtogroup util_containers
/// @{

/// The hash function
class DictionaryHasher
{
public:
	PtrSize operator()(const CString& cstr) const
	{
		PtrSize h = 0;
		auto str = cstr.get();
		for (; *str != '\0'; ++str)
		{
			h += *str;
		}
		return h;
	}
};

/// The collision evaluation function
class DictionaryEqual
{
public:
	Bool operator()(const CString& a, const CString& b) const
	{
		return a == b;
	}
};

/// The hash map that has as key an old school C string. When inserting the
/// char MUST NOT point to a temporary or the evaluation function will fail.
/// Its template struct because C++ does not offer template typedefs
template<
	typename T,
	typename TAlloc = HeapAllocator<std::pair<CString, T>>>
using Dictionary =
	std::unordered_map<
		CString,
		T,
		DictionaryHasher,
		DictionaryEqual,
		TAlloc>;

/// @}

} // end namespace anki

#endif


text:
package org.apache.nifi.cluster.manager.exception;

/**
 * Represents the exceptional case when an offload request is issued to a node that cannot be offloaded (e.g., not currently disconnected).
 */
public class IllegalNodeOffloadException extends IllegalClusterStateException {

    public IllegalNodeOffloadException() {
    }

    public IllegalNodeOffloadException(String msg) {
        super(msg);
    }

    public IllegalNodeOffloadException(Throwable cause) {
        super(cause);
    }

    public IllegalNodeOffloadException(String msg, Throwable cause) {
        super(msg, cause);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<SMARTPLUG id="edimax">
  <CMD id="setup">
    <Device.System.Power.State>ON</Device.System.Power.State>
  </CMD>
</SMARTPLUG>


text:
            <input id="playerName" readonly="readonly"></input>
            <button id="changePlayerNameButton">Change Name</button>
            Please Enter a Valid Name

            Score :

            High Score :

 Instructions: Collect the food as it appears.  WASD or arrow keys to move.

 Don't touch the edge of the screen or run into yourself.


text:
using UnityEngine;
using System;
using System.Collections.Generic;

public class ParriesBlueMagic : MonoBehaviour
{
	#region Variables / Properties

	public bool DebugMode = false;
	public AudioClip DeflectSound;
	public string ItemName = "Hero's Hilt";
	public string DeflectedTarget = "Enemy";
	public List<string> DefendableItemTags = new List<string>{"Blue Magic"};

	public bool DeflectsBlueMagic
	{
		get { return _ambassador.HasItem(ItemName); }
	}

	private Ambassador _ambassador;
	private Maestro _maestro;

	#endregion Variables / Properties

	#region Engine Hooks

	public void Start()
	{
		_ambassador = (Ambassador) FindObjectOfType(typeof(Ambassador));
		_maestro = Maestro.DetectLastInstance();

		if(_ambassador == null)
		{
			if(DebugMode)
				Debug.LogWarning("Was unable to find damage source or ambassador!" + Environment.NewLine
					             + "Ambassador: " + (_ambassador == null ? "Not Found" : "Found"));

			return;
		}

		if(DebugMode)
			Debug.Log("This weapon " + (DeflectsBlueMagic ? "can" : "can't") + " repel Blue Magic.");
	}

	public void OnTriggerEnter(Collider who)
	{
		bool isDeflectableObject = DefendableItemTags.Contains(who.tag);

		if(! DeflectsBlueMagic
		   || ! isDeflectableObject)
		{
			if(DebugMode)
			{
				Debug.Log("This weapon " + (DeflectsBlueMagic ? "can" : "cannot") + "deflect Blue Magic.");
				Debug.Log("GameObject " + who.gameObject.name + " " + (isDeflectableObject ? "is" : "is not") + " a deflectable object.");
			}

			return;
		}

		if(DeflectSound != null)
			_maestro.PlaySoundEffect(DeflectSound);

		GameObject original = who.gameObject;
		Projectile originalProjectile = original.GetComponent<Projectile>();
		DamageSource originalDamageSource = original.GetComponent<DamageSource>();

		originalProjectile.Velocity *= -1;
		originalProjectile.AffectedTags = new List<string>{ DeflectedTarget };

		originalDamageSource.AffectedTags = new List<string>{ DeflectedTarget };
	}

	#endregion Engine Hooks
}


text:
package org.jetbrains.plugins.scala.lang.formatting.settings

import com.intellij.application.options._
import com.intellij.application.options.codeStyle.CodeStyleSchemesModel
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.util.Disposer
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.ui.components.JBLabel
import com.intellij.uiDesigner.core.{GridConstraints, GridLayoutManager, Spacer}
import org.jetbrains.annotations.NonNls
import org.jetbrains.plugins.scala.lang.rearranger.ScalaArrangementPanel
import org.jetbrains.plugins.scala.{ScalaBundle, ScalaLanguage}

import java.awt._
import java.awt.event.ItemEvent
import javax.swing._
import scala.annotation.nowarn

class ScalaTabbedCodeStylePanel(currentSettings: CodeStyleSettings, settings: CodeStyleSettings)
  extends TabbedLanguageCodeStylePanel(ScalaLanguage.INSTANCE, currentSettings, settings) {

  import ScalaTabbedCodeStylePanel._

  private var formatterSelectorComboBox: JComboBox[String] = _
  private var outerPanel: JPanel = _
  private var shortenedPanel: ScalafmtTabbedLanguageCodeStylePanel = _
  // TODO: rework this whole project juggling mess, there should be a straightforward way of depending on a project
  //  from code style settings panels
  private var typeAnnotationsPanel: TypeAnnotationsPanel = _

  override def dispose(): Unit = {
    super.dispose()
    Disposer.dispose(shortenedPanel)
  }

  override def getPanel: JComponent = outerPanel

  private def innerPanel: JComponent = super.getPanel

  override protected def initTabs(settings: CodeStyleSettings): Unit = {
    super.initTabs(settings)
    addTab(new ScalaDocFormattingPanel(settings))
    addTab(new ImportsPanel(settings))
    addTab(new MultiLineStringCodeStylePanel(settings))
    addTab({typeAnnotationsPanel = new TypeAnnotationsPanel(settings); typeAnnotationsPanel})
    addTab(new ScalaArrangementPanel(settings))
    addTab(new CodeGenerationPanel(settings))
    addTab(new OtherCodeStylePanel(settings))
    initOuterFormatterPanel()
  }

  override def isModified(settings: CodeStyleSettings): Boolean = {
    val scalaSettings = settings.getCustomSettings(classOf[ScalaCodeStyleSettings])

    val formatterTypeChanged = scalaSettings.FORMATTER != getSelectedFormatterId
    formatterTypeChanged ||
      super.isModified(settings) ||
      shortenedPanel.exposeIsModified(settings)
  }

  private def getSelectedFormatterId: Int =
    formatters(formatterSelectorComboBox.getSelectedItem.toString)

  override def apply(settings: CodeStyleSettings): Unit = {
    val scalaSettings = settings.getCustomSettings(classOf[ScalaCodeStyleSettings])

    scalaSettings.FORMATTER = getSelectedFormatterId

    if (scalaSettings.USE_SCALAFMT_FORMATTER) {
      shortenedPanel.exposeApply(settings)
    } else {
      super.apply(settings)
    }

    syncPanels(scalaSettings.USE_SCALAFMT_FORMATTER)
  }

  override def resetImpl(settings: CodeStyleSettings): Unit = {
    val scalaSettings = settings.getCustomSettings(classOf[ScalaCodeStyleSettings])

    val formatterKey = formatters.find(_._2 == scalaSettings.FORMATTER).map(_._1).get
    formatterSelectorComboBox.setSelectedItem(formatterKey)

    toggleSettingsVisibility(scalaSettings.USE_SCALAFMT_FORMATTER)

    if (scalaSettings.USE_SCALAFMT_FORMATTER) {
      shortenedPanel.exposeResetImpl(settings)
    } else {
      super.resetImpl(settings)
    }

    syncPanels(scalaSettings.USE_SCALAFMT_FORMATTER)
  }

  private def initOuterFormatterPanel(): Unit = {
    formatterSelectorComboBox = new ComboBox(formatters.keys.toArray)
    formatterSelectorComboBox.addItemListener((_: ItemEvent) => {
      //USE_SCALAFMT_FORMATTER setting is immediately set to allow proper formatting for core formatter examples
      val scalaSettings = settings.getCustomSettings(classOf[ScalaCodeStyleSettings])
      val oldFormatter = scalaSettings.FORMATTER
      scalaSettings.FORMATTER = getSelectedFormatterId
      if (scalaSettings.FORMATTER != oldFormatter) {
        toggleSettingsVisibility(scalaSettings.USE_SCALAFMT_FORMATTER)
        syncPanels(scalaSettings.USE_SCALAFMT_FORMATTER)
      }
    })

    import GridConstraints._
    val CAN_SHRINK_AND_GROW = SIZEPOLICY_CAN_SHRINK | SIZEPOLICY_CAN_GROW

    def constraint(row: Int, col: Int, fill: Int, HSizePolicy: Int, VSizePolicy: Int) =
      new GridConstraints(row, col, 1, 1, ANCHOR_CENTER, fill, HSizePolicy, VSizePolicy, null, null, null, 0, false)

    val formatterSelectorPanel = new JPanel(new GridLayoutManager(1, 3, new Insets(0, 10, 0, 0), -1, -1))
    formatterSelectorPanel.add(new JBLabel(ScalaBundle.message("scala.root.code.style.panel.formatter")), constraint(0, 0, FILL_BOTH, SIZEPOLICY_FIXED, SIZEPOLICY_FIXED))
    formatterSelectorPanel.add(formatterSelectorComboBox, constraint(0, 1, FILL_HORIZONTAL, CAN_SHRINK_AND_GROW, SIZEPOLICY_FIXED))
    formatterSelectorPanel.add(new Spacer, constraint(0, 2, FILL_HORIZONTAL, SIZEPOLICY_WANT_GROW, SIZEPOLICY_CAN_SHRINK))

    outerPanel = new JPanel(new GridLayoutManager(7, 2, new Insets(0, 0, 0, 0), -1, -1))
    outerPanel.add(formatterSelectorPanel, constraint(0, 0, FILL_BOTH, SIZEPOLICY_FIXED, SIZEPOLICY_FIXED))
    outerPanel.add(innerPanel, constraint(1, 0, FILL_BOTH, CAN_SHRINK_AND_GROW, CAN_SHRINK_AND_GROW))

    shortenedPanel = new ScalafmtTabbedLanguageCodeStylePanel(currentSettings, settings)
    outerPanel.add(shortenedPanel.getPanel, constraint(2, 0, FILL_BOTH, CAN_SHRINK_AND_GROW, CAN_SHRINK_AND_GROW))
    // this is required in order scrolling works correctly with small settings window height
    // otherwise on small screens the settings can be practically unusable
    innerPanel.setMinimumSize(new Dimension(1, 1))

    toggleSettingsVisibility(false)
  }

  def onProjectSet(project: Project): Unit = {
    shortenedPanel.onProjectSet(project)
    typeAnnotationsPanel.onProjectSet(project)
  }

  // scalaFmtSettingsPanel.setModel should be called in order that its settings are saved properly
  // setModel in TabbedLanguageCodeStylePanel is final so we can't override and have to use workaround method
  def onModelSet(model: CodeStyleSchemesModel): Unit = shortenedPanel.setModel(model)

  private def syncPanels(useExternalFormatter: Boolean): Unit = {
    val tempSettings = settings.clone(): @nowarn("cat=deprecation")
    if (useExternalFormatter) {
      shortenedPanel.exposeApply(tempSettings)
      // we need to invoke applySettingsToModel, which is done inside onSomethingChanged
      shortenedPanel.onSomethingChanged()
      super.resetImpl(tempSettings)
    } else {
      super.apply(tempSettings)
      shortenedPanel.exposeResetImpl(tempSettings)
    }
  }

  private def toggleSettingsVisibility(useExternalFormatter: Boolean): Unit = {
    innerPanel.setVisible(!useExternalFormatter)
    shortenedPanel.getPanel.setVisible(useExternalFormatter)
  }
}

object ScalaTabbedCodeStylePanel {
  @NonNls
  private val formatters: Map[String, Int] = Map(
    "IntelliJ" -> ScalaCodeStyleSettings.INTELLIJ_FORMATTER,
    "Scalafmt" -> ScalaCodeStyleSettings.SCALAFMT_FORMATTER,
  )

  private class ScalafmtTabbedLanguageCodeStylePanel(currentSettings: CodeStyleSettings, settings: CodeStyleSettings)
    extends TabbedLanguageCodeStylePanel(ScalaLanguage.INSTANCE, currentSettings, settings) {

    private var scalaFmtSettingsPanel: ScalaFmtSettingsPanel = _

    override protected def initTabs(settings: CodeStyleSettings): Unit = {
      scalaFmtSettingsPanel = new ScalaFmtSettingsPanel(settings)
      addTab(scalaFmtSettingsPanel)
      addTab(new ImportsPanel(settings))
      addTab(new MultiLineStringCodeStylePanel(settings))
      addTab(new TypeAnnotationsPanel(settings))
      addTab(new ScalaArrangementPanel(settings))
      addTab(new CodeGenerationPanel(settings))
      val otherCodeStylePanel: OtherCodeStylePanel = new OtherCodeStylePanel(settings)
      addTab(otherCodeStylePanel)
      otherCodeStylePanel.toggleExternalFormatter(true)
    }

    def exposeIsModified(settings: CodeStyleSettings): Boolean = super.isModified(settings)
    def exposeApply(settings: CodeStyleSettings): Unit = super.apply(settings)
    def exposeResetImpl(settings: CodeStyleSettings): Unit = super.resetImpl(settings)

    def onProjectSet(project: Project): Unit = scalaFmtSettingsPanel.onProjectSet(project)
  }
}


text:
import React, {Component, PropTypes} from 'react';

import Icon from '../components/Icon';

class NoMatchPage extends Component {

  render() {
    return (

                <Icon name='paperplane' size='l'/> 404

                Not Found

    );
  }
}

NoMatchPage.displayName = 'NoMatchPage';

export default NoMatchPage;


text:
module Ironfan
  class Dsl < Builder
    include Gorillib::Resolution, CookbookRequirements

  end
end


text:
<?php

namespace OrbitalExpress\Entity;

use Symfony\Component\Security\Core\User\UserInterface;

class User implements UserInterface
{
	private $id_user;
	private $username;
	private $email;
	private $password;
	private $role;
	private $salt;

    public function getId_User() {
        return $this->id_user;
    }

    public function setId_User($id_user) {
        $this->id_user = $id_user;
    }

    public function getUsername() {
        return $this->username;
    }

    public function setUsername($username) {
        $this->username = $username;
    }

    public function getEmail() {
        return $this->email;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    public function getPassword() {
        return $this->password;
    }

    public function setPassword($password) {
        $this->password = $password;
    }

		public function getRole(){
			return $this ->role;
		}

		public function setRole($role){
			$this ->role = $role;
		}

		public function getSalt(){
			return $this ->salt;
		}

		public function setSalt($salt){
			$this ->salt = $salt;
		}

	/**
	* @inheritDoc
	*/
	public function getRoles(){
		return array($this -> getRole());
	}

	/**
	* @inheritDoc
	*/
	public function eraseCredentials(){
		// Nothing here
	}
}

?>


text:
const char default_name[] = "Program";

Program::Program()
{
  strcpy(name, default_name);

  window_width = DEFAULT_WINDOW_SIZE;
  window_height = DEFAULT_WINDOW_SIZE;
}

Program::Program(char *name)
{
  strcpy(this->name, name);

  window_width = DEFAULT_WINDOW_SIZE;
  window_height = DEFAULT_WINDOW_SIZE;
}

Program::Program(int window_width, int window_height)
{
  strcpy(name, default_name);

  this->window_width = window_width;
  this->window_height = window_height;
}

Program::Program(char *name, int window_width, int window_height)
{
  strcpy(this->name, name);

  this->window_width = window_width;
  this->window_height = window_height;
}

void Program::start()
{
}

void Program::render_scene()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glutSwapBuffers();
}

int Program::main(int argc, char *argv[])
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
  glutInitWindowSize(window_width, window_height);
  glutCreateWindow(name);

  glutDisplayFunc(&render_scene);
  glutKeyboardFunc(&keyboard_handler);
  glutSpecialFunc(&special_key_handler);

#ifndef __APPLE__
  GLenum err = glewInit();
  if(GLEW_OK != err) {
    fprintf(stderr, "Glew Error: %s",  glewGetErrorString(err));

    return 1;
  }
#endif

  start();

  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

  glEnable(GL_DEPTH_TEST);
  glEnable(GL_CULL_FACE);

  glutMainLoop();

  return 0;
}

void Program::keyboard_handler(unsigned char key, int x, int y)
{
  if(key == 0x1b)
    exit(0);
}

void Program::special_key_handler(int key, int x, int y)
{
}


text:
<?php declare(strict_types=1);

namespace Monolog;

final class Utils
{
    const DEFAULT_JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR;

    public static function getClass(object $object): string
    {
        $class = \get_class($object);

        if (false === ($pos = \strpos($class, "@anonymous\0"))) {
            return $class;
        }

        if (false === ($parent = \get_parent_class($class))) {
            return \substr($class, 0, $pos + 10);
        }

        return $parent . '@anonymous';
    }

    public static function substr(string $string, int $start, ?int $length = null): string
    {
        if (extension_loaded('mbstring')) {
            return mb_strcut($string, $start, $length);
        }

        return substr($string, $start, (null === $length) ? strlen($string) : $length);
    }

    /**
     * Makes sure if a relative path is passed in it is turned into an absolute path
     *
     * @param string $streamUrl stream URL or path without protocol
     */
    public static function canonicalizePath(string $streamUrl): string
    {
        $prefix = '';
        if ('file://' === substr($streamUrl, 0, 7)) {
            $streamUrl = substr($streamUrl, 7);
            $prefix = 'file://';
        }

        // other type of stream, not supported
        if (false !== strpos($streamUrl, '://')) {
            return $streamUrl;
        }

        // already absolute
        if (substr($streamUrl, 0, 1) === '/' || substr($streamUrl, 1, 1) === ':' || substr($streamUrl, 0, 2) === '\\\\') {
            return $prefix.$streamUrl;
        }

        $streamUrl = getcwd() . '/' . $streamUrl;

        return $prefix.$streamUrl;
    }

    /**
     * Return the JSON representation of a value
     *
     * @param  mixed             $data
     * @param  int               $encodeFlags  flags to pass to json encode, defaults to DEFAULT_JSON_FLAGS
     * @param  bool              $ignoreErrors whether to ignore encoding errors or to throw on error, when ignored and the encoding fails, "null" is returned which is valid json for null
     * @throws \RuntimeException if encoding fails and errors are not ignored
     * @return string            when errors are ignored and the encoding fails, "null" is returned which is valid json for null
     */
    public static function jsonEncode($data, ?int $encodeFlags = null, bool $ignoreErrors = false): string
    {
        if (null === $encodeFlags) {
            $encodeFlags = self::DEFAULT_JSON_FLAGS;
        }

        if ($ignoreErrors) {
            $json = @json_encode($data, $encodeFlags);
            if (false === $json) {
                return 'null';
            }

            return $json;
        }

        $json = json_encode($data, $encodeFlags);
        if (false === $json) {
            $json = self::handleJsonError(json_last_error(), $data);
        }

        return $json;
    }

    /**
     * Handle a json_encode failure.
     *
     * If the failure is due to invalid string encoding, try to clean the
     * input and encode again. If the second encoding attempt fails, the
     * initial error is not encoding related or the input can't be cleaned then
     * raise a descriptive exception.
     *
     * @param  int               $code        return code of json_last_error function
     * @param  mixed             $data        data that was meant to be encoded
     * @param  int               $encodeFlags flags to pass to json encode, defaults to JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION
     * @throws \RuntimeException if failure can't be corrected
     * @return string            JSON encoded data after error correction
     */
    public static function handleJsonError(int $code, $data, ?int $encodeFlags = null): string
    {
        if ($code !== JSON_ERROR_UTF8) {
            self::throwEncodeError($code, $data);
        }

        if (is_string($data)) {
            self::detectAndCleanUtf8($data);
        } elseif (is_array($data)) {
            array_walk_recursive($data, ['Monolog\Utils', 'detectAndCleanUtf8']);
        } else {
            self::throwEncodeError($code, $data);
        }

        if (null === $encodeFlags) {
            $encodeFlags = self::DEFAULT_JSON_FLAGS;
        }

        $json = json_encode($data, $encodeFlags);

        if ($json === false) {
            self::throwEncodeError(json_last_error(), $data);
        }

        return $json;
    }

    /**
     * @internal
     */
    public static function pcreLastErrorMessage(int $code): string
    {
        if (PHP_VERSION_ID >= 80000) {
            return preg_last_error_msg();
        }

        $constants = (get_defined_constants(true))['pcre'];
        $constants = array_filter($constants, function ($key) {
            return substr($key, -6) == '_ERROR';
        }, ARRAY_FILTER_USE_KEY);

        $constants = array_flip($constants);

        return $constants[$code] ?? 'UNDEFINED_ERROR';
    }

    /**
     * Throws an exception according to a given code with a customized message
     *
     * @param  int               $code return code of json_last_error function
     * @param  mixed             $data data that was meant to be encoded
     * @throws \RuntimeException
     */
    private static function throwEncodeError(int $code, $data): never
    {
        $msg = match ($code) {
            JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
            JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
            JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
            JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
            default => 'Unknown error',
        };

        throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true));
    }

    /**
     * Detect invalid UTF-8 string characters and convert to valid UTF-8.
     *
     * Valid UTF-8 input will be left unmodified, but strings containing
     * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed
     * original encoding of ISO-8859-15. This conversion may result in
     * incorrect output if the actual encoding was not ISO-8859-15, but it
     * will be clean UTF-8 output and will not rely on expensive and fragile
     * detection algorithms.
     *
     * Function converts the input in place in the passed variable so that it
     * can be used as a callback for array_walk_recursive.
     *
     * @param mixed $data Input to check and convert if needed, passed by ref
     */
    private static function detectAndCleanUtf8(&$data): void
    {
        if (is_string($data) && preg_match('//u', $data) !== 1) {
            $data = preg_replace_callback(
                '/[\x80-\xFF]+/',
                function ($m) {
                    return function_exists('mb_convert_encoding') ? mb_convert_encoding($m[0], 'UTF-8', 'ISO-8859-1') : utf8_encode($m[0]);
                },
                $data
            );
            if (!is_string($data)) {
                $pcreErrorCode = preg_last_error();

                throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . self::pcreLastErrorMessage($pcreErrorCode));
            }
            $data = str_replace(
                ['¤', '¦', '¨', '´', '¸', '¼', '½', '¾'],
                ['€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'],
                $data
            );
        }
    }

    /**
     * Converts a string with a valid 'memory_limit' format, to bytes.
     *
     * @param  string|false $val
     * @return int|false    Returns an integer representing bytes. Returns FALSE in case of error.
     */
    public static function expandIniShorthandBytes($val)
    {
        if (!is_string($val)) {
            return false;
        }

        // support -1
        if ((int) $val < 0) {
            return (int) $val;
        }

        if (preg_match('/^\s*(?<val>\d+)(?:\.\d+)?\s*(?<unit>[gmk]?)\s*$/i', $val, $match) !== 1) {
            return false;
        }

        $val = (int) $match['val'];
        switch (strtolower($match['unit'] ?? '')) {
            case 'g':
                $val *= 1024;
                // no break
            case 'm':
                $val *= 1024;
                // no break
            case 'k':
                $val *= 1024;
        }

        return $val;
    }

    public static function getRecordMessageForException(LogRecord $record): string
    {
        $context = '';
        $extra = '';

        try {
            if (\count($record->context) > 0) {
                $context = "\nContext: " . json_encode($record->context, JSON_THROW_ON_ERROR);
            }
            if (\count($record->extra) > 0) {
                $extra = "\nExtra: " . json_encode($record->extra, JSON_THROW_ON_ERROR);
            }
        } catch (\Throwable $e) {
            // noop
        }

        return "\nThe exception occurred while attempting to log: " . $record->message . $context . $extra;
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/type/fraction.proto

namespace Google\Type;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Represents a fraction in terms of a numerator divided by a denominator.
 *
 * Generated from protobuf message google.type.Fraction
 */
class Fraction extends \Google\Protobuf\Internal\Message
{
    /**
     * The portion of the denominator in the faction, e.g. 2 in 2/3.
     *
     * Generated from protobuf field int64 numerator = 1;
     */
    private $numerator = 0;
    /**
     * The value by which the numerator is divided, e.g. 3 in 2/3. Must be
     * positive.
     *
     * Generated from protobuf field int64 denominator = 2;
     */
    private $denominator = 0;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type int|string $numerator
     *           The portion of the denominator in the faction, e.g. 2 in 2/3.
     *     @type int|string $denominator
     *           The value by which the numerator is divided, e.g. 3 in 2/3. Must be
     *           positive.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Type\Fraction::initOnce();
        parent::__construct($data);
    }

    /**
     * The portion of the denominator in the faction, e.g. 2 in 2/3.
     *
     * Generated from protobuf field int64 numerator = 1;
     * @return int|string
     */
    public function getNumerator()
    {
        return $this->numerator;
    }

    /**
     * The portion of the denominator in the faction, e.g. 2 in 2/3.
     *
     * Generated from protobuf field int64 numerator = 1;
     * @param int|string $var
     * @return $this
     */
    public function setNumerator($var)
    {
        GPBUtil::checkInt64($var);
        $this->numerator = $var;

        return $this;
    }

    /**
     * The value by which the numerator is divided, e.g. 3 in 2/3. Must be
     * positive.
     *
     * Generated from protobuf field int64 denominator = 2;
     * @return int|string
     */
    public function getDenominator()
    {
        return $this->denominator;
    }

    /**
     * The value by which the numerator is divided, e.g. 3 in 2/3. Must be
     * positive.
     *
     * Generated from protobuf field int64 denominator = 2;
     * @param int|string $var
     * @return $this
     */
    public function setDenominator($var)
    {
        GPBUtil::checkInt64($var);
        $this->denominator = $var;

        return $this;
    }

}


text:
;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
;;
;; This file is part of GCC.
;;
;; GCC is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; GCC is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with GCC; see the file COPYING3.  If not see
;; <http://www.gnu.org/licenses/>.  */
;;
;; Pipeline description for the VR4130 family.
;;
;; The processor issues each 8-byte aligned pair of instructions together,
;; stalling the second instruction if it depends on the first.  Thus, if we
;; want two instructions to issue in parallel, we need to make sure that the
;; first one is 8-byte aligned.
;;
;; For the purposes of this pipeline description, we treat the processor
;; like a standard two-way superscalar architecture.  If scheduling were
;; the last pass to run, we could use the scheduler hooks to vary the
;; issue rate depending on whether an instruction is at an aligned or
;; unaligned address.  Unfortunately, delayed branch scheduling and
;; hazard avoidance are done after the final scheduling pass, and they
;; can change the addresses of many instructions.
;;
;; We get around this in two ways:
;;
;;   (1) By running an extra pass at the end of compilation.  This pass goes
;;	 through the function looking for pairs of instructions that could
;;	 execute in parallel.  It makes sure that the first instruction in
;;	 each pair is suitably aligned, inserting nops if necessary.  Doing
;;	 this gives the same kind of pipeline behavior we would see on a
;;	 normal superscalar target.
;;
;;	 This pass is generally a speed improvement, but the extra nops will
;;	 obviously make the program bigger.  It is therefore unsuitable for
;;	 -Os (at the very least).
;;
;;   (2) By modifying the scheduler hooks so that, where possible:
;;
;;	 (a) dependent instructions are separated by a non-dependent
;;	     instruction;
;;
;;	 (b) instructions that use the multiplication unit are separated
;;	     by non-multiplication instructions; and
;;
;;	 (c) memory access instructions are separated by non-memory
;;	     instructions.
;;
;;	 The idea is to keep conflicting instructions apart wherever possible
;;	 and thus make the schedule less dependent on alignment.

(define_automaton "vr4130_main, vr4130_muldiv, vr4130_mulpre")

(define_cpu_unit "vr4130_alu1, vr4130_alu2, vr4130_dcache" "vr4130_main")
(define_cpu_unit "vr4130_muldiv" "vr4130_muldiv")

;; This is a fake unit for pre-reload scheduling of multiplications.
;; It enforces the true post-reload repeat rate.
(define_cpu_unit "vr4130_mulpre" "vr4130_mulpre")

;; The scheduling hooks use this attribute for (b) above.
(define_attr "vr4130_class" "mul,mem,alu"
  (cond [(eq_attr "type" "load,store")
	 (const_string "mem")

	 (eq_attr "type" "mfhi,mflo,mthi,mtlo,imul,imul3,imadd,idiv")
	 (const_string "mul")]
	(const_string "alu")))

(define_insn_reservation "vr4130_multi" 1
  (and (eq_attr "cpu" "r4130")
       (eq_attr "type" "multi,unknown,atomic,syncloop"))
  "vr4130_alu1 + vr4130_alu2 + vr4130_dcache + vr4130_muldiv")

(define_insn_reservation "vr4130_int" 1
  (and (eq_attr "cpu" "r4130")
       (eq_attr "type" "arith,const,logical,move,nop,shift,signext,slt"))
  "vr4130_alu1 | vr4130_alu2")

(define_insn_reservation "vr4130_load" 3
  (and (eq_attr "cpu" "r4130")
       (eq_attr "type" "load"))
  "vr4130_dcache")

(define_insn_reservation "vr4130_store" 1
  (and (eq_attr "cpu" "r4130")
       (eq_attr "type" "store"))
  "vr4130_dcache")

(define_insn_reservation "vr4130_mfhilo" 3
  (and (eq_attr "cpu" "r4130")
       (eq_attr "type" "mfhi,mflo"))
  "vr4130_muldiv")

(define_insn_reservation "vr4130_mthilo" 1
  (and (eq_attr "cpu" "r4130")
       (eq_attr "type" "mthi,mtlo"))
  "vr4130_muldiv")

;; The product is available in LO & HI after one cycle.  Moving the result
;; into an integer register will take an additional three cycles, see mflo
;; & mfhi above.  Note that the same latencies and repeat rates apply if we
;; use "mtlo; macc" instead of "mult; mflo".
(define_insn_reservation "vr4130_mulsi" 4
  (and (eq_attr "cpu" "r4130")
       (and (eq_attr "type" "imul,imul3")
	    (eq_attr "mode" "SI")))
  "vr4130_muldiv + (vr4130_mulpre * 2)")

;; As for vr4130_mulsi, but the product is available in LO and HI
;; after 3 cycles.
(define_insn_reservation "vr4130_muldi" 6
  (and (eq_attr "cpu" "r4130")
       (and (eq_attr "type" "imul,imul3")
	    (eq_attr "mode" "DI")))
  "(vr4130_muldiv * 3) + (vr4130_mulpre * 4)")

;; maccs can execute in consecutive cycles without stalling, but it
;; is 3 cycles before the integer destination can be read.
(define_insn_reservation "vr4130_macc" 3
  (and (eq_attr "cpu" "r4130")
       (eq_attr "type" "imadd"))
  "vr4130_muldiv")

(define_bypass 1 "vr4130_mulsi,vr4130_macc" "vr4130_macc" "mips_linked_madd_p")
(define_bypass 1 "vr4130_mulsi,vr4130_macc" "vr4130_mfhilo")
(define_bypass 3 "vr4130_muldi" "vr4130_mfhilo")

(define_insn_reservation "vr4130_divsi" 36
  (and (eq_attr "cpu" "r4130")
       (and (eq_attr "type" "idiv")
	    (eq_attr "mode" "SI")))
  "vr4130_muldiv * 36")

(define_insn_reservation "vr4130_divdi" 72
  (and (eq_attr "cpu" "r4130")
       (and (eq_attr "type" "idiv")
	    (eq_attr "mode" "DI")))
  "vr4130_muldiv * 72")

(define_insn_reservation "vr4130_branch" 0
  (and (eq_attr "cpu" "r4130")
       (eq_attr "type" "branch,jump,call"))
  "vr4130_alu1 | vr4130_alu2")


text:
from test import get_client_credentials_session, cassette
from itertools import islice

def test_should_iterate_through_search_results():
    session = get_client_credentials_session()

    with cassette('fixtures/resources/catalog/iter_search/iterate_through_search_results.yaml'):
        docs = list(islice(session.catalog.search('mapreduce').iter(page_size=2), 3))

        # Data in the catalog can change over time so cannot search for exact strings
        # instead search for the keywords we are really interested in
        expected_substring = u'mapreduce'
        assert expected_substring in str(docs[0].title).lower()
        assert expected_substring in str(docs[1].title).lower()
        assert expected_substring in str(docs[2].title).lower()


text:
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');

module.exports = new UglifyJsPlugin({
    sourceMap: true,
    beautify: false, //prod
    output: {
        comments: false
    }, //prod
    mangle: {
        screw_ie8: true
    }, //prod
    compress: {
        screw_ie8: true,
        warnings: false,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true,
        negate_iife: false // we need this for lazy v8
    }
});