text:
package com.microsoft.azure.management.datafactory.v2018_06_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The settings that will be leveraged for Netezza source partitioning.
 */
public class NetezzaPartitionSettings {
    /**
     * The name of the column in integer type that will be used for proceeding
     * range partitioning. Type: string (or Expression with resultType string).
     */
    @JsonProperty(value = "partitionColumnName")
    private Object partitionColumnName;

    /**
     * The maximum value of column specified in partitionColumnName that will
     * be used for proceeding range partitioning. Type: string (or Expression
     * with resultType string).
     */
    @JsonProperty(value = "partitionUpperBound")
    private Object partitionUpperBound;

    /**
     * The minimum value of column specified in partitionColumnName that will
     * be used for proceeding range partitioning. Type: string (or Expression
     * with resultType string).
     */
    @JsonProperty(value = "partitionLowerBound")
    private Object partitionLowerBound;

    /**
     * Get the name of the column in integer type that will be used for proceeding range partitioning. Type: string (or Expression with resultType string).
     *
     * @return the partitionColumnName value
     */
    public Object partitionColumnName() {
        return this.partitionColumnName;
    }

    /**
     * Set the name of the column in integer type that will be used for proceeding range partitioning. Type: string (or Expression with resultType string).
     *
     * @param partitionColumnName the partitionColumnName value to set
     * @return the NetezzaPartitionSettings object itself.
     */
    public NetezzaPartitionSettings withPartitionColumnName(Object partitionColumnName) {
        this.partitionColumnName = partitionColumnName;
        return this;
    }

    /**
     * Get the maximum value of column specified in partitionColumnName that will be used for proceeding range partitioning. Type: string (or Expression with resultType string).
     *
     * @return the partitionUpperBound value
     */
    public Object partitionUpperBound() {
        return this.partitionUpperBound;
    }

    /**
     * Set the maximum value of column specified in partitionColumnName that will be used for proceeding range partitioning. Type: string (or Expression with resultType string).
     *
     * @param partitionUpperBound the partitionUpperBound value to set
     * @return the NetezzaPartitionSettings object itself.
     */
    public NetezzaPartitionSettings withPartitionUpperBound(Object partitionUpperBound) {
        this.partitionUpperBound = partitionUpperBound;
        return this;
    }

    /**
     * Get the minimum value of column specified in partitionColumnName that will be used for proceeding range partitioning. Type: string (or Expression with resultType string).
     *
     * @return the partitionLowerBound value
     */
    public Object partitionLowerBound() {
        return this.partitionLowerBound;
    }

    /**
     * Set the minimum value of column specified in partitionColumnName that will be used for proceeding range partitioning. Type: string (or Expression with resultType string).
     *
     * @param partitionLowerBound the partitionLowerBound value to set
     * @return the NetezzaPartitionSettings object itself.
     */
    public NetezzaPartitionSettings withPartitionLowerBound(Object partitionLowerBound) {
        this.partitionLowerBound = partitionLowerBound;
        return this;
    }

}


text:
// Copyright 2017 The Nomulus Authors. 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.

package google.registry.tools.params;

import org.joda.time.Interval;

/** Optional wrapper for IntervalParameter. */
public final class OptionalIntervalParameter
    extends OptionalParameterConverterValidator<Interval, IntervalParameter> {}

redpajama_set_name: RedPajamaGithub


text:
import time

from openerp.osv import fields, osv

class product_product(osv.osv):
    _inherit = "product.product"

    def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True):
        """
            Inherit read_group to calculate the sum of the non-stored fields, as it is not automatically done anymore through the XML.
        """
        res = super(product_product, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby, lazy=lazy)
        if context is None:
            context = {}
        fields_list = ['turnover', 'sale_avg_price', 'sale_purchase_price', 'sale_num_invoiced', 'purchase_num_invoiced',
                       'sales_gap', 'purchase_gap', 'total_cost', 'sale_expected', 'normal_cost', 'total_margin',
                       'expected_margin', 'total_margin_rate', 'expected_margin_rate']
        if any(x in fields for x in fields_list):
            # Calculate first for every product in which line it needs to be applied
            re_ind = 0
            prod_re = {}
            tot_products = []
            for re in res:
                if re.get('__domain'):
                    products = self.search(cr, uid, re['__domain'], context=context)
                    tot_products += products
                    for prod in products:
                        prod_re[prod] = re_ind
                re_ind += 1

            res_val = self._product_margin(cr, uid, tot_products, [x for x in fields if fields in fields_list], '', context=context)
            for key in res_val.keys():
                for l in res_val[key].keys():
                    re = res[prod_re[key]]
                    if re.get(l):
                        re[l] += res_val[key][l]
                    else:
                        re[l] = res_val[key][l]
        return res

    def _product_margin(self, cr, uid, ids, field_names, arg, context=None):
        res = {}
        if context is None:
            context = {}

        for val in self.browse(cr, uid, ids, context=context):
            res[val.id] = {}
            date_from = context.get('date_from', time.strftime('%Y-01-01'))
            date_to = context.get('date_to', time.strftime('%Y-12-31'))
            invoice_state = context.get('invoice_state', 'open_paid')
            if 'date_from' in field_names:
                res[val.id]['date_from'] = date_from
            if 'date_to' in field_names:
                res[val.id]['date_to'] = date_to
            if 'invoice_state' in field_names:
                res[val.id]['invoice_state'] = invoice_state
            invoice_types = ()
            states = ()
            if invoice_state == 'paid':
                states = ('paid',)
            elif invoice_state == 'open_paid':
                states = ('open', 'paid')
            elif invoice_state == 'draft_open_paid':
                states = ('draft', 'open', 'paid')
            if "force_company" in context:
                company_id = context['force_company']
            else:
                company_id = self.pool.get("res.users").browse(cr, uid, uid, context=context).company_id.id

            #Cost price is calculated afterwards as it is a property
            sqlstr="""select
                    sum(l.price_unit * l.quantity)/sum(nullif(l.quantity,0)) as avg_unit_price,
                    sum(l.quantity) as num_qty,
                    sum(l.quantity * (l.price_subtotal/(nullif(l.quantity,0)))) as total,
                    sum(l.quantity * pt.list_price) as sale_expected
                from account_invoice_line l
                left join account_invoice i on (l.invoice_id = i.id)
                left join product_product product on (product.id=l.product_id)
                left join product_template pt on (pt.id = product.product_tmpl_id)
                where l.product_id = %s and i.state in %s and i.type IN %s and (i.date_invoice IS NULL or (i.date_invoice>=%s and i.date_invoice<=%s and i.company_id=%s))
                """
            invoice_types = ('out_invoice', 'in_refund')
            cr.execute(sqlstr, (val.id, states, invoice_types, date_from, date_to, company_id))
            result = cr.fetchall()[0]
            res[val.id]['sale_avg_price'] = result[0] and result[0] or 0.0
            res[val.id]['sale_num_invoiced'] = result[1] and result[1] or 0.0
            res[val.id]['turnover'] = result[2] and result[2] or 0.0
            res[val.id]['sale_expected'] = result[3] and result[3] or 0.0
            res[val.id]['sales_gap'] = res[val.id]['sale_expected']-res[val.id]['turnover']
            prod_obj = self.pool.get("product.product")
            ctx = context.copy()
            ctx['force_company'] = company_id
            prod = prod_obj.browse(cr, uid, val.id, context=ctx)
            invoice_types = ('in_invoice', 'out_refund')
            cr.execute(sqlstr, (val.id, states, invoice_types, date_from, date_to, company_id))
            result = cr.fetchall()[0]
            res[val.id]['purchase_avg_price'] = result[0] and result[0] or 0.0
            res[val.id]['purchase_num_invoiced'] = result[1] and result[1] or 0.0
            res[val.id]['total_cost'] = result[2] and result[2] or 0.0
            res[val.id]['normal_cost'] = prod.standard_price * res[val.id]['purchase_num_invoiced']
            res[val.id]['purchase_gap'] = res[val.id]['normal_cost'] - res[val.id]['total_cost']

            if 'total_margin' in field_names:
                res[val.id]['total_margin'] = res[val.id]['turnover'] - res[val.id]['total_cost']
            if 'expected_margin' in field_names:
                res[val.id]['expected_margin'] = res[val.id]['sale_expected'] - res[val.id]['normal_cost']
            if 'total_margin_rate' in field_names:
                res[val.id]['total_margin_rate'] = res[val.id]['turnover'] and res[val.id]['total_margin'] * 100 / res[val.id]['turnover'] or 0.0
            if 'expected_margin_rate' in field_names:
                res[val.id]['expected_margin_rate'] = res[val.id]['sale_expected'] and res[val.id]['expected_margin'] * 100 / res[val.id]['sale_expected'] or 0.0
        return res

    _columns = {
        'date_from': fields.function(_product_margin, type='date', string='Margin Date From', multi='product_margin'),
        'date_to': fields.function(_product_margin, type='date', string='Margin Date To', multi='product_margin'),
        'invoice_state': fields.function(_product_margin, type='selection', selection=[
                ('paid','Paid'),('open_paid','Open and Paid'),('draft_open_paid','Draft, Open and Paid')
            ], string='Invoice State',multi='product_margin', readonly=True),
        'sale_avg_price' : fields.function(_product_margin, type='float', string='Avg. Unit Price', multi='product_margin',
            help="Avg. Price in Customer Invoices."),
        'purchase_avg_price' : fields.function(_product_margin, type='float', string='Avg. Unit Price', multi='product_margin',
            help="Avg. Price in Vendor Bills "),
        'sale_num_invoiced' : fields.function(_product_margin, type='float', string='# Invoiced in Sale', multi='product_margin',
            help="Sum of Quantity in Customer Invoices"),
        'purchase_num_invoiced' : fields.function(_product_margin, type='float', string='# Invoiced in Purchase', multi='product_margin',
            help="Sum of Quantity in Vendor Bills"),
        'sales_gap' : fields.function(_product_margin, type='float', string='Sales Gap', multi='product_margin',
            help="Expected Sale - Turn Over"),
        'purchase_gap' : fields.function(_product_margin, type='float', string='Purchase Gap', multi='product_margin',
            help="Normal Cost - Total Cost"),
        'turnover' : fields.function(_product_margin, type='float', string='Turnover' ,multi='product_margin',
            help="Sum of Multiplication of Invoice price and quantity of Customer Invoices"),
        'total_cost'  : fields.function(_product_margin, type='float', string='Total Cost', multi='product_margin',
            help="Sum of Multiplication of Invoice price and quantity of Vendor Bills "),
        'sale_expected' :  fields.function(_product_margin, type='float', string='Expected Sale', multi='product_margin',
            help="Sum of Multiplication of Sale Catalog price and quantity of Customer Invoices"),
        'normal_cost'  : fields.function(_product_margin, type='float', string='Normal Cost', multi='product_margin',
            help="Sum of Multiplication of Cost price and quantity of Vendor Bills"),
        'total_margin' : fields.function(_product_margin, type='float', string='Total Margin', multi='product_margin',
            help="Turnover - Standard price"),
        'expected_margin' : fields.function(_product_margin, type='float', string='Expected Margin', multi='product_margin',
            help="Expected Sale - Normal Cost"),
        'total_margin_rate' : fields.function(_product_margin, type='float', string='Total Margin Rate(%)', multi='product_margin',
            help="Total margin * 100 / Turnover"),
        'expected_margin_rate' : fields.function(_product_margin, type='float', string='Expected Margin (%)', multi='product_margin',
            help="Expected margin * 100 / Expected Sale"),
    }


