text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Reseller extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->model('Admin_model');
        $this->load->helper('url');
        $this->load->helper('form');
        $this->auth = new stdClass;
        $this->load->library('flexi_auth');
        $this->data = null;
        if ($this->flexi_auth->is_logged_in()) {
            $this->data['userinfo'] = $this->userinfo = $this->flexi_auth->get_user_by_identity_row_array();
            $this->user_id = $this->data['userinfo']['uacc_id'];
        }
    }

    function login_via_ajax() {
        if ($this->input->is_ajax_request()) {
            $this->load->model('demo_auth_model');
            $this->demo_auth_model->login_via_ajax();
            die(json_encode(array('message' => $this->flexi_auth->get_messages(), 'login_status' => $this->flexi_auth->is_logged_in())));
        }
    }

    function index() {
        $this->home();
    }

    function logout() {
        $this->Common_model->select_update('user_accounts', array('is_login' => 0), array('uacc_id' => $this->user_id));
        $this->flexi_auth->logout(TRUE);
        $this->session->set_flashdata('message', $this->flexi_auth->get_messages());
        redirect('reseller/home');
    }

    function get_client_ip() {
        //$c_info = new Users_info;
        //echo $ttt->c_ip();
        // echo $ttt->c_OS();
        // echo $ttt->c_Browser();
        //$c_info = new Users_info;
        echo $this->c_ip();
        die();
    }

    function include_files() {
        $this->data['header'] = $this->load->view('resseller/header', $this->data, TRUE);
        $this->data['common'] = $this->load->view('resseller/common', $this->data, TRUE);
        $this->data['footer'] = $this->load->view('resseller/footer', $this->data, TRUE);
        return $this->data;
    }

    function signup() {
        if ($this->input->post()) {
            $this->load->model('demo_auth_model');
            $result = $this->demo_auth_model->register_account();
        }
        $this->data['message'] = (!isset($this->data['message'])) ? $this->session->flashdata('message') : $this->data['message'];
        $this->data = $this->include_files();
        $this->load->view('resseller/signup', $this->data);
    }

    function home() {
        $this->data = $this->include_files();
        $this->load->view('resseller/home', $this->data);
    }

    function benefits() {
        $this->data = $this->include_files();
        $this->load->view('resseller/benefits', $this->data);
    }

    function earn() {
        $this->data = $this->include_files();
        $this->load->view('resseller/earn', $this->data);
    }

    function register() {
        $this->data = $this->include_files();
        $this->load->view('resseller/register', $this->data);
    }

    function faqs() {
        $this->data = $this->include_files();
        $this->load->view('resseller/faqs', $this->data);
    }

    function contact() {
        $this->data = $this->include_files();
        $this->load->view('resseller/contact', $this->data);
    }

    function update_profile() {
        $profiledata = array(
            'upro_first_name' => $this->input->post('first_name'),
            'upro_last_name' => $this->input->post('last_name'),
            'birth_date' => $this->input->post('birth_date'),
            'address' => $this->input->post('address'),
            'gender' => $this->input->post('gender'),
            'pincode' => $this->input->post('pincode'),
            'state' => $this->input->post('state'),
            'city' => $this->input->post('city')
        );
        if ($this->input->post('landline_no')) {
            $profiledata['landline_no'] = $this->input->post('landline_no');
        }
        if ($this->input->post('mobile_no')) {
            $profiledata['mobile_no'] = $this->input->post('mobile_no');
        }
        if ($this->input->post('other_no')) {
            $profiledata['other_no'] = $this->input->post('other_no');
        }
        $result = $this->Common_model->select_update('demo_user_profiles', $profiledata, array('upro_uacc_fk' => $this->user_id));
        if ($this->input->post('change_pwd') == 1) {
            $this->load->model('demo_auth_model');
            $change_password = $this->demo_auth_model->change_password();
            $this->session->set_flashdata('message', $this->data['message']);
            if ($change_password) {
                $this->session->set_flashdata('alert_class', 'alert-success');
            } else {
                $this->session->set_flashdata('alert_class', 'alert-danger');
            }
        } else if ($result) {
            $this->session->set_flashdata('message', 'Profile updated successfully');
            $this->session->set_flashdata('alert_class', 'alert-success');
        }
        $this->data['message'] = (!isset($this->data['message'])) ? $this->session->flashdata('message') : $this->data['message'];
        redirect('reseller/account');
    }

    function account() {
        if ($this->flexi_auth->is_logged_in() && $this->userinfo['uacc_group_fk'] == 2) {
            $this->data['states'] = $this->Common_model->select_all('states');
            if ($this->userinfo['city'] != null) {
                $this->data['cityname'] = $this->Common_model->select_where_row('cities', array('id' => $this->userinfo['city']));
            }
            $this->data['business_counts'] = $this->Common_model->business_counts($this->user_id);
            $this->data['message'] = (!isset($this->data['message'])) ? $this->session->flashdata('message') : $this->data['message'];
            $this->data = $this->include_files();
            $this->data['sidebar'] = $this->load->view('resseller/sidebar', $this->data, TRUE);
            $this->load->view('resseller/profile', $this->data);
        } else {
            redirect('reseller/home');
        }
    }

    function businesses() {
        if ($this->flexi_auth->is_logged_in() && $this->userinfo['uacc_group_fk'] == 2) {
            $this->load->library('pagination');
            $config = array();
            $config["base_url"] = base_url() . "reseller/businesses";
            $config["per_page"] = 5;
            $config['use_page_numbers'] = FALSE;

            $config['last_tag_open'] = '
';
            $config['last_tag_close'] = '
';
            $config['cur_tag_open'] = '
';
            $config['cur_tag_close'] = '
';
            $config['first_link'] = 'First';
            $config['first_tag_open'] = '
';
            $config['first_tag_close'] = '
';
            $config['last_link'] = 'Last';
            $config['last_tag_open'] = '
';
            $config['last_tag_close'] = '
';
            $config['next_link'] = 'Next';
            $config['next_tag_open'] = '
';
            $config['next_tag_close'] = '
';
            $config['prev_link'] = 'Previous';
            $config['prev_tag_open'] = '
';
            $config['prev_tag_close'] = '
';
            $config['num_tag_open'] = '
';
            $config['num_tag_close'] = '
';

            $total_row = $this->Common_model->businesses('', '', $this->user_id);
            $config["total_rows"] = $total_row['counts'];
            $config['num_links'] = $total_row['counts'];
            $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
            $this->data["results"] = $this->Common_model->businesses($config["per_page"], $page, $this->user_id);

            $this->pagination->initialize($config);
            $str_links = $this->pagination->create_links();
            $this->data["links"] = explode(' ', $str_links);

            $this->data['business_counts'] = $this->Common_model->business_counts($this->user_id);
            $this->data = $this->include_files();
            $this->data['sidebar'] = $this->load->view('resseller/sidebar', $this->data, TRUE);
            $this->load->view('resseller/businesses', $this->data);
        } else {
            redirect('reseller/home');
        }
    }

    public function payments() {
        if ($this->flexi_auth->is_logged_in() && $this->userinfo['uacc_group_fk'] == 2) {
            $this->load->library('pagination');
            $config = array();
            $config["base_url"] = base_url() . "reseller/payments";
            $config["per_page"] = 5;
            $config['use_page_numbers'] = FALSE;
            $config['last_tag_open'] = '
';
            $config['last_tag_close'] = '
';
            $config['cur_tag_open'] = '
';
            $config['cur_tag_close'] = '
';
            $config['first_link'] = 'First';
            $config['first_tag_open'] = '
';
            $config['first_tag_close'] = '
';
            $config['last_link'] = 'Last';
            $config['last_tag_open'] = '
';
            $config['last_tag_close'] = '
';
            $config['next_link'] = 'Next';
            $config['next_tag_open'] = '
';
            $config['next_tag_close'] = '
';
            $config['prev_link'] = 'Previous';
            $config['prev_tag_open'] = '
';
            $config['prev_tag_close'] = '
';
            $config['num_tag_open'] = '
';
            $config['num_tag_close'] = '
';

            $total_row = $this->Common_model->payments('', '', $this->user_id);
            $config["total_rows"] = $total_row['counts'];
            $config['num_links'] = $total_row['counts'];
            $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
            $this->data["results"] = $this->Common_model->payments($config["per_page"], $page, $this->user_id);

            $this->pagination->initialize($config);
            $str_links = $this->pagination->create_links();
            $this->data["links"] = explode(' ', $str_links);

            $this->data['business_counts'] = $this->Common_model->business_counts($this->user_id);
            $this->data = $this->include_files();
            $this->data['sidebar'] = $this->load->view('resseller/sidebar', $this->data, TRUE);
            $this->load->view('resseller/payments', $this->data);
        } else {
            redirect('reseller/home');
        }
    }

    function add_business($edit_business_id = null) {
        if ($this->flexi_auth->is_logged_in() && $this->userinfo['uacc_group_fk'] == 2) {
            if ($this->input->post()) {
                $from_timings_1 = implode(',', $this->input->post('from_timings'));
                $to_timings_1 = implode(',', $this->input->post('to_timings'));
                if ($this->input->post('dual_timings') == 1) {
                    $from_timings_2 = implode(',', $this->input->post('from_timings_1'));
                    $to_timings_2 = implode(',', $this->input->post('to_timings_1'));
                }
                $this->load->library('upload');
                $error = "";
                if (!empty($_FILES['avatar-1']['name'])) {
                    $config['upload_path'] = 'include_files/logo';
                    $config['allowed_types'] = 'gif|jpg|png';
                    $config['overwrite'] = FALSE;
                    $config['encrypt_name'] = TRUE;
                    $config['max_filename'] = 25;
                    $this->upload->initialize($config);
                    if (!$this->upload->do_upload('avatar-1')) {
                        $error = $this->upload->display_errors();
                    } else {
                        $file_info = $this->upload->data();
                        $company_logo = $file_info['file_name'];
                    }
                }
                if (!empty($_FILES['company_banner']['name'])) {
                    $config['upload_path'] = 'include_files/banners';
                    $config['allowed_types'] = 'gif|jpg|png';
                    $config['overwrite'] = FALSE;
                    $config['encrypt_name'] = TRUE;
                    $config['max_filename'] = 25;
                    $this->upload->initialize($config);
                    if (!$this->upload->do_upload('company_banner')) {
                        $error = $this->upload->display_errors();
                    } else {
                        $file_info = $this->upload->data();
                        $banner = $file_info['file_name'];
                    }
                }
                if ($error == "") {
                    $business_data = array(
                        'user_id' => $this->user_id,
                        'name' => $this->input->post('company_name'),
                        'category_id' => $this->input->post('category'),
                        'subcategory_id' => $this->input->post('subcategory'),
                        'address' => $this->input->post('company_address'),
                        'pincode' => $this->input->post('pincode'),
                        'state' => $this->input->post('state'),
                        'city' => $this->input->post('city'),
                        'email' => $this->input->post('email'),
                        'business_description' => $this->input->post('about_company'),
                        'services' => implode(',', $this->input->post('services')),
                        'payment_methods' => implode(',', $this->input->post('payment_mode')),
                        'min_price_range ' => $this->input->post('min_rate'),
                        'max_price_range' => $this->input->post('max_rate'),
                        'from_timings_1' => $from_timings_1,
                        'to_timings_1' => $to_timings_1,
                        'from_timings_2' => $from_timings_2,
                        'to_timings_2' => $to_timings_2,
                        'year_establishment' => $this->input->post('year_establishment')
                    );
                    if ($this->input->post('website')) {
                        $business_data['website'] = $this->input->post('website');
                    }
                    if ($this->input->post('contact_person_name')) {
                        $business_data['contact_person_name'] = $this->input->post('contact_person_name');
                    }
                    if ($this->input->post('other_locations')) {
                        $business_data['other_locations'] = implode(',', $this->input->post('other_locations'));
                    }
                    if ($this->input->post('landline_no') && $this->input->post('landline_code')) {
                        $business_data['landline_no'] = $this->input->post('landline_no');
                        $business_data['landline_code'] = $this->input->post('landline_code');
                    }
                    if ($this->input->post('mobile_no') && $this->input->post('mobile_code')) {
                        $business_data['mobile_no'] = $this->input->post('mobile_no');
                        $business_data['mobile_code'] = $this->input->post('mobile_code');
                    }
                    if ($this->input->post('other_no') && $this->input->post('other_code')) {
                        $business_data['other_no'] = $this->input->post('other_no');
                        $business_data['other_code'] = $this->input->post('other_code');
                    }

                    if (isset($banner) && $banner != "") {
                        $business_data['banner'] = $banner;
                        if ($edit_business_id != null) {
                            if (file_exists(FCPATH . 'include_files/banners/' . $this->input->post('old_banner'))) {
                                unlink(FCPATH . 'include_files/banners/' . $this->input->post('old_banner'));
                            }
                        }
                    }
                    if (isset($company_logo) && $company_logo != "") {
                        $business_data['logo'] = $company_logo;
                        if ($edit_business_id != null) {
                            if (file_exists(FCPATH . 'include_files/logo/' . $this->input->post('old_logo'))) {
                                unlink(FCPATH . 'include_files/logo/' . $this->input->post('old_logo'));
                            }
                        }
                    }
                    if ($edit_business_id != null) {
                        $old_images_post = $this->input->post('old_company_images');
                        $old_images_table = $this->db->query("select image from company_images where business_id = '" . $edit_business_id . "'")->result_array();
                        $final_images = array_diff(array_column($old_images_table, 'image'), $old_images_post);
                        foreach ($final_images as $row_image) {
                            if (file_exists(FCPATH . 'include_files/business_images/' . $row_image)) {
                                unlink(FCPATH . 'include_files/business_images/' . $row_image);
                                $this->Common_model->delete_where('company_images', array('business_id' => $edit_business_id, 'image' => $row_image));
                            }
                        }
                        $this->Common_model->select_update('businesses', $business_data, array('id' => $edit_business_id));
                        $business_id = $edit_business_id;
                    } else {
                        $business_data['earnings'] = $this->input->post('total_earnings');
                        $business_id = $this->Common_model->inserted_id('businesses', $business_data);
                    }
                    if ($business_id) {
                        $more_mobile_no_codes = $this->input->post('more_mobile_code');
                        $more_mobile_nos = $this->input->post('more_mobile_no');
                        $more_landline_no_codes = $this->input->post('more_landline_code');
                        $more_landline_nos = $this->input->post('more_landline_no');
                        $this->Common_model->delete_where('business_contacts', array('business_id' => $business_id));
                        if (count($more_mobile_nos) > count($more_landline_nos)) {
                            $more_contacts = $more_mobile_nos;
                        } else {
                            $more_contacts = $more_landline_nos;
                        }
                        foreach ($more_contacts as $key => $more_contact) {
                            $business_contacts_data = array(
                                'business_id' => $business_id
                            );
                            $add_record = '';
                            if ($more_landline_no_codes[$key] != "" && $more_landline_nos[$key]) {
                                $add_record = 1;
                                $business_contacts_data['landline_code_number'] = $more_landline_no_codes[$key];
                                $business_contacts_data['landline_number'] = $more_landline_nos[$key];
                            }
                            if ($more_mobile_no_codes[$key] != "" && $more_mobile_nos[$key] != "") {
                                $add_record = 1;
                                $business_contacts_data['mobile_no_code'] = $more_mobile_no_codes[$key];
                                $business_contacts_data['mobile_number'] = $more_mobile_nos[$key];
                            }
                            if ($add_record == 1) {
                                $this->Common_model->insert('business_contacts', $business_contacts_data);
                            }
                        }
                    }
                    if (!empty($_FILES['userFiles']['name'])) {
                        $filesCount = count($_FILES['userFiles']['name']);
                        for ($i = 0; $i < $filesCount; $i++) {
                            $_FILES['userFile']['name'] = $_FILES['userFiles']['name'][$i];
                            $_FILES['userFile']['type'] = $_FILES['userFiles']['type'][$i];
                            $_FILES['userFile']['tmp_name'] = $_FILES['userFiles']['tmp_name'][$i];
                            $_FILES['userFile']['error'] = $_FILES['userFiles']['error'][$i];
                            $_FILES['userFile']['size'] = $_FILES['userFiles']['size'][$i];

                            $uploadPath = 'include_files/business_images';
                            $config['upload_path'] = $uploadPath;
                            $config['allowed_types'] = 'gif|jpg|png';
                            $config['encrypt_name'] = TRUE;
                            $this->load->library('upload', $config);
                            $this->upload->initialize($config);
                            if ($this->upload->do_upload('userFile')) {
                                $fileData = $this->upload->data();
                                $uploadData[$i]['business_id'] = $business_id;
                                $uploadData[$i]['image'] = $fileData['file_name'];
                            }
                        }
                        if ($edit_business_id != null || $business_id) {
                            if (!empty($uploadData)) {
                                $insert = $this->db->insert_batch('company_images', $uploadData);
                            }
                            $statusMsg = ($business_id || $edit_business_id || $insert) ? 'Your ad has been saved succesfully !' : 'Some problem occurred, please try again.';
                            $this->session->set_flashdata('message', $statusMsg);
                        } else {
                            $this->session->set_flashdata('message', "Something went wrong!.Please try again later");
                            $this->data['businessinfo'] = $business_data;
                        }
                    }
                } else {
                    $this->session->set_flashdata('message', $error);
                    $this->data['businessinfo'] = $business_data;
                }
            }

            if ($edit_business_id != "") {
                $this->data['businessinfo'] = (array) $this->Common_model->get_business($edit_business_id);
                $this->data['contact_info'] = $this->Common_model->select_where('business_contacts', array('business_id' => $edit_business_id));
            }
            $this->data['categories'] = $this->Common_model->select_where('categories', array('status' => 1));
            $this->data['states'] = $this->Common_model->select_where('states', array('id' => 12));
            $this->data['business_counts'] = $this->Common_model->business_counts($this->user_id);
            $this->data['message'] = (!isset($this->data['message'])) ? $this->session->flashdata('message') : $this->data['message'];
            $this->data = $this->include_files();
            $this->data['sidebar'] = $this->load->view('resseller/sidebar', $this->data, TRUE);
            $this->load->view('resseller/add_business', $this->data);
        } else {
            redirect('reseller/home');
        }
    }

    function subcategories() {
        $subcategories = $this->Common_model->select_where('subcategories', array('category_id' => $this->input->post('category_id')));
        die(json_encode($subcategories));
    }

    function cities() {
        $cities = $this->Common_model->select_where('cities', array('state_id' => $this->input->post('state_id')));
        die(json_encode($cities));
    }

    function check_duplicates() {
        $landline_no = $this->input->post('landline_no');
        $mobile_no = $this->input->post('mobile_no');
        $other_no = $this->input->post('other_no');
        $results = $this->Common_model->get_duplicate_business($landline_no, $mobile_no, $other_no);
        die(json_encode(count($results)));
    }

    function company_images() {
        $images = $this->Common_model->get_company_images($this->input->post('business_id'));
        $company_images = array_column($images, 'image');
        $string = "";
        foreach ($company_images as $key => $image) {
            if ($key == 0) {
                $string .= base_url() . 'include_files/business_images/' . $image;
            } else {
                // $string .= ',"' . base_url().'include_files/business_images/'.$image . ',"';
            }
        }
        die(json_encode($string));
    }

    function forgotten_password() {
        if ($this->input->post()) {
            $this->load->model('demo_auth_model');
            $this->demo_auth_model->forgotten_password();
        }
        $this->data['message'] = (!isset($this->data['message'])) ? $this->session->flashdata('message') : $this->data['message'];
        $this->data = $this->include_files();
        $this->load->view('resseller/forgotten_password', $this->data);
    }

    function manual_reset_forgotten_password($user_id = FALSE, $token = FALSE) {
        if ($this->input->post()) {
            $this->load->model('demo_auth_model');
            $this->demo_auth_model->manual_reset_forgotten_password($user_id, $token);
        }
        $this->data['message'] = (!isset($this->data['message'])) ? $this->session->flashdata('message') : $this->data['message'];
        $this->data = $this->include_files();
        $this->load->view('resseller/reset_password', $this->data);
    }

}


text:
from majorkirby import GlobalConfigNode

from vpc import VPC
from data_plane import DataPlane
from application import Application
from worker import Worker
from public_hosted_zone import PublicHostedZone

from boto import cloudformation as cfn

import ConfigParser
import sys

def get_config(icp_config_path, profile):
    """Parses a configuration file

    Arguments
    :param icp_config_path: Path to the config file
    :param profile: Config profile to read
    """
    icp_config = ConfigParser.ConfigParser()
    icp_config.optionxform = str
    icp_config.read(icp_config_path)

    try:
        section = icp_config.items(profile)
    except ConfigParser.NoSectionError:
        sys.stderr.write('There is no section [{}] in the configuration '
                         'file\n'.format(profile))
        sys.stderr.write('you specified. Did you specify the correct file?')
        sys.exit(1)

    return {k: v.strip('"').strip("'") for k, v in section}

def build_graph(icp_config, aws_profile, **kwargs):
    """
    Builds graphs for all of the ICP stacks
    Args:
      icp_config (dict): dictionary representation of `default.yml`
      aws_profile (str): name of AWS profile to use for authentication
    """

    if kwargs['stack_color'] is not None:
        icp_config['StackColor'] = kwargs['stack_color'].capitalize()

    global_config = GlobalConfigNode(**icp_config)
    vpc = VPC(globalconfig=global_config, aws_profile=aws_profile)
    data_plane = DataPlane(globalconfig=global_config, VPC=vpc,
                           aws_profile=aws_profile)
    application = Application(globalconfig=global_config, VPC=vpc,
                              DataPlane=data_plane,
                              aws_profile=aws_profile)
    worker = Worker(globalconfig=global_config, VPC=vpc,
                    DataPlane=data_plane, aws_profile=aws_profile)
    public_hosted_zone = PublicHostedZone(globalconfig=global_config,
                                          Application=application,
                                          aws_profile=aws_profile)

    return data_plane, application, worker, public_hosted_zone