text:
<?php
/**
 * PayPal's method class.
 *
 * @package wc_checkout_com
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class WC_Gateway_Checkout_Com_PayPal for PayPal payment method.
 */
class WC_Gateway_Checkout_Com_PayPal extends WC_Payment_Gateway {

	/**
	 * WC_Gateway_Checkout_Com_PayPal constructor.
	 */
	public function __construct() {
		$this->id                 = 'wc_checkout_com_paypal';
		$this->method_title       = __( 'Checkout.com', 'checkout-com-unified-payments-api' );
		$this->method_description = __( 'The Checkout.com extension allows shop owners to process online payments through the Checkout.com Payment Gateway.', 'checkout-com-unified-payments-api' );
		$this->title              = __( 'PayPal', 'checkout-com-unified-payments-api' );
		$this->has_fields         = true;
		$this->supports           = [
			'products',
			'refunds',
			'subscriptions',
			'subscription_cancellation',
			'subscription_suspension',
			'subscription_reactivation',
			'subscription_date_changes',
		];

		$this->init_form_fields();
		$this->init_settings();

		// Turn these settings into variables we can use.
		foreach ( $this->settings as $setting_key => $value ) {
			$this->$setting_key = $value;
		}

		add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, [ $this, 'process_admin_options' ] );
	}

	/**
	 * Show module configuration in backend.
	 *
	 * @return string|void
	 */
	public function init_form_fields() {
		$this->form_fields = WC_Checkoutcom_Cards_Settings::paypal_settings();
		$this->form_fields = array_merge(
			$this->form_fields,
			[
				'screen_button' => [
					'id'    => 'screen_button',
					'type'  => 'screen_button',
					'title' => __( 'Other Settings', 'checkout-com-unified-payments-api' ),
				],
			]
		);
	}

	/**
	 * Generate links for the admin page.
	 *
	 * @param string $key The key.
	 * @param array  $value The value.
	 */
	public function generate_screen_button_html( $key, $value ) {
		WC_Checkoutcom_Admin::generate_links( $key, $value );
	}

	/**
	 * Show frames js on checkout page.
	 */
	public function payment_fields() {

		if ( ! empty( $this->get_option( 'description' ) ) ) {
			echo  $this->get_option( 'description' );
		}
	}

	/**
	 * Process payment with PayPal.
	 *
	 * @param int $order_id Order ID.
	 *
	 * @return array
	 */
	public function process_payment( $order_id ) {
		if ( ! session_id() ) {
			session_start();
		}

		$order = new WC_Order( $order_id );

		// Create payment with PayPal token.
		$result = (array) ( new WC_Checkoutcom_Api_Request )->create_payment( $order, [] );

		// Redirect to apm if redirection url is available.
		if ( isset( $result['3d'] ) && ! empty( $result['3d'] ) ) {

			return [
				'result'   => 'success',
				'redirect' => $result['3d'],
			];
		}

		// check if result has error and return error message.
		if ( isset( $result['error'] ) && ! empty( $result['error'] ) ) {
			WC_Checkoutcom_Utility::wc_add_notice_self( $result['error'] );
			return;
		}

		if ( class_exists( 'WC_Subscriptions_Order' ) ) {
			// Save source id for subscription.
			WC_Checkoutcom_Subscription::save_source_id( $order_id, $order, $result['source']['id'] );
		}

		// Set action id as woo transaction id.
		update_post_meta( $order_id, '_transaction_id', $result['action_id'] );
		update_post_meta( $order_id, '_cko_payment_id', $result['id'] );

		// Get cko auth status configured in admin.
		$status = WC_Admin_Settings::get_option( 'ckocom_order_authorised', 'on-hold' );

		/* translators: %s: Action ID. */
		$message = sprintf( esc_html__( 'Checkout.com Payment Authorised - Action ID : %s', 'checkout-com-unified-payments-api' ), $result['action_id'] );

		// check if payment was flagged.
		if ( $result['risk']['flagged'] ) {
			// Get cko auth status configured in admin.
			$status = WC_Admin_Settings::get_option( 'ckocom_order_flagged', 'flagged' );

			/* translators: %s: Action ID. */
			$message = sprintf( esc_html__( 'Checkout.com Payment Flagged - Action ID : %s', 'checkout-com-unified-payments-api' ), $result['action_id'] );
		}

		// add notes for the order and update status.
		$order->add_order_note( $message );
		$order->update_status( $status );

		// Reduce stock levels.
		wc_reduce_stock_levels( $order_id );

		// Remove cart.
		WC()->cart->empty_cart();

		// Return thank you page.
		return [
			'result'   => 'success',
			'redirect' => $this->get_return_url( $order ),
		];
	}

	/**
	 * Handle PayPal refund.
	 *
	 * @param int    $order_id Order ID.
	 * @param null   $amount  Amount to refund.
	 * @param string $reason Reason for refund.
	 *
	 * @return bool|WP_Error
	 */
	public function process_refund( $order_id, $amount = null, $reason = '' ) {
		$order  = wc_get_order( $order_id );
		$result = (array) WC_Checkoutcom_Api_Request::refund_payment( $order_id, $order );

		// check if result has error and return error message.
		if ( isset( $result['error'] ) && ! empty( $result['error'] ) ) {
			WC_Checkoutcom_Utility::wc_add_notice_self( $result['error'] );
			return false;
		}

		// Set action id as woo transaction id.
		update_post_meta( $order_id, '_transaction_id', $result['action_id'] );

		// Get cko auth status configured in admin.
		$status = WC_Admin_Settings::get_option( 'ckocom_order_refunded', 'refunded' );

		/* translators: %s: Action ID. */
		$message = sprintf( esc_html__( 'Checkout.com Payment refunded - Action ID : %s', 'checkout-com-unified-payments-api' ), $result['action_id'] );

		if ( isset( $_SESSION['cko-refund-is-less'] ) ) {
			if ( $_SESSION['cko-refund-is-less'] ) {
				/* translators: %s: Action ID. */
				$order->add_order_note( sprintf( esc_html__( 'Checkout.com Payment Partially refunded - Action ID : %s', 'checkout-com-unified-payments-api' ), $result['action_id'] ) );

				unset( $_SESSION['cko-refund-is-less'] );

				return true;
			}
		}

		// Add notes for the order and update status.
		$order->add_order_note( $message );
		$order->update_status( $status );

		return true;
	}

}