def build_stacks(icp_config, aws_profile, **kwargs):
    """Trigger actual building of graphs"""
    data_plane_graph, application_graph, worker_graph, \
        public_hosted_zone_graph = build_graph(icp_config, aws_profile,
                                               **kwargs)
    data_plane_graph.go()

    if kwargs['stack_color'] is not None:
        application_graph.go()
        worker_graph.go()

    if kwargs['activate_dns']:
        public_hosted_zone_graph.go()

def destroy_stacks(icp_config, aws_profile, **kwargs):
    """Destroy stacks that are associated with stack_color"""
    region = icp_config['Region']
    stack_type = icp_config['StackType']
    stack_color = kwargs['stack_color']

    cfn_conn = cfn.connect_to_region(region, profile_name=aws_profile)
    stack_tag = ('StackType', stack_type)
    color_tag = ('StackColor', stack_color.capitalize())

    [stack.delete() for stack in cfn_conn.describe_stacks()
     if color_tag in stack.tags.items() and stack_tag in stack.tags.items()]

redpajama_set_name: RedPajamaGithub


text:
package io.druid.indexing.common.actions;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableSet;
import com.metamx.emitter.service.ServiceMetricEvent;
import io.druid.indexing.common.task.Task;
import io.druid.query.DruidMetrics;
import io.druid.timeline.DataSegment;

import java.io.IOException;
import java.util.Set;

public class SegmentNukeAction implements TaskAction<Void>
{
  @JsonIgnore
  private final Set<DataSegment> segments;

  @JsonCreator
  public SegmentNukeAction(
      @JsonProperty("segments") Set<DataSegment> segments
  )
  {
    this.segments = ImmutableSet.copyOf(segments);
  }

  @JsonProperty
  public Set<DataSegment> getSegments()
  {
    return segments;
  }

  @Override
  public TypeReference<Void> getReturnTypeReference()
  {
    return new TypeReference<Void>()
    {
    };
  }

  @Override
  public Void perform(Task task, TaskActionToolbox toolbox) throws IOException
  {
    toolbox.verifyTaskLocks(task, segments);
    toolbox.getIndexerMetadataStorageCoordinator().deleteSegments(segments);

    // Emit metrics
    final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder()
        .setDimension(DruidMetrics.DATASOURCE, task.getDataSource())
        .setDimension(DruidMetrics.TASK_TYPE, task.getType());

    for (DataSegment segment : segments) {
      metricBuilder.setDimension(DruidMetrics.INTERVAL, segment.getInterval().toString());
      toolbox.getEmitter().emit(metricBuilder.build("segment/nuked/bytes", segment.getSize()));
    }

    return null;
  }

  @Override
  public boolean isAudited()
  {
    return true;
  }

  @Override
  public String toString()
  {
    return "SegmentNukeAction{" +
           "segments=" + segments +
           '}';
  }
}


text:
var TB = require('./index');

TB.test('TB', 'Test that testbear is working', function (callback) {
	TB.time('My time step');
	for (var i = 0; i < 1000000; i++) {

	}
	TB.time('My time step');
	TB.ok(true, 'Check that true is truthy');

	callback();
});

TB.test('Test that testbear is working without a group', function (callback) {
	TB.time('My time step');
	for (var i = 0; i < 1000000; i++) {

	}
	TB.time('My time step');
	TB.ok(true, 'Check that true is truthy');

	callback();
});

TB.test('TB', 'Test that testbear is working in groups with expects 2', function (callback) {
	TB.time('My time step');
	for (var i = 0; i < 1000000; i++) {

	}
	TB.time('My time step');
	TB.ok(true, 'Check that true is truthy');

	TB.expect(2);
	callback();
});

TB.test('TB', 'Test that testbear is working in groups with expects 3', function (callback) {
	TB.time('My time step');
	for (var i = 0; i < 1000000; i++) {

	}
	TB.time('My time step', 2);
	TB.ok(true, 'Check that true is truthy');
	TB.strictEqual(true, true, 'Check that strict true is truthy');
	TB.equal('1', 1, 'Check un-strict equals');
	TB.strictEqual(1, 1, 'Check strict equals');

	TB.expect(5, 'Check assertions run');
	callback();
});

TB.start();


text:
import mock
from flask import json

from tests.integration.integration_test_case import IntegrationTestCase

with open('data/en/1_0205.json') as json_data:
    data = json.load(json_data)

class TestStatic(IntegrationTestCase):
    @mock.patch('app.utilities.schema.load_schema_from_session_data')
    def test_contact(self, mock_contact):
        mock_contact.return_value = data
        self.launchSurvey('test', '0205')
        self.get('/contact-us')
        self.assertInBody('123456789012A')

    def test_contact_with_no_session(self):
        self.get('/contact-us')
        self.assertNotInBody('Please quote the reference')
        self.assertInBody('Opening hours')

    def test_cookies_and_privacy(self):
        self.get('/cookies-privacy')
        self.assertInBody('We can only use your information for research and statistical purposes. ')

    def test_cookies_and_settings(self):
        self.get('/cookies-settings')
        self.assertInBody('Cookies are small files saved on your phone, tablet or computer when you visit a website.')


text:
<?php

if(!isset($GLOBALS['rw_fmeow'])) die();

Model('CheckAdminAccess');
Model('GetData');

CheckAdminAccess();

$data = GetData("One", "Links");

ViewHtmlTop("Изменение ссылок", 'AdminEditLinks.css');
ViewHeader();

?>

<form id="f" method="POST" action="<?=$script?>?c=AdminEditLinks"></form>

Удалить

Ссылка

Комментарий

<?php $c = 0; ?>
<?php foreach($data[0]['links'] as $link): ?>

        <input form="f" type="checkbox" name="d[<?=$c?>]" />

        <input class="links-files__input" form="f" type="text" name="link[<?=$c?>]" value="<?=addslashes($link['link'])?>" />

        <textarea class="links-files__input" form="f" name="text[<?=$c?>]" rows="5"><?=addslashes($link['text'])?></textarea>

<?php $c++; ?>
<?php endforeach; ?>

        <input class="links-files__input" form="f" type="text" name="add" placeholder="Добавить записей:" />

        <input form="f" type="submit" value="Отправить" />


text:
var foo = bar
// alert is only defined in the 'browser' environment
alert("oh noes");


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace Microsoft.DotNet.Cli.Build
{
    public class SetBlobPropertiesBasedOnFileType : Task
    {
        private AzurePublisher _azurePublisher;

        [Required]
        public string AccountName { get; set; }

        [Required]
        public string AccountKey { get; set; }

        [Required]
        public string ContainerName { get; set; }

        [Required]
        public ITaskItem[] Items { get; set; }

        private AzurePublisher AzurePublisherTool
        {
            get
            {
                if (_azurePublisher == null)
                {
                    _azurePublisher = new AzurePublisher(AccountName, AccountKey, ContainerName);
                }

                return _azurePublisher;
            }
        }

        public override bool Execute()
        {
            if (Items.Length == 0)
            {
                Log.LogError("No items were provided for upload.");
                return false;
            }

            foreach (var item in Items)
            {
                string relativeBlobPath = item.GetMetadata("RelativeBlobPath");
                if (string.IsNullOrEmpty(relativeBlobPath))
                {
                    throw new Exception(string.Format(
                      "Metadata 'RelativeBlobPath' is missing for item '{0}'.",
                      item.ItemSpec));
                }

                AzurePublisherTool.SetBlobPropertiesBasedOnFileType(relativeBlobPath);
            }

            return true;
        }
    }
}


text:
#ifndef ZORBA_RSTRING_BUF_REP_H
#define ZORBA_RSTRING_BUF_REP_H

#include <cassert>
#include <stdexcept>

#include <zorba/config.h>
#include <zorba/internal/cxx_util.h>

#include "rep_base.h"
#include "rep_proxy.h"
#include "util/void_int.h"

namespace zorba {
namespace rstring_classes {

///////////////////////////////////////////////////////////////////////////////

/**
 * A %buf_rep is used to overlay a string onto an existing, fixed-capacity
 * character buffer.
 *
 * @tparam ResultRepType The representation type to be used for results.  For
 * operations that create new strings, e.g., operator+(), %buf_rep can not be
 * used because there is no existing buffer.
 */
template<class ResultRepType>
class buf_rep : public rep_base<void_int,typename ResultRepType::traits_type> {
  typedef rep_base<void_int,typename ResultRepType::traits_type> base_type;
  typedef typename base_type::raw_allocator raw_allocator;
public:
  typedef typename base_type::allocator_type allocator_type;
  typedef typename base_type::difference_type difference_type;
  typedef typename base_type::size_type size_type;
  typedef typename base_type::traits_type traits_type;

  typedef typename base_type::value_type value_type;
  typedef typename base_type::pointer pointer;
  typedef typename base_type::const_pointer const_pointer;
  typedef typename base_type::reference reference;
  typedef typename base_type::const_reference const_reference;

  typedef pointer iterator;
  typedef const_pointer const_iterator;
  typedef std::reverse_iterator<iterator> reverse_iterator;
  typedef std::reverse_iterator<const_iterator> const_reverse_iterator;

  typedef typename base_type::ref_count_type ref_count_type;
  typedef ResultRepType result_rep_type;

  /**
   *
   */
  static void assign( pointer to, size_type n, value_type c ) {
    base_type::assign( to, n, c );
  }

  /**
   *
   */
  static void copy( pointer to, const_pointer from, size_type n ) {
    base_type::copy( to, from, n );
  }

  /**
   *
   */
  static void move( pointer to, const_pointer from, size_type n ) {
    base_type::move( to, from, n );
  }

  /**
   * Constructs a %buf_rep.
   */
  buf_rep() : base_type( 0 ), p_( nullptr ) {
    this->set_length( 0 );
  }

  /**
   * Destroys this %buf_rep.
   */
  ~buf_rep() {
#ifdef ZORBA_DEBUG_STRING
    assert( !p_ );
#endif /* ZORBA_DEBUG_STRING */
  }

  // BUF_REP_CONSTRUCT_2CP_A_X
  /**
   * Constructs a %buf_rep from pointers.
   *
   * @param begin The pointer marking the beginning of the memory range.
   * @param end The pointer marking one past the end of the memory range.
   * @param a Not used.
   */
  void construct( const_pointer begin, const_pointer end,
                  allocator_type const &a );

  /**
   * Gets the string data.
   *
   * @return Returns said data.
   */
  pointer data() const {
    return p_;
  }

  /**
   * Disposes this %buf_rep.
   *
   * @param a The allocator that was used to create this %buf_rep.
   */
  void dispose( allocator_type const &a ) {
#ifdef ZORBA_DEBUG_STRING
    p_ = nullptr;
    this->set_capacity( 0 );
    this->set_length( 0 );
#endif /* ZORBA_DEBUG_STRING */
  }

  /**
   * Gets the singleton %buf_rep for the empty string.
   *
   * @return Returns said %buf_rep.
   */
  static buf_rep* empty_rep() {
    return 0;
  }

  /**
   * Reserves a minimum capacity.
   *
   * @param cap The minimum capacity to reserve.
   * @param a The allocator to use.
   * @throws std::length_error if \a cap > \c capacity() since a %buf_rep
   * can not grow in size.
   */
  void reserve( size_type cap, allocator_type const &a ) {
    if ( cap > this->capacity() )
      throw std::length_error( "reserve" );
  }

protected:
  pointer p_;
};

///////////////////////////////////////////////////////////////////////////////

/**
 * Partial template specialization for buf_rep that will implant it directly
 * inside of rstring.
 */
template<class ResultRepType>
class rep_proxy< buf_rep<ResultRepType> > : public buf_rep<ResultRepType> {
  typedef buf_rep<ResultRepType> RepType;
public:
  typedef typename RepType::allocator_type allocator_type;
  typedef typename RepType::difference_type difference_type;
  typedef typename RepType::size_type size_type;
  typedef typename RepType::traits_type traits_type;

  typedef typename RepType::value_type value_type;
  typedef typename RepType::pointer pointer;
  typedef typename RepType::const_pointer const_pointer;
  typedef typename RepType::reference reference;
  typedef typename RepType::const_reference const_reference;

  typedef typename RepType::iterator iterator;
  typedef typename RepType::const_iterator const_iterator;
  typedef typename RepType::reverse_iterator reverse_iterator;
  typedef typename RepType::const_reverse_iterator const_reverse_iterator;

  typedef rep_proxy<typename RepType::result_rep_type> result_rep_type;

  /**
   * Default constructor.
   */
  rep_proxy() { }

  /**
   * A %buf_rep can not be unshared, so this does nothing.
   */
  void make_unsharable_if_necessary( allocator_type const& ) {
    // do nothing
  }

  /**
   * A %buf_rep can not be reallocated.
   */
  void realloc( size_type, size_type, allocator_type const& ) {
    throw std::length_error( "realloc" );
  }

  /**
   * Shares 2 string representations.
   *
   * @param that The %rep_proxy of the representation to share.
   */
  void share( rep_proxy const &that, allocator_type const&,
              allocator_type const& ) {
    this->p_ = that.p_;
    this->set_capacity( that.capacity() );
    this->set_length( that.length() );
  }

  // REP_PROXY_BUF_REP_SWAP_X
  /**
   * Swaps this string representation for another.
   *
   * @param that The %rep_proxy to swap with.
   */
  void swap( rep_proxy &that );

  // REP_PROXY_BUF_REP_TAKE_X
  /**
   * Performs a destructive assignment.
   *
   * @param that The %rep_proxy to copy from.  It is set to the empty string.
   * @param this_alloc This allocator.
   * @param that_allor The allocator used by \a that.
   */
  void take( rep_proxy &that, allocator_type const &this_alloc,
             allocator_type const &that_alloc );

  /**
   * Compares 2 %rep_proxy objects for equality.
   *
   * @param i The first %rep_proxy.
   * @param j The second %rep_proxy.
   * @return Returns \c true only if they're equal.
   */
  friend bool operator==( rep_proxy const &i, rep_proxy const &j ) {
    return  i.data() == j.data() &&
            i.capacity() == j.capacity() &&
            i.length() == j.length();
  }

  /**
   * Compares 2 %rep_proxy objects for inequality.
   *
   * @param i The first %rep_proxy.
   * @param j The second %rep_proxy.
   * @return Returns \c true only if they're not equal.
   */
  friend bool operator!=( rep_proxy const &i, rep_proxy const &j ) {
    return !(i == j);
  }

private:
  // forbid these
  rep_proxy( rep_proxy const& );
  rep_proxy& operator=( rep_proxy const& );
};

///////////////////////////////////////////////////////////////////////////////

} // namespace rstring_classes
} // namespace zorba

#include "buf_rep.tcc"

#endif /* ZORBA_RSTRING_BUF_REP_H */
/*
 * Local variables:
 * mode: c++
 * End:
 */
/* vim:set et sw=2 ts=2: */


text:
package org.caleydo.view.bicluster.elem;

import static org.caleydo.view.bicluster.elem.ZoomLogic.initialOverviewScaleFactor;
import static org.caleydo.view.bicluster.elem.ZoomLogic.nextZoomDelta;
import static org.caleydo.view.bicluster.elem.ZoomLogic.toDirection;
import gleem.linalg.Vec2f;

import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.caleydo.core.data.collection.EDimension;
import org.caleydo.core.data.collection.table.Table;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.perspective.table.TablePerspective;
import org.caleydo.core.data.selection.SelectionManager;
import org.caleydo.core.data.selection.SelectionType;
import org.caleydo.core.data.virtualarray.VirtualArray;
import org.caleydo.core.event.EventListenerManager.ListenTo;
import org.caleydo.core.id.IDMappingManager;
import org.caleydo.core.id.IDMappingManagerRegistry;
import org.caleydo.core.id.IDType;
import org.caleydo.core.id.IIDTypeMapper;
import org.caleydo.core.util.color.Color;
import org.caleydo.core.util.function.AdvancedDoubleStatistics;
import org.caleydo.core.util.function.DoubleStatistics;
import org.caleydo.core.util.logging.Logger;
import org.caleydo.core.view.opengl.canvas.IGLMouseListener.IMouseEvent;
import org.caleydo.core.view.opengl.layout2.GLElement;
import org.caleydo.core.view.opengl.layout2.GLElementAccessor;
import org.caleydo.core.view.opengl.layout2.GLElementContainer;
import org.caleydo.core.view.opengl.layout2.IGLElementContext;
import org.caleydo.core.view.opengl.layout2.layout.GLLayouts;
import org.caleydo.core.view.opengl.layout2.renderer.GLRenderers;
import org.caleydo.core.view.opengl.picking.IPickingListener;
import org.caleydo.core.view.opengl.picking.Pick;
import org.caleydo.view.bicluster.elem.annotation.ALZHeatmapElement;
import org.caleydo.view.bicluster.elem.annotation.CategoricalLZHeatmapElement;
import org.caleydo.view.bicluster.elem.annotation.GoLZHeatmapElement;
import org.caleydo.view.bicluster.elem.band.AllBandsElement;
import org.caleydo.view.bicluster.elem.band.BandElement;
import org.caleydo.view.bicluster.elem.toolbar.AToolBarElement;
import org.caleydo.view.bicluster.elem.toolbar.LayoutToolBarElement;
import org.caleydo.view.bicluster.elem.toolbar.ParameterToolBarElement;
import org.caleydo.view.bicluster.elem.ui.MyUnboundSpinner;
import org.caleydo.view.bicluster.event.AlwaysShowToolBarEvent;
import org.caleydo.view.bicluster.event.ChangeMaxDistanceEvent;
import org.caleydo.view.bicluster.event.LZThresholdChangeEvent;
import org.caleydo.view.bicluster.event.ShowHideBandsEvent;
import org.caleydo.view.bicluster.event.ShowToolBarEvent;
import org.caleydo.view.bicluster.event.ZoomEvent;
import org.caleydo.view.bicluster.internal.prefs.MyPreferences;
import org.caleydo.view.bicluster.sorting.CategoricalSortingStrategyFactory;
import org.caleydo.view.bicluster.sorting.EThresholdMode;
import org.caleydo.view.bicluster.sorting.IntFloat;
import org.caleydo.view.bicluster.util.SetUtils;