text:
This is the source code for Custómica, my defunct startup ([customica.com](http://customica.com)).

Custómica was an online t-shirt store for the Argentinian market where anyone could design their own t-shirt right from their browser. You can read the post-mortem [here](http://leandro.me/posts/i-am-open-sourcing-my-defunct-startup-customica/).

It failed to gain any significant traction, so I'm releasing its source code. The application is [still running](http://customica.com) in read-only mode on a free Heroku dyno.

Custómica was written entirely by myself, from the database persistence code up to the user interface.

### About the code ###

Custómica is composed of two major components:

* A [Play](http://www.playframework.org/) application written in Java.
* A t-shirt designer component written in Flex.

The t-shirt designer produces an XML description of the design that is stored in the database and used by the Java code to generate PNG images of the designs used in the rest of the application. The designer is also able to read the XML description of an existing design, so that users can modify their t-shirt designs.

I started developing Custómica using a different stack (for the curious, it was based on [Wicket](http://wicket.apache.org/) and [Guice](http://code.google.com/p/google-guice/)). At some point in mid-2011, I decided to gradually migrate to the current stack. Unfortunately I never completed the migration. There's a lot of code from the old stack that never made it to the current version, mainly a test suite for the t-shirt design rendering code and a bunch of admin screens.

Custómica is no longer being actively developed. The last code changes were the modifications needed to make the app run on Heroku, specifically a quick and dirty read-only config switch to prevent the app from writing to the filesystem.

### License ###

MIT licensed.

## Requirements ##

### Play framework ###

You need to download [Play](http://www.playframework.org/) version **1.2.4** in order to run the app.

### A PostgreSQL database ###

Custómica is currently running on Heroku using a shared PostgreSQL database, so you need a local instance of PostgreSQL to run the app from your computer.

### Facebook app ID/secret ###

Custómica uses Facebook as its login system. For it to work you need a valid Facebook app ID/secret. You can register a new Facebook app [here](https://developers.facebook.com/).

## How to run it ##

You can start the app by cd-ing into the app directory and executing `play run` (assuming you've added the Play installation directory to your system PATH), but you need to define a few environment variables first:

* `DATABASE_URL`: URL for your PostgreSQL database (e.g. postgres://username:password@hostname:port/database.)
* `FACEBOOK_ID`: Your Facebook app ID.
* `FACEBOOK_SECRET`: Your Facebook app secret.
* `ADMIN_USER`: Your desired username for the administrative dashboard (details below.)
* `ADMIN_PASS`: Password for the administrative dashboard.
* `READ_ONLY`: Whether the app is running in read-only mode or not. Possible values: true, false.

You can easily do this as a single command:

```
play run -DDATABASE_URL=postgres://<user>:<pass>@<host>:<port>/<db> -DFACEBOOK_ID=<your app ID> \
-DFACEBOOK_SECRET=<your app secret> -DREAD_ONLY=<true or false> \
-DADMIN_USER=<dashboard username> -DADMIN_PASS=<dashboad password>
```

The app will be available at http://localhost:9000/ after running the command above.

If you're starting with an empty database, the first thing you should do is create a default t-shirt category from the administrative dashboard as explained below. If you omit this step, your users won't be able to save their custom-designed t-shirts.

Note that you need to run the app from the same domain that you've specified when you registered your Facebook application, otherwise the login system won't work. You can edit your /etc/hosts file as explained [here](http://leandro.me/posts/facebook-apps-and-etc-hosts/).

## Administrative dashboard ##

You can log into the administrative dashboard by going to `<your app url>/admin` and entering the username/password combo that you've specified in the `ADMIN_USER` and `ADMIN_PASS` environment variables.

From the administrative dashboard you can create t-shirt categories, edit/remove t-shirts created by the users and review your orders and regenerate the t-shirt pictures from the designs stored in the database.

### Default t-shirt category ###

If you're starting with an empty database, go to `<your app url>/admin/crud/categories/new` and create a new default category for your t-shirts. Don't forget to check the "isDefault" option.

## Read-only mode ##

Every time a user creates a new design, the application generates a couple of PNG images that are stored in the app's public/designs directory and used to display the new t-shirt design across the website.

Custómica used to run from a paid VPS before going belly up, but now I've moved it to Heroku where it's running on a free dyno (Cedar stack).

Given the way Heroku works, it's not possible to persist data in the filesystem, so instead of rewriting the code responsible of rendering and storing the t-shirt images, I decided to just code a configuration switch to run the app in read-only mode and check some of the existing designs into the Git repository (images in `public/designs` were originally ignored by Git.)

If you want to run Custómica on Heroku, remember to set the `READ_ONLY` environment variable to true.

## Final words ##

I'd like to thank all my friends who encouraged me to pursue this project. It was a terrific learning experience and I'm a much better developer and aspiring entrepreneur because of it.

If you'd like to get in touch with me, I'm [@LeandroLovisolo](http://twitter.com/LeandroLovisolo) on Twitter.

Thanks!

-- Leandro


text:
* Patches
    * GRAS-1638 CORE : Arrays of strings are being converted to one string.	Bug
    * GRAS-1584 CORE: Unlinking An Identity removes it from the linked Identities array. But the user can still login.	Bug


text:
| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-H4 | ESP32-S3 |
| ----------------- | ----- | -------- | -------- | -------- | -------- |

# ESP-IDF Eddystone Example

This example demonstrates Eddystone-compatible BLE scanning of eddystone frame, including UID and URL.

Eddystone is an open beacon protocol specification from Google aimed at improving "proximity-based experiences"
with support for both Android and iOS smart device platforms.

Learn more on [Beacons](https://developers.google.com/nearby/notifications/get-started) and [Eddystone](https://github.com/google/eddystone).

## How to Use Example

Before project configuration and build, be sure to set the correct chip target using:

```bash
idf.py set-target <chip_name>
```

### Hardware Required

* A development board with ESP32/ESP32-C3/ESP32-H4/ESP32-C2/ESP32-S3 SoC (e.g., ESP32-DevKitC, ESP-WROVER-KIT, etc.)
* A USB cable for Power supply and programming

See [Development Boards](https://www.espressif.com/en/products/devkits) for more information about it.

### Build and Flash

Run `idf.py -p PORT flash monitor` to build, flash and monitor the project.

(To exit the serial monitor, type ``Ctrl-]``.)

See the [Getting Started Guide](https://idf.espressif.com/) for full steps to configure and use ESP-IDF to build projects.

## Example Output

```
I (0) cpu_start: Starting scheduler on APP CPU.
I (585) BTDM_INIT: BT controller compile version [1342a48]
I (585) system_api: Base MAC address is not set
I (585) system_api: read default base MAC address from EFUSE
I (595) phy_init: phy_version 4670,719f9f6,Feb 18 2021,17:07:07
I (995) EDDYSTONE_DEMO: Register callback
I (1005) EDDYSTONE_DEMO: Start scanning...
I (18135) EDDYSTONE_DEMO: --------Eddystone Found----------
I (18145) EDDYSTONE_DEMO: Device address:: 55 5d 3b ea 11 88
I (18145) EDDYSTONE_DEMO: RSSI of packet:-46 dbm
I (18145) EDDYSTONE_DEMO: Eddystone UID inform:
I (18155) EDDYSTONE_DEMO: Measured power(RSSI at 0m distance):-65 dbm
I (18155) EDDYSTONE_DEMO: EDDYSTONE_DEMO: Namespace ID:0x
I (18165) EDDYSTONE_DEMO: 6e a8 0f c9 3b 13 8e 6d 91 78
I (18175) EDDYSTONE_DEMO: EDDYSTONE_DEMO: Instance ID:0x
I (18175) EDDYSTONE_DEMO: 01 01 01 00 00 00
I (18275) EDDYSTONE_DEMO: --------Eddystone Found----------
I (18275) EDDYSTONE_DEMO: Device address:: 55 5d 3b ea 11 88
I (18275) EDDYSTONE_DEMO: RSSI of packet:-46 dbm
I (18285) EDDYSTONE_DEMO: Eddystone UID inform:
I (18285) EDDYSTONE_DEMO: Measured power(RSSI at 0m distance):-65 dbm
I (18295) EDDYSTONE_DEMO: EDDYSTONE_DEMO: Namespace ID:0x
I (18295) EDDYSTONE_DEMO: 6e a8 0f c9 3b 13 8e 6d 91 78
I (18305) EDDYSTONE_DEMO: EDDYSTONE_DEMO: Instance ID:0x
I (18315) EDDYSTONE_DEMO: 01 01 01 00 00 00
```

## Troubleshooting

For any technical queries, please open an [issue](https://github.com/espressif/esp-idf/issues) on GitHub. We will get back to you soon.


text:
#ifndef _DB_REGION_H_
#define	_DB_REGION_H_

/*
 * The DB environment consists of some number of "regions", which are described
 * by the following four structures:
 *
 *	REGENV	   -- shared information about the environment
 *	REGENV_REF -- file describing system memory version of REGENV
 *	REGION	   -- shared information about a single region
 *	REGINFO	   -- per-process information about a REGION
 *
 * There are three types of memory that hold regions:
 *	per-process heap (malloc)
 *	file mapped into memory (mmap, MapViewOfFile)
 *	system memory (shmget, CreateFileMapping)
 *
 * By default, regions are created in filesystem-backed shared memory.  They
 * can also be created in system shared memory (DB_SYSTEM_MEM), or, if private
 * to a process, in heap memory (DB_PRIVATE).
 *
 * Regions in the filesystem are named "__db.001", "__db.002" and so on.  If
 * we're not using a private environment allocated in heap, "__db.001" will
 * always exist, as we use it to synchronize on the regions, whether they are
 * in filesystem-backed memory or system memory.
 *
 * The file "__db.001" contains a REGENV structure pointing to  an
 * array of REGION structures.  Each REGION structures describes an
 * underlying chunk of shared memory.
 *
 *	__db.001
 *	+---------+
 *	|REGENV   |
 *	+---------+
 *          |
 *         \/
 *	+---------+   +----------+
 *	|REGION   |-> | __db.001 |
 *	|	  |   +----------+
 *	+---------+   +----------+
 *	|REGION   |-> | __db.002 |
 *	|	  |   +----------+
 *	+---------+   +----------+
 *	|REGION   |-> | __db.003 |
 *	|	  |   +----------+
 *	+---------+   +----------+
 *	|REGION   |-> | __db.004 |
 *	|	  |   +----------+
 *	+---------+
 *
 * The tricky part about manipulating the regions is creating or joining the
 * database environment.  We have to be sure only a single thread of control
 * creates and/or recovers a database environment.  All other threads should
 * then join without seeing inconsistent data.
 *
 * We do this in two parts: first, we use the underlying O_EXCL flag to the
 * open system call to serialize creation of the __db.001 file.  The thread
 * of control creating that file then proceeds to create the remaining
 * regions in the environment, including the mutex region.  Once the mutex
 * region has been created, the creating thread of control fills in the
 * __db.001 file's magic number.  Other threads of control (the ones that
 * didn't create the __db.001 file), wait on the initialization of the
 * __db.001 file's magic number.  After it has been initialized, all threads
 * of control can proceed, using normal shared mutex locking procedures for
 * exclusion.
 *
 * REGIONs are not moved or removed during the life of the environment, and
 * so processes can have long-lived references to them.
 *
 * One of the REGION structures describes the environment region itself.
 *
 * The REGION array is not locked in any way.  It's an array so we don't have
 * to manipulate data structures after a crash -- on some systems, we have to
 * join and clean up the mutex region after application failure.  Using an
 * array means we don't have to worry about broken links or other nastiness
 * after the failure.
 *
 * All requests to create or join a region return a REGINFO structure, which
 * is held by the caller and used to open and subsequently close the reference
 * to the region.  The REGINFO structure contains the per-process information
 * that we need to access the region.
 *
 * The one remaining complication.  If the regions (including the environment
 * region) live in system memory, and the system memory isn't "named" somehow
 * in the filesystem name space, we need some way of finding it.  Do this by
 * by writing the REGENV_REF structure into the "__db.001" file.  When we find
 * a __db.001 file that is too small to be a real, on-disk environment, we use
 * the information it contains to redirect to the real "__db.001" file/memory.
 * This currently only happens when the REGENV file is in shared system memory.
 *
 * Although DB does not currently grow regions when they run out of memory, it
 * would be possible to do so.  To grow a region, allocate a new region of the
 * appropriate size, then copy the old region over it and insert the additional
 * memory into the already existing shalloc arena.  Region users must reset
 * their base addresses and any local pointers into the memory, of course.
 * This failed in historic versions of DB because the region mutexes lived in
 * the mapped memory, and when it was unmapped and remapped (or copied),
 * threads could lose track of it.  Also, some systems didn't support mutex
 * copying, e.g., from OSF1 V4.0:
 *
 *	The address of an msemaphore structure may be significant.  If the
 *	msemaphore structure contains any value copied from an msemaphore
 *	structure at a different address, the result is undefined.
 *
 * All mutexes are now maintained in a separate region which is never unmapped,
 * so growing regions should be possible.
 */

#if defined(__cplusplus)
extern "C" {
#endif

#define	DB_REGION_PREFIX	"__db"		/* DB file name prefix. */
#define	DB_REGION_FMT		"__db.%03d"	/* Region file name format. */
#define	DB_REGION_ENV		"__db.001"	/* Primary environment name. */
#define IS_DB_FILE(name)	(strncmp(name, DB_REGION_PREFIX,	\
				    sizeof(DB_REGION_PREFIX) - 1) == 0)

#define	INVALID_REGION_ID	0	/* Out-of-band region ID. */
#define	REGION_ID_ENV		1	/* Primary environment ID. */

typedef enum {
	INVALID_REGION_TYPE=0,		/* Region type. */
	REGION_TYPE_ENV,
	REGION_TYPE_LOCK,
	REGION_TYPE_LOG,
	REGION_TYPE_MPOOL,
	REGION_TYPE_MUTEX,
	REGION_TYPE_TXN } reg_type_t;

#define	INVALID_REGION_SEGID	-1	/* Segment IDs are either shmget(2) or
					 * Win16 segment identifiers.  They are
					 * both stored in a "long", and we need
					 * an out-of-band value.
					 */
/*
 * Nothing can live at region offset 0, because, in all cases, that's where
 * we store *something*.  Lots of code needs an out-of-band value for region
 * offsets, so we use 0.
 */
#define	INVALID_ROFF		0

/* Reference describing system memory version of REGENV. */
typedef struct __db_reg_env_ref {
	roff_t	   size;		/* Region size. */
	roff_t	   max;			/* Region max in bytes. */
	long	   segid;		/* UNIX shmget ID, VxWorks ID. */
} REGENV_REF;

/* Per-environment region information. */
typedef struct __db_reg_env { /* SHARED */
	/*
	 * !!!
	 * The magic, panic, version, envid and signature fields of the region
	 * are fixed in size, the timestamp field is the first field which is
	 * variable length.  These fields must never change in order, to
	 * guarantee we can always read them, no matter what release we have.
	 *
	 * !!!
	 * The magic and panic fields are NOT protected by any mutex, and for
	 * this reason cannot be anything more complicated than zero/non-zero.
	 */
	u_int32_t magic;		/* Valid region magic number. */
	u_int32_t panic;		/* Environment is dead. */

	u_int32_t majver;		/* Major DB version number. */
	u_int32_t minver;		/* Minor DB version number. */
	u_int32_t patchver;		/* Patch DB version number. */

	u_int32_t envid;		/* Unique environment ID. */

	u_int32_t signature;		/* Structure signatures. */

	time_t	  timestamp;		/* Creation time. */

	/*
	 * Flags saved in the init_flags field of the environment, representing
	 * flags to DB_ENV->set_flags and DB_ENV->open that need to be set.
	 */
	u_int32_t init_flags;
#define	DB_INITENV_CDB		0x0001	/* DB_INIT_CDB */
#define	DB_INITENV_CDB_ALLDB	0x0002	/* DB_INIT_CDB_ALLDB */
#define	DB_INITENV_LOCK		0x0004	/* DB_INIT_LOCK */
#define	DB_INITENV_LOG		0x0008	/* DB_INIT_LOG */
#define	DB_INITENV_MPOOL	0x0010	/* DB_INIT_MPOOL */
#define	DB_INITENV_REP		0x0020	/* DB_INIT_REP */
#define	DB_INITENV_TXN		0x0040	/* DB_INIT_TXN */

	/*
	 * The mtx_regenv mutex protects the environment reference count and
	 * memory allocation from the primary shared region (the crypto, thread
	 * control block and replication implementations allocate memory from
	 * the primary shared region).
	 *
	 * The rest of the fields are initialized at creation time, and don't
	 * need mutex protection.  The flags, op_timestamp and rep_timestamp
	 * fields are used by replication only and are protected by the
	 * replication mutex.  The rep_timestamp is is not protected when it
	 * is used in recovery as that is already single threaded.
	 */
	db_mutex_t mtx_regenv;		/* Refcnt, region allocation mutex. */
	u_int32_t  refcnt;		/* References to the environment. */

	u_int32_t region_cnt;		/* Number of REGIONs. */
	roff_t	  region_off;		/* Offset of region array */
	roff_t    lt_primary;		/* Lock primary. */
	roff_t    lg_primary;		/* Log primary. */
	roff_t    tx_primary;		/* Txn primary. */

	roff_t	  cipher_off;		/* Offset of cipher area */

	roff_t	  thread_off;		/* Offset of the thread area. */

	roff_t	  rep_off;		/* Offset of the replication area. */
#define	DB_REGENV_REPLOCKED	0x0001	/* Env locked for rep backup. */
	u_int32_t flags;		/* Shared environment flags. */
#define	DB_REGENV_TIMEOUT	30	/* Backup timeout. */
	time_t	  op_timestamp;		/* Timestamp for operations. */
	time_t	  rep_timestamp;	/* Timestamp for rep db handles. */
	u_int32_t reg_panic;		/* DB_REGISTER triggered panic */
	uintmax_t unused;		/* The ALLOC_LAYOUT structure follows
					 * the REGENV structure in memory and
					 * contains uintmax_t fields.  Force
					 * proper alignment of that structure.
					 */
} REGENV;

/* Per-region shared region information. */
typedef struct __db_region { /* SHARED */
	roff_t	size;			/* Region size in bytes. */
	roff_t  max;			/* Region max in bytes. */
	long	segid;			/* UNIX shmget(2), Win16 segment ID. */

	u_int32_t	id;		/* Region id. */
	reg_type_t	type;		/* Region type. */

	roff_t	primary;		/* Primary data structure offset. */
	roff_t  alloc;			/* Region allocation size in bytes. */
} REGION;

/*
 * Per-process/per-attachment information about a single region.
 */

/*
 * Structure used for tracking allocations in DB_PRIVATE regions.
 */
struct __db_region_mem_t;	typedef struct __db_region_mem_t REGION_MEM;
struct __db_region_mem_t {
	REGION_MEM *next;
};

struct __db_reginfo_t {		/* __env_region_attach IN parameters. */
	ENV	   *env;		/* Enclosing environment. */
	reg_type_t  type;		/* Region type. */
	u_int32_t   id;			/* Region id. */

				/* env_region_attach OUT parameters. */
	REGION	   *rp;			/* Shared region. */

	char	   *name;		/* Region file name. */
	DB_FH	   *fhp;		/* Region file handle */

	void	   *addr;		/* Region address. */
	void	   *head;		/* Head of the allocation struct. */
	void	   *primary;		/* Primary data structure address. */

					/* Private Memory Tracking. */
	size_t	    max_alloc;		/* Maximum bytes allocated. */
	size_t	    allocated;		/* Bytes allocated. */
	REGION_MEM  *mem;		/* List of memory to free */

	db_mutex_t  mtx_alloc;		/* number of mutex for allocation. */

#ifdef DB_WIN32
	HANDLE	wnt_handle;		/* Win/NT HANDLE. */
#endif

#define	REGION_CREATE		0x01	/* Caller created region. */
#define	REGION_CREATE_OK	0x02	/* Caller willing to create region. */
#define	REGION_JOIN_OK		0x04	/* Caller is looking for a match. */
#define	REGION_SHARED		0x08	/* Region is shared. */
#define	REGION_TRACKED		0x10	/* Region private memory is tracked. */
	u_int32_t   flags;
};

/*
 * R_ADDR	Return a per-process address for a shared region offset.
 * R_OFFSET	Return a shared region offset for a per-process address.
 */
#define	R_ADDR(reginfop, offset)					\
	(F_ISSET((reginfop)->env, ENV_PRIVATE) ?			\
	    ROFF_TO_P(offset) :						\
	    (void *)((u_int8_t *)((reginfop)->addr) + (offset)))
#define	R_OFFSET(reginfop, p)						\
	(F_ISSET((reginfop)->env, ENV_PRIVATE) ?			\
	    P_TO_ROFF(p) :						\
	    (roff_t)((u_int8_t *)(p) - (u_int8_t *)(reginfop)->addr))

/*
 * PANIC_ISSET, PANIC_CHECK:
 *	Check to see if the DB environment is dead.
 */
#define	PANIC_ISSET(env)						\
	((env) != NULL && (env)->reginfo != NULL &&			\
	    ((REGENV *)(env)->reginfo->primary)->panic != 0 &&		\
	    !F_ISSET((env)->dbenv, DB_ENV_NOPANIC))

#define	PANIC_CHECK(env)						\
	if (PANIC_ISSET(env))						\
		return (__env_panic_msg(env));

#define	PANIC_CHECK_RET(env, ret)			       		\
	if (PANIC_ISSET(env))						\
		ret = (__env_panic_msg(env));

#if defined(__cplusplus)
}
#endif
#endif /* !_DB_REGION_H_ */


text:
package dts

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// TransferInstanceClass invokes the dts.TransferInstanceClass API synchronously
func (client *Client) TransferInstanceClass(request *TransferInstanceClassRequest) (response *TransferInstanceClassResponse, err error) {
	response = CreateTransferInstanceClassResponse()
	err = client.DoAction(request, response)
	return
}

// TransferInstanceClassWithChan invokes the dts.TransferInstanceClass API asynchronously
func (client *Client) TransferInstanceClassWithChan(request *TransferInstanceClassRequest) (<-chan *TransferInstanceClassResponse, <-chan error) {
	responseChan := make(chan *TransferInstanceClassResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.TransferInstanceClass(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// TransferInstanceClassWithCallback invokes the dts.TransferInstanceClass API asynchronously
func (client *Client) TransferInstanceClassWithCallback(request *TransferInstanceClassRequest, callback func(response *TransferInstanceClassResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *TransferInstanceClassResponse
		var err error
		defer close(result)
		response, err = client.TransferInstanceClass(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// TransferInstanceClassRequest is the request struct for api TransferInstanceClass
type TransferInstanceClassRequest struct {
	*requests.RpcRequest
	InstanceClass string `position:"Query" name:"InstanceClass"`
	DtsJobId      string `position:"Query" name:"DtsJobId"`
	OrderType     string `position:"Query" name:"OrderType"`
}

// TransferInstanceClassResponse is the response struct for api TransferInstanceClass
type TransferInstanceClassResponse struct {
	*responses.BaseResponse
	EndTime        string `json:"EndTime" xml:"EndTime"`
	HttpStatusCode int    `json:"HttpStatusCode" xml:"HttpStatusCode"`
	RequestId      string `json:"RequestId" xml:"RequestId"`
	DtsJobId       string `json:"DtsJobId" xml:"DtsJobId"`
	ErrCode        string `json:"ErrCode" xml:"ErrCode"`
	Success        bool   `json:"Success" xml:"Success"`
	ChargeType     string `json:"ChargeType" xml:"ChargeType"`
	ErrMessage     string `json:"ErrMessage" xml:"ErrMessage"`
	Code           string `json:"Code" xml:"Code"`
	DynamicMessage string `json:"DynamicMessage" xml:"DynamicMessage"`
	InstanceId     string `json:"InstanceId" xml:"InstanceId"`
}

// CreateTransferInstanceClassRequest creates a request to invoke TransferInstanceClass API
func CreateTransferInstanceClassRequest() (request *TransferInstanceClassRequest) {
	request = &TransferInstanceClassRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Dts", "2020-01-01", "TransferInstanceClass", "dts", "openAPI")
	request.Method = requests.POST
	return
}

// CreateTransferInstanceClassResponse creates a response to parse from TransferInstanceClass response
func CreateTransferInstanceClassResponse() (response *TransferInstanceClassResponse) {
	response = &TransferInstanceClassResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "Components/StaticMeshComponent.h"
#include "TankBarrel.generated.h"

/**
 *
 */
// Hold's barrel params and Elevate it
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent), hidecategories=("Rendering", "Lighting"))
class BATTLETANK_API UTankBarrel : public UStaticMeshComponent
{
	GENERATED_BODY()

public:
	// -1 max down spped, +1 max up speed
	void Elevate(float RelativeSpeed);

	UPROPERTY(EditDefaultsOnly, Category = Setup_params)
	float MaxDegreesPerSecond = 8.f; // default

	UPROPERTY(EditDefaultsOnly, Category = Setup_params)
	float MinElevationDegrees = 0.f; // default

	UPROPERTY(EditDefaultsOnly, Category = Setup_params)
	float MaxElevationDegrees = 40.f; // default
};


text:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;

namespace aspCart.Infrastructure.Migrations
{
    public partial class addProductIdInOrderItem : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "ProductId",
                table: "OrderItem",
                nullable: true);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "ProductId",
                table: "OrderItem");
        }
    }
}


text:
#include <iostream>
#include <thread>
#include "attach.h"
#include "stdafx.h"

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>

typedef int (_RunCodeInMemoryInAttachedDll)();

HINSTANCE globalDllInstance = NULL;

class NotificationHelper {
public:
#pragma warning( push )
#pragma warning( disable : 4722 )
// disable c4722 here: Destructor never returns warning. Compiler sees ExitThread and assumes that
// there is a potential memory leak.
    ~NotificationHelper(){
        std::string eventName("_pydevd_pid_event_");
        eventName += std::to_string(GetCurrentProcessId());

        // When we finish we need to set the event that the caller is waiting for and
        // unload the dll (if we don't exit this dll we won't be able to reattach later on).
        auto event = CreateEventA(nullptr, false, false, eventName.c_str());
        if (event != nullptr) {
            SetEvent(event);
            CloseHandle(event);
        }
        FreeLibraryAndExitThread(globalDllInstance, 0);
    }
#pragma warning( pop )
};

DWORD WINAPI RunCodeInThread(LPVOID lpParam){
    NotificationHelper notificationHelper; // When we exit the scope the destructor should take care of the cleanup.

#ifdef BITS_32
    HMODULE attachModule = GetModuleHandleA("attach_x86.dll");
#else
    HMODULE attachModule = GetModuleHandleA("attach_amd64.dll");
#endif

    if (attachModule == nullptr) {
        std::cout << "Error: unable to get attach_x86.dll or attach_amd64.dll module handle." << std::endl;
        return 900;
    }

    _RunCodeInMemoryInAttachedDll* runCode = reinterpret_cast < _RunCodeInMemoryInAttachedDll* > (GetProcAddress(attachModule, "RunCodeInMemoryInAttachedDll"));
    if (runCode == nullptr) {
        std::cout << "Error: unable to GetProcAddress(attachModule, RunCodeInMemoryInAttachedDll) from attach_x86.dll or attach_amd64.dll." << std::endl;
        return 901;
    }

    runCode();
    return 0;
}

/**
 * When the dll is loaded we create a thread that will call 'RunCodeInMemoryInAttachedDll'
 * in the attach dll (when completed we unload this library for a reattach to work later on).
 */
BOOL WINAPI DllMain(
  _In_ HINSTANCE hinstDLL,
  _In_ DWORD     fdwReason,
  _In_ LPVOID    lpvReserved
){
    if(fdwReason == DLL_PROCESS_ATTACH){
        globalDllInstance = hinstDLL;
        DWORD threadId;
        CreateThread(nullptr, 0, &RunCodeInThread, nullptr, 0, &threadId);
    }
    else if(fdwReason == DLL_PROCESS_DETACH){
    }
    return true;
}


text:
module Rescaffolder
  module Template
    class HAML < Rescaffolder::Template::Base

      def self.form
<<-STRING
= form_for @<%= singular_name %> do |f|<% fields.each do |field| %>
  .field
    = f.label <%= field.name.intern.inspect %>
    <%= Rescaffolder::Template::HAML.field_markup(field) %><% end %>
  .actions
    = f.submit
STRING
      end

      def self.field_markup(field)
        "= #{super}"
      end

    end
  end
end


text:
package basic

import org.apache.spark.mllib.evaluation._
import org.apache.spark.rdd.RDD

/**
  * Created by chanjinpark on 2016. 7. 8..
  */
trait Evaluation {
  def logLoss(labelAndPreds: RDD[(Double, Double)]): Double= {
    import breeze.numerics.log
    import breeze.linalg._
    //val logloss = (p:Double, y:Double) => - ( y * log(p) + (1-y) * log( 1 - p) )
    val maxmin = (p:Double) => max(min(p, 1.0 - 1e-14), 1e-14)
    val logloss = (p:Double, y:Double) => - (y * log(maxmin(p)) + (1-y) * log(1 - maxmin(p)))

    val loglossErr = labelAndPreds.map {
      case (label, pred) => logloss(pred, label)
    }.sum() / labelAndPreds.count()

    loglossErr
  }

  def MSE(labelAndPreds: RDD[(Double, Double)]): Double = {
    labelAndPreds.map{case(v, p) => math.pow(v - p, 2)}.mean()
  }

  def classificationValue(v: Double, p: Double, threshold: Double) = {
    var (tp, tn, fp, fn) = (0, 0, 0, 0)
    if ( v == 1.0 ) {
      if ( p > threshold) tp = 1
      else fn = 1
    }
    else if (v == 0.0) {
      if ( p > threshold ) fp = 1
      else tn = 1
    }
    else {
      assert(false, "no label")
    }
    (tp, tn, fp, fn, 1)
  }

  def precisionNFalsePositive(labelAndPreds: RDD[(Double, Double)], threshold: Double): (Int, Int, Int, Int, Int)= {
    val pf = labelAndPreds.map(d => classificationValue(d._1, d._2, threshold)).
    reduce((a,b) => (a._1 + b._1, a._2 + b._2, a._3 + b._3, a._4 + b._4, a._5 + b._5))
    pf
  }
}

trait SparkEvaluation {
  def evalBinaryClassification(predictionAndLabels: RDD[(Double, Double)]) = {
    val metrics = new BinaryClassificationMetrics(predictionAndLabels)
    val precision = metrics.precisionByThreshold
    precision.foreach { case (t, p) =>
      println(s"Threshold: $t, Precision: $p")
    }

    val recall = metrics.recallByThreshold
    recall.foreach { case (t, r) =>
      println(s"Threshold: $t, Recall: $r")
    }

    val PRC = metrics.pr // Precision-Recall Curve

    val f1Score = metrics.fMeasureByThreshold    // F-measure
    f1Score.foreach { case (t, f) =>
      println(s"Threshold: $t, F-score: $f, Beta = 1")
    }

    val beta = 0.5
    val fScore = metrics.fMeasureByThreshold(beta)
    f1Score.foreach { case (t, f) =>
      println(s"Threshold: $t, F-score: $f, Beta = 0.5")
    }

    // AUPRC
    val auPRC = metrics.areaUnderPR
    println("Area under precision-recall curve = " + auPRC)

    val thresholds = precision.map(_._1)   // Compute thresholds used in ROC and PR curves

    val roc = metrics.roc     // ROC Curve
    val auROC = metrics.areaUnderROC     // AUROC
    println("Area under ROC = " + auROC)
    (precision, recall, auPRC, auROC)
  }

  def evalMulticlassClassificaiton(predictionAndLabels: RDD[(Double, Double)]) = {
    // Instantiate metrics object
    val metrics = new MulticlassMetrics(predictionAndLabels)

    // Confusion matrix
    println("Confusion matrix:")
    println(metrics.confusionMatrix)

    // Precision by label
    val labels = metrics.labels
    labels.foreach { l =>
      println(s"Precision($l) = " + metrics.precision(l))
    }

    // Recall by label
    labels.foreach { l =>
      println(s"Recall($l) = " + metrics.recall(l))
    }

    // False positive rate by label
    labels.foreach { l =>
      println(s"FPR($l) = " + metrics.falsePositiveRate(l))
    }

    // F-measure by label
    labels.foreach { l =>
      println(s"F1-Score($l) = " + metrics.fMeasure(l))
    }

    // Weighted stats
    println(s"Weighted precision: ${metrics.weightedPrecision}")
    println(s"Weighted recall: ${metrics.weightedRecall}")
    println(s"Weighted F1 score: ${metrics.weightedFMeasure}")
    println(s"Weighted false positive rate: ${metrics.weightedFalsePositiveRate}")
  }

  def evalMultilabelClassification(scoreAndLabels: RDD[(Array[Double], Array[Double])]) = {
    // Instantiate metrics object
    val metrics = new MultilabelMetrics(scoreAndLabels)

    // Summary stats
    println(s"Recall = ${metrics.recall}")
    println(s"Precision = ${metrics.precision}")
    println(s"F1 measure = ${metrics.f1Measure}")
    println(s"Accuracy = ${metrics.accuracy}")

    // Individual label stats
    metrics.labels.foreach(label =>
      println(s"Class $label precision = ${metrics.precision(label)}"))
    metrics.labels.foreach(label => println(s"Class $label recall = ${metrics.recall(label)}"))
    metrics.labels.foreach(label => println(s"Class $label F1-score = ${metrics.f1Measure(label)}"))

    // Micro stats
    println(s"Micro recall = ${metrics.microRecall}")
    println(s"Micro precision = ${metrics.microPrecision}")
    println(s"Micro F1 measure = ${metrics.microF1Measure}")

    // Hamming loss
    println(s"Hamming loss = ${metrics.hammingLoss}")

    // Subset accuracy
    println(s"Subset accuracy = ${metrics.subsetAccuracy}")
  }

  def evalRanking(relevantDocuments: RDD[(Array[Double], Array[Double])]) = {

  }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM ../../../dist/idl\nsIHelperAppLauncherDialog.idl
 */

#ifndef __gen_nsIHelperAppLauncherDialog_h__
#define __gen_nsIHelperAppLauncherDialog_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIHelperAppLauncher; /* forward declaration */

class nsIFile; /* forward declaration */

/* starting interface:    nsIHelperAppLauncherDialog */
#define NS_IHELPERAPPLAUNCHERDIALOG_IID_STR "bfc739f3-8d75-4034-a6f8-1039a5996bad"

#define NS_IHELPERAPPLAUNCHERDIALOG_IID \
  {0xbfc739f3, 0x8d75, 0x4034, \
    { 0xa6, 0xf8, 0x10, 0x39, 0xa5, 0x99, 0x6b, 0xad }}

class NS_NO_VTABLE nsIHelperAppLauncherDialog : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IHELPERAPPLAUNCHERDIALOG_IID)

  enum {
    REASON_CANTHANDLE = 0U,
    REASON_SERVERREQUEST = 1U,
    REASON_TYPESNIFFED = 2U
  };

  /* void show (in nsIHelperAppLauncher aLauncher, in nsISupports aWindowContext, in unsigned long aReason); */
  NS_IMETHOD Show(nsIHelperAppLauncher *aLauncher, nsISupports *aWindowContext, uint32_t aReason) = 0;

  /* void promptForSaveToFileAsync (in nsIHelperAppLauncher aLauncher, in nsISupports aWindowContext, in wstring aDefaultFileName, in wstring aSuggestedFileExtension, in boolean aForcePrompt); */
  NS_IMETHOD PromptForSaveToFileAsync(nsIHelperAppLauncher *aLauncher, nsISupports *aWindowContext, const char16_t * aDefaultFileName, const char16_t * aSuggestedFileExtension, bool aForcePrompt) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIHelperAppLauncherDialog, NS_IHELPERAPPLAUNCHERDIALOG_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIHELPERAPPLAUNCHERDIALOG \
  NS_IMETHOD Show(nsIHelperAppLauncher *aLauncher, nsISupports *aWindowContext, uint32_t aReason) override; \
  NS_IMETHOD PromptForSaveToFileAsync(nsIHelperAppLauncher *aLauncher, nsISupports *aWindowContext, const char16_t * aDefaultFileName, const char16_t * aSuggestedFileExtension, bool aForcePrompt) override;

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIHELPERAPPLAUNCHERDIALOG(_to) \
  NS_IMETHOD Show(nsIHelperAppLauncher *aLauncher, nsISupports *aWindowContext, uint32_t aReason) override { return _to Show(aLauncher, aWindowContext, aReason); } \
  NS_IMETHOD PromptForSaveToFileAsync(nsIHelperAppLauncher *aLauncher, nsISupports *aWindowContext, const char16_t * aDefaultFileName, const char16_t * aSuggestedFileExtension, bool aForcePrompt) override { return _to PromptForSaveToFileAsync(aLauncher, aWindowContext, aDefaultFileName, aSuggestedFileExtension, aForcePrompt); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIHELPERAPPLAUNCHERDIALOG(_to) \
  NS_IMETHOD Show(nsIHelperAppLauncher *aLauncher, nsISupports *aWindowContext, uint32_t aReason) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Show(aLauncher, aWindowContext, aReason); } \
  NS_IMETHOD PromptForSaveToFileAsync(nsIHelperAppLauncher *aLauncher, nsISupports *aWindowContext, const char16_t * aDefaultFileName, const char16_t * aSuggestedFileExtension, bool aForcePrompt) override { return !_to ? NS_ERROR_NULL_POINTER : _to->PromptForSaveToFileAsync(aLauncher, aWindowContext, aDefaultFileName, aSuggestedFileExtension, aForcePrompt); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsHelperAppLauncherDialog : public nsIHelperAppLauncherDialog
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIHELPERAPPLAUNCHERDIALOG

  nsHelperAppLauncherDialog();

private:
  ~nsHelperAppLauncherDialog();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS(nsHelperAppLauncherDialog, nsIHelperAppLauncherDialog)

nsHelperAppLauncherDialog::nsHelperAppLauncherDialog()
{
  /* member initializers and constructor code */
}

nsHelperAppLauncherDialog::~nsHelperAppLauncherDialog()
{
  /* destructor code */
}

/* void show (in nsIHelperAppLauncher aLauncher, in nsISupports aWindowContext, in unsigned long aReason); */
NS_IMETHODIMP nsHelperAppLauncherDialog::Show(nsIHelperAppLauncher *aLauncher, nsISupports *aWindowContext, uint32_t aReason)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void promptForSaveToFileAsync (in nsIHelperAppLauncher aLauncher, in nsISupports aWindowContext, in wstring aDefaultFileName, in wstring aSuggestedFileExtension, in boolean aForcePrompt); */
NS_IMETHODIMP nsHelperAppLauncherDialog::PromptForSaveToFileAsync(nsIHelperAppLauncher *aLauncher, nsISupports *aWindowContext, const char16_t * aDefaultFileName, const char16_t * aSuggestedFileExtension, bool aForcePrompt)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#define NS_HELPERAPPLAUNCHERDLG_CONTRACTID    "@mozilla.org/helperapplauncherdialog;1"

#endif /* __gen_nsIHelperAppLauncherDialog_h__ */


text:
module Anagram.A279688 (a279688, a279688_list) where
import Helpers.AnagramHelper (possibleAnagramBases, nIsBaseBAnagramOf2n)

a279688 :: Int -> Integer
a279688 n = a279688_list !! (n - 1)

a279688_list :: [Integer]
a279688_list = 0 : filter isAnyAnagram [1..]

-- There exists some base such that n & 2n are anagrams.
isAnyAnagram :: Integer -> Bool
isAnyAnagram n = any (nIsBaseBAnagramOf2n n) $ possibleAnagramBases n


text:
This server will render dynamic next.js/react pages on some routes, and normal ActionHero API requests on others.

This configuration works with both Next and ActionHero hot reloading of code.

A more detailed example showcasing how to use fetch and web sockets to interact with your API can be found here: https://github.com/actionhero/next-in-actionhero

## How to use

Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:

```bash
npx create-next-app --example custom-server-actionhero custom-server-actionhero-app
```

```bash
yarn create next-app --example custom-server-actionhero custom-server-actionhero-app
```

```bash
pnpm create next-app --example custom-server-actionhero custom-server-actionhero-app
```

## How does this work?

1. Create an initializer to load next.js and create a handler that can extract the normal node `req` and `res` from the connection

```js
// initializers/next.js

const { Initializer, api } = require('actionhero')
const next = require('next')

module.exports = class NextInitializer extends Initializer {
  constructor() {
    super()
    this.name = 'next'
  }

  async initialize() {
    api.next = {
      render: async (connection) => {
        if (connection.type !== 'web') {
          throw new Error('Connections for NEXT apps must be of type "web"')
        }
        const req = connection.rawConnection.req
        const res = connection.rawConnection.res
        return api.next.handle(req, res)
      },
    }

    api.next.dev = api.env === 'development'
    if (api.next.dev) {
      api.log('Running next in development mode...')
    }

    api.next.app = next({ dev: api.next.dev })
    api.next.handle = api.next.app.getRequestHandler()
    await api.next.app.prepare()
  }

  async stop() {
    await api.next.app.close()
  }
}
```

2.  Create an action which will run the above `api.next.render(connection)`. Note that we will not be relying on ActionHero to respond to the client's request in this case, and leave that up to next (via: `data.toRender = false`)

```js
// actions/next.js

const { Action, api } = require('actionhero')

module.exports = class CreateChatRoom extends Action {
  constructor() {
    super()
    this.name = 'render'
    this.description = 'I render the next.js react website'
  }

  async run(data) {
    data.toRender = false
    return api.next.render(data.connection)
  }
}
```

3. Tell ActionHero to use the api rather than the file server as the top-level route in `api.config.servers.web.rootEndpointType = 'api'`. This will allows "/" to listen to API requests. Also update `api.config.general.paths.public = [ path.join(__dirname, '/../static') ]`. In this configuration, the next 'static' renderer will take priority over the ActionHero 'public file' api. Note that any static assets (CSS, fonts, etc.) will need to be in "./static" rather than "./public".

Note that this is where the websocket server, if you enable it, will place the `ActionheroWebsocketClient` library.

4.  Configure a wild-card route at the lowest priority of your GET handler to catch all web requests that aren't caught by other actions:

```js
// config/routes.js

exports['default'] = {
  routes: (api) => {
    return {
      get: [
        { path: '/time', action: 'time' },

        { path: '/', matchTrailingPathParts: true, action: 'render' },
      ],
    }
  },
}
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

 Copyright 2013 Anis Kadri

 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.

-->

<plugin xmlns="http://cordova.apache.org/ns/plugins/1.0"
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="com.phonegap.androidonly"
    version="3.0.0">

    <name>JavaScript in yo droidz</name>

    <!-- android -->
    <platform name="android">
		<js-module src="www/android.js" name="Android">
            <clobbers target="android" />
        </js-module>
    </platform>
</plugin>


text:
class TagPromptsController < ApplicationController
  skip_before_action :verify_authenticity_token

  def action_allowed?
    true
  end

  # GET /tag_prompts/view
  def show
    @popup = false
    if params.key?(:popup) && params[:popup].to_s.casecmp('true').zero?
      @popup = true
      render layout: false
    end
  end

  def index
    @tagprompts = TagPrompt.all.order('prompt asc')
    @tagprompts.where!('prompt LIKE ?', "%#{params[:prompt]}%") if params.key?(:prompt) && (!params[:prompt] == '')
    @tagprompts.where!('desc LIKE ?', "%#{params[:desc]}%") if params.key?(:desc) && (!params[:desc] == '')
    @tagprompts.where!('control_type LIKE ?', "%#{params[:control_type]}%") if params.key?(:control_type) && (!params[:control_type] == '')
    render json: @tagprompts
  end

  def create
    @tagprompt = TagPrompt.new(tag_prompts_params)
    @tagprompt.save
    render json: @tagprompts
  end

  def update
    @tagprompt = TagPrompt.find(params[:id])
    @tagprompt.update(prompt: params[:prompt], desc: params[:desc], control_type: params[:control_type])
    render json: @tagprompts
  end

  def destroy
    @tagprompt = TagPrompt.find(params[:id])
    @tagprompt.destroy
    render nothing: true, status: 200
  end

  private

  def tag_prompts_params
    params.permit(:prompt, :desc, :control_type)
  end
end


text:
namespace MabService.Shared
{
    /// <summary>
    /// Mock Api Model
    /// </summary>
    public class MockApiModel
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MockApiModel"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="routeTemplate">The route template.</param>
        /// <param name="body">The body.</param>
        /// <param name="verb">The verb.</param>
        /// <param name="language">The language.</param>
        public MockApiModel(string name,
                            string routeTemplate,
                            string body,
                            MockApiHttpVerb verb,
                            MockApiLanguage language)
        {

            this.Name = name;
            this.RouteTemplate = routeTemplate;
            this.Body = body;
            this.Verb = verb;
            this.Language = language;
        }

        /// <summary>
        /// Gets or sets the identifier.
        /// </summary>
        /// <value>
        /// The identifier.
        /// </value>
        public string Name { get; }

        /// <summary>
        /// Gets or sets the route template.
        /// </summary>
        /// <value>
        /// The route template.
        /// </value>
        public string RouteTemplate { get; }

        /// <summary>
        /// Gets or sets the body.
        /// </summary>
        /// <value>
        /// The body.
        /// </value>
        public string Body { get; }

        /// <summary>
        /// Gets or sets the verb.
        /// </summary>
        /// <value>
        /// The verb.
        /// </value>
        public MockApiHttpVerb Verb { get; }

        /// <summary>
        /// Gets or sets the language.
        /// </summary>
        /// <value>
        /// The language.
        /// </value>
        public MockApiLanguage Language { get; }
    }
}


text:
describe("Ext.core.Element", function() {
    var domEl,
        element;

    afterEach(function() {
        if (element) {
            element.remove();
        }

        if (domEl && domEl.parentNode === document.body) {
            document.body.removeChild(domEl);
        }
    });

    describe("instantiation", function() {
        beforeEach(function() {
            domEl = document.createElement("div");
            Ext.getBody().appendChild(domEl);
        });

        it("should set dom element id if it hasn't already one", function() {
            element = new Ext.core.Element(domEl);

            expect(domEl.id).toBeDefined();
        });

        it("should not set dom element id if it has already one", function() {
            var id = Ext.id();

            domEl.id = id;
            element = new Ext.core.Element(domEl);

            expect(domEl.id).toEqual(id);
        });

        it("should set dom property to dom element", function() {
            element = new Ext.core.Element(domEl);

            expect(element.dom).toBe(domEl);
        });

        it("should set id property to dom id", function() {
            var id = Ext.id();

            domEl.id = id;
            element = new Ext.core.Element(domEl);

            expect(element.id).toEqual(id);
        });

        it("should not set dom or id property if first argument is undefined", function() {
            element = new Ext.core.Element();

            expect(element.id).toBeUndefined();
            expect(element.dom).toBeUndefined();
        });

        it("should find a dom element if a string corresponding to it's id is passed as first argument", function() {
            var id = Ext.id();

            domEl.id = id;

            element = new Ext.core.Element(id);

            expect(element.dom).toBe(domEl);
        });
    });

    describe("methods", function() {
        beforeEach(function() {
            element = Ext.getBody().createChild({tag: "div"});
            domEl = element.dom;
        });

        describe("set", function() {
            it("should call Ext.core.DomHelper.applyStyles if object passed as first argument has style property", function() {
                var style = {width:'100px'};

                spyOn(Ext.core.DomHelper, "applyStyles");

                element.set({style: style});

                expect(Ext.core.DomHelper.applyStyles).toHaveBeenCalledWith(element.dom, style);
            });

            it("should set dom element className if object passed as first argument has cls property", function() {
                var cls = "x-test-class";

                element.set({cls: cls});

                expect(element.dom.className).toEqual(cls);
            });

            it("should use setAttribute by default", function() {
                spyOn(element.dom, "setAttribute");

                element.set({align: "center"});

                expect(element.dom.setAttribute).toHaveBeenCalledWith("align", "center");
            });

            it("should be able to use expandos", function() {
                spyOn(element.dom, "setAttribute");

                element.set({align: "center"}, false);

                expect(element.dom.align).toEqual("center");
            });

        });

        describe("is", function() {
            it("Returns true if this element matches the passed simple selector", function() {
                element.set({cls: "x-test-class"});

                expect(element.is("div.x-test-class")).toBe(true);
            });
        });

        describe("focus", function() {
            it("should focus dom element", function() {
                spyOn(element.dom, "focus");

                element.focus();

                expect(element.dom.focus).toHaveBeenCalled();
            });

            it("should be able to defer dom element focus", function() {
                spyOn(element.dom, "focus");
                element.focus(1);

                waitsFor(function(){
                    return element.dom.focus.calls.length === 1;
                }, "element.dom.focus was never called");

                runs(function() {
                    expect(element.dom.focus).toHaveBeenCalled();
                });
            });

            it("should ignore any exception", function() {
                element.dom.focus = function() {
                    throw "error";
                };

                expect(element.focus).not.toThrow("error");
            });
        });

        describe("blur", function() {
            it("should blur dom element", function() {
                spyOn(element.dom, "blur");

                element.blur();

                expect(element.dom.blur).toHaveBeenCalled();
            });

            it("should ignore any exception", function() {
                element.dom.blur = function() {
                    throw "error";
                };

                expect(element.blur).not.toThrow("error");
            });
        });

        describe("getValue", function() {
            beforeEach(function() {
                element.dom.value = "10";
            });

            it("should return the dom value", function() {
                expect(element.getValue()).toEqual("10");
            });

            it("should return the dom value as Number", function() {
                expect(element.getValue(true)).toEqual(10);
            });
        });

        describe("listeners", function() {
            var options;

            beforeEach(function() {
                options = {delay: 10};
            });

            describe("addListener", function() {
                it("should call Ext.EventManager.on", function() {
                    spyOn(Ext.EventManager, "on");

                    element.addListener("click", Ext.emptyFn, fakeScope, options);

                    expect(Ext.EventManager.on).toHaveBeenCalledWith(element.dom, "click", Ext.emptyFn, fakeScope, options);
                });
            });

            describe("removeListener", function() {
                it("should call Ext.EventManager.un", function() {
                    spyOn(Ext.EventManager, "un");

                    element.removeListener("click", Ext.emptyFn, fakeScope);

                    expect(Ext.EventManager.un).toHaveBeenCalledWith(element.dom, "click", Ext.emptyFn, fakeScope);
                });
            });

            describe("removeAllListener", function() {
                it("should call Ext.EventManager.removeAll", function() {
                    spyOn(Ext.EventManager, "removeAll");

                    element.removeAllListeners();

                    expect(Ext.EventManager.removeAll).toHaveBeenCalledWith(element.dom);
                });
            });

            describe("purgeAllListener", function() {
                it("should call Ext.EventManager.purgeElement", function() {
                    spyOn(Ext.EventManager, "purgeElement");

                    element.purgeAllListeners();

                    expect(Ext.EventManager.purgeElement).toHaveBeenCalledWith(element);
                });
            });
        });

        describe("addUnits", function() {
            it("should return an empty string if size passed is an empty string", function() {
                expect(element.addUnits("")).toEqual("");
            });

            it("should return auto if size passed is 'auto' string", function() {
                expect(element.addUnits("auto")).toEqual("auto");
            });

            it("should return an empty string if size passed is undefined", function() {
                expect(element.addUnits(undefined)).toEqual("");
            });

            it("should return an empty string if size passed is null", function() {
                expect(element.addUnits(null)).toEqual("");
            });
        });

        describe("remove", function() {
            beforeEach(function() {
                spyOn(Ext, "removeNode").andCallThrough();
                element.remove();
            });

            it("should remove dom property", function() {
                expect(element.dom).toBeUndefined();
            });

            it("should call Ext.removeNode", function() {
                expect(Ext.removeNode).toHaveBeenCalledWith(domEl);
            });
        });

        describe("hover", function() {
            var overFn, outFn, options;
            beforeEach(function() {
                overFn = function() {
                    return 1;
                };

                outFn = function() {
                    return 2;
                };

                options = {
                    foo: true
                };

                spyOn(element, "on");
            });

            describe("mouseenter event", function() {
                it("should add a listener on mouseenter", function() {
                    element.hover(overFn, outFn, fakeScope, options);

                    expect(element.on).toHaveBeenCalledWith("mouseenter", overFn, fakeScope, options);
                });

                it("should set scope to element.dom if it is not passed in arguments", function() {
                    element.hover(overFn, outFn, null, options);

                    expect(element.on).toHaveBeenCalledWith("mouseenter", overFn, element.dom, options);
                });
            });

            describe("mouseleave event", function() {
                it("should add a listener on mouseleave", function() {
                    element.hover(overFn, outFn, fakeScope, options);

                    expect(element.on).toHaveBeenCalledWith("mouseleave", outFn, fakeScope, options);
                });

                it("should set scope to element.dom if it is not passed in arguments", function() {
                    element.hover(overFn, outFn, null, options);

                    expect(element.on).toHaveBeenCalledWith("mouseleave", outFn, element.dom, options);
                });
            });
        });

        describe("contains", function() {
            /**
             * TODO: Removed tests for now, need to reinstate once the refactoring is done.
             */
        });

        describe("getAttributeNs", function() {
            it("should call element getAttribute", function() {
                spyOn(element, "getAttribute");

                element.getAttributeNS("ns1", "align");

                expect(element.getAttribute).toHaveBeenCalledWith("align", "ns1");
            });
        });

        describe("getAttribute", function() {
            var element2, element3;
            beforeEach(function() {
                element2 = Ext.getBody().createChild({tag: "div"});

                if (element.dom.setAttribute) {
                    element.dom.setAttribute("qtip", "bar");
                    element2.dom.setAttribute("ext:qtip", "foo");
                } else {
                    element.dom["qtip"] = "bar";
                    element2.dom["ext:qtip"] = "foo";
                }

                if (element.dom.setAttributeNS) {
                    element3 = Ext.getBody().createChild({tag: "div"});
                    element3.dom.setAttributeNS("ext", "qtip", "foobar");
                }
            });

            afterEach(function() {
                if (element2) {
                    element2.remove();
                }

                if (element3) {
                    element3.remove();
                }
            });

            describe("without namespace", function() {
                it("should return the attribute value if it exists", function() {
                    expect(element.getAttribute("qtip")).toEqual("bar");
                });

                it("should return null if the attribute does not exist", function() {
                    expect(element.getAttribute("nothing")).toBeNull();
                });
            });

            describe("with namespace", function() {
                it("should return null on a non-namespaced attribute", function() {
                    expect(element.getAttribute("qtip", "ext")).toBeNull();
                });

                it("should return null if the attribute belong to another namespace", function() {
                    expect(element2.getAttribute("qtip", "nothing")).toBeNull();
                });

                it("should return the attribute value if it belongs to the namespace", function() {
                    if (element3) {
                        expect(element3.getAttribute("qtip", "ext")).toEqual("foobar");
                    }
                });

                it("should handle xml namespace", function() {
                    expect(element2.getAttribute("qtip", "ext")).toEqual("foo");
                });
            });
        });

        describe("update", function() {
            beforeEach(function() {
                element.dom.innerHTML = "hello world";
            });

            it("should update dom element innerHTML", function() {
                element.update("foobar");

                expect(element.dom).hasHTML("foobar");
            });

            it("should return element", function() {
                expect(element.update("foobar")).toBe(element);
            });
        });

        describe("prototype aliases", function() {
            it("should aliases addListener with on", function() {
                expect(element.on).toBe(element.addListener);
            });

            it("should aliases removeListener with un", function() {
                expect(element.un).toBe(element.removeListener);
            });

            it("should aliases removeAllListeners with clearListeners", function() {
                expect(element.clearListeners).toBe(element.removeAllListeners);
            });
        });
    });

    describe("class methods", function() {
        var element2, domEl2, id;

        beforeEach(function() {
            element = Ext.getBody().createChild({tag: "div"});
            domEl = element.dom;

            id = Ext.id();
            domEl2 = document.createElement("div");
            domEl2.id = id;
            document.body.appendChild(domEl2);

            spyOn(Ext.core.Element, "addToCache").andCallThrough();
        });

        afterEach(function() {
            if (element2) {
                element2.remove();
            }
            if (domEl2 && domEl2.parentNode === document.body) {
                document.body.removeChild(domEl2);
            }
        });

        describe("get", function() {
            describe("alias", function() {
                it("should alias Ext.core.Element.get with Ext.get", function() {
                    expect(Ext.get).toBe(Ext.core.Element.get);
                });
            });

            describe("passing string id as first argument", function() {
                describe("with a dom element which is not already encapsulated", function() {
                    it("should return a new Ext.core.Element", function() {
                        element2 = Ext.get(id);

                        expect(element2 instanceof Ext.core.Element).toBe(true);
                    });

                    it("should encapsulate the dom element in the Ext.core.Element", function() {
                        element2 = Ext.get(id);

                        expect(element2.dom).toBe(domEl2);
                    });

                    it("should add element to Ext.cache", function() {
                        element2 = Ext.get(id);

                        expect(Ext.core.Element.addToCache).toHaveBeenCalledWith(element2);
                    });
                });

                describe("with a dom element which is already encapsulated", function() {
                    it("should return the corresponding Ext.element", function() {
                        expect(Ext.get(domEl)).toBe(element);
                    });

                    it("should not add element to Ext.cache if it is already in", function() {
                        Ext.get(domEl);

                        expect(Ext.core.Element.addToCache).not.toHaveBeenCalled();
                    });
                });
            });

            describe("passing dom element as first argument", function() {
                describe("with a dom element which is not already encapsulated", function() {
                    it("should return a new Ext.core.Element", function() {
                        element2 = Ext.get(domEl2);

                        expect(element2 instanceof Ext.core.Element).toBe(true);
                    });

                    it("should encapsulate the dom element in the Ext.core.Element", function() {
                        element2 = Ext.get(domEl2);

                        expect(element2.dom).toBe(domEl2);
                    });

                    it("should add element to Ext.cache", function() {
                        element2 = Ext.get(domEl2);

                        expect(Ext.core.Element.addToCache).toHaveBeenCalledWith(element2);
                    });
                });

                describe("with a dom element which is already encapsulated", function() {
                    it("should return the corresponding Ext.element", function() {
                        expect(Ext.get(domEl.id)).toBe(element);
                    });

                    it("should not add element to Ext.cache if it is already in", function() {
                        Ext.get(domEl.id);

                        expect(Ext.core.Element.addToCache).not.toHaveBeenCalled();
                    });
                });
            });

            describe("passing an Ext.core.Element as first argument", function() {
                it("should return Ext.core.Element", function() {
                    expect(Ext.get(element)).toBe(element);
                });
            });

            describe("passing a CompositeElement as first argument", function() {
                var compositeElement;

                beforeEach(function() {
                    compositeElement = Ext.select("div");
                });

                it("should return Ext.core.Element", function() {
                    expect(Ext.get(compositeElement)).toBe(compositeElement);
                });
            });

            describe("passing an array as first argument", function() {
                it("should call Ext.core.Element.select", function() {
                    var arr = [domEl, domEl2];
                    spyOn(Ext.core.Element, "select");

                    Ext.get(arr);

                    expect(Ext.core.Element.select).toHaveBeenCalledWith(arr);
                });
            });

            describe("passing document as first argument", function() {
                it("should return an Ext.core.Element", function() {
                    expect(Ext.get(document) instanceof Ext.core.Element).toBe(true);
                });

                it("should return a bogus Ext.core.Element", function() {
                    expect(Ext.get(document).id).not.toBeDefined();
                });

                it("should return an Ext.core.Element that encapsulate document", function() {
                    expect(Ext.get(document).dom).toBe(document);
                });
            });
        });

        xdescribe("garbageCollector", function() {

        });

        describe("fly", function() {
            var flyWeight;

            beforeEach(function() {
                spyOn(Ext, "getDom").andCallThrough();

            });

            describe("global flyweight", function() {
                beforeEach(function() {
                    flyWeight = Ext.fly(domEl2);
                });

                it("should return an Ext.core.Element.Flyweight", function() {
                    expect(flyWeight instanceof Ext.core.Element.Flyweight).toBe(true);
                });

                it("should not cache a dom element", function() {
                    expect(Ext.cache[domEl2.id]).toBeUndefined();
                });

                it("should call Ext.getDom", function() {
                    expect(Ext.getDom).toHaveBeenCalledWith(domEl2);
                });

                it("should create a one time reference", function() {
                    expect(Ext.core.Element._flyweights._global).toEqual(flyWeight);
                });
            });

            describe("named reusable flyweight", function() {
                beforeEach(function() {
                    flyWeight = Ext.fly(domEl2, "myflyweight");
                });

                it("should return an Ext.core.Element.Flyweight", function() {
                    expect(flyWeight instanceof Ext.core.Element.Flyweight).toBe(true);
                });

                it("should not cache a dom element", function() {
                    expect(Ext.cache[domEl2.id]).toBeUndefined();
                });

                it("should call Ext.getDom", function() {
                    expect(Ext.getDom).toHaveBeenCalledWith(domEl2);
                });

                it("should create a one time reference", function() {
                    expect(Ext.core.Element._flyweights.myflyweight).toEqual(flyWeight);
                });
            });
        });

        describe("aliases", function() {
            it("should aliases Ext.core.Element.get with Ext.get", function() {
                expect(Ext.get).toBe(Ext.core.Element.get);
            });

            it("should aliases Ext.element.fly with Ext.fly", function() {
                expect(Ext.fly).toBe(Ext.core.Element.fly);
            });
        });
    });
}, "/src/dom/Element.js");


text:
These examples are ordered roughly from least to most complex. Definitely start with `pulse2demo.mc`.
For more info on any pattern, view its comments (Hotkey Ctrl+I in Golly).

## pulse2demo.mc
A small circuit that shows the basic principles of the CA.
## shiftregister.mc
A bunch of shift registers arranged to make a matrix display.
## hexcounter.mc
A binary to hex converter.
## langtonsant.mc
A small board for Langton's Ant.
## turing.mc
A BrainF\*\*\* computer.

Does not support `,` or `.`, but you don't *really* need those, do you?
## metalife.mc, metalife_galaxy.mc
Programmable metacells! These tiny metacells have an area of 32\*32, a period of 358, and support any totalistic (B\*/S\*) rule.

# Computer parts
The examples/computer folder contains parts for a working microprocessor. I haven't finished the info section on these files yet.
## shiftRegister.mc
Briefly holds binary strings for later use.
## registerBlock.mc
Four shift registers stacked atop each other to form a register block, along with an accumulator.
## RAM.mc
Holds 64 16-bit values. Can be extended to hold more.
## decimalDisplay.mc
A 16-bit unsigned decimal display.
## processor.mc
The finished microprocessor, with a blank instruction memory.
## compute-primes.mc
Three microprocessors that work together to find prime numbers. A picture of it after 50,000,000 generations is in the root directory of the repository, with the highest prime in its memory being 163.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="abc_action_bar_home_description">Navigate home</string>
    <string name="abc_action_bar_up_description">Navigate up</string>
    <string name="abc_action_menu_overflow_description">More options</string>
    <string name="abc_action_mode_done">Done</string>
    <string name="abc_activity_chooser_view_see_all">See all</string>
    <string name="abc_activitychooserview_choose_application">Choose an app</string>
    <string name="abc_searchview_description_clear">Clear query</string>
    <string name="abc_searchview_description_query">Search query</string>
    <string name="abc_searchview_description_search">Search</string>
    <string name="abc_searchview_description_submit">Submit query</string>
    <string name="abc_searchview_description_voice">Voice search</string>
    <string name="abc_shareactionprovider_share_with">Share with</string>
    <string name="abc_shareactionprovider_share_with_application">Share with %s</string>
    <string name="abc_action_bar_home_description_format">%1$s, %2$s</string>
    <string name="abc_action_bar_home_subtitle_description_format">%1$s, %2$s, %3$s</string>
    <string name="abc_search_hint">Search…</string>
    <string name="abc_toolbar_collapse_description">Collapse</string>
    <string name="app_name">AntiRepacking</string>
    <string name="status_bar_notification_info_overflow">999+</string>
</resources>


text:
<?php

namespace tests;

use houdunwang\config\Config;
use houdunwang\db\Db;
use PHPUnit\Framework\TestCase;
use tests\models\ModelValidate;

class ValidateTest extends TestCase
{
    public function setUp()
    {
        Config::loadFiles('tests/config');
        Db::execute('truncate model_validate');
    }

    public function test_validate()
    {
        $model           = new ModelValidate;
        $model->username = 'houdunren';
        $res             = $model->save();
        $error           = $model->getError();
        $this->assertFalse($res);
        $this->assertEquals($error[0], '年龄必须是数字');
        $model->age = 33;
        $res        = $model->save();
        $this->assertTrue($res >= 1);
    }

    public function test_user_validate()
    {
        $model           = new ModelValidate;
        $model->username = 'houdunwang';
        $model->age      = 78;
        $res             = $model->save();
        $this->assertTrue($res >= 1);
    }
}


text:
/*eslint-env mocha*/
/*global BOOMR_test,assert*/

describe("e2e/18-usertiming/05-usertiming-second-beacon-no-performance-now", function() {
	var t = BOOMR_test;
	var tf = BOOMR.plugins.TestFramework;

	it("Should pass basic beacon validation", function(done) {
		t.validateBeaconWasSent(done);
	});

	it("Should receive user timing data for marks/measures set before load beacon only", function() {
		if (t.isUserTimingSupported()) {
			var b = tf.beacons[0];
			assert.isString(b.usertiming);

			var data = UserTimingDecompression.decompressUserTiming(b.usertiming);
			var usertiming = {};

			for (var i = 0; i < data.length; i++) {
				usertiming[data[i].name] = data[i];
			}

			assert.isTrue("pre-load-mark-start" in usertiming);
			assert.isTrue("pre-load-mark-end" in usertiming);
			assert.isTrue("pre-load-measure" in usertiming);

			assert.isFalse("post-load-mark-start" in usertiming);
			assert.isFalse("post-load-mark-end" in usertiming);
			assert.isFalse("post-load-measure" in usertiming);
		}
	});

	it("Should receive user timing data for marks/measures set before post-load beacon only", function() {
		if (t.isUserTimingSupported()) {
			var b = tf.beacons[1];
			assert.isString(b.usertiming);

			var data = UserTimingDecompression.decompressUserTiming(b.usertiming);
			var usertiming = {};

			for (var i = 0; i < data.length; i++) {
				usertiming[data[i].name] = data[i];
			}

			assert.isTrue("post-load-mark-start" in usertiming);
			assert.isTrue("post-load-mark-end" in usertiming);
			assert.isTrue("post-load-measure" in usertiming);

			assert.isFalse("pre-load-mark-start" in usertiming);
			assert.isFalse("pre-load-mark-end" in usertiming);
			assert.isFalse("pre-load-measure" in usertiming);
		}
	});
});


text:
import { IMultiSelectable } from "./IMultiSelectable";
import { TreeNode } from "manifesto.js";

export interface MultiSelectableTreeNode extends IMultiSelectable, TreeNode {}


text:
package stroom.util.config;

import stroom.util.io.FileUtil;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static org.assertj.core.api.Assertions.assertThat;

class TestConfigure {

    @Test
    void testNotOK() {
        final Parameter parameter = new Parameter();
        parameter.setValue("some.value");
        parameter.setRegEx("[a-zA-Z0-9-]+");
        assertThat(parameter.validate()).isFalse();
    }

    @Test
    void test_marshal() {
        final ParameterFile list = new ParameterFile();
        list.getParameter().add(new Parameter("param1", "param2", "param3", null));
        list.getParameter().add(new Parameter("param4", "param5", "param6", "A"));

        final Configure configure = new Configure();
        configure.marshal(list, System.out);
    }

    @Test
    void test_Main() throws IOException {
        final Path testFile = Files.createTempFile("TestConfigure_server", "xml");
        final Path sourceFile = Paths.get("./src/test/resources/stroom/util/config/server.xml");
        Files.deleteIfExists(testFile);
        Files.copy(sourceFile, testFile);

        Configure.main(new String[]{
                "parameterFile=./src/test/resources/stroom/util/config/ConfigureTestParameters.xml",
                "processFile=" + FileUtil.getCanonicalPath(testFile), "readParameter=false", "exitOnError=false"});
    }
}


text:
require 'rack/parser'
require 'sinatra/base'
require 'sinatra/param'
require 'json'

class BaseController < Sinatra::Base
  enable :logging
  disable :show_exceptions
  use Rack::Parser
  helpers Sinatra::Param

  before do
    content_type :json
  end
end


text:
package com.arjuna.ats.internal.jta.resources.jts.orbspecific;

import com.arjuna.ArjunaOTS.JTAInterposedSynchronizationOperations;

/**
 * Implementation of the marker interface used to distinguish Synchronizations that
 * should be interposed in the JTA 1.1 TransactionSynchronizationRegistry sense of the term.
 */
public class JTAInterposedSynchronizationImple extends SynchronizationImple implements JTAInterposedSynchronizationOperations {

    public JTAInterposedSynchronizationImple(javax.transaction.Synchronization ptr) {
        super(ptr);
    }

    protected org.omg.PortableServer.Servant getPOATie() {
        return new com.arjuna.ArjunaOTS.JTAInterposedSynchronizationPOATie(this);
    }
}


text:
import collections

from supriya import UnaryOperator
from supriya.ugens.PureUGen import PureUGen

class UnaryOpUGen(PureUGen):
    """
    A unary operator ugen, created by applying a unary operator to a ugen.

    ::

        >>> ugen = supriya.ugens.SinOsc.ar()
        >>> unary_op_ugen = abs(ugen)
        >>> unary_op_ugen
        UnaryOpUGen.ar()

    ::

        >>> unary_op_ugen.operator
        UnaryOperator.ABSOLUTE_VALUE

    """

    ### CLASS VARIABLES ###

    __documentation_section__ = "Basic Operator UGens"

    _ordered_input_names = collections.OrderedDict([("source", None)])

    ### INITIALIZER ###

    def __init__(self, calculation_rate=None, source=None, special_index=None):
        PureUGen.__init__(
            self,
            calculation_rate=calculation_rate,
            source=source,
            special_index=special_index,
        )

    ### PUBLIC PROPERTIES ###

    @property
    def operator(self):
        """
        Gets operator of UnaryOpUgen.

        ::

            >>> source = supriya.ugens.SinOsc.ar()
            >>> unary_op_ugen = -source
            >>> unary_op_ugen.operator
            UnaryOperator.NEGATIVE

        Returns unary operator.
        """
        return UnaryOperator(self.special_index)