import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

/**
 * @author user
 *
 */
public class GLRootElement extends GLElementContainer {
	private static final Logger log = Logger.create(GLRootElement.class);

	private final ParameterToolBarElement toolbarParam = new ParameterToolBarElement();
	private final LayoutToolBarElement layoutParam = new LayoutToolBarElement();
	private final List<AToolBarElement> toolbars = Arrays.asList(toolbarParam, layoutParam);

	private boolean dimBands = MyPreferences.isShowDimBands();
	private boolean recBands = MyPreferences.isShowRecBands();

	private int maxDistance = MyPreferences.getMaxDistance();

	private boolean isShowAlwaysToolBar = false;

	private BiClustering clustering;
	private final AllClustersElement clusters = new AllClustersElement(this);
	private AllBandsElement bands;
	private TablePerspective x;

	/**
	 * a special layer just for watching for zooming events
	 */
	private final GLElement zoomLayer = new GLElement().setVisibility(EVisibility.PICKABLE)
.setPicker(
			GLRenderers.fillRect(Color.CYAN));

	private IIDTypeMapper<Integer, String> dim2label;
	private IIDTypeMapper<Integer, String> rec2label;

	public GLRootElement() {
		setLayout(GLLayouts.LAYERS);
		zoomLayer.onPick(new IPickingListener() {
			@Override
			public void pick(Pick pick) {
				onZoomLayerPick(pick);
			}
		});
		this.add(zoomLayer);

		this.layoutParam.fill(clusters.getLayout());
	}

	/**
	 * @param pick
	 */
	protected void onZoomLayerPick(Pick pick) {
		switch (pick.getPickingMode()) {
		case MOUSE_WHEEL:
			zoom((IMouseEvent) pick);
			break;
		default:
			break;
		}
	}

	/**
	 * @param f
	 */
	protected void zoom(IMouseEvent event) {
		final int dim = toDirection(event, EDimension.DIMENSION);
		final int rec = toDirection(event, EDimension.RECORD);
		if (dim == 0 && rec == 0)
			return;
		setZoom(dim, rec);
	}

	/**
	 * @param dim
	 * @param rec
	 */
	private void setZoom(int dim, int rec) {
		final Iterable<ClusterElement> clusters = this.clusters.allClusters();
		final int size = this.clusters.size();
		double[] dimValues = new double[size];
		double[] recValues = new double[size];
		int i = 0;
		for (ClusterElement elem : clusters) {
			if (elem.isFocused())
				continue;
			float d = nextZoomDelta(dim, elem.getZoom(EDimension.DIMENSION), elem.getDimSize());
			float r = nextZoomDelta(rec, elem.getZoom(EDimension.RECORD), elem.getRecSize());
			dimValues[i] = elem.getZoom(EDimension.DIMENSION) + d;
			recValues[i] = elem.getZoom(EDimension.RECORD) + r;
			i++;
		}
		final AdvancedDoubleStatistics dimStats = AdvancedDoubleStatistics.of(dimValues);
		final AdvancedDoubleStatistics recStats = AdvancedDoubleStatistics.of(recValues);
		final float dimNext = (float) dimStats.getMedian();
		final float recNext = (float) recStats.getMedian();

		for (ClusterElement elem : clusters) {
			if (elem.isFocused()) // no global zoom for focussed elements
				continue;
			elem.setZoom(dimNext, recNext);
		}
	}

	@ListenTo
	private void onZoomEvent(ZoomEvent event) {
		final EDimension dim = event.getDim();
		switch (event.getDirection()) {
		case -1:
			setZoom(-1, dim);
			return;
		case 0:
			zoomReset();
			return;
		case 1:
			setZoom(1, dim);
			return;
		}
	}

	/**
	 * @param dim
	 * @param dim
	 */
	private void setZoom(int dir, EDimension dim) {
		setZoom(dim == null || dim.isHorizontal() ? dir : 0, dim == null || dim.isVertical() ? dir : 0);
	}

	private void zoomReset() {
		for (ClusterElement elem : clusters.allClusters())
			elem.zoomReset();
	}

	@Override
	public void layout(int deltaTimeMs) {
		for (AToolBarElement toolbar : toolbars)
			if (toolbar.hasMoved()) {
				clusters.relayout();
				bands.relayout();
				break;
			}
		super.layout(deltaTimeMs);
	}

	/**
	 * @return the isShowAlwaysToolBar, see {@link #isShowAlwaysToolBar}
	 */
	public boolean isShowAlwaysToolBar() {
		return isShowAlwaysToolBar;
	}

	@ListenTo
	private void onAlwaysShowToolBarEvent(AlwaysShowToolBarEvent event) {
		this.isShowAlwaysToolBar = !isShowAlwaysToolBar;
		for (GLElement elem : clusters)
			GLElementAccessor.relayoutDown(elem);
	}

	/**
	 * @return the toolbars, see {@link #toolbars}
	 */
	public List<AToolBarElement> getToolbars() {
		return toolbars;
	}

	public boolean isRecBandsEnabled() {
		return recBands;
	}

	public boolean isDimBandsEnabled() {
		return dimBands;
	}

	public boolean isBandsEnabled(EDimension dim) {
		return dim.select(dimBands, recBands);
	}

	/**
	 * @return the maxDistance, see {@link #maxDistance}
	 */
	public int getMaxDistance() {
		return maxDistance;
	}

	@ListenTo
	private void onChangeMaxDistanceEvent(ChangeMaxDistanceEvent event) {
		this.maxDistance = event.getMaxDistance();
		this.clusters.onChangeMaxDistance();
		this.clusters.relayout();
		this.bands.relayout();
	}

	@Override
	protected void init(IGLElementContext context) {
		super.init(context);
		// show the global toolbar as a popup
		toolbarParam.toggle(context);
	}

	@ListenTo
	private void onShowToolBar(ShowToolBarEvent event) {
		if (context == null)
			return;
		boolean parameters = event.isShowParameter();
		if (parameters)
			toolbars.get(0).toggle(context);
		else
			toolbars.get(1).toggle(context);
		clusters.relayout();
	}

	/**
	 * @param biClustering
	 * @param size
	 * @param maxDimThreshold
	 * @param maxRecThreshold
	 */
	public void init(BiClustering biClustering, TablePerspective x, Vec2f size, double maxDimThreshold,
			double maxRecThreshold) {
		this.x = x;
		this.clustering = biClustering;

		this.dim2label = x2Label(this.x.getDimensionPerspective().getIdType());
		this.rec2label = x2Label(this.x.getRecordPerspective().getIdType());

		for (AToolBarElement toolbar : getToolbars())
			toolbar.init(biClustering);

		bands = new AllBandsElement(x);
		this.clear();
		this.add(zoomLayer);
		this.add(bands);
		this.add(clusters);

		final int count = biClustering.getBiClusterCount();
		log.info(count + " bi clusters loaded.");
		List<Dimension> dimensions = new ArrayList<>();
		for (int i = 0; i < count; ++i) {
			final ClusterElement el = new NormalClusterElement(i, clustering.getData(i), clustering, maxDimThreshold,
					maxRecThreshold);
			clusters.add(el);
			dimensions.add(el.getSizes());
		}

		final Map<EDimension, Float> scales = initialOverviewScaleFactor(dimensions, size.x(), size.y());
		final float dimScale = scales.get(EDimension.DIMENSION);
		final float recScale = scales.get(EDimension.RECORD);

		log.info("creating bands");
		final List<GLElement> l = clusters.asList();
		for (int i = 0; i < l.size(); ++i) {
			ClusterElement start = (ClusterElement) l.get(i);
			start.setZoom(dimScale, recScale);

			for (int j = i + 1; j < l.size(); ++j) {
				ClusterElement end = (ClusterElement) l.get(j);
				Edge edge = new Edge(start, end);
				start.addEdge(end, edge);
				end.addEdge(start, edge);
				bands.add(new BandElement(edge, EDimension.RECORD, bands.getRecordSelectionManager(), rec2label));
				bands.add(new BandElement(edge, EDimension.DIMENSION, bands.getDimensionSelectionManager(), dim2label));
			}
		}
		bands.updateSelection();
		bands.updateStructure();
	}

	public void initializeScaleFactor(Vec2f size) {
		if (clusters.isAnyFocussed())
			return;
		List<Dimension> dimensions = new ArrayList<>();
		final List<GLElement> l = clusters.asList();
		for (int i = 0; i < l.size(); ++i) {
			ClusterElement elem = (ClusterElement) l.get(i);
			dimensions.add(elem.getSizes());
		}

		final Map<EDimension, Float> scales = initialOverviewScaleFactor(dimensions, size.x(), size.y());
		final float dimScale = scales.get(EDimension.DIMENSION);
		final float recScale = scales.get(EDimension.RECORD);

		for (int i = 0; i < l.size(); ++i) {
			ClusterElement start = (ClusterElement) l.get(i);
			start.setZoom(dimScale, recScale);
		}
		bands.updateStructure();
	}

	/**
	 * @param idType
	 * @return
	 */
	private static IIDTypeMapper<Integer, String> x2Label(IDType idType) {
		return IDMappingManagerRegistry.get().getIDMappingManager(idType)
				.getIDTypeMapper(idType, idType.getIDCategory().getHumanReadableIDType());
	}

	/**
	 *
	 */
	public void reset() {
		this.x = null;
		this.clustering = null;

		this.clear();
		clusters.clear();
		this.bands = null;
	}

	@ListenTo
	private void listenTo(LZThresholdChangeEvent event) {
		final EDimension dim = event.getDim();
		final int numberThreshold = event.getNumberThreshold();
		final float threshold = event.getThreshold();
		final EThresholdMode mode = event.getMode();

		// 1. update thresholds
		Iterable<NormalClusterElement> allNormalClusters = allNormalClusters();
		DoubleStatistics.Builder b = DoubleStatistics.builder();
		final Vec2f total = getSize();
		for (NormalClusterElement cluster : allNormalClusters) {
			Dimension old = cluster.getSizes();
			cluster.setThreshold(dim, threshold, numberThreshold, mode);
			Dimension new_ = cluster.getSizes();
			float s = ZoomLogic.adaptScaleFactorToSize(dim, old, new_, cluster.getZoom(EDimension.DIMENSION),
					cluster.getZoom(EDimension.RECORD), total.x(), total.y());
			// System.out.println(s);
			b.add(s);
		}
		float s = (float) b.build().getMin();
		if (s != 1.0f) {
			for (ClusterElement elem : clusters.allClusters()) {
				elem.scaleZoom(dim.select(s, 1), dim.select(1, s));
			}
		}

		// 2. update overlaps
		updateAllEdges();
		clusters.relayout();
	}

	/**
	 * @return
	 */
	private Dimension getSizes() {
		return new Dimension(x.getNrDimensions(), x.getNrRecords());
	}

	private Iterable<NormalClusterElement> allNormalClusters() {
		return Iterables.filter(clusters, NormalClusterElement.class);
	}

	@ListenTo
	private void onShowHideBandsEvent(ShowHideBandsEvent event) {
		this.dimBands = event.isShowDimBand();
		this.recBands = event.isShowRecBand();
		this.bands.relayout();
		this.clusters.onChangeMaxDistance();
	}

	/**
	 *
	 * @param isDimensionThresholds
	 * @param thresholds
	 *            bicluster id x threshold
	 */
	public void setThresholds(EDimension dimension, Map<Integer, Float> thresholds) {
		float thresh = Float.NEGATIVE_INFINITY;
		for (NormalClusterElement elem : allNormalClusters()) {
			int number = elem.getBiClusterNumber();
			if (thresholds.containsKey(number)) {
				float t = thresholds.get(number);
				if (Float.isInfinite(thresh))
					thresh = t;
				if (t != thresh)
					thresh = Float.NaN;
				elem.setThreshold(dimension, t, MyUnboundSpinner.UNBOUND, EThresholdMode.ABS);
			}
		}
		if (!Float.isNaN(thresh) && !Float.isInfinite(thresh)) { // all the same set that in the parameter toolbar
			this.toolbarParam.setThreshold(dimension, thresh);
		}
		updateAllEdges();
	}

	private void updateAllEdges() {
		// update all edges
		for (ClusterElement elem : clusters.allClusters()) {
			elem.updateOutgoingEdges(true, true);
		}
		for (ClusterElement elem : clusters.allClusters()) {
			elem.onEdgeUpdateDone();
		}
		bands.relayout();
	}

	/**
	 * @param shared
	 * @param selection
	 * @param mouseOver
	 * @return
	 */
	public boolean isAnyRecSelected(Collection<Integer> ids, SelectionType... toCheck) {
		return isAnySelected(ids, bands.getRecordSelectionManager(), toCheck);
	}

	/**
	 * checks whether any of the given ids is an active element within the given SelectionTypes
	 *
	 * @param ids
	 * @param manager
	 * @param toCheck
	 * @return
	 */
	private boolean isAnySelected(Collection<Integer> ids, SelectionManager manager, SelectionType[] toCheck) {
		if (toCheck.length == 0)
			return false;
		for (SelectionType type : toCheck) {
			if (SetUtils.containsAny(manager.getElements(type), ids))
				return true;
		}
		return false;
	}

	public boolean isAnyDimSelected(Collection<Integer> ids, SelectionType... toCheck) {
		return isAnySelected(ids, bands.getRecordSelectionManager(), toCheck);
	}

	/**
	 *
	 */
	public void focusPrevious() {
		if (clusters != null)
			clusters.focusPrevious();
	}

	public void focusNext() {
		if (clusters != null)
			clusters.focusNext();
	}

	/**
	 * @param record
	 * @param t
	 */
	public void addCategoricalAnnotation(EDimension dimension, TablePerspective t) {
		final Integer oppositeID = dimension.select(t.getRecordPerspective(), t.getDimensionPerspective())
				.getVirtualArray().get(0);
		final Table table = t.getDataDomain().getTable();
		final IDType target = dimension.select(t.getDataDomain().getDimensionIDType(), t.getDataDomain()
				.getRecordIDType());
		ATableBasedDataDomain source = clustering.getXDataDomain();
		if (source.getDimensionIDCategory().isOfCategory(target)) {
			final IIDTypeMapper<Integer, Integer> mapper = source.getDimensionIDMappingManager().getIDTypeMapper(
					source.getDimensionIDType(), target);
			final CategoricalSortingStrategyFactory factory = new CategoricalSortingStrategyFactory(
					EDimension.DIMENSION, oppositeID, table, mapper);
			toolbarParam.addSortingMode(factory, EDimension.DIMENSION);
			for (NormalClusterElement cluster : allNormalClusters())
				cluster.addAnnotation(new CategoricalLZHeatmapElement(EDimension.DIMENSION, factory));
		} else if (source.getRecordIDCategory().isOfCategory(target)) {
			final IIDTypeMapper<Integer, Integer> mapper = source.getRecordIDMappingManager().getIDTypeMapper(
					source.getRecordIDType(), target);

			final CategoricalSortingStrategyFactory factory = new CategoricalSortingStrategyFactory(EDimension.RECORD,
					oppositeID, table, mapper);
			toolbarParam.addSortingMode(factory, EDimension.RECORD);
			for (NormalClusterElement cluster : allNormalClusters())
				cluster.addAnnotation(new CategoricalLZHeatmapElement(EDimension.RECORD, factory));
		}
	}

	public void addMultiAnnotation(EDimension dim, TablePerspective t) {
		final IDType annotateTo = clustering.getIDType(dim);
		final IDMappingManagerRegistry registry = IDMappingManagerRegistry.get();
		// record of annotation to gene/samples

		final ATableBasedDataDomain d = t.getDataDomain();
		final Table table = d.getTable();

		final IDType go = t.getRecordPerspective().getIdType();
		final IDMappingManager m = registry.getIDMappingManager(annotateTo);
		IIDTypeMapper<Integer, Integer> rec2annotateTo = m.getIDTypeMapper(go,
				annotateTo);

		IDType goLabel = rec2annotateTo.getPath().get(0).getToIDType();
		IIDTypeMapper<Integer, String> rec2label = m.getIDTypeMapper(go, goLabel);

		for (NormalClusterElement cluster : allNormalClusters()) {
			Integer col = cluster.getBiClusterNumber();
			List<Integer> records = findBestColumns(col, t);
			if (records.isEmpty())
				continue;
			for (Integer record : records) {
				float pValue = ((Number) table.getRaw(col, record)).floatValue();
				Set<Integer> containedGenes = containedGenes(record, rec2annotateTo);
				if (containedGenes == null || containedGenes.isEmpty())
					continue;
				final Set<String> labels = rec2label.apply(record);
				String label = labels == null ? record.toString() : (labels.size() == 1 ? labels.iterator().next()
						.toString() : StringUtils.join(labels, ", "));
				cluster.addAnnotation(new GoLZHeatmapElement(dim, label, pValue, Predicates.in(containedGenes), d));
			}
		}
	}

	private Set<Integer> containedGenes(Integer record, IIDTypeMapper<Integer, Integer> rec2annotateTo) {
		return rec2annotateTo.apply(record);
	}

	public void removeMultiAnnotation(EDimension dimension, TablePerspective t) {
		ATableBasedDataDomain d = t.getDataDomain();

		for (NormalClusterElement cluster : allNormalClusters()) {
			for (ALZHeatmapElement a : ImmutableList.copyOf(cluster.getAnnotations())) {
				if (a instanceof GoLZHeatmapElement && ((GoLZHeatmapElement) a).getOrigin() == d)
					cluster.removeAnnotation(a);
			}
		}
	}

	private static List<Integer> findBestColumns(Integer col, TablePerspective t) {
		final VirtualArray va = t.getRecordPerspective().getVirtualArray();
		List<IntFloat> tmp = new ArrayList<>(va.size());
		final int max = MyPreferences.getMaxNumberofGOs();
		final float pMax = MyPreferences.getMaximalGOPValue();
		final Table table = t.getDataDomain().getTable();
		for (Integer rec : va) {
			final Number n = (Number) table.getRaw(col, rec);
			if (n == null)
				continue;
			float p = n.floatValue();
			if (p > pMax || Float.isNaN(p))
				continue;
			tmp.add(new IntFloat(rec, p));
		}
		Collections.sort(tmp, IntFloat.BY_MEMBERSHIP);
		List<Integer> top = Lists.transform(tmp, IntFloat.TO_INDEX);
		if (max < tmp.size())
			return top.subList(0, max);
		return top;
	}

	/**
	 * @param record
	 * @param t
	 */
	public void removeAnnotation(EDimension dimension, TablePerspective t) {
		final Integer oppositeID = dimension.select(t.getRecordPerspective(), t.getDimensionPerspective())
				.getVirtualArray().get(0);
		final IDType target = dimension.select(t.getDataDomain().getDimensionIDType(), t.getDataDomain()
				.getRecordIDType());
		ATableBasedDataDomain source = clustering.getXDataDomain();
		if (source.getDimensionIDCategory().isOfCategory(target)) {
			for (NormalClusterElement cluster : allNormalClusters()) {
				for (CategoricalLZHeatmapElement h : Iterables.filter(cluster.getAnnotations(),
						CategoricalLZHeatmapElement.class)) {
					if (h.is(oppositeID, target)) {
						cluster.removeAnnotation(h);
						toolbarParam.removeSortingMode(h.getData(), h.getDim());
						break;
					}
				}
			}
		} else if (source.getRecordIDCategory().isOfCategory(target)) {
			for (NormalClusterElement cluster : allNormalClusters()) {
				for (CategoricalLZHeatmapElement h : Iterables.filter(cluster.getAnnotations(),
						CategoricalLZHeatmapElement.class)) {
					if (h.is(oppositeID, target)) {
						cluster.removeAnnotation(h);
						toolbarParam.removeSortingMode(h.getData(), h.getDim());
						break;
					}
				}
			}
		}
	}
}


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

module.exports = function () {
	return function (req, res, next) {
		req.domain = domain.create();

		res.on('close', function () {
			req.domain.dispose();
		});

		res.on('finish', function () {
			req.domain.dispose();
		});

		req.domain.on('error', function (err) {

			//console.error('caught domain error---------------------------------------');
			//console.log(err.stack);
			// Once a domain is disposed, further errors from the emitters in that set will be ignored.
			res.writeHead(200, {'Content-Type': 'application/json'});
			res.end(JSON.stringify({success: false, result: err}));
			console.log(err.stack);
			throw err;
			//next(err);
		});

		req.domain.run(next);
	};
};


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <title>Archive</title>
    <meta name="description" content="">

    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Merriweather:300,300italic,400,400italic,700italic,700">
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lato:300,400,700">
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Source+Code+Pro:300,400,700">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="/assets/css/vendors/slidebars.min.css">
    <link rel="stylesheet" href="/assets/css/vendors/rrssb.css">
    <link rel="stylesheet" href="/assets/css/main.css">
    <link rel="stylesheet" href="/assets/css/post.css">

    <link rel="icon" type="image/x-icon" href="/assets/images/favicon.ico">

    <link rel="apple-touch-icon-precomposed" href="/assets/images/apple-touch-icon.png" />
    <link rel="apple-touch-icon-precomposed" sizes="57x57" href="/assets/images/apple-touch-icon-57x57.png" />
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/assets/images/apple-touch-icon-72x72.png" />
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/assets/images/apple-touch-icon-114x114.png" />
    <link rel="apple-touch-icon-precomposed" sizes="120x120" href="/assets/images/apple-touch-icon-120x120.png" />
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/assets/images/apple-touch-icon-144x144.png" />
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="/assets/images/apple-touch-icon-152x152.png" />

    <link rel="canonical" href="/archive/">
    <link rel="alternate" type="application/rss+xml" title="Gilhooley" href="/feed.xml" />

    <svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="32px" height="32px" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50;" xml:space="preserve">
        <filter id="dropshadow" height="130%">
            <feGaussianBlur in="SourceAlpha" stdDeviation="10"/>
            <feOffset dx="0" dy="0" result="offsetblur"/>
            <feMerge>
                <feMergeNode/>
                <feMergeNode in="SourceGraphic"/>
            </feMerge>
        </filter>
        <path d="M43.935,25.145c0-10.318-8.364-18.683-18.683-18.683c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615c8.072,0,14.615,6.543,14.615,14.615H43.935z">
            <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.5s" repeatCount="indefinite"/>
        </path>
    </svg>

Archive

2015

            Start of Backpacking: Munich and Salzburg

            Weekend 25th: Adventures with the Bowers family in Jurbise

            Weekend July 20th: Fairs, Fun, and Staying Home

            Week One:Hallo! Ich bin David.

            Hello World!

    Menu

Gilhooley

                    Archive

                Gilhooley ‐ Copyright © 2015

                Powered by Jekyll using Travelogue


text:
<?php

    namespace papalapa\yiistart\widgets;

    use yii\grid\ActionColumn;

    /**
     * Class GridActionColumn
     * @package papalapa\yiistart\widgets
     */
    class GridActionColumn extends ActionColumn
    {
        /**
         * @var array
         */
        public $permissions = [];

        /**
         * @inheritdoc
         */
        public function init()
        {
            $this->initDefaultButton('view', 'eye-open');
            $this->initDefaultButton('update', 'pencil');
            $this->initDefaultButton('delete', 'trash', [
                'data-confirm' => \Yii::t('yii', 'Are you sure you want to delete this item?'),
                'data-method'  => 'post',
            ]);

            $this->visibleButtons = [
                'view'   => array_key_exists('view', $this->permissions) ? \Yii::$app->user->can($this->permissions['view']) : false,
                'update' => array_key_exists('update', $this->permissions) ? \Yii::$app->user->can($this->permissions['update']) : false,
                'delete' => array_key_exists('delete', $this->permissions) ? \Yii::$app->user->can($this->permissions['delete']) : false,
            ];

            parent::init();
        }
    }


text:
<?php

/**
 * Newsletter problem resource model
 *
 * @category    Mage
 * @package     Mage_Newsletter
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Newsletter_Model_Resource_Problem extends Mage_Core_Model_Resource_Db_Abstract
{
    /**
     * Define main table
     *
     */
    protected function _construct()
    {
        $this->_init('newsletter/problem', 'problem_id');
    }
}


text:
if Rails.env.development?
  user = User.create(name: 'admin',
                     email: 'admin@domain.tld',
                     password: 'password',
                     password_confirmation: 'password',
                     admin: true)

  post = user.posts.create(raw_content: 'Hello world #cut article',
                           title: 'Test post',
                           published_at: Time.now,
                           published: true)

  post.tags.create(name: 'ruby')

  Comment.create(name: 'admin',
                 blog_record_id: post.id,
                 email: 'ksevelyar@yandex.ru',
                 content: 'test comment',
                 ip: '127.0.0.1')
end


text:
@class NSArray_int;

@interface TLRPCmessages_restoreMessages : TLMetaRpc

@property (nonatomic, retain) NSArray *n_id;

- (Class)responseClass;

- (int)impliedResponseSignature;

@end

@interface TLRPCmessages_restoreMessages$messages_restoreMessages : TLRPCmessages_restoreMessages

@end


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.Reflection;
using System.Resources;

[assembly: AssemblyTitle("Microsoft Azure NotificationHubs Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure NotificationHubs management functions for managing the Microsoft Azure NotificationHubs service.")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]


text:
@implementation LHDescriptionHelpers

+ (NSString *)stringFromNodeState:(LHNodeState)state {
    switch (state) {
        case LHNodeStateNotInitialized:
            return @"not initialized";
        case LHNodeStateInactive:
            return @"inactive";
        case LHNodeStateDeactivating:
            return @"deactivating";
        case LHNodeStateActivating:
            return @"activating";
        case LHNodeStateActive:
            return @"active";
    }
}

+ (NSString *)descriptionForNodePath:(NSArray<id<LHNode>> *)path {
    NSMutableString *description = [NSMutableString string];
    for (id<LHNode> node in path) {
        if (description.length > 0) {
            [description appendString:@" -> "];
        }
        [description appendString:node.label ?: @"(unnamed)"];
    }
    return [description copy];
}

@end


text:
class Client::Gitlab::RepositoriesController < ClientController
  before_action :load_chat

  def index
    @repos = @chat.gitlab_repos
    @callback_url = GitlabService.callback_url @chat
  end
end


text:
package cn.felord.wepay.ali.sdk.api.domain;

import java.util.List;

import cn.felord.wepay.ali.sdk.api.AlipayObject;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiListField;

/**
 * 商品适用信息
 *
 * @author auto create
 * @version $Id: $Id
 */
public class AlipayItemLimitPeriodInfo extends AlipayObject {

	private static final long serialVersionUID = 8544535458573479772L;

	/**
	 * 区间范围枚举,分为:
INCLUDE(包含)
EXCLUDE(排除)
	 */
	@ApiField("rule")
	private String rule;

	/**
	 * 单位描述,分为:
MINUTE(分钟)
HOUR(小时)
WEEK_DAY(星期几)
DAY(日)
WEEK(周)
MONTH(月)
ALL(整个销售周期)
	 */
	@ApiField("unit")
	private String unit;

	/**
	 * 区间范围值,参数类型为Number
	 */
	@ApiListField("value")
	@ApiField("number")
	private List<Long> value;

	/**
	 *
Getter for the field rule.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getRule() {
		return this.rule;
	}
	/**
	 *
Setter for the field rule.

	 *
	 * @param rule a {@link java.lang.String} object.
	 */
	public void setRule(String rule) {
		this.rule = rule;
	}

	/**
	 *
Getter for the field unit.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getUnit() {
		return this.unit;
	}
	/**
	 *
Setter for the field unit.

	 *
	 * @param unit a {@link java.lang.String} object.
	 */
	public void setUnit(String unit) {
		this.unit = unit;
	}

	/**
	 *
Getter for the field value.

	 *
	 * @return a {@link java.util.List} object.
	 */
	public List<Long> getValue() {
		return this.value;
	}
	/**
	 *
Setter for the field value.

	 *
	 * @param value a {@link java.util.List} object.
	 */
	public void setValue(List<Long> value) {
		this.value = value;
	}

}


text:
package com.tws;

import com.ib.client.EWrapperMsgGenerator;

public class OptionComputation {

    public final int    reqId      ;
    public final int    tickType   ;
    public final double impliedVol ;
    public final double delta      ;
    public final double optPrice   ;
    public final double pvDividend ;
    public final double gamma      ;
    public final double vega       ;
    public final double theta      ;
    public final double undPrice   ;

    public OptionComputation(
            int    reqId      ,
            int    tickType   ,
            double impliedVol ,
            double delta      ,
            double optPrice   ,
            double pvDividend ,
            double gamma      ,
            double vega       ,
            double theta      ,
            double undPrice
    ) {
        this.reqId      = reqId      ;
        this.tickType   = tickType   ;
        this.impliedVol = impliedVol ;
        this.delta      = delta      ;
        this.optPrice   = optPrice   ;
        this.pvDividend = pvDividend ;
        this.gamma      = gamma      ;
        this.vega       = vega       ;
        this.theta      = theta      ;
        this.undPrice   = undPrice   ;
    }

    @Override
    public String toString(){
        return EWrapperMsgGenerator.tickOptionComputation(
                this.reqId      ,
                this.tickType   ,
                this.impliedVol ,
                this.delta      ,
                this.optPrice   ,
                this.pvDividend ,
                this.gamma      ,
                this.vega       ,
                this.theta      ,
                this.undPrice
        );
    }
}


text:
module NavigationHelpers
  # Maps a name to a path. Used by the
  #
  #   When /^I go to (.+)$/ do |page_name|
  #
  # step definition in web_steps.rb
  #
  def path_to(page_name)
    case page_name
    when /^Calendar$/ then '/calendar'
    when /^third_party$/ then third_party_events_path
    when /^Sign In$/ then new_user_session_path
    when /^Account Creation$/ then new_account_path
    when /^Account Deletion$/ then '/accounts/root/edit'
    # Add more mappings here.
    # Here is an example that pulls values out of the Regexp:
    #
    #   when /^(.*)'s profile page$/i
    #     user_profile_path(User.find_by_login($1))

    else
      begin
        page_name =~ /^the (.*) page$/
        path_components = $1.split(/\s+/)
        self.send(path_components.push('path').join('_').to_sym)
      rescue NoMethodError, ArgumentError
        raise "Can't find mapping from \"#{page_name}\" to a path.\n" +
          "Now, go and add a mapping in #{__FILE__}"
      end
    end
  end
end

World(NavigationHelpers)


text:
```cpp
auto operator /(const integer &v) const -> integer;
```

Divides the value of this object (left hand side of the operator) by `v` (right hand side of the operator), resulting in a new `c8::integer` object that represents the quotient.  Any remainder is lost.

### Return Value ###

A new `c8::integer` object with a value equal to the quotient of the value of this object divided by `v`.

### Exceptions ###

* `std::bad_alloc` in the event of a memory allocation failure.
* `c8::divide_by_zero` if the divisor, `v` is zero.

## See Also ##

* [class integer](c8_integer)
* [c8 library](c8)


text:
var mongodb = require('mongodb');
var database = {};

MongoClient = mongodb.MongoClient;

// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/test';

// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Unable to connect to the mongoDB server. Error:', err);
  } else {
    console.log('Connection established to', url);

    // Build our object to export
    database.find = function(collection, parameters, callback) {
    	return db.collection(collection).find(parameters).toArray(callback);
    };

    database.insert = function(collection, parameters, callback) {
      return db.collection(collection).insertOne(parameters, callback);
    };

    database.update = function(collection, query, criteria) {
      return db.collection(collection).update(query, criteria);
    }

    database.close = function() {
    	db.close();
    };

  }
});

module.exports = database;


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/security/oauth2
                           http://www.springframework.org/schema/security/spring-security-oauth2.xsd">

    <oauth:authorization-server client-details-service-ref="clientDetails"
                                token-services-ref="tokenServices">
        <oauth:refresh-token/>
        <oauth:password/>
    </oauth:authorization-server>

    <oauth:resource-server id="resourceServerFilter" token-services-ref="tokenServices"/>

    <bean id="oauthAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="demo"/>
        <!--<property name="exceptionRenderer" ref="oauthAccessDeniedRenderer"/>-->
    </bean>

    <bean id="clientAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="typeName" value="Basic"/>
        <!--<property name="exceptionRenderer" ref="oauthAccessDeniedRenderer"/>-->
    </bean>

    <bean id="oauthAccessDeniedHandler"
          class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler">

        <!--<property name="exceptionRenderer" ref="oauthAccessDeniedRenderer"/>-->
    </bean>

    <!--<bean id="oauthAccessDeniedRenderer"-->
          <!--class="com.sbhachu.oauth.demo.exception.renderer.OAuthExceptionRenderer"/>-->

    <bean id="clientCredentialsTokenEndpointFilter"
          class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
        <property name="authenticationManager" ref="clientAuthenticationManager"/>
    </bean>

    <bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
        <property name="tokenStore" ref="tokenStore"/>
        <property name="supportRefreshToken" value="true"/>
        <property name="clientDetailsService" ref="clientDetails"/>
    </bean>

</beans>


text:
/* ==========================================================================
   Helpers.js - JS Shims, helpers

   Consider using one of these libraries to provide support for
   javascript's natives across browsers

   * https://github.com/kriskowal/es5-shim
   * http://lodash.com/
   * http://sugarjs.com/
   ========================================================================== */

/*
   Array Remove
   By John Resig (MIT Licensed)
   http://ejohn.org/blog/javascript-array-remove/
   ========================================================================== */
Array.prototype.remove = Array.prototype.remove || function (from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};

/*
   String substitute, ported from MooTools
   Usage: https://gist.github.com/mrmartineau/7926397
   ========================================================================== */
String.prototype.substitute = function (object) {
	return this.replace(/\{(.+?)\}/g, function (match, name) {
		return name in object ? object[name] : match;
	});
};

/*
   Object create patch
   ========================================================================== */
if (!('create' in Object.prototype)) {
	Object.create = (function () {
		function F() { }

		return function (o) {
			if (arguments.length != 1) {
				throw new Error('Object.create implementation only accepts one parameter.');
			}
			F.prototype = o;
			return new F();
		};
	})();
}

/*
   Object comparison is not the same as if you compare primitive types.
   https://gist.github.com/nicbell/6081098
   ========================================================================== */
Object.compare = function (obj1, obj2) {
	for (var p in obj1) {
		if ( obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) {
			return false;
		}

		switch (typeof (obj1[p])) {
			case 'object':
				if (!Object.compare(obj1[p], obj2[p])) {
					return false;
				}
				break;
			case 'function':
				if (typeof (obj2[p]) == 'undefined' || (p != 'compare' && obj1[p].toString() != obj2[p].toString())) {
					return false;
				}
				break;
			default:
				if (obj1[p] != obj2[p]) {
					return false;
				}
		}
	}

	for (var p in obj2) {
		if (typeof (obj1[p]) == 'undefined') {
			return false;
		}
	}
	return true;
};


text:
package com.graphhopper.reader.osgb.dpn.potentialHazards;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import com.graphhopper.reader.Way;
import com.graphhopper.reader.osgb.OsToOsmAttributeMappingVisitor;
import com.graphhopper.reader.osgb.dpn.potentialhazards.Sand;

public class SandTest {
    static OsToOsmAttributeMappingVisitor visitor;
    @Mock
    Way way;

    @BeforeClass
    public static void createVisitor() {
        visitor = new Sand();
    }

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testVisitWayAttribute() throws Exception {
        visitor.visitWayAttribute("sand", way);
        verify(way).getTag("natural");
        verify(way).setTag("natural", "sand");
        verifyNoMoreInteractions(way);
    }

}


text:
import fs from 'fs';
import path from 'path';
import promisify from 'es6-promisify';
import {convertOneFile} from './one-file';
import {
  InvalidSourceFile, InvalidDirectory, InvalidJsonString
} from './errors';

export function convertManyFiles(fromPath, fileNames, toPath) {
  const allFiles = convertAllFiles(fromPath, fileNames, toPath);

  const checkFromPath = () =>
    checkPathExists(fromPath)
      .catch(() => {throw new InvalidDirectory(fromPath);});

  const checkToPath = () =>
    checkPathExists(toPath)
      .catch(() => {throw new InvalidDirectory(toPath);});

  const convertEm = () =>
    Promise.all(filterConversions(allFiles));

  return checkFromPath()
    .then(checkToPath)
    .then(convertEm)
  ;
}

export class Result {

  constructor() {
    this.fileName = null;
  }

  static convertedFile(fileName) {
    const result = new Result();
    result.fileName = fileName;
    return result;
  }

}

const checkPathExists = aPath => promisify(fs.access)(aPath, fs.R_OK);

function convertAllFiles(fromPath, fileNames, toPath) {
  const fromFileName = fileName => path.join(fromPath, fileName);
  const toFileName = fileName => path.join(toPath, fileName);

  return fileNames.map(fileName => {
    const destFileName = toFileName(fileName);
    return convertOneFile(fromFileName(fileName), destFileName)
      .then(() => Result.convertedFile(destFileName))
    }
  );
}

const filterConversions = allFiles =>
  allFiles.map(filterOutErrorsToIgnore);

const filterOutErrorsToIgnore = file => file
  .catch(errorGuard)
  .then(x => x);

const errorGuard = reason => {
  if (reason instanceof InvalidSourceFile) return reason;
  if (reason instanceof InvalidJsonString) return reason;
};


text:
EventHandler* EntityScriptEventHandler::spawnCopy()
{
   return new EntityScriptEventHandler(*this);
}

void EntityScriptEventHandler::handle(Event e)
{
	e.arguments.push_back(owner);
	ScriptEventHandler::handle(e);
	popEntity("me", owner);
}

EntityScriptEventHandler::EntityScriptEventHandler(XMLNode def)
   : ScriptEventHandler(def)
{
   argNames.push_back("me");
}

void EntityScriptEventHandler::registerOwner(Entity* o)
{
   owner = o;
}