text
stringlengths
2
100k
meta
dict
<?xml version="1.0" encoding="utf-8"?> <resources> <!--player--> <string name="prefs_appearance_entry_value_default" translatable="false">default</string> <string name="prefs_appearance_entry_value_flat" translatable="false">flat</string> <string name="prefs_appearance_entry_value_spotify" translatable="false">spotify</string> <string name="prefs_appearance_entry_value_fullscreen" translatable="false">fullscreen</string> <string name="prefs_appearance_entry_value_big_image" translatable="false">big_image</string> <string name="prefs_appearance_entry_value_clean" translatable="false">clean</string> <string name="prefs_appearance_entry_value_mini" translatable="false">mini</string> <!-- dark mode Q--> <string name="prefs_dark_mode_2_entry_value_light" translatable="false">light</string> <string name="prefs_dark_mode_2_entry_value_dark" translatable="false">dark</string> <string name="prefs_dark_mode_2_entry_value_follow_system" translatable="false">follow_system</string> <!--icon shape--> <string name="prefs_icon_shape_square" translatable="false">square</string> <string name="prefs_icon_shape_rounded" translatable="false">round</string> <string name="prefs_icon_shape_cut_corner" translatable="false">cut_corner</string> <!--quick action--> <string name="prefs_quick_action_entry_value_hide" translatable="false">hide</string> <string name="prefs_quick_action_entry_value_play" translatable="false">play</string> <string name="prefs_quick_action_entry_value_shuffle" translatable="false">shuffle</string> <string name="prefs_detail_section_entry_value_most_played" translatable="false">most played</string> <string name="prefs_detail_section_entry_value_recently_added" translatable="false">recently added</string> <string name="prefs_detail_section_entry_value_related_artists" translatable="false">related artist</string> <string name="prefs_auto_download_images_entry_value_always">always</string> <string name="prefs_auto_download_images_entry_value_wifi">wifi</string> <string name="prefs_auto_download_images_entry_value_never">never</string> <string-array name="prefs_detail_sections_entry_values_default"> <item>@string/prefs_detail_section_entry_value_most_played</item> <item>@string/prefs_detail_section_entry_value_recently_added</item> <item>@string/prefs_detail_section_entry_value_related_artists</item> </string-array> </resources>
{ "pile_set_name": "Github" }
<?php /* * This file is part of the php-code-coverage package. * * (c) Sebastian Bergmann <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\CodeCoverage\Report\Xml; class Project extends Node { public function __construct($name) { $this->init(); $this->setProjectName($name); } private function init() { $dom = new \DOMDocument; $dom->loadXML('<?xml version="1.0" ?><phpunit xmlns="http://schema.phpunit.de/coverage/1.0"><project/></phpunit>'); $this->setContextNode( $dom->getElementsByTagNameNS( 'http://schema.phpunit.de/coverage/1.0', 'project' )->item(0) ); } private function setProjectName($name) { $this->getContextNode()->setAttribute('name', $name); } public function getTests() { $testsNode = $this->getContextNode()->getElementsByTagNameNS( 'http://schema.phpunit.de/coverage/1.0', 'tests' )->item(0); if (!$testsNode) { $testsNode = $this->getContextNode()->appendChild( $this->getDom()->createElementNS( 'http://schema.phpunit.de/coverage/1.0', 'tests' ) ); } return new Tests($testsNode); } public function asDom() { return $this->getDom(); } }
{ "pile_set_name": "Github" }
defmodule Accent.Project do use Accent.Schema schema "projects" do field(:name, :string) field(:main_color, :string) field(:logo, :string) field(:last_synced_at, :utc_datetime) field(:locked_file_operations, :boolean, default: false) field(:translations_count, :integer, virtual: true, default: :not_loaded) field(:reviewed_count, :integer, virtual: true, default: :not_loaded) field(:conflicts_count, :integer, virtual: true, default: :not_loaded) has_many(:integrations, Accent.Integration) has_many(:revisions, Accent.Revision) has_many(:target_revisions, Accent.Revision, where: [master: false]) has_many(:versions, Accent.Version) has_many(:operations, Accent.Operation) has_many(:collaborators, Accent.Collaborator) belongs_to(:language, Accent.Language) timestamps() end @optional_fields ~w( name main_color logo last_synced_at locked_file_operations )a def changeset(model, params) do model |> cast(params, @optional_fields) |> validate_required([:name, :main_color]) end end
{ "pile_set_name": "Github" }
A pluggable API specification generator. Currently supports the OpenAPI Specification (f.k.a. the Swagger specification). Features: - Supports the OpenAPI Specification (versions 2 and 3) - Framework-agnostic - Utilities for parsing docstrings WWW: https://github.com/marshmallow-code/apispec
{ "pile_set_name": "Github" }
<template> <div class="components-default-style"> <div> <img class="default-style-img" src="../common/images/nodata.png" alt="" :style="{width: width, height: height}" /> <p class="gray">暂无数据</p> </div> </div> </template> <script> export default { name: "notFundData", props: { width: { type: String, default: '128px' }, height: { type: String, default: '86px' } }, } </script> <style lang="scss" scoped> .components-default-style { width: 100%; height: 100%; text-align: center; position: relative; display: flex; justify-content: center; align-items: center; & > div { display: inline-block; } .default-style-img { display: inline-block; } } </style>
{ "pile_set_name": "Github" }
using System.Collections.Generic; using Essensoft.AspNetCore.Payment.Alipay.Response; namespace Essensoft.AspNetCore.Payment.Alipay.Request { /// <summary> /// alipay.eco.logistics.express.price.modify /// </summary> public class AlipayEcoLogisticsExpressPriceModifyRequest : IAlipayRequest<AlipayEcoLogisticsExpressPriceModifyResponse> { /// <summary> /// 更新寄件价格接口 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.eco.logistics.express.price.modify"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
{ "pile_set_name": "Github" }
--- archs: [ armv7, armv7s, arm64, arm64e ] platform: ios install-name: /usr/lib/libcoretls.dylib current-version: 167 compatibility-version: 1 exports: - archs: [ armv7, armv7s, arm64, arm64e ] symbols: [ _CipherSuiteCount, _CurvesCount, _KnownCipherSuites, _KnownCurves, _KnownSigAlgs, _SigAlgsCount, _Ssl3Callouts, _Tls12Callouts, _Tls1Callouts, _sslCipherSuiteGetKeyExchangeMethod, _sslCipherSuiteGetKeydataSize, _sslCipherSuiteGetMacAlgorithm, _sslCipherSuiteGetMacSize, _sslCipherSuiteGetMinSupportedTLSVersion, _sslCipherSuiteGetSymmetricCipherAlgorithm, _sslCipherSuiteGetSymmetricCipherBlockIvSize, _sslCipherSuiteGetSymmetricCipherKeySize, _tls_add_debug_logger, _tls_cache_cleanup, _tls_cache_create, _tls_cache_delete_session_data, _tls_cache_destroy, _tls_cache_empty, _tls_cache_load_session_data, _tls_cache_save_session_data, _tls_cache_set_default_ttls, _tls_handshake_close, _tls_handshake_continue, _tls_handshake_create, _tls_handshake_destroy, _tls_handshake_get_acceptable_dn_list, _tls_handshake_get_ciphersuites, _tls_handshake_get_client_random, _tls_handshake_get_config, _tls_handshake_get_fallback, _tls_handshake_get_false_start, _tls_handshake_get_master_secret, _tls_handshake_get_max_protocol_version, _tls_handshake_get_min_dh_group_size, _tls_handshake_get_min_protocol_version, _tls_handshake_get_negotiated_cipherspec, _tls_handshake_get_negotiated_curve, _tls_handshake_get_negotiated_ems, _tls_handshake_get_negotiated_protocol_version, _tls_handshake_get_peer_acceptable_client_auth_type, _tls_handshake_get_peer_acceptable_dn_list, _tls_handshake_get_peer_alpn_data, _tls_handshake_get_peer_certificates, _tls_handshake_get_peer_hostname, _tls_handshake_get_peer_npn_data, _tls_handshake_get_peer_ocsp_enabled, _tls_handshake_get_peer_ocsp_request_extensions, _tls_handshake_get_peer_ocsp_responder_id_list, _tls_handshake_get_peer_ocsp_response, _tls_handshake_get_peer_psk_identity, _tls_handshake_get_peer_psk_identity_hint, _tls_handshake_get_peer_requested_ciphersuites, _tls_handshake_get_peer_requested_ecdh_curves, _tls_handshake_get_peer_sct_enabled, _tls_handshake_get_peer_sct_list, _tls_handshake_get_peer_signature_algorithms, _tls_handshake_get_server_identity_change, _tls_handshake_get_server_random, _tls_handshake_get_session_match, _tls_handshake_get_session_proposed, _tls_handshake_get_sni_hostname, _tls_handshake_internal_client_random, _tls_handshake_internal_master_secret, _tls_handshake_internal_prf, _tls_handshake_internal_server_random, _tls_handshake_internal_set_master_secret_function, _tls_handshake_internal_set_session_ticket, _tls_handshake_negotiate, _tls_handshake_process, _tls_handshake_request_renegotiation, _tls_handshake_retransmit_timer_expired, _tls_handshake_send_alert, _tls_handshake_set_acceptable_client_auth_type, _tls_handshake_set_acceptable_dn_list, _tls_handshake_set_alpn_data, _tls_handshake_set_callbacks, _tls_handshake_set_ciphersuites, _tls_handshake_set_client_auth, _tls_handshake_set_client_auth_type, _tls_handshake_set_config, _tls_handshake_set_curves, _tls_handshake_set_dh_parameters, _tls_handshake_set_ems_enable, _tls_handshake_set_encrypt_rsa_public_key, _tls_handshake_set_fallback, _tls_handshake_set_false_start, _tls_handshake_set_identity, _tls_handshake_set_max_protocol_version, _tls_handshake_set_min_dh_group_size, _tls_handshake_set_min_protocol_version, _tls_handshake_set_mtu, _tls_handshake_set_npn_data, _tls_handshake_set_npn_enable, _tls_handshake_set_ocsp_enable, _tls_handshake_set_ocsp_request_extensions, _tls_handshake_set_ocsp_responder_id_list, _tls_handshake_set_ocsp_response, _tls_handshake_set_peer_ec_public_key, _tls_handshake_set_peer_hostname, _tls_handshake_set_peer_rsa_public_key, _tls_handshake_set_peer_trust, _tls_handshake_set_psk_identity, _tls_handshake_set_psk_identity_hint, _tls_handshake_set_psk_secret, _tls_handshake_set_renegotiation, _tls_handshake_set_resumption, _tls_handshake_set_sct_enable, _tls_handshake_set_sct_list, _tls_handshake_set_server_identity_change, _tls_handshake_set_session_ticket_enabled, _tls_handshake_set_sigalgs, _tls_handshake_set_user_agent, _tls_private_key_create, _tls_private_key_destroy, _tls_private_key_ecdsa_create, _tls_private_key_get_context, _tls_private_key_rsa_create, _tls_record_advance_read_cipher, _tls_record_advance_write_cipher, _tls_record_create, _tls_record_decrypt, _tls_record_decrypted_size, _tls_record_destroy, _tls_record_encrypt, _tls_record_encrypted_size, _tls_record_get_header_size, _tls_record_init_pending_ciphers, _tls_record_parse_header, _tls_record_parse_ssl2_header, _tls_record_rollback_write_cipher, _tls_record_set_protocol_version, _tls_record_set_record_splitting, _tls_stream_parser_create, _tls_stream_parser_destroy, _tls_stream_parser_parse ] ...
{ "pile_set_name": "Github" }
<?php //============================================================+ // File name : tcpdf_colors.php // Version : 1.0.004 // Begin : 2002-04-09 // Last Update : 2014-04-25 // Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - [email protected] // License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html) // ------------------------------------------------------------------- // Copyright (C) 2002-2013 Nicola Asuni - Tecnick.com LTD // // This file is part of TCPDF software library. // // TCPDF is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // TCPDF is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with TCPDF. If not, see <http://www.gnu.org/licenses/>. // // See LICENSE.TXT file for more information. // ------------------------------------------------------------------- // // Description : Array of WEB safe colors // //============================================================+ /** * @file * PHP color class for TCPDF * @author Nicola Asuni * @package com.tecnick.tcpdf */ /** * @class TCPDF_COLORS * PHP color class for TCPDF * @package com.tecnick.tcpdf * @version 1.0.004 * @author Nicola Asuni - [email protected] */ class TCPDF_COLORS { /** * Array of WEB safe colors * @public static */ public static $webcolor = array ( 'aliceblue' => 'f0f8ff', 'antiquewhite' => 'faebd7', 'aqua' => '00ffff', 'aquamarine' => '7fffd4', 'azure' => 'f0ffff', 'beige' => 'f5f5dc', 'bisque' => 'ffe4c4', 'black' => '000000', 'blanchedalmond' => 'ffebcd', 'blue' => '0000ff', 'blueviolet' => '8a2be2', 'brown' => 'a52a2a', 'burlywood' => 'deb887', 'cadetblue' => '5f9ea0', 'chartreuse' => '7fff00', 'chocolate' => 'd2691e', 'coral' => 'ff7f50', 'cornflowerblue' => '6495ed', 'cornsilk' => 'fff8dc', 'crimson' => 'dc143c', 'cyan' => '00ffff', 'darkblue' => '00008b', 'darkcyan' => '008b8b', 'darkgoldenrod' => 'b8860b', 'dkgray' => 'a9a9a9', 'darkgray' => 'a9a9a9', 'darkgrey' => 'a9a9a9', 'darkgreen' => '006400', 'darkkhaki' => 'bdb76b', 'darkmagenta' => '8b008b', 'darkolivegreen' => '556b2f', 'darkorange' => 'ff8c00', 'darkorchid' => '9932cc', 'darkred' => '8b0000', 'darksalmon' => 'e9967a', 'darkseagreen' => '8fbc8f', 'darkslateblue' => '483d8b', 'darkslategray' => '2f4f4f', 'darkslategrey' => '2f4f4f', 'darkturquoise' => '00ced1', 'darkviolet' => '9400d3', 'deeppink' => 'ff1493', 'deepskyblue' => '00bfff', 'dimgray' => '696969', 'dimgrey' => '696969', 'dodgerblue' => '1e90ff', 'firebrick' => 'b22222', 'floralwhite' => 'fffaf0', 'forestgreen' => '228b22', 'fuchsia' => 'ff00ff', 'gainsboro' => 'dcdcdc', 'ghostwhite' => 'f8f8ff', 'gold' => 'ffd700', 'goldenrod' => 'daa520', 'gray' => '808080', 'grey' => '808080', 'green' => '008000', 'greenyellow' => 'adff2f', 'honeydew' => 'f0fff0', 'hotpink' => 'ff69b4', 'indianred' => 'cd5c5c', 'indigo' => '4b0082', 'ivory' => 'fffff0', 'khaki' => 'f0e68c', 'lavender' => 'e6e6fa', 'lavenderblush' => 'fff0f5', 'lawngreen' => '7cfc00', 'lemonchiffon' => 'fffacd', 'lightblue' => 'add8e6', 'lightcoral' => 'f08080', 'lightcyan' => 'e0ffff', 'lightgoldenrodyellow' => 'fafad2', 'ltgray' => 'd3d3d3', 'lightgray' => 'd3d3d3', 'lightgrey' => 'd3d3d3', 'lightgreen' => '90ee90', 'lightpink' => 'ffb6c1', 'lightsalmon' => 'ffa07a', 'lightseagreen' => '20b2aa', 'lightskyblue' => '87cefa', 'lightslategray' => '778899', 'lightslategrey' => '778899', 'lightsteelblue' => 'b0c4de', 'lightyellow' => 'ffffe0', 'lime' => '00ff00', 'limegreen' => '32cd32', 'linen' => 'faf0e6', 'magenta' => 'ff00ff', 'maroon' => '800000', 'mediumaquamarine' => '66cdaa', 'mediumblue' => '0000cd', 'mediumorchid' => 'ba55d3', 'mediumpurple' => '9370d8', 'mediumseagreen' => '3cb371', 'mediumslateblue' => '7b68ee', 'mediumspringgreen' => '00fa9a', 'mediumturquoise' => '48d1cc', 'mediumvioletred' => 'c71585', 'midnightblue' => '191970', 'mintcream' => 'f5fffa', 'mistyrose' => 'ffe4e1', 'moccasin' => 'ffe4b5', 'navajowhite' => 'ffdead', 'navy' => '000080', 'oldlace' => 'fdf5e6', 'olive' => '808000', 'olivedrab' => '6b8e23', 'orange' => 'ffa500', 'orangered' => 'ff4500', 'orchid' => 'da70d6', 'palegoldenrod' => 'eee8aa', 'palegreen' => '98fb98', 'paleturquoise' => 'afeeee', 'palevioletred' => 'd87093', 'papayawhip' => 'ffefd5', 'peachpuff' => 'ffdab9', 'peru' => 'cd853f', 'pink' => 'ffc0cb', 'plum' => 'dda0dd', 'powderblue' => 'b0e0e6', 'purple' => '800080', 'red' => 'ff0000', 'rosybrown' => 'bc8f8f', 'royalblue' => '4169e1', 'saddlebrown' => '8b4513', 'salmon' => 'fa8072', 'sandybrown' => 'f4a460', 'seagreen' => '2e8b57', 'seashell' => 'fff5ee', 'sienna' => 'a0522d', 'silver' => 'c0c0c0', 'skyblue' => '87ceeb', 'slateblue' => '6a5acd', 'slategray' => '708090', 'slategrey' => '708090', 'snow' => 'fffafa', 'springgreen' => '00ff7f', 'steelblue' => '4682b4', 'tan' => 'd2b48c', 'teal' => '008080', 'thistle' => 'd8bfd8', 'tomato' => 'ff6347', 'turquoise' => '40e0d0', 'violet' => 'ee82ee', 'wheat' => 'f5deb3', 'white' => 'ffffff', 'whitesmoke' => 'f5f5f5', 'yellow' => 'ffff00', 'yellowgreen' => '9acd32' ); // end of web colors /** * Array of valid JavaScript color names * @public static */ public static $jscolor = array ('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray'); /** * Array of Spot colors (C,M,Y,K,name) * Color keys must be in lowercase and without spaces. * As long as no open standard for spot colours exists, you have to buy a colour book by one of the colour manufacturers and insert the values and names of spot colours directly. * Common industry standard spot colors are: ANPA-COLOR, DIC, FOCOLTONE, GCMI, HKS, PANTONE, TOYO, TRUMATCH. * @public static */ public static $spotcolor = array ( // special registration colors 'none' => array( 0, 0, 0, 0, 'None'), 'all' => array(100, 100, 100, 100, 'All'), // standard CMYK colors 'cyan' => array(100, 0, 0, 0, 'Cyan'), 'magenta' => array( 0, 100, 0, 0, 'Magenta'), 'yellow' => array( 0, 0, 100, 0, 'Yellow'), 'key' => array( 0, 0, 0, 100, 'Key'), // alias 'white' => array( 0, 0, 0, 0, 'White'), 'black' => array( 0, 0, 0, 100, 'Black'), // standard RGB colors 'red' => array( 0, 100, 100, 0, 'Red'), 'green' => array(100, 0, 100, 0, 'Green'), 'blue' => array(100, 100, 0, 0, 'Blue'), // Add here standard spot colors or dynamically define them with AddSpotColor() // ... ); // end of spot colors // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** * Return the Spot color array. * @param $name (string) Name of the spot color. * @param $spotc (array) Reference to an array of spot colors. * @return (array) Spot color array or false if not defined. * @since 5.9.125 (2011-10-03) * @public static */ public static function getSpotColor($name, &$spotc) { if (isset($spotc[$name])) { return $spotc[$name]; } $color = preg_replace('/[\s]*/', '', $name); // remove extra spaces $color = strtolower($color); if (isset(self::$spotcolor[$color])) { if (!isset($spotc[$name])) { $i = (1 + count($spotc)); $spotc[$name] = array('C' => self::$spotcolor[$color][0], 'M' => self::$spotcolor[$color][1], 'Y' => self::$spotcolor[$color][2], 'K' => self::$spotcolor[$color][3], 'name' => self::$spotcolor[$color][4], 'i' => $i); } return $spotc[self::$spotcolor[$color][4]]; } return false; } /** * Returns an array (RGB or CMYK) from an html color name, or a six-digit (i.e. #3FE5AA), or three-digit (i.e. #7FF) hexadecimal color, or a javascript color array, or javascript color name. * @param $hcolor (string) HTML color. * @param $spotc (array) Reference to an array of spot colors. * @param $defcol (array) Color to return in case of error. * @return array RGB or CMYK color, or false in case of error. * @public static */ public static function convertHTMLColorToDec($hcolor, &$spotc, $defcol=array('R'=>128,'G'=>128,'B'=>128)) { $color = preg_replace('/[\s]*/', '', $hcolor); // remove extra spaces $color = strtolower($color); // check for javascript color array syntax if (strpos($color, '[') !== false) { if (preg_match('/[\[][\"\'](t|g|rgb|cmyk)[\"\'][\,]?([0-9\.]*)[\,]?([0-9\.]*)[\,]?([0-9\.]*)[\,]?([0-9\.]*)[\]]/', $color, $m) > 0) { $returncolor = array(); switch ($m[1]) { case 'cmyk': { // RGB $returncolor['C'] = max(0, min(100, (floatval($m[2]) * 100))); $returncolor['M'] = max(0, min(100, (floatval($m[3]) * 100))); $returncolor['Y'] = max(0, min(100, (floatval($m[4]) * 100))); $returncolor['K'] = max(0, min(100, (floatval($m[5]) * 100))); break; } case 'rgb': { // RGB $returncolor['R'] = max(0, min(255, (floatval($m[2]) * 255))); $returncolor['G'] = max(0, min(255, (floatval($m[3]) * 255))); $returncolor['B'] = max(0, min(255, (floatval($m[4]) * 255))); break; } case 'g': { // grayscale $returncolor['G'] = max(0, min(255, (floatval($m[2]) * 255))); break; } case 't': default: { // transparent (empty array) break; } } return $returncolor; } } elseif ((substr($color, 0, 4) != 'cmyk') AND (substr($color, 0, 3) != 'rgb') AND (($dotpos = strpos($color, '.')) !== false)) { // remove class parent (i.e.: color.red) $color = substr($color, ($dotpos + 1)); if ($color == 'transparent') { // transparent (empty array) return array(); } } if (strlen($color) == 0) { return $defcol; } // RGB ARRAY if (substr($color, 0, 3) == 'rgb') { $codes = substr($color, 4); $codes = str_replace(')', '', $codes); $returncolor = explode(',', $codes); foreach ($returncolor as $key => $val) { if (strpos($val, '%') > 0) { // percentage $returncolor[$key] = (255 * intval($val) / 100); } else { $returncolor[$key] = intval($val); } // normalize value $returncolor[$key] = max(0, min(255, $returncolor[$key])); } return $returncolor; } // CMYK ARRAY if (substr($color, 0, 4) == 'cmyk') { $codes = substr($color, 5); $codes = str_replace(')', '', $codes); $returncolor = explode(',', $codes); foreach ($returncolor as $key => $val) { if (strpos($val, '%') !== false) { // percentage $returncolor[$key] = (100 * intval($val) / 100); } else { $returncolor[$key] = intval($val); } // normalize value $returncolor[$key] = max(0, min(100, $returncolor[$key])); } return $returncolor; } if ($color[0] != '#') { // COLOR NAME if (isset(self::$webcolor[$color])) { // web color $color_code = self::$webcolor[$color]; } else { // spot color $returncolor = self::getSpotColor($hcolor, $spotc); if ($returncolor === false) { $returncolor = $defcol; } return $returncolor; } } else { $color_code = substr($color, 1); } // HEXADECIMAL REPRESENTATION switch (strlen($color_code)) { case 3: { // 3-digit RGB hexadecimal representation $r = substr($color_code, 0, 1); $g = substr($color_code, 1, 1); $b = substr($color_code, 2, 1); $returncolor = array(); $returncolor['R'] = max(0, min(255, hexdec($r.$r))); $returncolor['G'] = max(0, min(255, hexdec($g.$g))); $returncolor['B'] = max(0, min(255, hexdec($b.$b))); break; } case 6: { // 6-digit RGB hexadecimal representation $returncolor = array(); $returncolor['R'] = max(0, min(255, hexdec(substr($color_code, 0, 2)))); $returncolor['G'] = max(0, min(255, hexdec(substr($color_code, 2, 2)))); $returncolor['B'] = max(0, min(255, hexdec(substr($color_code, 4, 2)))); break; } case 8: { // 8-digit CMYK hexadecimal representation $returncolor = array(); $returncolor['C'] = max(0, min(100, round(hexdec(substr($color_code, 0, 2)) / 2.55))); $returncolor['M'] = max(0, min(100, round(hexdec(substr($color_code, 2, 2)) / 2.55))); $returncolor['Y'] = max(0, min(100, round(hexdec(substr($color_code, 4, 2)) / 2.55))); $returncolor['K'] = max(0, min(100, round(hexdec(substr($color_code, 6, 2)) / 2.55))); break; } default: { $returncolor = $defcol; break; } } return $returncolor; } /** * Convert a color array into a string representation. * @param $c (array) Array of colors. * @return (string) The color array representation. * @since 5.9.137 (2011-12-01) * @public static */ public static function getColorStringFromArray($c) { $c = array_values($c); $color = '['; switch (count($c)) { case 4: { // CMYK $color .= sprintf('%F %F %F %F', (max(0, min(100, floatval($c[0]))) / 100), (max(0, min(100, floatval($c[1]))) / 100), (max(0, min(100, floatval($c[2]))) / 100), (max(0, min(100, floatval($c[3]))) / 100)); break; } case 3: { // RGB $color .= sprintf('%F %F %F', (max(0, min(255, floatval($c[0]))) / 255), (max(0, min(255, floatval($c[1]))) / 255), (max(0, min(255, floatval($c[2]))) / 255)); break; } case 1: { // grayscale $color .= sprintf('%F', (max(0, min(255, floatval($c[0]))) / 255)); break; } } $color .= ']'; return $color; } /** * Convert color to javascript color. * @param $color (string) color name or "#RRGGBB" * @protected * @since 2.1.002 (2008-02-12) * @public static */ public static function _JScolor($color) { if (substr($color, 0, 1) == '#') { return sprintf("['RGB',%F,%F,%F]", (hexdec(substr($color, 1, 2)) / 255), (hexdec(substr($color, 3, 2)) / 255), (hexdec(substr($color, 5, 2)) / 255)); } if (!in_array($color, self::$jscolor)) { // default transparent color $color = $jscolor[0]; } return 'color.'.$color; } } // END OF TCPDF_COLORS CLASS //============================================================+ // END OF FILE //============================================================+
{ "pile_set_name": "Github" }
package com.oney.gcm; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import com.facebook.react.ReactInstanceManager; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.modules.core.DeviceEventManagerModule; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.json.*; import android.preference.PreferenceManager; import android.util.Log; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.content.res.Resources; import android.app.PendingIntent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.app.Notification; import android.app.NotificationManager; import android.media.RingtoneManager; import android.net.Uri; public class GcmModule extends ReactContextBaseJavaModule implements LifecycleEventListener { private final static String TAG = GcmModule.class.getCanonicalName(); private Intent mIntent; private boolean mIsInForeground; public GcmModule(ReactApplicationContext reactContext, Intent intent) { super(reactContext); mIntent = intent; Log.d(TAG, "mIntent is null: " + (mIntent == null)); if (getReactApplicationContext().hasCurrentActivity()) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(reactContext); SharedPreferences.Editor editor = preferences.edit(); editor.putString("GcmMainActivity", getCurrentActivity().getClass().getSimpleName()); editor.apply(); } if (mIntent == null) { listenGcmRegistration(); listenGcmReceiveNotification(); getReactApplicationContext().addLifecycleEventListener(this); } } @Override public String getName() { return "GcmModule"; } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); if (mIntent != null) { Bundle bundle = mIntent.getBundleExtra("bundle"); String bundleString = convertJSON(bundle); Log.d(TAG, "bundleString: " + bundleString); constants.put("launchNotification", bundleString); } return constants; } private void sendEvent(String eventName, Object params) { getReactApplicationContext() .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } private void listenGcmRegistration() { IntentFilter intentFilter = new IntentFilter("RNGcmRegistrationServiceResult"); getReactApplicationContext().registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); boolean success = bundle.getBoolean("success"); if (success) { String token = bundle.getString("token"); WritableMap params = Arguments.createMap(); params.putString("deviceToken", token); sendEvent("remoteNotificationsRegistered", params); } else { String message = bundle.getString("message"); WritableMap params = Arguments.createMap(); params.putString("message", message); sendEvent("remoteNotificationsRegisteredError", params); } } }, intentFilter); } private String convertJSON(Bundle bundle) { JSONObject json = new JSONObject(); Set<String> keys = bundle.keySet(); for (String key : keys) { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { json.put(key, JSONObject.wrap(bundle.get(key))); } else { json.put(key, bundle.get(key)); } } catch(JSONException e) { return null; } } return json.toString(); } private void listenGcmReceiveNotification() { IntentFilter intentFilter = new IntentFilter("com.oney.gcm.GCMReceiveNotification"); getReactApplicationContext().registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "GCMReceiveNotification BroadcastReceiver"); if (getReactApplicationContext().hasActiveCatalystInstance()) { Bundle bundle = intent.getBundleExtra("bundle"); String bundleString = convertJSON(bundle); WritableMap params = Arguments.createMap(); params.putString("dataJSON", bundleString); params.putBoolean("isInForeground", mIsInForeground); sendEvent("remoteNotificationReceived", params); abortBroadcast(); } else { } } }, intentFilter); } @ReactMethod public void requestPermissions() { getReactApplicationContext().startService(new Intent(getReactApplicationContext(), GcmRegistrationService.class)); } @ReactMethod public void stopService() { if (mIntent != null) { new android.os.Handler().postDelayed(new Runnable() { public void run() { getReactApplicationContext().stopService(mIntent); } }, 1000); } } private Class getMainActivityClass() { try { String packageName = getReactApplicationContext().getPackageName(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getReactApplicationContext()); String activityString = preferences.getString("GcmMainActivity", null); if (activityString == null) { Log.d(TAG, "GcmMainActivity is null"); return null; } else { return Class.forName(packageName + "." + activityString); } } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } } @ReactMethod public void createNotification(ReadableMap infos) { Resources resources = getReactApplicationContext().getResources(); String packageName = getReactApplicationContext().getPackageName(); Class intentClass = getMainActivityClass(); Log.d(TAG, "packageName: " + packageName); if (intentClass == null) { Log.d(TAG, "intentClass is null"); return; } int largeIconResourceId = resources.getIdentifier(infos.getString("largeIcon"), "mipmap", packageName); int smallIconResourceId = android.R.drawable.ic_dialog_info; if(infos.hasKey("smallIcon")){ smallIconResourceId = resources.getIdentifier(infos.getString("smallIcon"), "mipmap", packageName); } Intent intent = new Intent(getReactApplicationContext(), intentClass); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(getReactApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT); Bitmap largeIcon = BitmapFactory.decodeResource(resources, largeIconResourceId); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getReactApplicationContext()) .setLargeIcon(largeIcon) .setSmallIcon(smallIconResourceId) .setContentTitle(infos.getString("subject")) .setContentText(infos.getString("message")) .setAutoCancel(infos.getBoolean("autoCancel")) .setSound(defaultSoundUri) .setTicker(infos.getString("ticker")) .setCategory(NotificationCompat.CATEGORY_CALL) .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getReactApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); Notification notif = notificationBuilder.build(); notif.defaults |= Notification.DEFAULT_VIBRATE; notif.defaults |= Notification.DEFAULT_SOUND; notif.defaults |= Notification.DEFAULT_LIGHTS; notificationManager.notify(0, notif); } @Override public void onHostResume() { mIsInForeground = true; } @Override public void onHostPause() { mIsInForeground = false; } @Override public void onHostDestroy() { } }
{ "pile_set_name": "Github" }
// // MLBCommonHeaderView.m // MyOne3 // // Created by meilbn on 2/26/16. // Copyright © 2016 meilbn. All rights reserved. // #import "MLBCommonHeaderView.h" @interface MLBCommonHeaderView () @property (strong, nonatomic) UILabel *commentsCountLabel; @property (strong, nonatomic) UIButton *rightButton; @end @implementation MLBCommonHeaderView { MLBHeaderViewType viewType; } + (CGFloat)headerViewHeight { return 40; } #pragma mark - LifeCycle - (instancetype)initWithHeaderViewType:(MLBHeaderViewType)type { self = [super init]; if (self) { viewType = type; [self setupViews]; } return self; } #pragma mark - Private Method - (void)setupViews { if (viewType == MLBHeaderViewTypeNone || _commentsCountLabel) { return; } self.backgroundColor = MLBColorF5F5F5; self.clipsToBounds = YES; NSString *leftText; NSString *rightButtonImageNamePrefix; switch (viewType) { case MLBHeaderViewTypeNone: break; case MLBHeaderViewTypeComment: { leftText = @"评论列表"; // rightButtonImageNamePrefix = @"review"; break; } case MLBHeaderViewTypeRelatedRec: { leftText = @"相关推荐"; break; } case MLBHeaderViewTypeRelatedMusic: { leftText = @"相似歌曲"; rightButtonImageNamePrefix = @"music_list_play"; break; } case MLBHeaderViewTypeMovieStory: { leftText = @"电影故事"; rightButtonImageNamePrefix = @"unofficial_plot"; break; } case MLBHeaderViewTypeMovieReview: { leftText = @"评审团短评"; break; } case MLBHeaderViewTypeMovieComment: { leftText = @"评论列表"; rightButtonImageNamePrefix = @"moviereview"; break; } case MLBHeaderViewTypeScoreRatio: { leftText = @"分数比例"; break; } } _commentsCountLabel = [MLBUIFactory labelWithTextColor:MLBColor7F7F7F font:FontWithSize(12)]; _commentsCountLabel.backgroundColor = MLBColorF5F5F5; _commentsCountLabel.text = leftText; [self addSubview:_commentsCountLabel]; [_commentsCountLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.equalTo(self); make.left.equalTo(self).offset(12); }]; if (IsStringNotEmpty(rightButtonImageNamePrefix)) { _rightButton = [MLBUIFactory buttonWithImageName:rightButtonImageNamePrefix ? [NSString stringWithFormat:@"%@_normal", rightButtonImageNamePrefix] : nil highlightImageName:rightButtonImageNamePrefix ? [NSString stringWithFormat:@"%@_highlighted", rightButtonImageNamePrefix] : nil target:self action:@selector(rightButtonClicked)]; [self addSubview:_rightButton]; [_rightButton mas_makeConstraints:^(MASConstraintMaker *make) { make.width.height.equalTo(@40); make.centerY.equalTo(self); make.right.equalTo(self).offset(-8); }]; } } #pragma mark - Action - (void)rightButtonClicked { DDLogDebug(@"common header view %@", NSStringFromSelector(_cmd)); } @end
{ "pile_set_name": "Github" }
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/subtle" "errors" "io" "math/big" "golang.org/x/crypto/curve25519" ) const ( kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1" kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1" kexAlgoECDH256 = "ecdh-sha2-nistp256" kexAlgoECDH384 = "ecdh-sha2-nistp384" kexAlgoECDH521 = "ecdh-sha2-nistp521" kexAlgoCurve25519SHA256 = "[email protected]" ) // kexResult captures the outcome of a key exchange. type kexResult struct { // Session hash. See also RFC 4253, section 8. H []byte // Shared secret. See also RFC 4253, section 8. K []byte // Host key as hashed into H. HostKey []byte // Signature of H. Signature []byte // A cryptographic hash function that matches the security // level of the key exchange algorithm. It is used for // calculating H, and for deriving keys from H and K. Hash crypto.Hash // The session ID, which is the first H computed. This is used // to derive key material inside the transport. SessionID []byte } // handshakeMagics contains data that is always included in the // session hash. type handshakeMagics struct { clientVersion, serverVersion []byte clientKexInit, serverKexInit []byte } func (m *handshakeMagics) write(w io.Writer) { writeString(w, m.clientVersion) writeString(w, m.serverVersion) writeString(w, m.clientKexInit) writeString(w, m.serverKexInit) } // kexAlgorithm abstracts different key exchange algorithms. type kexAlgorithm interface { // Server runs server-side key agreement, signing the result // with a hostkey. Server(p packetConn, rand io.Reader, magics *handshakeMagics, s Signer) (*kexResult, error) // Client runs the client-side key agreement. Caller is // responsible for verifying the host key signature. Client(p packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) } // dhGroup is a multiplicative group suitable for implementing Diffie-Hellman key agreement. type dhGroup struct { g, p, pMinus1 *big.Int } func (group *dhGroup) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error) { if theirPublic.Cmp(bigOne) <= 0 || theirPublic.Cmp(group.pMinus1) >= 0 { return nil, errors.New("ssh: DH parameter out of bounds") } return new(big.Int).Exp(theirPublic, myPrivate, group.p), nil } func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) { hashFunc := crypto.SHA1 var x *big.Int for { var err error if x, err = rand.Int(randSource, group.pMinus1); err != nil { return nil, err } if x.Sign() > 0 { break } } X := new(big.Int).Exp(group.g, x, group.p) kexDHInit := kexDHInitMsg{ X: X, } if err := c.writePacket(Marshal(&kexDHInit)); err != nil { return nil, err } packet, err := c.readPacket() if err != nil { return nil, err } var kexDHReply kexDHReplyMsg if err = Unmarshal(packet, &kexDHReply); err != nil { return nil, err } kInt, err := group.diffieHellman(kexDHReply.Y, x) if err != nil { return nil, err } h := hashFunc.New() magics.write(h) writeString(h, kexDHReply.HostKey) writeInt(h, X) writeInt(h, kexDHReply.Y) K := make([]byte, intLength(kInt)) marshalInt(K, kInt) h.Write(K) return &kexResult{ H: h.Sum(nil), K: K, HostKey: kexDHReply.HostKey, Signature: kexDHReply.Signature, Hash: crypto.SHA1, }, nil } func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { hashFunc := crypto.SHA1 packet, err := c.readPacket() if err != nil { return } var kexDHInit kexDHInitMsg if err = Unmarshal(packet, &kexDHInit); err != nil { return } var y *big.Int for { if y, err = rand.Int(randSource, group.pMinus1); err != nil { return } if y.Sign() > 0 { break } } Y := new(big.Int).Exp(group.g, y, group.p) kInt, err := group.diffieHellman(kexDHInit.X, y) if err != nil { return nil, err } hostKeyBytes := priv.PublicKey().Marshal() h := hashFunc.New() magics.write(h) writeString(h, hostKeyBytes) writeInt(h, kexDHInit.X) writeInt(h, Y) K := make([]byte, intLength(kInt)) marshalInt(K, kInt) h.Write(K) H := h.Sum(nil) // H is already a hash, but the hostkey signing will apply its // own key-specific hash algorithm. sig, err := signAndMarshal(priv, randSource, H) if err != nil { return nil, err } kexDHReply := kexDHReplyMsg{ HostKey: hostKeyBytes, Y: Y, Signature: sig, } packet = Marshal(&kexDHReply) err = c.writePacket(packet) return &kexResult{ H: H, K: K, HostKey: hostKeyBytes, Signature: sig, Hash: crypto.SHA1, }, nil } // ecdh performs Elliptic Curve Diffie-Hellman key exchange as // described in RFC 5656, section 4. type ecdh struct { curve elliptic.Curve } func (kex *ecdh) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) { ephKey, err := ecdsa.GenerateKey(kex.curve, rand) if err != nil { return nil, err } kexInit := kexECDHInitMsg{ ClientPubKey: elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y), } serialized := Marshal(&kexInit) if err := c.writePacket(serialized); err != nil { return nil, err } packet, err := c.readPacket() if err != nil { return nil, err } var reply kexECDHReplyMsg if err = Unmarshal(packet, &reply); err != nil { return nil, err } x, y, err := unmarshalECKey(kex.curve, reply.EphemeralPubKey) if err != nil { return nil, err } // generate shared secret secret, _ := kex.curve.ScalarMult(x, y, ephKey.D.Bytes()) h := ecHash(kex.curve).New() magics.write(h) writeString(h, reply.HostKey) writeString(h, kexInit.ClientPubKey) writeString(h, reply.EphemeralPubKey) K := make([]byte, intLength(secret)) marshalInt(K, secret) h.Write(K) return &kexResult{ H: h.Sum(nil), K: K, HostKey: reply.HostKey, Signature: reply.Signature, Hash: ecHash(kex.curve), }, nil } // unmarshalECKey parses and checks an EC key. func unmarshalECKey(curve elliptic.Curve, pubkey []byte) (x, y *big.Int, err error) { x, y = elliptic.Unmarshal(curve, pubkey) if x == nil { return nil, nil, errors.New("ssh: elliptic.Unmarshal failure") } if !validateECPublicKey(curve, x, y) { return nil, nil, errors.New("ssh: public key not on curve") } return x, y, nil } // validateECPublicKey checks that the point is a valid public key for // the given curve. See [SEC1], 3.2.2 func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool { if x.Sign() == 0 && y.Sign() == 0 { return false } if x.Cmp(curve.Params().P) >= 0 { return false } if y.Cmp(curve.Params().P) >= 0 { return false } if !curve.IsOnCurve(x, y) { return false } // We don't check if N * PubKey == 0, since // // - the NIST curves have cofactor = 1, so this is implicit. // (We don't foresee an implementation that supports non NIST // curves) // // - for ephemeral keys, we don't need to worry about small // subgroup attacks. return true } func (kex *ecdh) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { packet, err := c.readPacket() if err != nil { return nil, err } var kexECDHInit kexECDHInitMsg if err = Unmarshal(packet, &kexECDHInit); err != nil { return nil, err } clientX, clientY, err := unmarshalECKey(kex.curve, kexECDHInit.ClientPubKey) if err != nil { return nil, err } // We could cache this key across multiple users/multiple // connection attempts, but the benefit is small. OpenSSH // generates a new key for each incoming connection. ephKey, err := ecdsa.GenerateKey(kex.curve, rand) if err != nil { return nil, err } hostKeyBytes := priv.PublicKey().Marshal() serializedEphKey := elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y) // generate shared secret secret, _ := kex.curve.ScalarMult(clientX, clientY, ephKey.D.Bytes()) h := ecHash(kex.curve).New() magics.write(h) writeString(h, hostKeyBytes) writeString(h, kexECDHInit.ClientPubKey) writeString(h, serializedEphKey) K := make([]byte, intLength(secret)) marshalInt(K, secret) h.Write(K) H := h.Sum(nil) // H is already a hash, but the hostkey signing will apply its // own key-specific hash algorithm. sig, err := signAndMarshal(priv, rand, H) if err != nil { return nil, err } reply := kexECDHReplyMsg{ EphemeralPubKey: serializedEphKey, HostKey: hostKeyBytes, Signature: sig, } serialized := Marshal(&reply) if err := c.writePacket(serialized); err != nil { return nil, err } return &kexResult{ H: H, K: K, HostKey: reply.HostKey, Signature: sig, Hash: ecHash(kex.curve), }, nil } var kexAlgoMap = map[string]kexAlgorithm{} func init() { // This is the group called diffie-hellman-group1-sha1 in RFC // 4253 and Oakley Group 2 in RFC 2409. p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16) kexAlgoMap[kexAlgoDH1SHA1] = &dhGroup{ g: new(big.Int).SetInt64(2), p: p, pMinus1: new(big.Int).Sub(p, bigOne), } // This is the group called diffie-hellman-group14-sha1 in RFC // 4253 and Oakley Group 14 in RFC 3526. p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16) kexAlgoMap[kexAlgoDH14SHA1] = &dhGroup{ g: new(big.Int).SetInt64(2), p: p, pMinus1: new(big.Int).Sub(p, bigOne), } kexAlgoMap[kexAlgoECDH521] = &ecdh{elliptic.P521()} kexAlgoMap[kexAlgoECDH384] = &ecdh{elliptic.P384()} kexAlgoMap[kexAlgoECDH256] = &ecdh{elliptic.P256()} kexAlgoMap[kexAlgoCurve25519SHA256] = &curve25519sha256{} } // curve25519sha256 implements the [email protected] key // agreement protocol, as described in // https://git.libssh.org/projects/libssh.git/tree/doc/[email protected] type curve25519sha256 struct{} type curve25519KeyPair struct { priv [32]byte pub [32]byte } func (kp *curve25519KeyPair) generate(rand io.Reader) error { if _, err := io.ReadFull(rand, kp.priv[:]); err != nil { return err } curve25519.ScalarBaseMult(&kp.pub, &kp.priv) return nil } // curve25519Zeros is just an array of 32 zero bytes so that we have something // convenient to compare against in order to reject curve25519 points with the // wrong order. var curve25519Zeros [32]byte func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) { var kp curve25519KeyPair if err := kp.generate(rand); err != nil { return nil, err } if err := c.writePacket(Marshal(&kexECDHInitMsg{kp.pub[:]})); err != nil { return nil, err } packet, err := c.readPacket() if err != nil { return nil, err } var reply kexECDHReplyMsg if err = Unmarshal(packet, &reply); err != nil { return nil, err } if len(reply.EphemeralPubKey) != 32 { return nil, errors.New("ssh: peer's curve25519 public value has wrong length") } var servPub, secret [32]byte copy(servPub[:], reply.EphemeralPubKey) curve25519.ScalarMult(&secret, &kp.priv, &servPub) if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 { return nil, errors.New("ssh: peer's curve25519 public value has wrong order") } h := crypto.SHA256.New() magics.write(h) writeString(h, reply.HostKey) writeString(h, kp.pub[:]) writeString(h, reply.EphemeralPubKey) kInt := new(big.Int).SetBytes(secret[:]) K := make([]byte, intLength(kInt)) marshalInt(K, kInt) h.Write(K) return &kexResult{ H: h.Sum(nil), K: K, HostKey: reply.HostKey, Signature: reply.Signature, Hash: crypto.SHA256, }, nil } func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { packet, err := c.readPacket() if err != nil { return } var kexInit kexECDHInitMsg if err = Unmarshal(packet, &kexInit); err != nil { return } if len(kexInit.ClientPubKey) != 32 { return nil, errors.New("ssh: peer's curve25519 public value has wrong length") } var kp curve25519KeyPair if err := kp.generate(rand); err != nil { return nil, err } var clientPub, secret [32]byte copy(clientPub[:], kexInit.ClientPubKey) curve25519.ScalarMult(&secret, &kp.priv, &clientPub) if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 { return nil, errors.New("ssh: peer's curve25519 public value has wrong order") } hostKeyBytes := priv.PublicKey().Marshal() h := crypto.SHA256.New() magics.write(h) writeString(h, hostKeyBytes) writeString(h, kexInit.ClientPubKey) writeString(h, kp.pub[:]) kInt := new(big.Int).SetBytes(secret[:]) K := make([]byte, intLength(kInt)) marshalInt(K, kInt) h.Write(K) H := h.Sum(nil) sig, err := signAndMarshal(priv, rand, H) if err != nil { return nil, err } reply := kexECDHReplyMsg{ EphemeralPubKey: kp.pub[:], HostKey: hostKeyBytes, Signature: sig, } if err := c.writePacket(Marshal(&reply)); err != nil { return nil, err } return &kexResult{ H: H, K: K, HostKey: hostKeyBytes, Signature: sig, Hash: crypto.SHA256, }, nil }
{ "pile_set_name": "Github" }
[remap] importer="texture" type="StreamTexture" path="res://.import/11.png-2f21e82f1775ebdc44bac4521423f996.stex" metadata={ "vram_texture": false } [deps] source_file="res://Assets/UI/Images/Animations/Cogs/Small/11.png" dest_files=[ "res://.import/11.png-2f21e82f1775ebdc44bac4521423f996.stex" ] [params] compress/mode=0 compress/lossy_quality=0.7 compress/hdr_mode=0 compress/bptc_ldr=0 compress/normal_map=0 flags/repeat=0 flags/filter=true flags/mipmaps=false flags/anisotropic=false flags/srgb=2 process/fix_alpha_border=true process/premult_alpha=false process/HDR_as_SRGB=false process/invert_color=false stream=false size_limit=0 detect_3d=true svg/scale=1.0
{ "pile_set_name": "Github" }
# -:- encoding: utf-8 -:- # This file is part of the MapProxy project. # Copyright (C) 2010 Omniscale <http://omniscale.de> # # 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. import os from mapproxy.request import Request from mapproxy.response import Response from mapproxy.util.collections import LRU from mapproxy.wsgiapp import make_wsgi_app as make_mapproxy_wsgi_app from mapproxy.compat import iteritems from threading import Lock import logging log = logging.getLogger(__name__) def asbool(value): """ >>> all([asbool(True), asbool('trUE'), asbool('ON'), asbool(1)]) True >>> any([asbool(False), asbool('false'), asbool('foo'), asbool(None)]) False """ value = str(value).lower() return value in ('1', 'true', 'yes', 'on') def app_factory(global_options, config_dir, allow_listing=False, **local_options): """ Create a new MultiMapProxy app. :param config_dir: directory with all mapproxy configurations :param allow_listing: allow to list all available apps """ return make_wsgi_app(config_dir, asbool(allow_listing)) def make_wsgi_app(config_dir, allow_listing=True, debug=False): """ Create a MultiMapProxy with the given config directory. :param config_dir: the directory with all project configurations. :param allow_listing: True if MapProxy should list all instances at the root URL """ config_dir = os.path.abspath(config_dir) loader = DirectoryConfLoader(config_dir) return MultiMapProxy(loader, list_apps=allow_listing, debug=debug) class MultiMapProxy(object): def __init__(self, loader, list_apps=False, app_cache_size=100, debug=False): self.loader = loader self.list_apps = list_apps self._app_init_lock = Lock() self.apps = LRU(app_cache_size) self.debug = debug def __call__(self, environ, start_response): req = Request(environ) return self.handle(req)(environ, start_response) def handle(self, req): app_name = req.pop_path() if not app_name: return self.index_list(req) if not app_name or ( app_name not in self.apps and not self.loader.app_available(app_name) ): return Response('not found', status=404) # safe instance/app name for authorization req.environ['mapproxy.instance_name'] = app_name return self.proj_app(app_name) def index_list(self, req): """ Return greeting response with a list of available apps (if enabled with list_apps). """ import mapproxy.version html = "<html><body><h1>Welcome to MapProxy %s</h1>" % mapproxy.version.version url = req.script_url if self.list_apps: html += "<h2>available instances:</h2><ul>" html += '\n'.join('<li><a href="%(url)s/%(name)s/">%(name)s</a></li>' % {'url': url, 'name': app} for app in self.loader.available_apps()) html += '</ul>' html += '</body></html>' return Response(html, content_type='text/html') def proj_app(self, proj_name): """ Return the (cached) project app. """ proj_app, timestamps = self.apps.get(proj_name, (None, None)) if proj_app: if self.loader.needs_reload(proj_name, timestamps): # discard cached app proj_app = None if not proj_app: with self._app_init_lock: proj_app, timestamps = self.apps.get(proj_name, (None, None)) if self.loader.needs_reload(proj_name, timestamps): proj_app, timestamps = self.create_app(proj_name) self.apps[proj_name] = proj_app, timestamps else: proj_app, timestamps = self.apps[proj_name] return proj_app def create_app(self, proj_name): """ Returns a new configured MapProxy app and a dict with the timestamps of all configuration files. """ mapproxy_conf = self.loader.app_conf(proj_name)['mapproxy_conf'] log.info('initializing project app %s with %s', proj_name, mapproxy_conf) app = make_mapproxy_wsgi_app(mapproxy_conf, debug=self.debug) return app, app.config_files class ConfLoader(object): def needs_reload(self, app_name, timestamps): """ Returns ``True`` if the configuration of `app_name` changed since `timestamp`. """ raise NotImplementedError() def app_available(self, app_name): """ Returns ``True`` if `app_name` is available. """ raise NotImplementedError() def available_apps(self): """ Returns a list with all available lists. """ raise NotImplementedError() def app_conf(self, app_name): """ Returns a configuration dict for the given `app_name`, None if the app is not found. The configuration dict contains at least 'mapproxy_conf' with the filename of the configuration. """ raise NotImplementedError() class DirectoryConfLoader(ConfLoader): """ Load application configurations from a directory. """ def __init__(self, base_dir, suffix='.yaml'): self.base_dir = base_dir self.suffix = suffix def needs_reload(self, app_name, timestamps): if not timestamps: return True for conf_file, timestamp in iteritems(timestamps): m_time = os.path.getmtime(conf_file) if m_time > timestamp: return True return False def _is_conf_file(self, fname): if not os.path.isfile(fname): return False if self.suffix: return fname.lower().endswith(self.suffix) else: return True def app_name_from_filename(self, fname): """ >>> DirectoryConfLoader('/tmp/').app_name_from_filename('/tmp/foobar.yaml') 'foobar' """ _path, fname = os.path.split(fname) app_name, _ext = os.path.splitext(fname) return app_name def filename_from_app_name(self, app_name): """ >>> DirectoryConfLoader('/tmp/').filename_from_app_name('foobar') '/tmp/foobar.yaml' """ return os.path.join(self.base_dir, app_name + self.suffix or '') def available_apps(self): apps = [] for f in os.listdir(self.base_dir): if self._is_conf_file(os.path.join(self.base_dir, f)): app_name = self.app_name_from_filename(f) apps.append(app_name) apps.sort() return apps def app_available(self, app_name): conf_file = self.filename_from_app_name(app_name) return self._is_conf_file(conf_file) def app_conf(self, app_name): conf_file = self.filename_from_app_name(app_name) if not self._is_conf_file(conf_file): return None return {'mapproxy_conf': conf_file}
{ "pile_set_name": "Github" }
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Controller * @subpackage Dispatcher * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $ */ /** Zend_Controller_Dispatcher_Interface */ require_once 'Zend/Controller/Dispatcher/Interface.php'; /** * @category Zend * @package Zend_Controller * @subpackage Dispatcher * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_Controller_Dispatcher_Abstract implements Zend_Controller_Dispatcher_Interface { /** * Default action * @var string */ protected $_defaultAction = 'index'; /** * Default controller * @var string */ protected $_defaultController = 'index'; /** * Default module * @var string */ protected $_defaultModule = 'default'; /** * Front Controller instance * @var Zend_Controller_Front */ protected $_frontController; /** * Array of invocation parameters to use when instantiating action * controllers * @var array */ protected $_invokeParams = array(); /** * Path delimiter character * @var string */ protected $_pathDelimiter = '_'; /** * Response object to pass to action controllers, if any * @var Zend_Controller_Response_Abstract|null */ protected $_response = null; /** * Word delimiter characters * @var array */ protected $_wordDelimiter = array('-', '.'); /** * Constructor * * @return void */ public function __construct(array $params = array()) { $this->setParams($params); } /** * Formats a string into a controller name. This is used to take a raw * controller name, such as one stored inside a Zend_Controller_Request_Abstract * object, and reformat it to a proper class name that a class extending * Zend_Controller_Action would use. * * @param string $unformatted * @return string */ public function formatControllerName($unformatted) { return ucfirst($this->_formatName($unformatted)) . 'Controller'; } /** * Formats a string into an action name. This is used to take a raw * action name, such as one that would be stored inside a Zend_Controller_Request_Abstract * object, and reformat into a proper method name that would be found * inside a class extending Zend_Controller_Action. * * @param string $unformatted * @return string */ public function formatActionName($unformatted) { $formatted = $this->_formatName($unformatted, true); return strtolower(substr($formatted, 0, 1)) . substr($formatted, 1) . 'Action'; } /** * Verify delimiter * * Verify a delimiter to use in controllers or actions. May be a single * string or an array of strings. * * @param string|array $spec * @return array * @throws Zend_Controller_Dispatcher_Exception with invalid delimiters */ public function _verifyDelimiter($spec) { if (is_string($spec)) { return (array) $spec; } elseif (is_array($spec)) { $allStrings = true; foreach ($spec as $delim) { if (!is_string($delim)) { $allStrings = false; break; } } if (!$allStrings) { require_once 'Zend/Controller/Dispatcher/Exception.php'; throw new Zend_Controller_Dispatcher_Exception('Word delimiter array must contain only strings'); } return $spec; } require_once 'Zend/Controller/Dispatcher/Exception.php'; throw new Zend_Controller_Dispatcher_Exception('Invalid word delimiter'); } /** * Retrieve the word delimiter character(s) used in * controller or action names * * @return array */ public function getWordDelimiter() { return $this->_wordDelimiter; } /** * Set word delimiter * * Set the word delimiter to use in controllers and actions. May be a * single string or an array of strings. * * @param string|array $spec * @return Zend_Controller_Dispatcher_Abstract */ public function setWordDelimiter($spec) { $spec = $this->_verifyDelimiter($spec); $this->_wordDelimiter = $spec; return $this; } /** * Retrieve the path delimiter character(s) used in * controller names * * @return array */ public function getPathDelimiter() { return $this->_pathDelimiter; } /** * Set path delimiter * * Set the path delimiter to use in controllers. May be a single string or * an array of strings. * * @param string $spec * @return Zend_Controller_Dispatcher_Abstract */ public function setPathDelimiter($spec) { if (!is_string($spec)) { require_once 'Zend/Controller/Dispatcher/Exception.php'; throw new Zend_Controller_Dispatcher_Exception('Invalid path delimiter'); } $this->_pathDelimiter = $spec; return $this; } /** * Formats a string from a URI into a PHP-friendly name. * * By default, replaces words separated by the word separator character(s) * with camelCaps. If $isAction is false, it also preserves replaces words * separated by the path separation character with an underscore, making * the following word Title cased. All non-alphanumeric characters are * removed. * * @param string $unformatted * @param boolean $isAction Defaults to false * @return string */ protected function _formatName($unformatted, $isAction = false) { // preserve directories if (!$isAction) { $segments = explode($this->getPathDelimiter(), $unformatted); } else { $segments = (array) $unformatted; } foreach ($segments as $key => $segment) { $segment = str_replace($this->getWordDelimiter(), ' ', strtolower($segment)); $segment = preg_replace('/[^a-z0-9 ]/', '', $segment); $segments[$key] = str_replace(' ', '', ucwords($segment)); } return implode('_', $segments); } /** * Retrieve front controller instance * * @return Zend_Controller_Front */ public function getFrontController() { if (null === $this->_frontController) { require_once 'Zend/Controller/Front.php'; $this->_frontController = Zend_Controller_Front::getInstance(); } return $this->_frontController; } /** * Set front controller instance * * @param Zend_Controller_Front $controller * @return Zend_Controller_Dispatcher_Abstract */ public function setFrontController(Zend_Controller_Front $controller) { $this->_frontController = $controller; return $this; } /** * Add or modify a parameter to use when instantiating an action controller * * @param string $name * @param mixed $value * @return Zend_Controller_Dispatcher_Abstract */ public function setParam($name, $value) { $name = (string) $name; $this->_invokeParams[$name] = $value; return $this; } /** * Set parameters to pass to action controller constructors * * @param array $params * @return Zend_Controller_Dispatcher_Abstract */ public function setParams(array $params) { $this->_invokeParams = array_merge($this->_invokeParams, $params); return $this; } /** * Retrieve a single parameter from the controller parameter stack * * @param string $name * @return mixed */ public function getParam($name) { if(isset($this->_invokeParams[$name])) { return $this->_invokeParams[$name]; } return null; } /** * Retrieve action controller instantiation parameters * * @return array */ public function getParams() { return $this->_invokeParams; } /** * Clear the controller parameter stack * * By default, clears all parameters. If a parameter name is given, clears * only that parameter; if an array of parameter names is provided, clears * each. * * @param null|string|array single key or array of keys for params to clear * @return Zend_Controller_Dispatcher_Abstract */ public function clearParams($name = null) { if (null === $name) { $this->_invokeParams = array(); } elseif (is_string($name) && isset($this->_invokeParams[$name])) { unset($this->_invokeParams[$name]); } elseif (is_array($name)) { foreach ($name as $key) { if (is_string($key) && isset($this->_invokeParams[$key])) { unset($this->_invokeParams[$key]); } } } return $this; } /** * Set response object to pass to action controllers * * @param Zend_Controller_Response_Abstract|null $response * @return Zend_Controller_Dispatcher_Abstract */ public function setResponse(Zend_Controller_Response_Abstract $response = null) { $this->_response = $response; return $this; } /** * Return the registered response object * * @return Zend_Controller_Response_Abstract|null */ public function getResponse() { return $this->_response; } /** * Set the default controller (minus any formatting) * * @param string $controller * @return Zend_Controller_Dispatcher_Abstract */ public function setDefaultControllerName($controller) { $this->_defaultController = (string) $controller; return $this; } /** * Retrieve the default controller name (minus formatting) * * @return string */ public function getDefaultControllerName() { return $this->_defaultController; } /** * Set the default action (minus any formatting) * * @param string $action * @return Zend_Controller_Dispatcher_Abstract */ public function setDefaultAction($action) { $this->_defaultAction = (string) $action; return $this; } /** * Retrieve the default action name (minus formatting) * * @return string */ public function getDefaultAction() { return $this->_defaultAction; } /** * Set the default module * * @param string $module * @return Zend_Controller_Dispatcher_Abstract */ public function setDefaultModule($module) { $this->_defaultModule = (string) $module; return $this; } /** * Retrieve the default module * * @return string */ public function getDefaultModule() { return $this->_defaultModule; } }
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- import json import pytest import logging import pprint log = logging.getLogger(__name__) def test_ping(host): with host.sudo(): assert host.salt('test.ping', '--timeout=120') def test_target_python_version(host, target_python_version): with host.sudo(): ret = host.salt('grains.item', 'pythonversion', '--timeout=120') assert ret["pythonversion"][0] == target_python_version def test_target_salt_version(host, target_salt_version): with host.sudo(): ret = host.salt('grains.item', 'saltversion', '--timeout=120') assert ret["saltversion"].startswith(target_salt_version)
{ "pile_set_name": "Github" }
/* * Copyright 2018-2019 B2i Healthcare Pte Ltd, http://b2i.sg * * 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 com.b2international.snowowl.snomed.fhir; import java.util.Collection; import java.util.List; import java.util.Set; import com.b2international.commons.http.ExtendedLocale; import com.b2international.snowowl.eventbus.IEventBus; import com.b2international.snowowl.fhir.core.LogicalId; import com.b2international.snowowl.fhir.core.model.dt.Uri; import com.b2international.snowowl.fhir.core.provider.FhirApiProvider; import com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants; import com.b2international.snowowl.snomed.core.domain.SnomedConcept; import com.b2international.snowowl.snomed.datastore.SnomedDatastoreActivator; import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; /** * Abstract superclass provider for the SNOMED CT FHIR support * * @since 7.1 * @see FhirApiProvider */ public abstract class SnomedFhirApiProvider extends FhirApiProvider { protected static final Set<String> SUPPORTED_URIS = ImmutableSet.of( SnomedTerminologyComponentConstants.SNOMED_SHORT_NAME, SnomedTerminologyComponentConstants.SNOMED_INT_LINK, SnomedUri.SNOMED_BASE_URI_STRING ); protected String repositoryId; public SnomedFhirApiProvider(IEventBus bus, List<ExtendedLocale> locales) { super(bus, locales); this.repositoryId = SnomedDatastoreActivator.REPOSITORY_UUID; } @Override protected String getRepositoryId() { return repositoryId; } @Override protected String getCodeSystemShortName() { return SnomedTerminologyComponentConstants.SNOMED_SHORT_NAME; } public Collection<String> getSupportedURIs() { return SUPPORTED_URIS; } public boolean isSupported(LogicalId logicalId) { return logicalId.getRepositoryId().startsWith(SnomedDatastoreActivator.REPOSITORY_UUID); } public final boolean isSupported(String uri) { if (Strings.isNullOrEmpty(uri)) return false; boolean foundInList = getSupportedURIs().stream() .filter(uri::equalsIgnoreCase) .findAny() .isPresent(); //extension and version is part of the URI boolean extensionUri = uri.startsWith(SnomedUri.SNOMED_BASE_URI_STRING); return foundInList || extensionUri; } protected Uri getFhirUri() { return SnomedUri.SNOMED_BASE_URI; } protected final String getPreferredTermOrId(SnomedConcept concept) { return concept.getPt() != null ? concept.getPt().getTerm() : concept.getId(); } }
{ "pile_set_name": "Github" }
/* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package assert import ( http "net/http" url "net/url" time "time" ) // Condition uses a Comparison to assert a complex condition. func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { return Condition(a.t, comp, msgAndArgs...) } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // a.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") // a.Contains(["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") // a.Contains({"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { return Contains(a.t, s, contains, msgAndArgs...) } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // a.Empty(obj) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { return Empty(a.t, object, msgAndArgs...) } // Equal asserts that two objects are equal. // // a.Equal(123, 123, "123 and 123 should be equal") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { return Equal(a.t, expected, actual, msgAndArgs...) } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // if assert.Error(t, err, "An error was expected") { // assert.Equal(t, err, expectedError) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { return EqualError(a.t, theError, errString, msgAndArgs...) } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // a.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { return EqualValues(a.t, expected, actual, msgAndArgs...) } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if a.Error(err, "An error was expected") { // assert.Equal(t, err, expectedError) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { return Error(a.t, err, msgAndArgs...) } // Exactly asserts that two objects are equal is value and type. // // a.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { return Exactly(a.t, expected, actual, msgAndArgs...) } // Fail reports a failure through func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { return Fail(a.t, failureMessage, msgAndArgs...) } // FailNow fails test func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool { return FailNow(a.t, failureMessage, msgAndArgs...) } // False asserts that the specified value is false. // // a.False(myBool, "myBool should be false") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { return False(a.t, value, msgAndArgs...) } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { return HTTPBodyContains(a.t, handler, method, url, values, str) } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { return HTTPBodyNotContains(a.t, handler, method, url, values, str) } // HTTPError asserts that a specified handler returns an error status code. // // a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPError(a.t, handler, method, url, values) } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPRedirect(a.t, handler, method, url, values) } // HTTPSuccess asserts that a specified handler returns a success status code. // // a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values) bool { return HTTPSuccess(a.t, handler, method, url, values) } // Implements asserts that an object is implemented by the specified interface. // // a.Implements((*MyInterface)(nil), new(MyObject), "MyObject") func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { return Implements(a.t, interfaceObject, object, msgAndArgs...) } // InDelta asserts that the two numerals are within delta of each other. // // a.InDelta(math.Pi, (22 / 7.0), 0.01) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { return InDelta(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaSlice is the same as InDelta, except it compares two slices. func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) } // InEpsilon asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) } // InEpsilonSlice is the same as InEpsilon, except it compares two slices. func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { return InEpsilonSlice(a.t, expected, actual, delta, msgAndArgs...) } // IsType asserts that the specified objects are of the same type. func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { return IsType(a.t, expectedType, object, msgAndArgs...) } // JSONEq asserts that two JSON strings are equivalent. // // a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { return JSONEq(a.t, expected, actual, msgAndArgs...) } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // a.Len(mySlice, 3, "The size of slice is not 3") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { return Len(a.t, object, length, msgAndArgs...) } // Nil asserts that the specified object is nil. // // a.Nil(err, "err should be nothing") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { return Nil(a.t, object, msgAndArgs...) } // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if a.NoError(err) { // assert.Equal(t, actualObj, expectedObj) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { return NoError(a.t, err, msgAndArgs...) } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // a.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") // a.NotContains(["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") // a.NotContains({"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { return NotContains(a.t, s, contains, msgAndArgs...) } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if a.NotEmpty(obj) { // assert.Equal(t, "two", obj[1]) // } // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { return NotEmpty(a.t, object, msgAndArgs...) } // NotEqual asserts that the specified values are NOT equal. // // a.NotEqual(obj1, obj2, "two objects shouldn't be equal") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { return NotEqual(a.t, expected, actual, msgAndArgs...) } // NotNil asserts that the specified object is not nil. // // a.NotNil(err, "err should be something") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { return NotNil(a.t, object, msgAndArgs...) } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // a.NotPanics(func(){ // RemainCalm() // }, "Calling RemainCalm() should NOT panic") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { return NotPanics(a.t, f, msgAndArgs...) } // NotRegexp asserts that a specified regexp does not match a string. // // a.NotRegexp(regexp.MustCompile("starts"), "it's starting") // a.NotRegexp("^start", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { return NotRegexp(a.t, rx, str, msgAndArgs...) } // NotZero asserts that i is not the zero value for its type and returns the truth. func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { return NotZero(a.t, i, msgAndArgs...) } // Panics asserts that the code inside the specified PanicTestFunc panics. // // a.Panics(func(){ // GoCrazy() // }, "Calling GoCrazy() should panic") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { return Panics(a.t, f, msgAndArgs...) } // Regexp asserts that a specified regexp matches a string. // // a.Regexp(regexp.MustCompile("start"), "it's starting") // a.Regexp("start...$", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { return Regexp(a.t, rx, str, msgAndArgs...) } // True asserts that the specified value is true. // // a.True(myBool, "myBool should be true") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { return True(a.t, value, msgAndArgs...) } // WithinDuration asserts that the two times are within duration delta of each other. // // a.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) } // Zero asserts that i is the zero value for its type and returns the truth. func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { return Zero(a.t, i, msgAndArgs...) }
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2014 Benoit Steiner <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" #include <Eigen/CXX11/Tensor> using Eigen::Tensor; template<int DataLayout> static void test_simple_patch() { Tensor<float, 4, DataLayout> tensor(2,3,5,7); tensor.setRandom(); array<ptrdiff_t, 4> patch_dims; patch_dims[0] = 1; patch_dims[1] = 1; patch_dims[2] = 1; patch_dims[3] = 1; Tensor<float, 5, DataLayout> no_patch; no_patch = tensor.extract_patches(patch_dims); if (DataLayout == ColMajor) { VERIFY_IS_EQUAL(no_patch.dimension(0), 1); VERIFY_IS_EQUAL(no_patch.dimension(1), 1); VERIFY_IS_EQUAL(no_patch.dimension(2), 1); VERIFY_IS_EQUAL(no_patch.dimension(3), 1); VERIFY_IS_EQUAL(no_patch.dimension(4), tensor.size()); } else { VERIFY_IS_EQUAL(no_patch.dimension(0), tensor.size()); VERIFY_IS_EQUAL(no_patch.dimension(1), 1); VERIFY_IS_EQUAL(no_patch.dimension(2), 1); VERIFY_IS_EQUAL(no_patch.dimension(3), 1); VERIFY_IS_EQUAL(no_patch.dimension(4), 1); } for (int i = 0; i < tensor.size(); ++i) { VERIFY_IS_EQUAL(tensor.data()[i], no_patch.data()[i]); } patch_dims[0] = 2; patch_dims[1] = 3; patch_dims[2] = 5; patch_dims[3] = 7; Tensor<float, 5, DataLayout> single_patch; single_patch = tensor.extract_patches(patch_dims); if (DataLayout == ColMajor) { VERIFY_IS_EQUAL(single_patch.dimension(0), 2); VERIFY_IS_EQUAL(single_patch.dimension(1), 3); VERIFY_IS_EQUAL(single_patch.dimension(2), 5); VERIFY_IS_EQUAL(single_patch.dimension(3), 7); VERIFY_IS_EQUAL(single_patch.dimension(4), 1); } else { VERIFY_IS_EQUAL(single_patch.dimension(0), 1); VERIFY_IS_EQUAL(single_patch.dimension(1), 2); VERIFY_IS_EQUAL(single_patch.dimension(2), 3); VERIFY_IS_EQUAL(single_patch.dimension(3), 5); VERIFY_IS_EQUAL(single_patch.dimension(4), 7); } for (int i = 0; i < tensor.size(); ++i) { VERIFY_IS_EQUAL(tensor.data()[i], single_patch.data()[i]); } patch_dims[0] = 1; patch_dims[1] = 2; patch_dims[2] = 2; patch_dims[3] = 1; Tensor<float, 5, DataLayout> twod_patch; twod_patch = tensor.extract_patches(patch_dims); if (DataLayout == ColMajor) { VERIFY_IS_EQUAL(twod_patch.dimension(0), 1); VERIFY_IS_EQUAL(twod_patch.dimension(1), 2); VERIFY_IS_EQUAL(twod_patch.dimension(2), 2); VERIFY_IS_EQUAL(twod_patch.dimension(3), 1); VERIFY_IS_EQUAL(twod_patch.dimension(4), 2*2*4*7); } else { VERIFY_IS_EQUAL(twod_patch.dimension(0), 2*2*4*7); VERIFY_IS_EQUAL(twod_patch.dimension(1), 1); VERIFY_IS_EQUAL(twod_patch.dimension(2), 2); VERIFY_IS_EQUAL(twod_patch.dimension(3), 2); VERIFY_IS_EQUAL(twod_patch.dimension(4), 1); } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { for (int k = 0; k < 4; ++k) { for (int l = 0; l < 7; ++l) { int patch_loc; if (DataLayout == ColMajor) { patch_loc = i + 2 * (j + 2 * (k + 4 * l)); } else { patch_loc = l + 7 * (k + 4 * (j + 2 * i)); } for (int x = 0; x < 2; ++x) { for (int y = 0; y < 2; ++y) { if (DataLayout == ColMajor) { VERIFY_IS_EQUAL(tensor(i,j+x,k+y,l), twod_patch(0,x,y,0,patch_loc)); } else { VERIFY_IS_EQUAL(tensor(i,j+x,k+y,l), twod_patch(patch_loc,0,x,y,0)); } } } } } } } patch_dims[0] = 1; patch_dims[1] = 2; patch_dims[2] = 3; patch_dims[3] = 5; Tensor<float, 5, DataLayout> threed_patch; threed_patch = tensor.extract_patches(patch_dims); if (DataLayout == ColMajor) { VERIFY_IS_EQUAL(threed_patch.dimension(0), 1); VERIFY_IS_EQUAL(threed_patch.dimension(1), 2); VERIFY_IS_EQUAL(threed_patch.dimension(2), 3); VERIFY_IS_EQUAL(threed_patch.dimension(3), 5); VERIFY_IS_EQUAL(threed_patch.dimension(4), 2*2*3*3); } else { VERIFY_IS_EQUAL(threed_patch.dimension(0), 2*2*3*3); VERIFY_IS_EQUAL(threed_patch.dimension(1), 1); VERIFY_IS_EQUAL(threed_patch.dimension(2), 2); VERIFY_IS_EQUAL(threed_patch.dimension(3), 3); VERIFY_IS_EQUAL(threed_patch.dimension(4), 5); } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { for (int k = 0; k < 3; ++k) { for (int l = 0; l < 3; ++l) { int patch_loc; if (DataLayout == ColMajor) { patch_loc = i + 2 * (j + 2 * (k + 3 * l)); } else { patch_loc = l + 3 * (k + 3 * (j + 2 * i)); } for (int x = 0; x < 2; ++x) { for (int y = 0; y < 3; ++y) { for (int z = 0; z < 5; ++z) { if (DataLayout == ColMajor) { VERIFY_IS_EQUAL(tensor(i,j+x,k+y,l+z), threed_patch(0,x,y,z,patch_loc)); } else { VERIFY_IS_EQUAL(tensor(i,j+x,k+y,l+z), threed_patch(patch_loc,0,x,y,z)); } } } } } } } } } void test_cxx11_tensor_patch() { CALL_SUBTEST(test_simple_patch<ColMajor>()); CALL_SUBTEST(test_simple_patch<RowMajor>()); // CALL_SUBTEST(test_expr_shuffling()); }
{ "pile_set_name": "Github" }
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using OpenTracing.Contrib.NetCore.Internal; namespace OpenTracing.Contrib.NetCore { /// <summary> /// Starts and stops all OpenTracing instrumentation components. /// </summary> internal class InstrumentationService : IHostedService { private readonly DiagnosticManager _diagnosticsManager; public InstrumentationService(DiagnosticManager diagnosticManager) { _diagnosticsManager = diagnosticManager ?? throw new ArgumentNullException(nameof(diagnosticManager)); } public Task StartAsync(CancellationToken cancellationToken) { _diagnosticsManager.Start(); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _diagnosticsManager.Stop(); return Task.CompletedTask; } } }
{ "pile_set_name": "Github" }
# In-Memory Columnar Storage Spark SQL可以将数据缓存到内存中,我们可以见到的通过调用cache table tableName即可将一张表缓存到内存中,来极大的提高查询效率。这就涉及到内存中的数据的存储形式,我们知道基于关系型的数据可以存储为基于行存储结构或者基于列存储结构,或者基于行和列的混合存储,即Row Based Storage、Column Based Storage、 PAX Storage。 Spark SQL 将数据加载到内存是以列的存储结构。称为In-Memory Columnar Storage。若直接存储Java Object会产生很大的内存开销,并且这样是基于Row的存储结构。查询某些列速度略慢,虽然数据以及载入内存,查询效率还是低于面向列的存储结构。 Spark SQL的In-Memory Columnar Storage是位于spark列下面org.apache.spark.sql.columnar包内。核心的类有 ColumnBuilder, InMemoryColumnarTableScan, ColumnAccessor, ColumnType。如果列有压缩的情况:compression包下面有具体的build列和access列的类。 当我们调用```sql("cache table src") ```时,会产生一个catalyst.plans.logical.CacheTableCommand,是一个LogicalPlan。 ``` case class CacheTableCommand(tableName: String, plan: Option[LogicalPlan], isLazy: Boolean) extends Command abstract class Command extends LeafNode { self: Product => def output: Seq[Attribute] = Seq.empty } abstract class LeafNode extends LogicalPlan with trees.LeafNode[LogicalPlan] { self: Product => } ``` 在生成物理计划的时候,会转换成execution.CacheTableComman的Physical Plan。 ``` case logical.CacheTableCommand(tableName, optPlan, isLazy) => Seq(execution.CacheTableCommand(tableName, optPlan, isLazy)) ``` ``` case class CacheTableCommand( tableName: String, plan: Option[LogicalPlan], isLazy: Boolean) extends LeafNode with Command { override protected lazy val sideEffectResult = { import sqlContext._ plan.foreach(_.registerTempTable(tableName)) cacheTable(tableName) if (!isLazy) { // Performs eager caching table(tableName).count() } Seq.empty[Row] } override def output: Seq[Attribute] = Seq.empty } ``` 接着调用CacheManager的cacheTable函数,然后调cacheQuery函数。在cacheQuery里面生成了InMemoryRelation对象,就是列式存储的数据结构。 ``` private[sql] trait CacheManager { ... def cacheTable(tableName: String): Unit = cacheQuery(table(tableName), Some(tableName)) ... private[sql] def cacheQuery( query: SchemaRDD, tableName: Option[String] = None, storageLevel: StorageLevel = MEMORY_AND_DISK): Unit = writeLock { val planToCache = query.queryExecution.analyzed if (lookupCachedData(planToCache).nonEmpty) { logWarning("Asked to cache already cached data.") } else { cachedData += CachedData( planToCache, InMemoryRelation( useCompression, columnBatchSize, storageLevel, query.queryExecution.executedPlan, tableName)) } } ... } ``` ### 用法 SparkSQL中有三种方法触发cache: 1. sqlContext.sql("cache table tableName") 2. sqlContext.cacheTable("tableName") 3. schemaRDD.cache() 以上三种用法都会使用到列存储的方式对rdd进行缓存。如果调用了普通rdd的cache方法,是不会触发列式存储的cache。 在Spark1.2.0中,cache table的执行时eager模式的,如果想触发lazy模式,可以主动添加lazy关键字,例如```cache lazy table tabelName```。 而在Spark1.2.0之前,cache table的默认语义是lazy的,所以需要主动触发action才会真正执行cache操作。 ### InMemoryRelation InMemoryRelation继承自LogicalPlan。_cachedColumnBuffers这个类型为RDD[CachedBatch]的私有字段。CachedBatch是Array[Array[Byte]]的封装。 ``` case class CachedBatch(buffers: Array[Array[Byte]], stats: Row) ``` ![](/images/column-store3.png) 构造一个InMemoryRelation需要该Relation 1. output Attribute 2. 是否需要useCoompression来压缩,默认为false 3. 一次处理的多少行数据batchSize 4. storageLevel 缓存到什么地方 5. child 即SparkPlan 6. table名 7. _cachedColumnBuffers最终将table放入内存的存储句柄,是一个RDD[CachedBatch] 8. _statistics是统计信息 ``` private[sql] case class InMemoryRelation( output: Seq[Attribute], useCompression: Boolean, batchSize: Int, storageLevel: StorageLevel, child: SparkPlan, tableName: Option[String])( private var _cachedColumnBuffers: RDD[CachedBatch] = null, private var _statistics: Statistics = null) extends LogicalPlan with MultiInstanceRelation ``` 可以通过设置: spark.sql.inMemoryColumnarStorage.compressed为true来设置内存中的列存储是否需要压缩。 spark.sql.inMemoryColumnarStorage.batchSize来设置一次处理多少row spark.sql.defaultSizeInBytes来设置初始化的column的bufferbytes的默认大小,这里只是其中一个参数。 缓存主流程: 1. 判断_cachedColumnBuffers是否为null,如果不是null,则已经Cache了当前table,重复cache不会触发cache操作,如果是null,则调用buildBuffers。 2. child是物理执行计划SparkPlan 3. 执行mapPartitions操作,对当前RDD的每个分区的数据进行操作。 4. 对于每一个分区,迭代里面的数据生成新的Iterator。每个Iterator里面是CachedBatch 5. 对于child.output的每一列,都会生成一个ColumnBuilder,最后组合为一个columnBuilders是一个数组。 6. 数组内每个CommandBuilder持有一个ByteBuffer 7. 遍历原始分区的记录,将对于的行转为列,并将数据存到ByteBuffer内。 8. 最后将此RDD调用persist方法,将RDD缓存。 9. 将cached赋给_cachedColumnBuffers。 ``` if (_cachedColumnBuffers == null) { buildBuffers() } private def buildBuffers(): Unit = { val output = child.output val cached = child.execute().mapPartitions { rowIterator => new Iterator[CachedBatch] { def next() = { val columnBuilders = output.map { attribute => val columnType = ColumnType(attribute.dataType) val initialBufferSize = columnType.defaultSize * batchSize ColumnBuilder(columnType.typeId, initialBufferSize, attribute.name, useCompression) }.toArray var rowCount = 0 while (rowIterator.hasNext && rowCount < batchSize) { val row = rowIterator.next() var i = 0 while (i < row.length) { columnBuilders(i).appendFrom(row, i) i += 1 } rowCount += 1 } val stats = Row.fromSeq( columnBuilders.map(_.columnStats.collectedStatistics).foldLeft(Seq.empty[Any])(_ ++ _)) batchStats += stats CachedBatch(columnBuilders.map(_.build().array()), stats) } def hasNext = rowIterator.hasNext } }.persist(storageLevel) cached.setName(tableName.map(n => s"In-memory table $n").getOrElse(child.toString)) _cachedColumnBuffers = cached } ``` ### ColumnBuilder columnBuilders是一个存储ColumnBuilder的数组。 ``` val columnBuilders = output.map { attribute => val columnType = ColumnType(attribute.dataType) val initialBufferSize = columnType.defaultSize * batchSize ColumnBuilder(columnType.typeId, initialBufferSize, attribute.name, useCompression) }.toArray ``` 初始化ColumnBuilder的时候会传入的参数: 1. columnType.typeId 表示列的数据类型 2. initialBufferSize ByteBuffer的初始化大小,列类型默认长度 \* batchSize ,默认batchSize是1000。拿Int类型举例,initialBufferSize of IntegerType = 4 \* 1000 3. attribute.name 即字段名age,name,etc 4. useCompression 是否开启压缩 ColumnType封装了该类型的typeId和该类型的defaultSize。并且提供了extract、append、getField方法,来向buffer里追加和获取数据。 ``` private[sql] sealed abstract class ColumnType[T <: DataType, JvmType]( val typeId: Int, val defaultSize: Int) { def extract(buffer: ByteBuffer): JvmType def append(v: JvmType, buffer: ByteBuffer): Unit def actualSize(row: Row, ordinal: Int): Int = defaultSize ... } ``` ColumnBuilder的主要职责是:管理ByteBuffer,包括初始化buffer,添加数据到buffer内,检查剩余空间,和申请新的空间这几项主要职责。 initialize负责初始化buffer。 ``` override def initialize( initialSize: Int, columnName: String = "", useCompression: Boolean = false) = { val size = if (initialSize == 0) DEFAULT_INITIAL_BUFFER_SIZE else initialSize this.columnName = columnName // Reserves 4 bytes for column type ID buffer = ByteBuffer.allocate(4 + size * columnType.defaultSize) buffer.order(ByteOrder.nativeOrder()).putInt(columnType.typeId) } ``` appendFrom是负责添加数据。 ``` override def appendFrom(row: Row, ordinal: Int): Unit = { buffer = ensureFreeSpace(buffer, columnType.actualSize(row, ordinal)) columnType.append(row, ordinal, buffer) } ``` ensureFreeSpace主要是操作buffer,如果要追加的数据大于剩余空间,就扩大buffer。 ``` private[columnar] def ensureFreeSpace(orig: ByteBuffer, size: Int) = { if (orig.remaining >= size) { orig } else { // grow in steps of initial size val capacity = orig.capacity() val newSize = capacity + size.max(capacity / 8 + 1) val pos = orig.position() ByteBuffer .allocate(newSize) .order(ByteOrder.nativeOrder()) .put(orig.array(), 0, pos) } } ```
{ "pile_set_name": "Github" }
config BR2_PACKAGE_LTRACE_ARCH_SUPPORTS bool default y if BR2_aarch64 default y if BR2_arm default y if BR2_i386 default y if BR2_mips default y if BR2_mipsel default y if BR2_powerpc default y if BR2_sparc default y if BR2_x86_64 default y if BR2_xtensa config BR2_PACKAGE_LTRACE bool "ltrace" depends on BR2_USE_WCHAR # elfutils depends on !BR2_STATIC_LIBS # elfutils depends on BR2_TOOLCHAIN_USES_UCLIBC || BR2_TOOLCHAIN_USES_GLIBC # elfutils depends on BR2_PACKAGE_LTRACE_ARCH_SUPPORTS select BR2_PACKAGE_ELFUTILS help Debugging program which runs a specified command until it exits. While the command is executing, ltrace intercepts and records the dynamic library calls which are called by the executed process and the signals received by that process. http://ltrace.org comment "ltrace needs a uClibc or glibc toolchain w/ wchar, dynamic library" depends on BR2_PACKAGE_LTRACE_ARCH_SUPPORTS depends on !BR2_USE_WCHAR || BR2_STATIC_LIBS \ || !(BR2_TOOLCHAIN_USES_UCLIBC || BR2_TOOLCHAIN_USES_GLIBC)
{ "pile_set_name": "Github" }
#include "pch.h" #include "target_state.h" #include "common/start_visible.h" #include "keyboard_state.h" #include "common/shared_constants.h" TargetState::TargetState(int ms_delay) : // TODO: All this processing should be done w/o a separate thread etc. in pre_wnd_proc of winkey_popup to avoid // multithreading. Use SetTimer for delayed events delay(std::chrono::milliseconds(ms_delay)), thread(&TargetState::thread_proc, this) { } constexpr unsigned VK_S = 0x53; bool TargetState::signal_event(unsigned vk_code, bool key_down) { std::unique_lock lock(mutex); // Ignore repeated key presses if (!events.empty() && events.back().key_down == key_down && events.back().vk_code == vk_code) { return false; } // Hide the overlay when WinKey + Shift + S is pressed if (key_down && state == Shown && vk_code == VK_S && (GetKeyState(VK_LSHIFT) || GetKeyState(VK_RSHIFT))) { // We cannot use normal hide() here, there is stuff that needs deinitialization. // It can be safely done when the user releases the WinKey. instance->quick_hide(); } const bool win_key_released = !key_down && (vk_code == VK_LWIN || vk_code == VK_RWIN); constexpr auto overlay_fade_in_animation_time = std::chrono::milliseconds(300); const auto overlay_active = state == Shown && (std::chrono::system_clock::now() - signal_timestamp > overlay_fade_in_animation_time); const bool suppress_win_release = win_key_released && (state == ForceShown || overlay_active) && !nonwin_key_was_pressed_during_shown; events.push_back({ key_down, vk_code }); lock.unlock(); cv.notify_one(); if (suppress_win_release) { // Send a 0xFF VK code, which is outside of the VK code range, to prevent // the start menu from appearing. INPUT input[3] = { {}, {}, {} }; input[0].type = INPUT_KEYBOARD; input[0].ki.wVk = 0xFF; input[0].ki.dwExtraInfo = CommonSharedConstants::KEYBOARDMANAGER_INJECTED_FLAG; input[1].type = INPUT_KEYBOARD; input[1].ki.wVk = 0xFF; input[1].ki.dwFlags = KEYEVENTF_KEYUP; input[1].ki.dwExtraInfo = CommonSharedConstants::KEYBOARDMANAGER_INJECTED_FLAG; input[2].type = INPUT_KEYBOARD; input[2].ki.wVk = vk_code; input[2].ki.dwFlags = KEYEVENTF_KEYUP; input[2].ki.dwExtraInfo = CommonSharedConstants::KEYBOARDMANAGER_INJECTED_FLAG; SendInput(3, input, sizeof(INPUT)); } return suppress_win_release; } void TargetState::was_hidden() { std::unique_lock<std::recursive_mutex> lock(mutex); // Ignore callbacks from the D2DOverlayWindow if (state == ForceShown) { return; } state = Hidden; events.clear(); lock.unlock(); cv.notify_one(); } void TargetState::exit() { std::unique_lock lock(mutex); events.clear(); state = Exiting; lock.unlock(); cv.notify_one(); thread.join(); } KeyEvent TargetState::next() { auto e = events.front(); events.pop_front(); return e; } void TargetState::handle_hidden() { std::unique_lock lock(mutex); if (events.empty()) cv.wait(lock); if (events.empty() || state == Exiting) return; auto event = next(); if (event.key_down && (event.vk_code == VK_LWIN || event.vk_code == VK_RWIN)) { state = Timeout; winkey_timestamp = std::chrono::system_clock::now(); } } void TargetState::handle_shown(const bool forced) { std::unique_lock lock(mutex); if (events.empty()) { cv.wait(lock); } if (events.empty() || state == Exiting) { return; } auto event = next(); if (event.vk_code == VK_LWIN || event.vk_code == VK_RWIN) { if (!forced && (!event.key_down || !winkey_held())) { state = Hidden; } return; } if (event.key_down) { nonwin_key_was_pressed_during_shown = true; lock.unlock(); instance->on_held_press(event.vk_code); } } void TargetState::thread_proc() { while (true) { switch (state) { case Hidden: handle_hidden(); break; case Timeout: handle_timeout(); break; case Shown: handle_shown(false); break; case ForceShown: handle_shown(true); break; case Exiting: default: return; } } } void TargetState::handle_timeout() { std::unique_lock lock(mutex); auto wait_time = delay - (std::chrono::system_clock::now() - winkey_timestamp); if (events.empty()) { cv.wait_for(lock, wait_time); } if (state == Exiting) { return; } // Skip all VK_*WIN-down events while (!events.empty()) { auto event = events.front(); if (event.key_down && (event.vk_code == VK_LWIN || event.vk_code == VK_RWIN)) events.pop_front(); else break; } // If we've detected that a user is holding anything other than VK_*WIN or start menu is visible, we should hide if (!events.empty() || !only_winkey_key_held() || is_start_visible()) { state = Hidden; return; } if (std::chrono::system_clock::now() - winkey_timestamp < delay) { return; } signal_timestamp = std::chrono::system_clock::now(); nonwin_key_was_pressed_during_shown = false; state = Shown; lock.unlock(); instance->on_held(); } void TargetState::set_delay(int ms_delay) { std::unique_lock lock(mutex); delay = std::chrono::milliseconds(ms_delay); } void TargetState::toggle_force_shown() { std::unique_lock lock(mutex); events.clear(); if (state != ForceShown) { state = ForceShown; instance->on_held(); } else { state = Hidden; } } bool TargetState::active() const { return state == ForceShown || state == Shown; }
{ "pile_set_name": "Github" }
#!/usr/bin/env bash #;**********************************************************************; # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2017 - 2020, Intel Corporation # Copyright (c) 2018 - 2020, Fraunhofer SIT sponsored by Infineon Technologies AG # # All rights reserved. #;**********************************************************************; # source the int-log-compiler-common sript . ${srcdir}/script/int-log-compiler-common.sh sanity_test # start simulator if needed if [[ ${INTEGRATION_TCTI} == "mssim" || ${INTEGRATION_TCTI} == "swtpm" ]]; then echo "Trying to start simulator ${INTEGRATION_TCTI}" try_simulator_start TPM20TEST_SOCKET_PORT="${SIM_PORT_DATA}" TPM20TEST_TCTI="${INTEGRATION_TCTI}:host=${TPM20TEST_SOCKET_ADDRESS},port=${TPM20TEST_SOCKET_PORT}" else # Device will be used. TPM20TEST_TCTI="${INTEGRATION_TCTI}:${TPM20TEST_DEVICE_FILE}" fi while true; do # Some debug prints echo "TPM20TEST_TCTI_NAME=${TPM20TEST_TCTI_NAME}" echo "TPM20TEST_DEVICE_FILE=${TPM20TEST_DEVICE_FILE}" echo "TPM20TEST_SOCKET_ADDRESS=${TPM20TEST_SOCKET_ADDRESS}" echo "TPM20TEST_SOCKET_PORT=${TPM20TEST_SOCKET_PORT}" echo "TPM20TEST_TCTI=${TPM20TEST_TCTI}" if [ "${TPM20TEST_TCTI_NAME}" != "device" ]; then env TPM20TEST_TCTI_NAME="${TPM20TEST_TCTI_NAME}" \ TPM20TEST_SOCKET_ADDRESS="${TPM20TEST_SOCKET_ADDRESS}" \ TPM20TEST_SOCKET_PORT="${TPM20TEST_SOCKET_PORT}" \ TPM20TEST_TCTI="${TPM20TEST_TCTI}" \ G_MESSAGES_DEBUG=all ./test/helper/tpm_startup if [ $? -ne 0 ]; then echo "TPM_StartUp failed" ret=99 break fi else env TPM20TEST_TCTI_NAME=${TPM20TEST_TCTI_NAME} \ TPM20TEST_DEVICE_FILE=${TPM20TEST_DEVICE_FILE} \ G_MESSAGES_DEBUG=all ./test/helper/tpm_transientempty if [ $? -ne 0 ]; then echo "TPM transient area not empty => skipping" ret=99 break fi fi # Certificate generation for simulator tests if [ "${TPM20TEST_TCTI_NAME}" != "device" ]; then EKPUB_FILE=${TEST_BIN}_ekpub.pem EKCERT_FILE=${TEST_BIN}_ekcert.crt EKCERT_PEM_FILE=${TEST_BIN}_ekcert.pem env TPM20TEST_TCTI_NAME="${TPM20TEST_TCTI_NAME}" \ TPM20TEST_SOCKET_ADDRESS="${TPM20TEST_SOCKET_ADDRESS}" \ TPM20TEST_SOCKET_PORT="${TPM20TEST_SOCKET_PORT}" \ TPM20TEST_TCTI="${TPM20TEST_TCTI}" \ TPM20TEST_DEVICE_FILE="${TPM20TEST_DEVICE_FILE}" \ G_MESSAGES_DEBUG=all ./test/helper/tpm_getek ${EKPUB_FILE} if [ $? -ne 0 ]; then echo "TPM_getek failed" ret=99 break fi EKECCPUB_FILE=${TEST_BIN}_ekeccpub.pem EKECCCERT_FILE=${TEST_BIN}_ekecccert.crt EKECCCERT_PEM_FILE=${TEST_BIN}_ekecccert.pem env TPM20TEST_TCTI_NAME="${TPM20TEST_TCTI_NAME}" \ TPM20TEST_SOCKET_ADDRESS="${TPM20TEST_SOCKET_ADDRESS}" \ TPM20TEST_SOCKET_PORT="${TPM20TEST_SOCKET_PORT}" \ TPM20TEST_TCTI="${TPM20TEST_TCTI}" \ TPM20TEST_DEVICE_FILE="${TPM20TEST_DEVICE_FILE}" \ G_MESSAGES_DEBUG=all ./test/helper/tpm_getek_ecc ${EKECCPUB_FILE} if [ $? -ne 0 ]; then echo "TPM_getek_ecc failed" ret=99 break fi INTERMEDCA_FILE=${TEST_BIN}_intermedecc-ca ROOTCA_FILE=${TEST_BIN}_root-ca SCRIPTDIR="$(dirname $(realpath $0))/" ${SCRIPTDIR}/ekca/create_ca.sh "${EKPUB_FILE}" "${EKECCPUB_FILE}" "${EKCERT_FILE}" \ "${EKECCCERT_FILE}" "${INTERMEDCA_FILE}" "${ROOTCA_FILE}" >${TEST_BIN}_ca.log 2>&1 if [ $? -ne 0 ]; then echo "ek-cert ca failed" ret=99 break fi # Determine the fingerprint of the RSA EK public. FINGERPRINT=$(openssl pkey -pubin -inform PEM -in ${EKPUB_FILE} -outform DER | shasum -a 256 | cut -f 1 -d ' ') export FAPI_TEST_FINGERPRINT=" { \"hashAlg\" : \"sha256\", \"digest\" : \"${FINGERPRINT}\" }" openssl x509 -inform DER -in ${EKCERT_FILE} -outform PEM -out ${EKCERT_PEM_FILE} export FAPI_TEST_CERTIFICATE="file:${EKCERT_PEM_FILE}" # Determine the fingerprint of the RSA EK public. FINGERPRINT_ECC=$(openssl pkey -pubin -inform PEM -in ${EKECCPUB_FILE} -outform DER | shasum -a 256 | cut -f 1 -d ' ') export FAPI_TEST_FINGERPRINT_ECC=" { \"hashAlg\" : \"sha256\", \"digest\" : \"${FINGERPRINT_ECC}\" }" openssl x509 -inform DER -in ${EKECCCERT_FILE} -outform PEM -out ${EKECCCERT_PEM_FILE} export FAPI_TEST_CERTIFICATE_ECC="file:${EKECCCERT_PEM_FILE}" cat $EKCERT_FILE | \ env TPM20TEST_TCTI_NAME="${TPM20TEST_TCTI_NAME}" \ TPM20TEST_SOCKET_ADDRESS="${TPM20TEST_SOCKET_ADDRESS}" \ TPM20TEST_SOCKET_PORT="${TPM20TEST_SOCKET_PORT}" \ TPM20TEST_TCTI="${TPM20TEST_TCTI}" \ TPM20TEST_DEVICE_FILE="${TPM20TEST_DEVICE_FILE}" \ G_MESSAGES_DEBUG=all ./test/helper/tpm_writeekcert 1C00002 if [ $? -ne 0 ]; then echo "TPM_writeekcert failed" ret=99 break fi cat $EKECCCERT_FILE | \ env TPM20TEST_TCTI_NAME="${TPM20TEST_TCTI_NAME}" \ TPM20TEST_SOCKET_ADDRESS="${TPM20TEST_SOCKET_ADDRESS}" \ TPM20TEST_SOCKET_PORT="${TPM20TEST_SOCKET_PORT}" \ TPM20TEST_TCTI="${TPM20TEST_TCTI}" \ TPM20TEST_DEVICE_FILE="${TPM20TEST_DEVICE_FILE}" \ G_MESSAGES_DEBUG=all ./test/helper/tpm_writeekcert 1C0000A if [ $? -ne 0 ]; then echo "TPM_writeekcert failed" ret=99 fi fi # certificate generation TPMSTATE_FILE1=${TEST_BIN}_state1 TPMSTATE_FILE2=${TEST_BIN}_state2 env TPM20TEST_TCTI_NAME="${TPM20TEST_TCTI_NAME}" \ TPM20TEST_SOCKET_ADDRESS="${TPM20TEST_SOCKET_ADDRESS}" \ TPM20TEST_SOCKET_PORT="${TPM20TEST_SOCKET_PORT}" \ TPM20TEST_TCTI="${TPM20TEST_TCTI}" \ TPM20TEST_DEVICE_FILE="${TPM20TEST_DEVICE_FILE}" \ G_MESSAGES_DEBUG=all ./test/helper/tpm_dumpstate>${TPMSTATE_FILE1} if [ $? -ne 0 ]; then echo "Error during dumpstate" ret=99 break fi echo "Execute the test script" if [ "${TPM20TEST_TCTI_NAME}" == "device" ]; then # No root certificate needed env TPM20TEST_TCTI_NAME="${TPM20TEST_TCTI_NAME}" \ TPM20TEST_SOCKET_ADDRESS="${TPM20TEST_SOCKET_ADDRESS}" \ TPM20TEST_SOCKET_PORT="${TPM20TEST_SOCKET_PORT}" \ TPM20TEST_TCTI="${TPM20TEST_TCTI}" \ TPM20TEST_DEVICE_FILE="${TPM20TEST_DEVICE_FILE}" \ G_MESSAGES_DEBUG=all ${@: -1} else # Run test with generated certificate. env TPM20TEST_TCTI_NAME="${TPM20TEST_TCTI_NAME}" \ TPM20TEST_SOCKET_ADDRESS="${TPM20TEST_SOCKET_ADDRESS}" \ TPM20TEST_SOCKET_PORT="${TPM20TEST_SOCKET_PORT}" \ TPM20TEST_TCTI="${TPM20TEST_TCTI}" \ FAPI_TEST_ROOT_CERT=${ROOTCA_FILE}.pem \ TPM20TEST_DEVICE_FILE="${TPM20TEST_DEVICE_FILE}" \ G_MESSAGES_DEBUG=all ${@: -1} fi ret=$? echo "Script returned $ret" #We check the state before a reboot to see if transients and NV were chagned. env TPM20TEST_TCTI_NAME="${TPM20TEST_TCTI_NAME}" \ TPM20TEST_SOCKET_ADDRESS="${TPM20TEST_SOCKET_ADDRESS}" \ TPM20TEST_SOCKET_PORT="${TPM20TEST_SOCKET_PORT}" \ TPM20TEST_TCTI="${TPM20TEST_TCTI}" \ G_MESSAGES_DEBUG=all ./test/helper/tpm_dumpstate>${TPMSTATE_FILE2} if [ $? -ne 0 ]; then echo "Error during dumpstate" ret=99 break fi if [ "$(cat ${TPMSTATE_FILE1})" != "$(cat ${TPMSTATE_FILE2})" ]; then echo "TPM changed state during test" echo "State before ($TPMSTATE_FILE1):" cat ${TPMSTATE_FILE1} echo "State after ($TPMSTATE_FILE2):" cat ${TPMSTATE_FILE2} ret=1 break fi #TODO: Add a tpm-restart/reboot here break done if [ "${TPM20TEST_TCTI_NAME}" != "device" ]; then # This sleep is sadly necessary: If we kill the tabrmd w/o sleeping for a # second after the test finishes the simulator will die too. Bug in the # simulator? sleep 1 # teardown daemon_stop ${SIM_PID_FILE} rm -rf ${SIM_TMP_DIR} ${SIM_PID_FILE} fi exit $ret
{ "pile_set_name": "Github" }
#include "stdafx.h" #include <math.h> #include "Avx64CalcMat4x4Inv.h" //#define MAT_INV_DEBUG // Remove comment to enable extra printfs bool Mat4x4InvCpp(Mat4x4 m_inv, Mat4x4 m, float epsilon, bool* is_singular) { __declspec(align(32)) Mat4x4 m2; __declspec(align(32)) Mat4x4 m3; __declspec(align(32)) Mat4x4 m4; float t1, t2, t3, t4; float c1, c2, c3, c4; // Make sure matrices are properly aligned if (((uintptr_t)m_inv & 0x1f) != 0) return false; if (((uintptr_t)m & 0x1f) != 0) return false; // Calculate the required matrix trace values Mat4x4Mul(m2, m, m); Mat4x4Mul(m3, m2, m); Mat4x4Mul(m4, m3, m); t1 = Mat4x4Trace(m); t2 = Mat4x4Trace(m2); t3 = Mat4x4Trace(m3); t4 = Mat4x4Trace(m4); #ifdef MAT_INV_DEBUG printf("t1: %16e\n", t1); printf("t2: %16e\n", t2); printf("t3: %16e\n", t3); printf("t4: %16e\n", t4); #endif c1 = -t1; c2 = -1.0f / 2.0f * (c1 * t1 + t2); c3 = -1.0f / 3.0f * (c2 * t1 + c1 * t2 + t3); c4 = -1.0f / 4.0f * (c3 * t1 + c2 * t2 + c1 * t3 + t4); #ifdef MAT_INV_DEBUG printf("c1: %16e\n", c1); printf("c2: %16e\n", c2); printf("c3: %16e\n", c3); printf("c4: %16e\n", c4); #endif // Make sure matrix is not singular if ((*is_singular = (fabs(c4) < epsilon)) != false) return false; // Calculate = -1.0 / c4 * (m3 + c1 * m2 + c2 * m + c3 * I) __declspec(align(32)) Mat4x4 I; __declspec(align(32)) Mat4x4 tempA, tempB, tempC, tempD; Mat4x4SetI(I); Mat4x4MulScalar(tempA, I, c3); Mat4x4MulScalar(tempB, m, c2); Mat4x4MulScalar(tempC, m2, c1); Mat4x4Add(tempD, tempA, tempB); Mat4x4Add(tempD, tempD, tempC); Mat4x4Add(tempD, tempD, m3); Mat4x4MulScalar(m_inv, tempD, -1.0f / c4); return true; } void Avx64Mat4x4Inv(Mat4x4 m, const char* s) { Mat4x4Printf(m, s); for (int i = 0; i <= 1; i++) { const float epsilon = 1.0e-9f; __declspec(align(32)) Mat4x4 m_inv; __declspec(align(32)) Mat4x4 m_ver; bool rc, is_singular; if (i == 0) { printf("\nCalculating inverse matrix - Mat4x4InvCpp\n"); rc = Mat4x4InvCpp(m_inv, m, epsilon, &is_singular); } else { printf("\nCalculating inverse matrix - Mat4x4Inv_\n"); rc = Mat4x4Inv_(m_inv, m, epsilon, &is_singular); } if (!rc) { if (is_singular) printf("Matrix 'm' is singular\n"); else printf("Error occurred during calculation of matrix inverse\n"); } else { Mat4x4Printf(m_inv, "\nInverse matrix\n"); Mat4x4Mul(m_ver, m_inv, m); Mat4x4Printf(m_ver, "\nInverse matrix verification\n"); } } } void Avx64CalcMat4x4Inv(void) { __declspec(align(32)) Mat4x4 m; printf("Results for Avx64CalcMat4x4Inv\n"); Mat4x4SetRow(m, 0, 2, 7, 3, 4); Mat4x4SetRow(m, 1, 5, 9, 6, 4.75); Mat4x4SetRow(m, 2, 6.5, 3, 4, 10); Mat4x4SetRow(m, 3, 7, 5.25, 8.125, 6); Avx64Mat4x4Inv(m, "\nTest Matrix #1\n"); Mat4x4SetRow(m, 0, 0.5, 12, 17.25, 4); Mat4x4SetRow(m, 1, 5, 2, 6.75, 8); Mat4x4SetRow(m, 2, 13.125, 1, 3, 9.75); Mat4x4SetRow(m, 3, 16, 1.625, 7, 0.25); Avx64Mat4x4Inv(m, "\nTest Matrix #2\n"); Mat4x4SetRow(m, 0, 2, 0, 0, 1); Mat4x4SetRow(m, 1, 0, 4, 5, 0); Mat4x4SetRow(m, 2, 0, 0, 0, 7); Mat4x4SetRow(m, 3, 0, 0, 0, 6); Avx64Mat4x4Inv(m, "\nTest Matrix #3\n"); } int _tmain(int argc, _TCHAR* argv[]) { #ifdef _DEBUG Avx64CalcMat4x4InvTest(); #endif Avx64CalcMat4x4Inv(); Avx64CalcMat4x4InvTimed(); return 0; }
{ "pile_set_name": "Github" }
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use rand::RngCore; use std::{ fs, io, path::{Path, PathBuf}, }; /// A simple wrapper for creating a temporary directory that is automatically deleted when it's /// dropped. Used in lieu of tempfile due to the large number of dependencies. #[derive(Debug, PartialEq)] pub struct TempPath { path_buf: PathBuf, persist: bool, } impl Drop for TempPath { fn drop(&mut self) { if !self.persist { fs::remove_dir_all(&self.path_buf) .or_else(|_| fs::remove_file(&self.path_buf)) .unwrap_or(()); } } } impl TempPath { /// Create new, uninitialized temporary path in the system temp directory. pub fn new() -> Self { Self::new_with_temp_dir(std::env::temp_dir()) } /// Create new, uninitialized temporary path in the specified directory. pub fn new_with_temp_dir(temp_dir: PathBuf) -> Self { let mut temppath = temp_dir; let mut rng = rand::thread_rng(); let mut bytes = [0_u8; 16]; rng.fill_bytes(&mut bytes); temppath.push(hex::encode(&bytes)); TempPath { path_buf: temppath, persist: false, } } /// Return the underlying path to this temporary directory. pub fn path(&self) -> &Path { &self.path_buf } /// Keep the temp path pub fn persist(&mut self) { self.persist = true; } pub fn create_as_file(&self) -> io::Result<()> { let mut builder = fs::OpenOptions::new(); builder.write(true).create_new(true); builder.open(self.path())?; Ok(()) } pub fn create_as_dir(&self) -> io::Result<()> { let builder = fs::DirBuilder::new(); builder.create(self.path())?; Ok(()) } } impl std::convert::AsRef<Path> for TempPath { fn as_ref(&self) -> &Path { self.path() } } impl Default for TempPath { fn default() -> Self { Self::new() } }
{ "pile_set_name": "Github" }
# SPDX-License-Identifier: GPL-2.0 all: TEST_PROGS := main.sh TEST_FILES := cpu.sh cpufreq.sh governor.sh module.sh special-tests.sh include ../lib.mk clean:
{ "pile_set_name": "Github" }
package allen.test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.springframework.core.io.FileSystemResource; import com.alipay.simplehbase.exception.SimpleHBaseException; /** * CachedFileSystemResource. * * @author xinzhi.zhang * */ public class CachedFileSystemResource extends FileSystemResource { private byte[] data; public CachedFileSystemResource(String path) { super(path); } @Override synchronized public InputStream getInputStream() { if (data == null) { try { InputStream tem = super.getInputStream(); List<Byte> temData = new ArrayList<Byte>(); for (int i = tem.read(); i != -1; i = tem.read()) { temData.add((byte) i); } data = new byte[temData.size()]; for (int i = 0; i < temData.size(); i++) { data[i] = temData.get(i); } } catch (IOException e) { throw new SimpleHBaseException(e); } } return new ByteArrayInputStream(data); } }
{ "pile_set_name": "Github" }
.so man2/utimes.2
{ "pile_set_name": "Github" }
.file "vpaes-x86.s" .text .align 6,0x90 L_vpaes_consts: .long 218628480,235210255,168496130,67568393 .long 252381056,17041926,33884169,51187212 .long 252645135,252645135,252645135,252645135 .long 1512730624,3266504856,1377990664,3401244816 .long 830229760,1275146365,2969422977,3447763452 .long 3411033600,2979783055,338359620,2782886510 .long 4209124096,907596821,221174255,1006095553 .long 191964160,3799684038,3164090317,1589111125 .long 182528256,1777043520,2877432650,3265356744 .long 1874708224,3503451415,3305285752,363511674 .long 1606117888,3487855781,1093350906,2384367825 .long 197121,67569157,134941193,202313229 .long 67569157,134941193,202313229,197121 .long 134941193,202313229,197121,67569157 .long 202313229,197121,67569157,134941193 .long 33619971,100992007,168364043,235736079 .long 235736079,33619971,100992007,168364043 .long 168364043,235736079,33619971,100992007 .long 100992007,168364043,235736079,33619971 .long 50462976,117835012,185207048,252579084 .long 252314880,51251460,117574920,184942860 .long 184682752,252054788,50987272,118359308 .long 118099200,185467140,251790600,50727180 .long 2946363062,528716217,1300004225,1881839624 .long 1532713819,1532713819,1532713819,1532713819 .long 3602276352,4288629033,3737020424,4153884961 .long 1354558464,32357713,2958822624,3775749553 .long 1201988352,132424512,1572796698,503232858 .long 2213177600,1597421020,4103937655,675398315 .long 2749646592,4273543773,1511898873,121693092 .long 3040248576,1103263732,2871565598,1608280554 .long 2236667136,2588920351,482954393,64377734 .long 3069987328,291237287,2117370568,3650299247 .long 533321216,3573750986,2572112006,1401264716 .long 1339849704,2721158661,548607111,3445553514 .long 2128193280,3054596040,2183486460,1257083700 .long 655635200,1165381986,3923443150,2344132524 .long 190078720,256924420,290342170,357187870 .long 1610966272,2263057382,4103205268,309794674 .long 2592527872,2233205587,1335446729,3402964816 .long 3973531904,3225098121,3002836325,1918774430 .long 3870401024,2102906079,2284471353,4117666579 .long 617007872,1021508343,366931923,691083277 .long 2528395776,3491914898,2968704004,1613121270 .long 3445188352,3247741094,844474987,4093578302 .long 651481088,1190302358,1689581232,574775300 .long 4289380608,206939853,2555985458,2489840491 .long 2130264064,327674451,3566485037,3349835193 .long 2470714624,316102159,3636825756,3393945945 .byte 86,101,99,116,111,114,32,80,101,114,109,117,116,97,116,105 .byte 111,110,32,65,69,83,32,102,111,114,32,120,56,54,47,83 .byte 83,83,69,51,44,32,77,105,107,101,32,72,97,109,98,117 .byte 114,103,32,40,83,116,97,110,102,111,114,100,32,85,110,105 .byte 118,101,114,115,105,116,121,41,0 .align 6,0x90 .align 4 __vpaes_preheat: addl (%esp),%ebp movdqa -48(%ebp),%xmm7 movdqa -16(%ebp),%xmm6 ret .align 4 __vpaes_encrypt_core: movl $16,%ecx movl 240(%edx),%eax movdqa %xmm6,%xmm1 movdqa (%ebp),%xmm2 pandn %xmm0,%xmm1 pand %xmm6,%xmm0 movdqu (%edx),%xmm5 .byte 102,15,56,0,208 movdqa 16(%ebp),%xmm0 pxor %xmm5,%xmm2 psrld $4,%xmm1 addl $16,%edx .byte 102,15,56,0,193 leal 192(%ebp),%ebx pxor %xmm2,%xmm0 jmp L000enc_entry .align 4,0x90 L001enc_loop: movdqa 32(%ebp),%xmm4 movdqa 48(%ebp),%xmm0 .byte 102,15,56,0,226 .byte 102,15,56,0,195 pxor %xmm5,%xmm4 movdqa 64(%ebp),%xmm5 pxor %xmm4,%xmm0 movdqa -64(%ebx,%ecx,1),%xmm1 .byte 102,15,56,0,234 movdqa 80(%ebp),%xmm2 movdqa (%ebx,%ecx,1),%xmm4 .byte 102,15,56,0,211 movdqa %xmm0,%xmm3 pxor %xmm5,%xmm2 .byte 102,15,56,0,193 addl $16,%edx pxor %xmm2,%xmm0 .byte 102,15,56,0,220 addl $16,%ecx pxor %xmm0,%xmm3 .byte 102,15,56,0,193 andl $48,%ecx subl $1,%eax pxor %xmm3,%xmm0 L000enc_entry: movdqa %xmm6,%xmm1 movdqa -32(%ebp),%xmm5 pandn %xmm0,%xmm1 psrld $4,%xmm1 pand %xmm6,%xmm0 .byte 102,15,56,0,232 movdqa %xmm7,%xmm3 pxor %xmm1,%xmm0 .byte 102,15,56,0,217 movdqa %xmm7,%xmm4 pxor %xmm5,%xmm3 .byte 102,15,56,0,224 movdqa %xmm7,%xmm2 pxor %xmm5,%xmm4 .byte 102,15,56,0,211 movdqa %xmm7,%xmm3 pxor %xmm0,%xmm2 .byte 102,15,56,0,220 movdqu (%edx),%xmm5 pxor %xmm1,%xmm3 jnz L001enc_loop movdqa 96(%ebp),%xmm4 movdqa 112(%ebp),%xmm0 .byte 102,15,56,0,226 pxor %xmm5,%xmm4 .byte 102,15,56,0,195 movdqa 64(%ebx,%ecx,1),%xmm1 pxor %xmm4,%xmm0 .byte 102,15,56,0,193 ret .align 4 __vpaes_decrypt_core: leal 608(%ebp),%ebx movl 240(%edx),%eax movdqa %xmm6,%xmm1 movdqa -64(%ebx),%xmm2 pandn %xmm0,%xmm1 movl %eax,%ecx psrld $4,%xmm1 movdqu (%edx),%xmm5 shll $4,%ecx pand %xmm6,%xmm0 .byte 102,15,56,0,208 movdqa -48(%ebx),%xmm0 xorl $48,%ecx .byte 102,15,56,0,193 andl $48,%ecx pxor %xmm5,%xmm2 movdqa 176(%ebp),%xmm5 pxor %xmm2,%xmm0 addl $16,%edx leal -352(%ebx,%ecx,1),%ecx jmp L002dec_entry .align 4,0x90 L003dec_loop: movdqa -32(%ebx),%xmm4 movdqa -16(%ebx),%xmm1 .byte 102,15,56,0,226 .byte 102,15,56,0,203 pxor %xmm4,%xmm0 movdqa (%ebx),%xmm4 pxor %xmm1,%xmm0 movdqa 16(%ebx),%xmm1 .byte 102,15,56,0,226 .byte 102,15,56,0,197 .byte 102,15,56,0,203 pxor %xmm4,%xmm0 movdqa 32(%ebx),%xmm4 pxor %xmm1,%xmm0 movdqa 48(%ebx),%xmm1 .byte 102,15,56,0,226 .byte 102,15,56,0,197 .byte 102,15,56,0,203 pxor %xmm4,%xmm0 movdqa 64(%ebx),%xmm4 pxor %xmm1,%xmm0 movdqa 80(%ebx),%xmm1 .byte 102,15,56,0,226 .byte 102,15,56,0,197 .byte 102,15,56,0,203 pxor %xmm4,%xmm0 addl $16,%edx .byte 102,15,58,15,237,12 pxor %xmm1,%xmm0 subl $1,%eax L002dec_entry: movdqa %xmm6,%xmm1 movdqa -32(%ebp),%xmm2 pandn %xmm0,%xmm1 pand %xmm6,%xmm0 psrld $4,%xmm1 .byte 102,15,56,0,208 movdqa %xmm7,%xmm3 pxor %xmm1,%xmm0 .byte 102,15,56,0,217 movdqa %xmm7,%xmm4 pxor %xmm2,%xmm3 .byte 102,15,56,0,224 pxor %xmm2,%xmm4 movdqa %xmm7,%xmm2 .byte 102,15,56,0,211 movdqa %xmm7,%xmm3 pxor %xmm0,%xmm2 .byte 102,15,56,0,220 movdqu (%edx),%xmm0 pxor %xmm1,%xmm3 jnz L003dec_loop movdqa 96(%ebx),%xmm4 .byte 102,15,56,0,226 pxor %xmm0,%xmm4 movdqa 112(%ebx),%xmm0 movdqa (%ecx),%xmm2 .byte 102,15,56,0,195 pxor %xmm4,%xmm0 .byte 102,15,56,0,194 ret .align 4 __vpaes_schedule_core: addl (%esp),%ebp movdqu (%esi),%xmm0 movdqa 320(%ebp),%xmm2 movdqa %xmm0,%xmm3 leal (%ebp),%ebx movdqa %xmm2,4(%esp) call __vpaes_schedule_transform movdqa %xmm0,%xmm7 testl %edi,%edi jnz L004schedule_am_decrypting movdqu %xmm0,(%edx) jmp L005schedule_go L004schedule_am_decrypting: movdqa 256(%ebp,%ecx,1),%xmm1 .byte 102,15,56,0,217 movdqu %xmm3,(%edx) xorl $48,%ecx L005schedule_go: cmpl $192,%eax ja L006schedule_256 je L007schedule_192 L008schedule_128: movl $10,%eax L009loop_schedule_128: call __vpaes_schedule_round decl %eax jz L010schedule_mangle_last call __vpaes_schedule_mangle jmp L009loop_schedule_128 .align 4,0x90 L007schedule_192: movdqu 8(%esi),%xmm0 call __vpaes_schedule_transform movdqa %xmm0,%xmm6 pxor %xmm4,%xmm4 movhlps %xmm4,%xmm6 movl $4,%eax L011loop_schedule_192: call __vpaes_schedule_round .byte 102,15,58,15,198,8 call __vpaes_schedule_mangle call __vpaes_schedule_192_smear call __vpaes_schedule_mangle call __vpaes_schedule_round decl %eax jz L010schedule_mangle_last call __vpaes_schedule_mangle call __vpaes_schedule_192_smear jmp L011loop_schedule_192 .align 4,0x90 L006schedule_256: movdqu 16(%esi),%xmm0 call __vpaes_schedule_transform movl $7,%eax L012loop_schedule_256: call __vpaes_schedule_mangle movdqa %xmm0,%xmm6 call __vpaes_schedule_round decl %eax jz L010schedule_mangle_last call __vpaes_schedule_mangle pshufd $255,%xmm0,%xmm0 movdqa %xmm7,20(%esp) movdqa %xmm6,%xmm7 call L_vpaes_schedule_low_round movdqa 20(%esp),%xmm7 jmp L012loop_schedule_256 .align 4,0x90 L010schedule_mangle_last: leal 384(%ebp),%ebx testl %edi,%edi jnz L013schedule_mangle_last_dec movdqa 256(%ebp,%ecx,1),%xmm1 .byte 102,15,56,0,193 leal 352(%ebp),%ebx addl $32,%edx L013schedule_mangle_last_dec: addl $-16,%edx pxor 336(%ebp),%xmm0 call __vpaes_schedule_transform movdqu %xmm0,(%edx) pxor %xmm0,%xmm0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 pxor %xmm3,%xmm3 pxor %xmm4,%xmm4 pxor %xmm5,%xmm5 pxor %xmm6,%xmm6 pxor %xmm7,%xmm7 ret .align 4 __vpaes_schedule_192_smear: pshufd $128,%xmm6,%xmm1 pshufd $254,%xmm7,%xmm0 pxor %xmm1,%xmm6 pxor %xmm1,%xmm1 pxor %xmm0,%xmm6 movdqa %xmm6,%xmm0 movhlps %xmm1,%xmm6 ret .align 4 __vpaes_schedule_round: movdqa 8(%esp),%xmm2 pxor %xmm1,%xmm1 .byte 102,15,58,15,202,15 .byte 102,15,58,15,210,15 pxor %xmm1,%xmm7 pshufd $255,%xmm0,%xmm0 .byte 102,15,58,15,192,1 movdqa %xmm2,8(%esp) L_vpaes_schedule_low_round: movdqa %xmm7,%xmm1 pslldq $4,%xmm7 pxor %xmm1,%xmm7 movdqa %xmm7,%xmm1 pslldq $8,%xmm7 pxor %xmm1,%xmm7 pxor 336(%ebp),%xmm7 movdqa -16(%ebp),%xmm4 movdqa -48(%ebp),%xmm5 movdqa %xmm4,%xmm1 pandn %xmm0,%xmm1 psrld $4,%xmm1 pand %xmm4,%xmm0 movdqa -32(%ebp),%xmm2 .byte 102,15,56,0,208 pxor %xmm1,%xmm0 movdqa %xmm5,%xmm3 .byte 102,15,56,0,217 pxor %xmm2,%xmm3 movdqa %xmm5,%xmm4 .byte 102,15,56,0,224 pxor %xmm2,%xmm4 movdqa %xmm5,%xmm2 .byte 102,15,56,0,211 pxor %xmm0,%xmm2 movdqa %xmm5,%xmm3 .byte 102,15,56,0,220 pxor %xmm1,%xmm3 movdqa 32(%ebp),%xmm4 .byte 102,15,56,0,226 movdqa 48(%ebp),%xmm0 .byte 102,15,56,0,195 pxor %xmm4,%xmm0 pxor %xmm7,%xmm0 movdqa %xmm0,%xmm7 ret .align 4 __vpaes_schedule_transform: movdqa -16(%ebp),%xmm2 movdqa %xmm2,%xmm1 pandn %xmm0,%xmm1 psrld $4,%xmm1 pand %xmm2,%xmm0 movdqa (%ebx),%xmm2 .byte 102,15,56,0,208 movdqa 16(%ebx),%xmm0 .byte 102,15,56,0,193 pxor %xmm2,%xmm0 ret .align 4 __vpaes_schedule_mangle: movdqa %xmm0,%xmm4 movdqa 128(%ebp),%xmm5 testl %edi,%edi jnz L014schedule_mangle_dec addl $16,%edx pxor 336(%ebp),%xmm4 .byte 102,15,56,0,229 movdqa %xmm4,%xmm3 .byte 102,15,56,0,229 pxor %xmm4,%xmm3 .byte 102,15,56,0,229 pxor %xmm4,%xmm3 jmp L015schedule_mangle_both .align 4,0x90 L014schedule_mangle_dec: movdqa -16(%ebp),%xmm2 leal 416(%ebp),%esi movdqa %xmm2,%xmm1 pandn %xmm4,%xmm1 psrld $4,%xmm1 pand %xmm2,%xmm4 movdqa (%esi),%xmm2 .byte 102,15,56,0,212 movdqa 16(%esi),%xmm3 .byte 102,15,56,0,217 pxor %xmm2,%xmm3 .byte 102,15,56,0,221 movdqa 32(%esi),%xmm2 .byte 102,15,56,0,212 pxor %xmm3,%xmm2 movdqa 48(%esi),%xmm3 .byte 102,15,56,0,217 pxor %xmm2,%xmm3 .byte 102,15,56,0,221 movdqa 64(%esi),%xmm2 .byte 102,15,56,0,212 pxor %xmm3,%xmm2 movdqa 80(%esi),%xmm3 .byte 102,15,56,0,217 pxor %xmm2,%xmm3 .byte 102,15,56,0,221 movdqa 96(%esi),%xmm2 .byte 102,15,56,0,212 pxor %xmm3,%xmm2 movdqa 112(%esi),%xmm3 .byte 102,15,56,0,217 pxor %xmm2,%xmm3 addl $-16,%edx L015schedule_mangle_both: movdqa 256(%ebp,%ecx,1),%xmm1 .byte 102,15,56,0,217 addl $-16,%ecx andl $48,%ecx movdqu %xmm3,(%edx) ret .globl _vpaes_set_encrypt_key .align 4 _vpaes_set_encrypt_key: L_vpaes_set_encrypt_key_begin: pushl %ebp pushl %ebx pushl %esi pushl %edi movl 20(%esp),%esi leal -56(%esp),%ebx movl 24(%esp),%eax andl $-16,%ebx movl 28(%esp),%edx xchgl %esp,%ebx movl %ebx,48(%esp) movl %eax,%ebx shrl $5,%ebx addl $5,%ebx movl %ebx,240(%edx) movl $48,%ecx movl $0,%edi leal L_vpaes_consts+0x30-L016pic_point,%ebp call __vpaes_schedule_core L016pic_point: movl 48(%esp),%esp xorl %eax,%eax popl %edi popl %esi popl %ebx popl %ebp ret .globl _vpaes_set_decrypt_key .align 4 _vpaes_set_decrypt_key: L_vpaes_set_decrypt_key_begin: pushl %ebp pushl %ebx pushl %esi pushl %edi movl 20(%esp),%esi leal -56(%esp),%ebx movl 24(%esp),%eax andl $-16,%ebx movl 28(%esp),%edx xchgl %esp,%ebx movl %ebx,48(%esp) movl %eax,%ebx shrl $5,%ebx addl $5,%ebx movl %ebx,240(%edx) shll $4,%ebx leal 16(%edx,%ebx,1),%edx movl $1,%edi movl %eax,%ecx shrl $1,%ecx andl $32,%ecx xorl $32,%ecx leal L_vpaes_consts+0x30-L017pic_point,%ebp call __vpaes_schedule_core L017pic_point: movl 48(%esp),%esp xorl %eax,%eax popl %edi popl %esi popl %ebx popl %ebp ret .globl _vpaes_encrypt .align 4 _vpaes_encrypt: L_vpaes_encrypt_begin: pushl %ebp pushl %ebx pushl %esi pushl %edi leal L_vpaes_consts+0x30-L018pic_point,%ebp call __vpaes_preheat L018pic_point: movl 20(%esp),%esi leal -56(%esp),%ebx movl 24(%esp),%edi andl $-16,%ebx movl 28(%esp),%edx xchgl %esp,%ebx movl %ebx,48(%esp) movdqu (%esi),%xmm0 call __vpaes_encrypt_core movdqu %xmm0,(%edi) movl 48(%esp),%esp popl %edi popl %esi popl %ebx popl %ebp ret .globl _vpaes_decrypt .align 4 _vpaes_decrypt: L_vpaes_decrypt_begin: pushl %ebp pushl %ebx pushl %esi pushl %edi leal L_vpaes_consts+0x30-L019pic_point,%ebp call __vpaes_preheat L019pic_point: movl 20(%esp),%esi leal -56(%esp),%ebx movl 24(%esp),%edi andl $-16,%ebx movl 28(%esp),%edx xchgl %esp,%ebx movl %ebx,48(%esp) movdqu (%esi),%xmm0 call __vpaes_decrypt_core movdqu %xmm0,(%edi) movl 48(%esp),%esp popl %edi popl %esi popl %ebx popl %ebp ret .globl _vpaes_cbc_encrypt .align 4 _vpaes_cbc_encrypt: L_vpaes_cbc_encrypt_begin: pushl %ebp pushl %ebx pushl %esi pushl %edi movl 20(%esp),%esi movl 24(%esp),%edi movl 28(%esp),%eax movl 32(%esp),%edx subl $16,%eax jc L020cbc_abort leal -56(%esp),%ebx movl 36(%esp),%ebp andl $-16,%ebx movl 40(%esp),%ecx xchgl %esp,%ebx movdqu (%ebp),%xmm1 subl %esi,%edi movl %ebx,48(%esp) movl %edi,(%esp) movl %edx,4(%esp) movl %ebp,8(%esp) movl %eax,%edi leal L_vpaes_consts+0x30-L021pic_point,%ebp call __vpaes_preheat L021pic_point: cmpl $0,%ecx je L022cbc_dec_loop jmp L023cbc_enc_loop .align 4,0x90 L023cbc_enc_loop: movdqu (%esi),%xmm0 pxor %xmm1,%xmm0 call __vpaes_encrypt_core movl (%esp),%ebx movl 4(%esp),%edx movdqa %xmm0,%xmm1 movdqu %xmm0,(%ebx,%esi,1) leal 16(%esi),%esi subl $16,%edi jnc L023cbc_enc_loop jmp L024cbc_done .align 4,0x90 L022cbc_dec_loop: movdqu (%esi),%xmm0 movdqa %xmm1,16(%esp) movdqa %xmm0,32(%esp) call __vpaes_decrypt_core movl (%esp),%ebx movl 4(%esp),%edx pxor 16(%esp),%xmm0 movdqa 32(%esp),%xmm1 movdqu %xmm0,(%ebx,%esi,1) leal 16(%esi),%esi subl $16,%edi jnc L022cbc_dec_loop L024cbc_done: movl 8(%esp),%ebx movl 48(%esp),%esp movdqu %xmm1,(%ebx) L020cbc_abort: popl %edi popl %esi popl %ebx popl %ebp ret
{ "pile_set_name": "Github" }
<!DOCTYPE html> <!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]--> <!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]--> <!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]--> <!--[if (gte IE 9)|!(IE)]><!--> <html lang="en" xmlns="http://www.w3.org/1999/html"> <!--<![endif]--> <head> <!-- Basic Page Needs ================================================== --> <meta charset="utf-8" /> <title>icon-vk: Font Awesome Icons</title> <meta name="description" content="Font Awesome, the iconic font designed for Bootstrap"> <meta name="author" content="Dave Gandy"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--<meta name="viewport" content="initial-scale=1; maximum-scale=1">--> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- CSS ================================================== --> <link rel="stylesheet" href="../../assets/css/site.css"> <link rel="stylesheet" href="../../assets/css/pygments.css"> <link rel="stylesheet" href="../../assets/font-awesome/css/font-awesome.css"> <!--[if IE 7]> <link rel="stylesheet" href="../../assets/font-awesome/css/font-awesome-ie7.css"> <![endif]--> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="../../assets/ico/favicon.ico"> <script type="text/javascript" src="//use.typekit.net/wnc7ioh.js"></script> <script type="text/javascript">try{Typekit.load();}catch(e){}</script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-30136587-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body data-spy="scroll" data-target=".navbar"> <div class="wrapper"> <!-- necessary for sticky footer. wrap all content except footer --> <div class="navbar navbar-inverse navbar-static-top hidden-print"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="../../"><i class="icon-flag"></i> Font Awesome</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class="hidden-tablet "><a href="../../">Home</a></li> <li><a href="../../get-started/">Get Started</a></li> <li class="dropdown-split-left"><a href="../../icons/">Icons</a></li> <li class="dropdown dropdown-split-right hidden-phone"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-caret-down"></i> </a> <ul class="dropdown-menu pull-right"> <li><a href="../../icons/"><i class="icon-flag icon-fixed-width"></i>&nbsp; Icons</a></li> <li class="divider"></li> <li><a href="../../icons/#new"><i class="icon-shield icon-fixed-width"></i>&nbsp; New Icons in 3.2.1</a></li> <li><a href="../../icons/#web-application"><i class="icon-camera-retro icon-fixed-width"></i>&nbsp; Web Application Icons</a></li> <li><a href="../../icons/#currency"><i class="icon-won icon-fixed-width"></i>&nbsp; Currency Icons</a></li> <li><a href="../../icons/#text-editor"><i class="icon-file-text-alt icon-fixed-width"></i>&nbsp; Text Editor Icons</a></li> <li><a href="../../icons/#directional"><i class="icon-hand-right icon-fixed-width"></i>&nbsp; Directional Icons</a></li> <li><a href="../../icons/#video-player"><i class="icon-play-sign icon-fixed-width"></i>&nbsp; Video Player Icons</a></li> <li><a href="../../icons/#brand"><i class="icon-github icon-fixed-width"></i>&nbsp; Brand Icons</a></li> <li><a href="../../icons/#medical"><i class="icon-medkit icon-fixed-width"></i>&nbsp; Medical Icons</a></li> </ul> </li> <li class="dropdown-split-left"><a href="../../examples/">Examples</a></li> <li class="dropdown dropdown-split-right hidden-phone"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-caret-down"></i> </a> <ul class="dropdown-menu pull-right"> <li><a href="../../examples/">Examples</a></li> <li class="divider"></li> <li><a href="../../examples/#new-styles">New Styles</a></li> <li><a href="../../examples/#inline-icons">Inline Icons</a></li> <li><a href="../../examples/#larger-icons">Larger Icons</a></li> <li><a href="../../examples/#bordered-pulled">Bordered & Pulled</a></li> <li><a href="../../examples/#buttons">Buttons</a></li> <li><a href="../../examples/#button-groups">Button Groups</a></li> <li><a href="../../examples/#button-dropdowns">Button Dropdowns</a></li> <li><a href="../../examples/#bulleted-lists">Bulleted Lists</a></li> <li><a href="../../examples/#navigation">Navigation</a></li> <li><a href="../../examples/#form-inputs">Form Inputs</a></li> <li><a href="../../examples/#animated-spinner">Animated Spinner</a></li> <li><a href="../../examples/#rotated-flipped">Rotated &amp; Flipped</a></li> <li><a href="../../examples/#stacked">Stacked</a></li> <li><a href="../../examples/#custom">Custom CSS</a></li> </ul> </li> <li><a href="../../whats-new/"> <span class="hidden-tablet">What's </span>New</a> </li> <li><a href="../../community/">Community</a></li> <li><a href="../../license/">License</a></li> </ul> <ul class="nav pull-right"> <li><a href="http://blog.fontawesome.io">Blog</a></li> </ul> </div> </div> </div> </div> <div class="jumbotron jumbotron-icon"> <div class="container"> <div class="info-icons"> <i class="icon-vk icon-6"></i>&nbsp;&nbsp; <span class="hidden-phone"> <i class="icon-vk icon-5"></i>&nbsp;&nbsp; <span class="hidden-tablet"><i class="icon-vk icon-4"></i>&nbsp;&nbsp;</span> <i class="icon-vk icon-3"></i>&nbsp;&nbsp; <i class="icon-vk icon-2"></i>&nbsp; </span> <i class="icon-vk icon-1"></i> </div> <h1 class="info-class"> icon-vk <small> <i class="icon-vk"></i> &middot; Unicode: <span class="upper">f189</span> &middot; Created: v3.2 &middot; Categories: Brand Icons </small> </h1> </div> </div> <div class="container"> <section> <div class="row-fluid"> <div class="span9"> <p>After you get <a href="../../integration/">up and running</a>, you can place Font Awesome icons just about anywhere with the <code>&lt;i&gt;</code> tag:</p> <div class="well well-transparent"> <div style="font-size: 24px; line-height: 1.5em;"> <i class="icon-vk"></i> icon-vk </div> </div> <div class="highlight"><pre><code class="html"><span class="nt">&lt;i</span> <span class="na">class=</span><span class="s">&quot;icon-vk&quot;</span><span class="nt">&gt;&lt;/i&gt;</span> icon-vk </code></pre></div> <br> <div class="lead"><i class="icon-info-sign"></i> Looking for more? Check out the <a href="../../examples/">examples</a>.</div> </div> <div class="span3"> <div class="info-ad"><div id="carbonads-container"><div class="carbonad"><div id="azcarbon"></div><script type="text/javascript">var z = document.createElement("script"); z.type = "text/javascript"; z.async = true; z.src = "http://engine.carbonads.com/z/32291/azcarbon_2_1_0_VERT"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(z, s);</script></div></div> </div> </div> </div> </section> </div> <div class="push"><!-- necessary for sticky footer --></div> </div> <footer class="footer hidden-print"> <div class="container text-center"> <div> <i class="icon-flag"></i> Font Awesome 3.2.1 <span class="hidden-phone">&middot;</span><br class="visible-phone"> Created and Maintained by <a href="http://twitter.com/davegandy">Dave Gandy</a> </div> <div> Font Awesome licensed under <a href="http://scripts.sil.org/OFL">SIL OFL 1.1</a> <span class="hidden-phone">&middot;</span><br class="visible-phone"> Code licensed under <a href="http://opensource.org/licenses/mit-license.html">MIT License</a> <span class="hidden-phone hidden-tablet">&middot;</span><br class="visible-phone visible-tablet"> Documentation licensed under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a> </div> <div> Thanks to <a href="http://maxcdn.com"><i class="icon-maxcdn"></i> MaxCDN</a> for providing the excellent <a href="http://www.bootstrapcdn.com/#tab_fontawesome">BootstrapCDN for Font Awesome</a> </div> <div class="project"> <a href="https://github.com/FortAwesome/Font-Awesome">GitHub Project</a> &middot; <a href="https://github.com/FortAwesome/Font-Awesome/issues">Issues</a> </div> </div> </footer> <script src="http://platform.twitter.com/widgets.js"></script> <script src="../../assets/js/jquery-1.7.1.min.js"></script> <script src="../../assets/js/ZeroClipboard-1.1.7.min.js"></script> <script src="../../assets/js/bootstrap-2.3.1.min.js"></script> <script src="../../assets/js/site.js"></script> </body> </html>
{ "pile_set_name": "Github" }
// // SavedLocationsManager.h // CycleStreets // // Created by Neil Edwards on 14/10/2014. // Copyright (c) 2014 CycleStreets Ltd. All rights reserved. // #import "FrameworkObject.h" #import "SynthesizeSingleton.h" @class SavedLocationVO; @interface SavedLocationsManager : FrameworkObject SYNTHESIZE_SINGLETON_FOR_CLASS_HEADER(SavedLocationsManager); @property (nonatomic,readonly) NSMutableArray *dataProvider; -(void)addSavedLocation:(SavedLocationVO*)location; -(void)removeSavedLocation:(SavedLocationVO*)location; -(void)saveLocations; @end
{ "pile_set_name": "Github" }
#ifndef Renderer_HPP #define Renderer_HPP #include "FBO.hpp" #include "PresetFrameIO.hpp" #include "BeatDetect.hpp" #include <string> #include <pthread.h> #ifdef USE_GLES1 #include <GLES/gl.h> #else #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/gl.h> #include <GL/glu.h> #endif #endif #ifdef USE_FTGL #ifdef WIN32 #include <FTGL.h> #include <FTGLPixmapFont.h> #include <FTGLExtrdFont.h> #else #include <FTGL/FTGL.h> #include <FTGL/FTGLPixmapFont.h> #include <FTGL/FTGLExtrdFont.h> #endif #endif /** USE_FTGL */ class BeatDetect; class TextureManager; class Renderer { public: bool showfps; bool showtitle; bool showpreset; bool showhelp; bool showstats; bool studio; bool correction; bool noSwitch; int totalframes; float realfps; std::string title; int drawtitle; int texsize; Renderer( int width, int height, int gx, int gy, int texsize, BeatDetect *beatDetect, std::string presetURL, std::string title_fontURL, std::string menu_fontURL, int xpos, int ypos, bool usefbo ); ~Renderer(); void RenderFrame(PresetOutputs *presetOutputs, PresetInputs *presetInputs); void ResetTextures(); void reset(int w, int h); GLuint initRenderToTexture(); void PerPixelMath(PresetOutputs *presetOutputs, PresetInputs *presetInputs); void WaveformMath(PresetOutputs *presetOutputs, PresetInputs *presetInputs, bool isSmoothing); void setPresetName(const std::string& theValue) { m_presetName = theValue; } std::string presetName() const { return m_presetName; } private: RenderTarget *renderTarget; BeatDetect *beatDetect; TextureManager *textureManager; //per pixel equation variables float **gridx; //grid containing interpolated mesh float **gridy; float **origx2; //original mesh float **origy2; int gx; int gy; std::string m_presetName; int vx; int vy; int vw; int vh; bool useFBO; float aspect; pthread_mutex_t _renderer_lock; #ifdef USE_FTGL FTGLPixmapFont *title_font; FTGLPixmapFont *other_font; FTGLExtrdFont *poly_font; #endif /** USE_FTGL */ std::string title_fontURL; std::string menu_fontURL; std::string presetURL; void draw_waveform(PresetOutputs * presetOutputs); void Interpolation(PresetOutputs *presetOutputs, PresetInputs *presetInputs); void rescale_per_pixel_matrices(); void maximize_colors(PresetOutputs *presetOutputs); void render_texture_to_screen(PresetOutputs *presetOutputs); void render_texture_to_studio(PresetOutputs *presetOutputs, PresetInputs *presetInputs); void draw_fps( float realfps ); void draw_stats(PresetInputs *presetInputs); void draw_help( ); void draw_preset(); void draw_title(); void draw_title_to_screen(bool flip); void maximize_colors(); void draw_title_to_texture(); void draw_motion_vectors(PresetOutputs *presetOutputs); void draw_borders(PresetOutputs *presetOutputs); void draw_shapes(PresetOutputs *presetOutputs); void draw_custom_waves(PresetOutputs *presetOutputs); void modulate_opacity_by_volume(PresetOutputs *presetOutputs) ; void darken_center(); }; #endif
{ "pile_set_name": "Github" }
Demo_mazak es un conjunto complejo de controladores HAL. Incluyen la tarjeta de movimiento Motenc-Lite, una tarjeta parport PMDX y una tarjeta IO ISA de propósito general. Esta configuración se usa para la Mazak V5 de Cardinal Engineering y se incluye aquí como un ejemplo de una manera de distribuir las habilidades HAL en varios dispositivos. Esta demostración incluye un ejemplo del uso de un puerto paralelo para leer un codificador de volante. Trae ClassicLadder para manejar la mayor parte de la lógica de la máquina para el cambio de velocidades y herramientas. No espere poder ejecutar esto tal como está a menos que tenga un conjunto de hardware coincidente. Sin el conjunto exacto de dispositivos, aún puede estudiar los archivos hal para ver como se logran muchas de estas cosas.
{ "pile_set_name": "Github" }
int main() { int i; i=0; loop: assert(i<10); i++; if(i<10) goto loop; assert(i==10); }
{ "pile_set_name": "Github" }
package org.jboss.resteasy.test.providers.priority.resource; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.annotation.Priority; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; import javax.ws.rs.ext.Provider; @Provider @Priority(20) public class ProviderPriorityFooParamConverterProviderBBB implements ParamConverterProvider { @SuppressWarnings("unchecked") @Override public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { return (ParamConverter<T>) new ProviderPriorityFooParamConverter("BBB"); } }
{ "pile_set_name": "Github" }
; RUN: %lli %s > /dev/null define i32 @foo(i32 %x, i32 %y, double %d) { entry: %d.int64 = bitcast double %d to i64 %d.top64 = lshr i64 %d.int64, 32 %d.top = trunc i64 %d.top64 to i32 %d.bottom = trunc i64 %d.int64 to i32 %topCorrect = icmp eq i32 %d.top, 3735928559 %bottomCorrect = icmp eq i32 %d.bottom, 4277009102 %right = and i1 %topCorrect, %bottomCorrect %nRight = xor i1 %right, true %retVal = zext i1 %nRight to i32 ret i32 %retVal } define i32 @main() { entry: %call = call i32 @foo(i32 0, i32 1, double 0xDEADBEEFFEEDFACE) ret i32 %call }
{ "pile_set_name": "Github" }
{% load i18n %}{% autoescape off %} {% blocktrans %}Password reset on {{ site_name }}{% endblocktrans %} {% endautoescape %}
{ "pile_set_name": "Github" }
import pytest from vyper import compiler from vyper.exceptions import FunctionDeclarationException, StructureException fail_list = [ ( """ @external def foo() -> int128: pass """, FunctionDeclarationException, ), ( """ @external def foo() -> int128: if False: return 123 """, FunctionDeclarationException, ), ( """ @external def test() -> int128: if 1 == 1 : return 1 if True: return 0 else: assert False """, FunctionDeclarationException, ), ( """ @internal def valid_address(sender: address) -> bool: selfdestruct(sender) return True """, StructureException, ), ( """ @internal def valid_address(sender: address) -> bool: selfdestruct(sender) a: address = sender """, StructureException, ), ( """ @internal def valid_address(sender: address) -> bool: if sender == ZERO_ADDRESS: selfdestruct(sender) _sender: address = sender else: return False """, StructureException, ), ] @pytest.mark.parametrize("bad_code,exc", fail_list) def test_return_mismatch(bad_code, exc): with pytest.raises(exc): compiler.compile_code(bad_code) valid_list = [ """ @external def foo() -> int128: return 123 """, """ @external def foo() -> int128: if True: return 123 else: raise "test" """, """ @external def foo() -> int128: if False: return 123 else: selfdestruct(msg.sender) """, """ @external def foo() -> int128: if False: return 123 return 333 """, """ @external def test() -> int128: if 1 == 1 : return 1 else: assert False return 0 """, """ @external def test() -> int128: x: bytes32 = EMPTY_BYTES32 if False: if False: return 0 else: x = keccak256(x) return 1 else: x = keccak256(x) return 1 return 1 """, ] @pytest.mark.parametrize("good_code", valid_list) def test_return_success(good_code): assert compiler.compile_code(good_code) is not None
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 5cdad5d030c1f2143a2fb2b8ee388911 PrefabImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
require 'yajl' require 'securerandom' # SecureRandom.uuid require_relative 'oms_common' module OMS class AuditdPlugin def initialize(log) @log = log end def transform_and_wrap(event, hostname, time) if event.nil? @log.error "Transformation of Auditd Plugin input failed; Empty input" return nil end if !event.has_key?("records") or event["records"].nil? @log.error "Transformation of Auditd Plugin input failed; Missing field 'records'" return nil end if !event["records"].is_a?(Array) or event["records"].size == 0 @log.error "Transformation of Auditd Plugin input failed; Invalid 'records' value" return nil end if !event.has_key?("Timestamp") or event["Timestamp"].nil? @log.error "Transformation of Auditd Plugin input failed; Missing field 'Timestamp'" return nil end if !event.has_key?("SerialNumber") or event["SerialNumber"].nil? @log.error "Transformation of Auditd Plugin input failed; Missing field 'SerialNumber'" return nil end records = [] event["records"].each do |record| if !record.is_a?(Hash) || record.empty? @log.error "Transformation of Auditd Plugin input failed; Invalid data in data record" return nil end record["Timestamp"] = OMS::Common.format_time(event["Timestamp"].to_f) record["AuditID"] = event["Timestamp"] + ":" + event["SerialNumber"].to_s record["SerialNumber"] = event["SerialNumber"] record["Computer"] = hostname if event.has_key?("ProcessFlags") record["ProcessFlags"] = event["ProcessFlags"] end records.push(record) end wrapper = { "DataType"=>"LINUX_AUDITD_BLOB", "IPName"=>"Security", "DataItems"=>records } return wrapper end end # class end # module
{ "pile_set_name": "Github" }
#! /bin/sh packageinfo='./packageinfo.sh' case "$#" in 2) case "$1" in -p|--packageinfo) packageinfo="$2" esac ;; 0) ;; *) echo "Usage: $0 [-p packageinfo.sh]" exit 1 ;; esac # This script must be executed from the TLD of the source tree... . "$packageinfo" NAME="$version" case "$repotype::$point" in dev::) case "${proto}.${major}" in 4.[012]) NAME="${NAME}p${point}" ;; *) NAME="${NAME}" ;; esac ;; stable::[1-9]* | dev::[0-9]*) case "${proto}.${major}" in 4.[012]) NAME="${NAME}p${point}" ;; *) NAME="${NAME}.${point}" ;; esac ;; NEW) ;; '') ;; *) echo "Unexpected value for 'point' <$point>! (repotype is <$repotype>)" exit 1 ;; esac case $special in '') ;; *) NAME="${NAME}-${special}" ;; esac case "$prerelease::$repotype" in ''::*) ;; beta::stable) NAME="${NAME}-beta${betapoint}" ;; rc::dev|RC::dev) NAME="${NAME}-RC" ;; rc::stable|RC::stable) NAME="${NAME}-RC${rcpoint}" ;; *) echo "Unexpected value for 'prerelease::repotype' <$prerelease::$repotype>!" exit 1 ;; esac echo "$NAME"
{ "pile_set_name": "Github" }
{ "description": "A list of vegetables.", "vegetables": [ "acorn squash", "alfalfa sprout", "amaranth", "anise", "artichoke", "arugula", "asparagus", "aubergine", "azuki bean", "banana squash", "basil", "bean sprout", "beet", "black bean", "black-eyed pea", "bok choy", "borlotti bean", "broad beans", "broccoflower", "broccoli", "brussels sprout", "butternut squash", "cabbage", "calabrese", "caraway", "carrot", "cauliflower", "cayenne pepper", "celeriac", "celery", "chamomile", "chard", "chayote", "chickpea", "chives", "cilantro", "collard green", "corn", "corn salad", "courgette", "cucumber", "daikon", "delicata", "dill", "eggplant", "endive", "fennel", "fiddlehead", "frisee", "garlic", "gem squash", "ginger", "green bean", "green pepper", "habanero", "herbs and spice", "horseradish", "hubbard squash", "jalapeno", "jerusalem artichoke", "jicama", "kale", "kidney bean", "kohlrabi", "lavender", "leek ", "legume", "lemon grass", "lentils", "lettuce", "lima bean", "mamey", "mangetout", "marjoram", "mung bean", "mushroom", "mustard green", "navy bean", "new zealand spinach", "nopale", "okra", "onion", "oregano", "paprika", "parsley", "parsnip", "patty pan", "pea", "pinto bean", "potato", "pumpkin", "radicchio", "radish", "rhubarb", "rosemary", "runner bean", "rutabaga", "sage", "scallion", "shallot", "skirret", "snap pea", "soy bean", "spaghetti squash", "spinach", "squash ", "sweet potato", "tabasco pepper", "taro", "tat soi", "thyme", "topinambur", "tubers", "turnip", "wasabi", "water chestnut", "watercress", "white radish", "yam", "zucchini" ] }
{ "pile_set_name": "Github" }
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef BOOST_PREPROCESSOR_REPETITION_ENUM_TRAILING_HPP # define BOOST_PREPROCESSOR_REPETITION_ENUM_TRAILING_HPP # # include <boost/preprocessor/cat.hpp> # include <boost/preprocessor/config/config.hpp> # include <boost/preprocessor/debug/error.hpp> # include <boost/preprocessor/detail/auto_rec.hpp> # include <boost/preprocessor/repetition/repeat.hpp> # include <boost/preprocessor/tuple/elem.hpp> # include <boost/preprocessor/tuple/rem.hpp> # # /* BOOST_PP_ENUM_TRAILING */ # # if 0 # define BOOST_PP_ENUM_TRAILING(count, macro, data) # endif # # define BOOST_PP_ENUM_TRAILING BOOST_PP_CAT(BOOST_PP_ENUM_TRAILING_, BOOST_PP_AUTO_REC(BOOST_PP_REPEAT_P, 4)) # # if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG() # define BOOST_PP_ENUM_TRAILING_1(c, m, d) BOOST_PP_REPEAT_1(c, BOOST_PP_ENUM_TRAILING_M_1, (m, d)) # define BOOST_PP_ENUM_TRAILING_2(c, m, d) BOOST_PP_REPEAT_2(c, BOOST_PP_ENUM_TRAILING_M_2, (m, d)) # define BOOST_PP_ENUM_TRAILING_3(c, m, d) BOOST_PP_REPEAT_3(c, BOOST_PP_ENUM_TRAILING_M_3, (m, d)) # else # define BOOST_PP_ENUM_TRAILING_1(c, m, d) BOOST_PP_ENUM_TRAILING_1_I(c, m, d) # define BOOST_PP_ENUM_TRAILING_2(c, m, d) BOOST_PP_ENUM_TRAILING_2_I(c, m, d) # define BOOST_PP_ENUM_TRAILING_3(c, m, d) BOOST_PP_ENUM_TRAILING_3_I(c, m, d) # define BOOST_PP_ENUM_TRAILING_1_I(c, m, d) BOOST_PP_REPEAT_1(c, BOOST_PP_ENUM_TRAILING_M_1, (m, d)) # define BOOST_PP_ENUM_TRAILING_2_I(c, m, d) BOOST_PP_REPEAT_2(c, BOOST_PP_ENUM_TRAILING_M_2, (m, d)) # define BOOST_PP_ENUM_TRAILING_3_I(c, m, d) BOOST_PP_REPEAT_3(c, BOOST_PP_ENUM_TRAILING_M_3, (m, d)) # endif # # define BOOST_PP_ENUM_TRAILING_4(c, m, d) BOOST_PP_ERROR(0x0003) # # if BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_STRICT() # define BOOST_PP_ENUM_TRAILING_M_1(z, n, md) BOOST_PP_ENUM_TRAILING_M_1_IM(z, n, BOOST_PP_TUPLE_REM_2 md) # define BOOST_PP_ENUM_TRAILING_M_2(z, n, md) BOOST_PP_ENUM_TRAILING_M_2_IM(z, n, BOOST_PP_TUPLE_REM_2 md) # define BOOST_PP_ENUM_TRAILING_M_3(z, n, md) BOOST_PP_ENUM_TRAILING_M_3_IM(z, n, BOOST_PP_TUPLE_REM_2 md) # define BOOST_PP_ENUM_TRAILING_M_1_IM(z, n, im) BOOST_PP_ENUM_TRAILING_M_1_I(z, n, im) # define BOOST_PP_ENUM_TRAILING_M_2_IM(z, n, im) BOOST_PP_ENUM_TRAILING_M_2_I(z, n, im) # define BOOST_PP_ENUM_TRAILING_M_3_IM(z, n, im) BOOST_PP_ENUM_TRAILING_M_3_I(z, n, im) # else # define BOOST_PP_ENUM_TRAILING_M_1(z, n, md) BOOST_PP_ENUM_TRAILING_M_1_I(z, n, BOOST_PP_TUPLE_ELEM(2, 0, md), BOOST_PP_TUPLE_ELEM(2, 1, md)) # define BOOST_PP_ENUM_TRAILING_M_2(z, n, md) BOOST_PP_ENUM_TRAILING_M_2_I(z, n, BOOST_PP_TUPLE_ELEM(2, 0, md), BOOST_PP_TUPLE_ELEM(2, 1, md)) # define BOOST_PP_ENUM_TRAILING_M_3(z, n, md) BOOST_PP_ENUM_TRAILING_M_3_I(z, n, BOOST_PP_TUPLE_ELEM(2, 0, md), BOOST_PP_TUPLE_ELEM(2, 1, md)) # endif # # define BOOST_PP_ENUM_TRAILING_M_1_I(z, n, m, d) , m(z, n, d) # define BOOST_PP_ENUM_TRAILING_M_2_I(z, n, m, d) , m(z, n, d) # define BOOST_PP_ENUM_TRAILING_M_3_I(z, n, m, d) , m(z, n, d) # # endif
{ "pile_set_name": "Github" }
local e = {} local o = require "luci.dispatcher" local a = luci.util.execi( "/bin/busybox top -bn1 | grep 'pppd plugin rp-pppoe.so' | grep -v 'grep'") for t in a do local a, n, h, s, o = t:match( "^ *(%d+) +(%d+) +.+rp_pppoe_sess 1:+([A-Fa-f0-9]+:[A-Fa-f0-9]+:[A-Fa-f0-9]+:[A-Fa-f0-9]+:[A-Fa-f0-9]+:[A-Fa-f0-9]+[A-Fa-f0-9]) +.+options +(%S.-%S)%:(%S.-%S) ") local t = tonumber(a) if t then e["%02i.%s" % {t, "online"}] = { ['PID'] = a, ['PPID'] = n, ['MAC'] = h, ['GATEWAY'] = s, ['CIP'] = o, ['BLACKLIST'] = 0 } end end f = SimpleForm("processes", translate("PPPoE Server")) f.reset = false f.submit = false f.description = translate( "The PPPoE server is a broadband access authentication server that prevents ARP spoofing.") t = f:section(Table, e, translate("Online Users")) t:option(DummyValue, "GATEWAY", translate("Server IP")) t:option(DummyValue, "CIP", translate("IP address")) t:option(DummyValue, "MAC", translate("MAC")) kill = t:option(Button, "_kill", translate("Forced offline")) kill.inputstyle = "reset" function kill.write(e, t) null, e.tag_error[t] = luci.sys.process.signal(e.map:get(t, "PID"), 9) luci.http.redirect(o.build_url("admin/services/pppoe-server/online")) end return f
{ "pile_set_name": "Github" }
<dc:title>{title}</dc:title>
{ "pile_set_name": "Github" }
/* * rt5631.c -- RT5631 ALSA Soc Audio driver * * Copyright 2011 Realtek Microelectronics * * Author: flove <[email protected]> * * Based on WM8753.c * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/pm.h> #include <linux/i2c.h> #include <linux/regmap.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/soc-dapm.h> #include <sound/initval.h> #include <sound/tlv.h> #include "rt5631.h" struct rt5631_priv { struct regmap *regmap; int codec_version; int master; int sysclk; int rx_rate; int bclk_rate; int dmic_used_flag; }; static const struct reg_default rt5631_reg[] = { { RT5631_SPK_OUT_VOL, 0x8888 }, { RT5631_HP_OUT_VOL, 0x8080 }, { RT5631_MONO_AXO_1_2_VOL, 0xa080 }, { RT5631_AUX_IN_VOL, 0x0808 }, { RT5631_ADC_REC_MIXER, 0xf0f0 }, { RT5631_VDAC_DIG_VOL, 0x0010 }, { RT5631_OUTMIXER_L_CTRL, 0xffc0 }, { RT5631_OUTMIXER_R_CTRL, 0xffc0 }, { RT5631_AXO1MIXER_CTRL, 0x88c0 }, { RT5631_AXO2MIXER_CTRL, 0x88c0 }, { RT5631_DIG_MIC_CTRL, 0x3000 }, { RT5631_MONO_INPUT_VOL, 0x8808 }, { RT5631_SPK_MIXER_CTRL, 0xf8f8 }, { RT5631_SPK_MONO_OUT_CTRL, 0xfc00 }, { RT5631_SPK_MONO_HP_OUT_CTRL, 0x4440 }, { RT5631_SDP_CTRL, 0x8000 }, { RT5631_MONO_SDP_CTRL, 0x8000 }, { RT5631_STEREO_AD_DA_CLK_CTRL, 0x2010 }, { RT5631_GEN_PUR_CTRL_REG, 0x0e00 }, { RT5631_INT_ST_IRQ_CTRL_2, 0x071a }, { RT5631_MISC_CTRL, 0x2040 }, { RT5631_DEPOP_FUN_CTRL_2, 0x8000 }, { RT5631_SOFT_VOL_CTRL, 0x07e0 }, { RT5631_ALC_CTRL_1, 0x0206 }, { RT5631_ALC_CTRL_3, 0x2000 }, { RT5631_PSEUDO_SPATL_CTRL, 0x0553 }, }; /** * rt5631_write_index - write index register of 2nd layer */ static void rt5631_write_index(struct snd_soc_codec *codec, unsigned int reg, unsigned int value) { snd_soc_write(codec, RT5631_INDEX_ADD, reg); snd_soc_write(codec, RT5631_INDEX_DATA, value); } /** * rt5631_read_index - read index register of 2nd layer */ static unsigned int rt5631_read_index(struct snd_soc_codec *codec, unsigned int reg) { unsigned int value; snd_soc_write(codec, RT5631_INDEX_ADD, reg); value = snd_soc_read(codec, RT5631_INDEX_DATA); return value; } static int rt5631_reset(struct snd_soc_codec *codec) { return snd_soc_write(codec, RT5631_RESET, 0); } static bool rt5631_volatile_register(struct device *dev, unsigned int reg) { switch (reg) { case RT5631_RESET: case RT5631_INT_ST_IRQ_CTRL_2: case RT5631_INDEX_ADD: case RT5631_INDEX_DATA: case RT5631_EQ_CTRL: return 1; default: return 0; } } static bool rt5631_readable_register(struct device *dev, unsigned int reg) { switch (reg) { case RT5631_RESET: case RT5631_SPK_OUT_VOL: case RT5631_HP_OUT_VOL: case RT5631_MONO_AXO_1_2_VOL: case RT5631_AUX_IN_VOL: case RT5631_STEREO_DAC_VOL_1: case RT5631_MIC_CTRL_1: case RT5631_STEREO_DAC_VOL_2: case RT5631_ADC_CTRL_1: case RT5631_ADC_REC_MIXER: case RT5631_ADC_CTRL_2: case RT5631_VDAC_DIG_VOL: case RT5631_OUTMIXER_L_CTRL: case RT5631_OUTMIXER_R_CTRL: case RT5631_AXO1MIXER_CTRL: case RT5631_AXO2MIXER_CTRL: case RT5631_MIC_CTRL_2: case RT5631_DIG_MIC_CTRL: case RT5631_MONO_INPUT_VOL: case RT5631_SPK_MIXER_CTRL: case RT5631_SPK_MONO_OUT_CTRL: case RT5631_SPK_MONO_HP_OUT_CTRL: case RT5631_SDP_CTRL: case RT5631_MONO_SDP_CTRL: case RT5631_STEREO_AD_DA_CLK_CTRL: case RT5631_PWR_MANAG_ADD1: case RT5631_PWR_MANAG_ADD2: case RT5631_PWR_MANAG_ADD3: case RT5631_PWR_MANAG_ADD4: case RT5631_GEN_PUR_CTRL_REG: case RT5631_GLOBAL_CLK_CTRL: case RT5631_PLL_CTRL: case RT5631_INT_ST_IRQ_CTRL_1: case RT5631_INT_ST_IRQ_CTRL_2: case RT5631_GPIO_CTRL: case RT5631_MISC_CTRL: case RT5631_DEPOP_FUN_CTRL_1: case RT5631_DEPOP_FUN_CTRL_2: case RT5631_JACK_DET_CTRL: case RT5631_SOFT_VOL_CTRL: case RT5631_ALC_CTRL_1: case RT5631_ALC_CTRL_2: case RT5631_ALC_CTRL_3: case RT5631_PSEUDO_SPATL_CTRL: case RT5631_INDEX_ADD: case RT5631_INDEX_DATA: case RT5631_EQ_CTRL: case RT5631_VENDOR_ID: case RT5631_VENDOR_ID1: case RT5631_VENDOR_ID2: return 1; default: return 0; } } static const DECLARE_TLV_DB_SCALE(out_vol_tlv, -4650, 150, 0); static const DECLARE_TLV_DB_SCALE(dac_vol_tlv, -95625, 375, 0); static const DECLARE_TLV_DB_SCALE(in_vol_tlv, -3450, 150, 0); /* {0, +20, +24, +30, +35, +40, +44, +50, +52}dB */ static unsigned int mic_bst_tlv[] = { TLV_DB_RANGE_HEAD(7), 0, 0, TLV_DB_SCALE_ITEM(0, 0, 0), 1, 1, TLV_DB_SCALE_ITEM(2000, 0, 0), 2, 2, TLV_DB_SCALE_ITEM(2400, 0, 0), 3, 5, TLV_DB_SCALE_ITEM(3000, 500, 0), 6, 6, TLV_DB_SCALE_ITEM(4400, 0, 0), 7, 7, TLV_DB_SCALE_ITEM(5000, 0, 0), 8, 8, TLV_DB_SCALE_ITEM(5200, 0, 0), }; static int rt5631_dmic_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct rt5631_priv *rt5631 = snd_soc_codec_get_drvdata(codec); ucontrol->value.integer.value[0] = rt5631->dmic_used_flag; return 0; } static int rt5631_dmic_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct rt5631_priv *rt5631 = snd_soc_codec_get_drvdata(codec); rt5631->dmic_used_flag = ucontrol->value.integer.value[0]; return 0; } /* MIC Input Type */ static const char *rt5631_input_mode[] = { "Single ended", "Differential"}; static const SOC_ENUM_SINGLE_DECL( rt5631_mic1_mode_enum, RT5631_MIC_CTRL_1, RT5631_MIC1_DIFF_INPUT_SHIFT, rt5631_input_mode); static const SOC_ENUM_SINGLE_DECL( rt5631_mic2_mode_enum, RT5631_MIC_CTRL_1, RT5631_MIC2_DIFF_INPUT_SHIFT, rt5631_input_mode); /* MONO Input Type */ static const SOC_ENUM_SINGLE_DECL( rt5631_monoin_mode_enum, RT5631_MONO_INPUT_VOL, RT5631_MONO_DIFF_INPUT_SHIFT, rt5631_input_mode); /* SPK Ratio Gain Control */ static const char *rt5631_spk_ratio[] = {"1.00x", "1.09x", "1.27x", "1.44x", "1.56x", "1.68x", "1.99x", "2.34x"}; static const SOC_ENUM_SINGLE_DECL( rt5631_spk_ratio_enum, RT5631_GEN_PUR_CTRL_REG, RT5631_SPK_AMP_RATIO_CTRL_SHIFT, rt5631_spk_ratio); static const struct snd_kcontrol_new rt5631_snd_controls[] = { /* MIC */ SOC_ENUM("MIC1 Mode Control", rt5631_mic1_mode_enum), SOC_SINGLE_TLV("MIC1 Boost", RT5631_MIC_CTRL_2, RT5631_MIC1_BOOST_SHIFT, 8, 0, mic_bst_tlv), SOC_ENUM("MIC2 Mode Control", rt5631_mic2_mode_enum), SOC_SINGLE_TLV("MIC2 Boost", RT5631_MIC_CTRL_2, RT5631_MIC2_BOOST_SHIFT, 8, 0, mic_bst_tlv), /* MONO IN */ SOC_ENUM("MONOIN Mode Control", rt5631_monoin_mode_enum), SOC_DOUBLE_TLV("MONOIN_RX Capture Volume", RT5631_MONO_INPUT_VOL, RT5631_L_VOL_SHIFT, RT5631_R_VOL_SHIFT, RT5631_VOL_MASK, 1, in_vol_tlv), /* AXI */ SOC_DOUBLE_TLV("AXI Capture Volume", RT5631_AUX_IN_VOL, RT5631_L_VOL_SHIFT, RT5631_R_VOL_SHIFT, RT5631_VOL_MASK, 1, in_vol_tlv), /* DAC */ SOC_DOUBLE_TLV("PCM Playback Volume", RT5631_STEREO_DAC_VOL_2, RT5631_L_VOL_SHIFT, RT5631_R_VOL_SHIFT, RT5631_DAC_VOL_MASK, 1, dac_vol_tlv), SOC_DOUBLE("PCM Playback Switch", RT5631_STEREO_DAC_VOL_1, RT5631_L_MUTE_SHIFT, RT5631_R_MUTE_SHIFT, 1, 1), /* AXO */ SOC_SINGLE("AXO1 Playback Switch", RT5631_MONO_AXO_1_2_VOL, RT5631_L_MUTE_SHIFT, 1, 1), SOC_SINGLE("AXO2 Playback Switch", RT5631_MONO_AXO_1_2_VOL, RT5631_R_VOL_SHIFT, 1, 1), /* OUTVOL */ SOC_DOUBLE("OUTVOL Channel Switch", RT5631_SPK_OUT_VOL, RT5631_L_EN_SHIFT, RT5631_R_EN_SHIFT, 1, 0), /* SPK */ SOC_DOUBLE("Speaker Playback Switch", RT5631_SPK_OUT_VOL, RT5631_L_MUTE_SHIFT, RT5631_R_MUTE_SHIFT, 1, 1), SOC_DOUBLE_TLV("Speaker Playback Volume", RT5631_SPK_OUT_VOL, RT5631_L_VOL_SHIFT, RT5631_R_VOL_SHIFT, 39, 1, out_vol_tlv), /* MONO OUT */ SOC_SINGLE("MONO Playback Switch", RT5631_MONO_AXO_1_2_VOL, RT5631_MUTE_MONO_SHIFT, 1, 1), /* HP */ SOC_DOUBLE("HP Playback Switch", RT5631_HP_OUT_VOL, RT5631_L_MUTE_SHIFT, RT5631_R_MUTE_SHIFT, 1, 1), SOC_DOUBLE_TLV("HP Playback Volume", RT5631_HP_OUT_VOL, RT5631_L_VOL_SHIFT, RT5631_R_VOL_SHIFT, RT5631_VOL_MASK, 1, out_vol_tlv), /* DMIC */ SOC_SINGLE_EXT("DMIC Switch", 0, 0, 1, 0, rt5631_dmic_get, rt5631_dmic_put), SOC_DOUBLE("DMIC Capture Switch", RT5631_DIG_MIC_CTRL, RT5631_DMIC_L_CH_MUTE_SHIFT, RT5631_DMIC_R_CH_MUTE_SHIFT, 1, 1), /* SPK Ratio Gain Control */ SOC_ENUM("SPK Ratio Control", rt5631_spk_ratio_enum), }; static int check_sysclk1_source(struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink) { unsigned int reg; reg = snd_soc_read(source->codec, RT5631_GLOBAL_CLK_CTRL); return reg & RT5631_SYSCLK_SOUR_SEL_PLL; } static int check_dmic_used(struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink) { struct rt5631_priv *rt5631 = snd_soc_codec_get_drvdata(source->codec); return rt5631->dmic_used_flag; } static int check_dacl_to_outmixl(struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink) { unsigned int reg; reg = snd_soc_read(source->codec, RT5631_OUTMIXER_L_CTRL); return !(reg & RT5631_M_DAC_L_TO_OUTMIXER_L); } static int check_dacr_to_outmixr(struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink) { unsigned int reg; reg = snd_soc_read(source->codec, RT5631_OUTMIXER_R_CTRL); return !(reg & RT5631_M_DAC_R_TO_OUTMIXER_R); } static int check_dacl_to_spkmixl(struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink) { unsigned int reg; reg = snd_soc_read(source->codec, RT5631_SPK_MIXER_CTRL); return !(reg & RT5631_M_DAC_L_TO_SPKMIXER_L); } static int check_dacr_to_spkmixr(struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink) { unsigned int reg; reg = snd_soc_read(source->codec, RT5631_SPK_MIXER_CTRL); return !(reg & RT5631_M_DAC_R_TO_SPKMIXER_R); } static int check_adcl_select(struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink) { unsigned int reg; reg = snd_soc_read(source->codec, RT5631_ADC_REC_MIXER); return !(reg & RT5631_M_MIC1_TO_RECMIXER_L); } static int check_adcr_select(struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink) { unsigned int reg; reg = snd_soc_read(source->codec, RT5631_ADC_REC_MIXER); return !(reg & RT5631_M_MIC2_TO_RECMIXER_R); } /** * onebit_depop_power_stage - auto depop in power stage. * @enable: power on/off * * When power on/off headphone, the depop sequence is done by hardware. */ static void onebit_depop_power_stage(struct snd_soc_codec *codec, int enable) { unsigned int soft_vol, hp_zc; /* enable one-bit depop function */ snd_soc_update_bits(codec, RT5631_DEPOP_FUN_CTRL_2, RT5631_EN_ONE_BIT_DEPOP, 0); /* keep soft volume and zero crossing setting */ soft_vol = snd_soc_read(codec, RT5631_SOFT_VOL_CTRL); snd_soc_write(codec, RT5631_SOFT_VOL_CTRL, 0); hp_zc = snd_soc_read(codec, RT5631_INT_ST_IRQ_CTRL_2); snd_soc_write(codec, RT5631_INT_ST_IRQ_CTRL_2, hp_zc & 0xf7ff); if (enable) { /* config one-bit depop parameter */ rt5631_write_index(codec, RT5631_TEST_MODE_CTRL, 0x84c0); rt5631_write_index(codec, RT5631_SPK_INTL_CTRL, 0x309f); rt5631_write_index(codec, RT5631_CP_INTL_REG2, 0x6530); /* power on capless block */ snd_soc_write(codec, RT5631_DEPOP_FUN_CTRL_2, RT5631_EN_CAP_FREE_DEPOP); } else { /* power off capless block */ snd_soc_write(codec, RT5631_DEPOP_FUN_CTRL_2, 0); msleep(100); } /* recover soft volume and zero crossing setting */ snd_soc_write(codec, RT5631_SOFT_VOL_CTRL, soft_vol); snd_soc_write(codec, RT5631_INT_ST_IRQ_CTRL_2, hp_zc); } /** * onebit_depop_mute_stage - auto depop in mute stage. * @enable: mute/unmute * * When mute/unmute headphone, the depop sequence is done by hardware. */ static void onebit_depop_mute_stage(struct snd_soc_codec *codec, int enable) { unsigned int soft_vol, hp_zc; /* enable one-bit depop function */ snd_soc_update_bits(codec, RT5631_DEPOP_FUN_CTRL_2, RT5631_EN_ONE_BIT_DEPOP, 0); /* keep soft volume and zero crossing setting */ soft_vol = snd_soc_read(codec, RT5631_SOFT_VOL_CTRL); snd_soc_write(codec, RT5631_SOFT_VOL_CTRL, 0); hp_zc = snd_soc_read(codec, RT5631_INT_ST_IRQ_CTRL_2); snd_soc_write(codec, RT5631_INT_ST_IRQ_CTRL_2, hp_zc & 0xf7ff); if (enable) { schedule_timeout_uninterruptible(msecs_to_jiffies(10)); /* config one-bit depop parameter */ rt5631_write_index(codec, RT5631_SPK_INTL_CTRL, 0x307f); snd_soc_update_bits(codec, RT5631_HP_OUT_VOL, RT5631_L_MUTE | RT5631_R_MUTE, 0); msleep(300); } else { snd_soc_update_bits(codec, RT5631_HP_OUT_VOL, RT5631_L_MUTE | RT5631_R_MUTE, RT5631_L_MUTE | RT5631_R_MUTE); msleep(100); } /* recover soft volume and zero crossing setting */ snd_soc_write(codec, RT5631_SOFT_VOL_CTRL, soft_vol); snd_soc_write(codec, RT5631_INT_ST_IRQ_CTRL_2, hp_zc); } /** * onebit_depop_power_stage - step by step depop sequence in power stage. * @enable: power on/off * * When power on/off headphone, the depop sequence is done in step by step. */ static void depop_seq_power_stage(struct snd_soc_codec *codec, int enable) { unsigned int soft_vol, hp_zc; /* depop control by register */ snd_soc_update_bits(codec, RT5631_DEPOP_FUN_CTRL_2, RT5631_EN_ONE_BIT_DEPOP, RT5631_EN_ONE_BIT_DEPOP); /* keep soft volume and zero crossing setting */ soft_vol = snd_soc_read(codec, RT5631_SOFT_VOL_CTRL); snd_soc_write(codec, RT5631_SOFT_VOL_CTRL, 0); hp_zc = snd_soc_read(codec, RT5631_INT_ST_IRQ_CTRL_2); snd_soc_write(codec, RT5631_INT_ST_IRQ_CTRL_2, hp_zc & 0xf7ff); if (enable) { /* config depop sequence parameter */ rt5631_write_index(codec, RT5631_SPK_INTL_CTRL, 0x303e); /* power on headphone and charge pump */ snd_soc_update_bits(codec, RT5631_PWR_MANAG_ADD3, RT5631_PWR_CHARGE_PUMP | RT5631_PWR_HP_L_AMP | RT5631_PWR_HP_R_AMP, RT5631_PWR_CHARGE_PUMP | RT5631_PWR_HP_L_AMP | RT5631_PWR_HP_R_AMP); /* power on soft generator and depop mode2 */ snd_soc_write(codec, RT5631_DEPOP_FUN_CTRL_1, RT5631_POW_ON_SOFT_GEN | RT5631_EN_DEPOP2_FOR_HP); msleep(100); /* stop depop mode */ snd_soc_update_bits(codec, RT5631_PWR_MANAG_ADD3, RT5631_PWR_HP_DEPOP_DIS, RT5631_PWR_HP_DEPOP_DIS); } else { /* config depop sequence parameter */ rt5631_write_index(codec, RT5631_SPK_INTL_CTRL, 0x303F); snd_soc_write(codec, RT5631_DEPOP_FUN_CTRL_1, RT5631_POW_ON_SOFT_GEN | RT5631_EN_MUTE_UNMUTE_DEPOP | RT5631_PD_HPAMP_L_ST_UP | RT5631_PD_HPAMP_R_ST_UP); msleep(75); snd_soc_write(codec, RT5631_DEPOP_FUN_CTRL_1, RT5631_POW_ON_SOFT_GEN | RT5631_PD_HPAMP_L_ST_UP | RT5631_PD_HPAMP_R_ST_UP); /* start depop mode */ snd_soc_update_bits(codec, RT5631_PWR_MANAG_ADD3, RT5631_PWR_HP_DEPOP_DIS, 0); /* config depop sequence parameter */ snd_soc_write(codec, RT5631_DEPOP_FUN_CTRL_1, RT5631_POW_ON_SOFT_GEN | RT5631_EN_DEPOP2_FOR_HP | RT5631_PD_HPAMP_L_ST_UP | RT5631_PD_HPAMP_R_ST_UP); msleep(80); snd_soc_write(codec, RT5631_DEPOP_FUN_CTRL_1, RT5631_POW_ON_SOFT_GEN); /* power down headphone and charge pump */ snd_soc_update_bits(codec, RT5631_PWR_MANAG_ADD3, RT5631_PWR_CHARGE_PUMP | RT5631_PWR_HP_L_AMP | RT5631_PWR_HP_R_AMP, 0); } /* recover soft volume and zero crossing setting */ snd_soc_write(codec, RT5631_SOFT_VOL_CTRL, soft_vol); snd_soc_write(codec, RT5631_INT_ST_IRQ_CTRL_2, hp_zc); } /** * depop_seq_mute_stage - step by step depop sequence in mute stage. * @enable: mute/unmute * * When mute/unmute headphone, the depop sequence is done in step by step. */ static void depop_seq_mute_stage(struct snd_soc_codec *codec, int enable) { unsigned int soft_vol, hp_zc; /* depop control by register */ snd_soc_update_bits(codec, RT5631_DEPOP_FUN_CTRL_2, RT5631_EN_ONE_BIT_DEPOP, RT5631_EN_ONE_BIT_DEPOP); /* keep soft volume and zero crossing setting */ soft_vol = snd_soc_read(codec, RT5631_SOFT_VOL_CTRL); snd_soc_write(codec, RT5631_SOFT_VOL_CTRL, 0); hp_zc = snd_soc_read(codec, RT5631_INT_ST_IRQ_CTRL_2); snd_soc_write(codec, RT5631_INT_ST_IRQ_CTRL_2, hp_zc & 0xf7ff); if (enable) { schedule_timeout_uninterruptible(msecs_to_jiffies(10)); /* config depop sequence parameter */ rt5631_write_index(codec, RT5631_SPK_INTL_CTRL, 0x302f); snd_soc_write(codec, RT5631_DEPOP_FUN_CTRL_1, RT5631_POW_ON_SOFT_GEN | RT5631_EN_MUTE_UNMUTE_DEPOP | RT5631_EN_HP_R_M_UN_MUTE_DEPOP | RT5631_EN_HP_L_M_UN_MUTE_DEPOP); snd_soc_update_bits(codec, RT5631_HP_OUT_VOL, RT5631_L_MUTE | RT5631_R_MUTE, 0); msleep(160); } else { /* config depop sequence parameter */ rt5631_write_index(codec, RT5631_SPK_INTL_CTRL, 0x302f); snd_soc_write(codec, RT5631_DEPOP_FUN_CTRL_1, RT5631_POW_ON_SOFT_GEN | RT5631_EN_MUTE_UNMUTE_DEPOP | RT5631_EN_HP_R_M_UN_MUTE_DEPOP | RT5631_EN_HP_L_M_UN_MUTE_DEPOP); snd_soc_update_bits(codec, RT5631_HP_OUT_VOL, RT5631_L_MUTE | RT5631_R_MUTE, RT5631_L_MUTE | RT5631_R_MUTE); msleep(150); } /* recover soft volume and zero crossing setting */ snd_soc_write(codec, RT5631_SOFT_VOL_CTRL, soft_vol); snd_soc_write(codec, RT5631_INT_ST_IRQ_CTRL_2, hp_zc); } static int hp_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct rt5631_priv *rt5631 = snd_soc_codec_get_drvdata(codec); switch (event) { case SND_SOC_DAPM_PRE_PMD: if (rt5631->codec_version) { onebit_depop_mute_stage(codec, 0); onebit_depop_power_stage(codec, 0); } else { depop_seq_mute_stage(codec, 0); depop_seq_power_stage(codec, 0); } break; case SND_SOC_DAPM_POST_PMU: if (rt5631->codec_version) { onebit_depop_power_stage(codec, 1); onebit_depop_mute_stage(codec, 1); } else { depop_seq_power_stage(codec, 1); depop_seq_mute_stage(codec, 1); } break; default: break; } return 0; } static int set_dmic_params(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct rt5631_priv *rt5631 = snd_soc_codec_get_drvdata(codec); switch (rt5631->rx_rate) { case 44100: case 48000: snd_soc_update_bits(codec, RT5631_DIG_MIC_CTRL, RT5631_DMIC_CLK_CTRL_MASK, RT5631_DMIC_CLK_CTRL_TO_32FS); break; case 32000: case 22050: snd_soc_update_bits(codec, RT5631_DIG_MIC_CTRL, RT5631_DMIC_CLK_CTRL_MASK, RT5631_DMIC_CLK_CTRL_TO_64FS); break; case 16000: case 11025: case 8000: snd_soc_update_bits(codec, RT5631_DIG_MIC_CTRL, RT5631_DMIC_CLK_CTRL_MASK, RT5631_DMIC_CLK_CTRL_TO_128FS); break; default: return -EINVAL; } return 0; } static const struct snd_kcontrol_new rt5631_recmixl_mixer_controls[] = { SOC_DAPM_SINGLE("OUTMIXL Capture Switch", RT5631_ADC_REC_MIXER, RT5631_M_OUTMIXL_RECMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("MIC1_BST1 Capture Switch", RT5631_ADC_REC_MIXER, RT5631_M_MIC1_RECMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("AXILVOL Capture Switch", RT5631_ADC_REC_MIXER, RT5631_M_AXIL_RECMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("MONOIN_RX Capture Switch", RT5631_ADC_REC_MIXER, RT5631_M_MONO_IN_RECMIXL_BIT, 1, 1), }; static const struct snd_kcontrol_new rt5631_recmixr_mixer_controls[] = { SOC_DAPM_SINGLE("MONOIN_RX Capture Switch", RT5631_ADC_REC_MIXER, RT5631_M_MONO_IN_RECMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("AXIRVOL Capture Switch", RT5631_ADC_REC_MIXER, RT5631_M_AXIR_RECMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("MIC2_BST2 Capture Switch", RT5631_ADC_REC_MIXER, RT5631_M_MIC2_RECMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("OUTMIXR Capture Switch", RT5631_ADC_REC_MIXER, RT5631_M_OUTMIXR_RECMIXR_BIT, 1, 1), }; static const struct snd_kcontrol_new rt5631_spkmixl_mixer_controls[] = { SOC_DAPM_SINGLE("RECMIXL Playback Switch", RT5631_SPK_MIXER_CTRL, RT5631_M_RECMIXL_SPKMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("MIC1_P Playback Switch", RT5631_SPK_MIXER_CTRL, RT5631_M_MIC1P_SPKMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("DACL Playback Switch", RT5631_SPK_MIXER_CTRL, RT5631_M_DACL_SPKMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("OUTMIXL Playback Switch", RT5631_SPK_MIXER_CTRL, RT5631_M_OUTMIXL_SPKMIXL_BIT, 1, 1), }; static const struct snd_kcontrol_new rt5631_spkmixr_mixer_controls[] = { SOC_DAPM_SINGLE("OUTMIXR Playback Switch", RT5631_SPK_MIXER_CTRL, RT5631_M_OUTMIXR_SPKMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("DACR Playback Switch", RT5631_SPK_MIXER_CTRL, RT5631_M_DACR_SPKMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("MIC2_P Playback Switch", RT5631_SPK_MIXER_CTRL, RT5631_M_MIC2P_SPKMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("RECMIXR Playback Switch", RT5631_SPK_MIXER_CTRL, RT5631_M_RECMIXR_SPKMIXR_BIT, 1, 1), }; static const struct snd_kcontrol_new rt5631_outmixl_mixer_controls[] = { SOC_DAPM_SINGLE("RECMIXL Playback Switch", RT5631_OUTMIXER_L_CTRL, RT5631_M_RECMIXL_OUTMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("RECMIXR Playback Switch", RT5631_OUTMIXER_L_CTRL, RT5631_M_RECMIXR_OUTMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("DACL Playback Switch", RT5631_OUTMIXER_L_CTRL, RT5631_M_DACL_OUTMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("MIC1_BST1 Playback Switch", RT5631_OUTMIXER_L_CTRL, RT5631_M_MIC1_OUTMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("MIC2_BST2 Playback Switch", RT5631_OUTMIXER_L_CTRL, RT5631_M_MIC2_OUTMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("MONOIN_RXP Playback Switch", RT5631_OUTMIXER_L_CTRL, RT5631_M_MONO_INP_OUTMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("AXILVOL Playback Switch", RT5631_OUTMIXER_L_CTRL, RT5631_M_AXIL_OUTMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("AXIRVOL Playback Switch", RT5631_OUTMIXER_L_CTRL, RT5631_M_AXIR_OUTMIXL_BIT, 1, 1), SOC_DAPM_SINGLE("VDAC Playback Switch", RT5631_OUTMIXER_L_CTRL, RT5631_M_VDAC_OUTMIXL_BIT, 1, 1), }; static const struct snd_kcontrol_new rt5631_outmixr_mixer_controls[] = { SOC_DAPM_SINGLE("VDAC Playback Switch", RT5631_OUTMIXER_R_CTRL, RT5631_M_VDAC_OUTMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("AXIRVOL Playback Switch", RT5631_OUTMIXER_R_CTRL, RT5631_M_AXIR_OUTMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("AXILVOL Playback Switch", RT5631_OUTMIXER_R_CTRL, RT5631_M_AXIL_OUTMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("MONOIN_RXN Playback Switch", RT5631_OUTMIXER_R_CTRL, RT5631_M_MONO_INN_OUTMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("MIC2_BST2 Playback Switch", RT5631_OUTMIXER_R_CTRL, RT5631_M_MIC2_OUTMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("MIC1_BST1 Playback Switch", RT5631_OUTMIXER_R_CTRL, RT5631_M_MIC1_OUTMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("DACR Playback Switch", RT5631_OUTMIXER_R_CTRL, RT5631_M_DACR_OUTMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("RECMIXR Playback Switch", RT5631_OUTMIXER_R_CTRL, RT5631_M_RECMIXR_OUTMIXR_BIT, 1, 1), SOC_DAPM_SINGLE("RECMIXL Playback Switch", RT5631_OUTMIXER_R_CTRL, RT5631_M_RECMIXL_OUTMIXR_BIT, 1, 1), }; static const struct snd_kcontrol_new rt5631_AXO1MIX_mixer_controls[] = { SOC_DAPM_SINGLE("MIC1_BST1 Playback Switch", RT5631_AXO1MIXER_CTRL, RT5631_M_MIC1_AXO1MIX_BIT , 1, 1), SOC_DAPM_SINGLE("MIC2_BST2 Playback Switch", RT5631_AXO1MIXER_CTRL, RT5631_M_MIC2_AXO1MIX_BIT, 1, 1), SOC_DAPM_SINGLE("OUTVOLL Playback Switch", RT5631_AXO1MIXER_CTRL, RT5631_M_OUTMIXL_AXO1MIX_BIT , 1 , 1), SOC_DAPM_SINGLE("OUTVOLR Playback Switch", RT5631_AXO1MIXER_CTRL, RT5631_M_OUTMIXR_AXO1MIX_BIT, 1, 1), }; static const struct snd_kcontrol_new rt5631_AXO2MIX_mixer_controls[] = { SOC_DAPM_SINGLE("MIC1_BST1 Playback Switch", RT5631_AXO2MIXER_CTRL, RT5631_M_MIC1_AXO2MIX_BIT, 1, 1), SOC_DAPM_SINGLE("MIC2_BST2 Playback Switch", RT5631_AXO2MIXER_CTRL, RT5631_M_MIC2_AXO2MIX_BIT, 1, 1), SOC_DAPM_SINGLE("OUTVOLL Playback Switch", RT5631_AXO2MIXER_CTRL, RT5631_M_OUTMIXL_AXO2MIX_BIT, 1, 1), SOC_DAPM_SINGLE("OUTVOLR Playback Switch", RT5631_AXO2MIXER_CTRL, RT5631_M_OUTMIXR_AXO2MIX_BIT, 1 , 1), }; static const struct snd_kcontrol_new rt5631_spolmix_mixer_controls[] = { SOC_DAPM_SINGLE("SPKVOLL Playback Switch", RT5631_SPK_MONO_OUT_CTRL, RT5631_M_SPKVOLL_SPOLMIX_BIT, 1, 1), SOC_DAPM_SINGLE("SPKVOLR Playback Switch", RT5631_SPK_MONO_OUT_CTRL, RT5631_M_SPKVOLR_SPOLMIX_BIT, 1, 1), }; static const struct snd_kcontrol_new rt5631_spormix_mixer_controls[] = { SOC_DAPM_SINGLE("SPKVOLL Playback Switch", RT5631_SPK_MONO_OUT_CTRL, RT5631_M_SPKVOLL_SPORMIX_BIT, 1, 1), SOC_DAPM_SINGLE("SPKVOLR Playback Switch", RT5631_SPK_MONO_OUT_CTRL, RT5631_M_SPKVOLR_SPORMIX_BIT, 1, 1), }; static const struct snd_kcontrol_new rt5631_monomix_mixer_controls[] = { SOC_DAPM_SINGLE("OUTVOLL Playback Switch", RT5631_SPK_MONO_OUT_CTRL, RT5631_M_OUTVOLL_MONOMIX_BIT, 1, 1), SOC_DAPM_SINGLE("OUTVOLR Playback Switch", RT5631_SPK_MONO_OUT_CTRL, RT5631_M_OUTVOLR_MONOMIX_BIT, 1, 1), }; /* Left SPK Volume Input */ static const char *rt5631_spkvoll_sel[] = {"Vmid", "SPKMIXL"}; static const SOC_ENUM_SINGLE_DECL( rt5631_spkvoll_enum, RT5631_SPK_OUT_VOL, RT5631_L_EN_SHIFT, rt5631_spkvoll_sel); static const struct snd_kcontrol_new rt5631_spkvoll_mux_control = SOC_DAPM_ENUM("Left SPKVOL SRC", rt5631_spkvoll_enum); /* Left HP Volume Input */ static const char *rt5631_hpvoll_sel[] = {"Vmid", "OUTMIXL"}; static const SOC_ENUM_SINGLE_DECL( rt5631_hpvoll_enum, RT5631_HP_OUT_VOL, RT5631_L_EN_SHIFT, rt5631_hpvoll_sel); static const struct snd_kcontrol_new rt5631_hpvoll_mux_control = SOC_DAPM_ENUM("Left HPVOL SRC", rt5631_hpvoll_enum); /* Left Out Volume Input */ static const char *rt5631_outvoll_sel[] = {"Vmid", "OUTMIXL"}; static const SOC_ENUM_SINGLE_DECL( rt5631_outvoll_enum, RT5631_MONO_AXO_1_2_VOL, RT5631_L_EN_SHIFT, rt5631_outvoll_sel); static const struct snd_kcontrol_new rt5631_outvoll_mux_control = SOC_DAPM_ENUM("Left OUTVOL SRC", rt5631_outvoll_enum); /* Right Out Volume Input */ static const char *rt5631_outvolr_sel[] = {"Vmid", "OUTMIXR"}; static const SOC_ENUM_SINGLE_DECL( rt5631_outvolr_enum, RT5631_MONO_AXO_1_2_VOL, RT5631_R_EN_SHIFT, rt5631_outvolr_sel); static const struct snd_kcontrol_new rt5631_outvolr_mux_control = SOC_DAPM_ENUM("Right OUTVOL SRC", rt5631_outvolr_enum); /* Right HP Volume Input */ static const char *rt5631_hpvolr_sel[] = {"Vmid", "OUTMIXR"}; static const SOC_ENUM_SINGLE_DECL( rt5631_hpvolr_enum, RT5631_HP_OUT_VOL, RT5631_R_EN_SHIFT, rt5631_hpvolr_sel); static const struct snd_kcontrol_new rt5631_hpvolr_mux_control = SOC_DAPM_ENUM("Right HPVOL SRC", rt5631_hpvolr_enum); /* Right SPK Volume Input */ static const char *rt5631_spkvolr_sel[] = {"Vmid", "SPKMIXR"}; static const SOC_ENUM_SINGLE_DECL( rt5631_spkvolr_enum, RT5631_SPK_OUT_VOL, RT5631_R_EN_SHIFT, rt5631_spkvolr_sel); static const struct snd_kcontrol_new rt5631_spkvolr_mux_control = SOC_DAPM_ENUM("Right SPKVOL SRC", rt5631_spkvolr_enum); /* SPO Left Channel Input */ static const char *rt5631_spol_src_sel[] = { "SPOLMIX", "MONOIN_RX", "VDAC", "DACL"}; static const SOC_ENUM_SINGLE_DECL( rt5631_spol_src_enum, RT5631_SPK_MONO_HP_OUT_CTRL, RT5631_SPK_L_MUX_SEL_SHIFT, rt5631_spol_src_sel); static const struct snd_kcontrol_new rt5631_spol_mux_control = SOC_DAPM_ENUM("SPOL SRC", rt5631_spol_src_enum); /* SPO Right Channel Input */ static const char *rt5631_spor_src_sel[] = { "SPORMIX", "MONOIN_RX", "VDAC", "DACR"}; static const SOC_ENUM_SINGLE_DECL( rt5631_spor_src_enum, RT5631_SPK_MONO_HP_OUT_CTRL, RT5631_SPK_R_MUX_SEL_SHIFT, rt5631_spor_src_sel); static const struct snd_kcontrol_new rt5631_spor_mux_control = SOC_DAPM_ENUM("SPOR SRC", rt5631_spor_src_enum); /* MONO Input */ static const char *rt5631_mono_src_sel[] = {"MONOMIX", "MONOIN_RX", "VDAC"}; static const SOC_ENUM_SINGLE_DECL( rt5631_mono_src_enum, RT5631_SPK_MONO_HP_OUT_CTRL, RT5631_MONO_MUX_SEL_SHIFT, rt5631_mono_src_sel); static const struct snd_kcontrol_new rt5631_mono_mux_control = SOC_DAPM_ENUM("MONO SRC", rt5631_mono_src_enum); /* Left HPO Input */ static const char *rt5631_hpl_src_sel[] = {"Left HPVOL", "Left DAC"}; static const SOC_ENUM_SINGLE_DECL( rt5631_hpl_src_enum, RT5631_SPK_MONO_HP_OUT_CTRL, RT5631_HP_L_MUX_SEL_SHIFT, rt5631_hpl_src_sel); static const struct snd_kcontrol_new rt5631_hpl_mux_control = SOC_DAPM_ENUM("HPL SRC", rt5631_hpl_src_enum); /* Right HPO Input */ static const char *rt5631_hpr_src_sel[] = {"Right HPVOL", "Right DAC"}; static const SOC_ENUM_SINGLE_DECL( rt5631_hpr_src_enum, RT5631_SPK_MONO_HP_OUT_CTRL, RT5631_HP_R_MUX_SEL_SHIFT, rt5631_hpr_src_sel); static const struct snd_kcontrol_new rt5631_hpr_mux_control = SOC_DAPM_ENUM("HPR SRC", rt5631_hpr_src_enum); static const struct snd_soc_dapm_widget rt5631_dapm_widgets[] = { /* Vmid */ SND_SOC_DAPM_VMID("Vmid"), /* PLL1 */ SND_SOC_DAPM_SUPPLY("PLL1", RT5631_PWR_MANAG_ADD2, RT5631_PWR_PLL1_BIT, 0, NULL, 0), /* Input Side */ /* Input Lines */ SND_SOC_DAPM_INPUT("MIC1"), SND_SOC_DAPM_INPUT("MIC2"), SND_SOC_DAPM_INPUT("AXIL"), SND_SOC_DAPM_INPUT("AXIR"), SND_SOC_DAPM_INPUT("MONOIN_RXN"), SND_SOC_DAPM_INPUT("MONOIN_RXP"), SND_SOC_DAPM_INPUT("DMIC"), /* MICBIAS */ SND_SOC_DAPM_MICBIAS("MIC Bias1", RT5631_PWR_MANAG_ADD2, RT5631_PWR_MICBIAS1_VOL_BIT, 0), SND_SOC_DAPM_MICBIAS("MIC Bias2", RT5631_PWR_MANAG_ADD2, RT5631_PWR_MICBIAS2_VOL_BIT, 0), /* Boost */ SND_SOC_DAPM_PGA("MIC1 Boost", RT5631_PWR_MANAG_ADD2, RT5631_PWR_MIC1_BOOT_GAIN_BIT, 0, NULL, 0), SND_SOC_DAPM_PGA("MIC2 Boost", RT5631_PWR_MANAG_ADD2, RT5631_PWR_MIC2_BOOT_GAIN_BIT, 0, NULL, 0), SND_SOC_DAPM_PGA("MONOIN_RXP Boost", RT5631_PWR_MANAG_ADD4, RT5631_PWR_MONO_IN_P_VOL_BIT, 0, NULL, 0), SND_SOC_DAPM_PGA("MONOIN_RXN Boost", RT5631_PWR_MANAG_ADD4, RT5631_PWR_MONO_IN_N_VOL_BIT, 0, NULL, 0), SND_SOC_DAPM_PGA("AXIL Boost", RT5631_PWR_MANAG_ADD4, RT5631_PWR_AXIL_IN_VOL_BIT, 0, NULL, 0), SND_SOC_DAPM_PGA("AXIR Boost", RT5631_PWR_MANAG_ADD4, RT5631_PWR_AXIR_IN_VOL_BIT, 0, NULL, 0), /* MONO In */ SND_SOC_DAPM_MIXER("MONO_IN", SND_SOC_NOPM, 0, 0, NULL, 0), /* REC Mixer */ SND_SOC_DAPM_MIXER("RECMIXL Mixer", RT5631_PWR_MANAG_ADD2, RT5631_PWR_RECMIXER_L_BIT, 0, &rt5631_recmixl_mixer_controls[0], ARRAY_SIZE(rt5631_recmixl_mixer_controls)), SND_SOC_DAPM_MIXER("RECMIXR Mixer", RT5631_PWR_MANAG_ADD2, RT5631_PWR_RECMIXER_R_BIT, 0, &rt5631_recmixr_mixer_controls[0], ARRAY_SIZE(rt5631_recmixr_mixer_controls)), /* Because of record duplication for L/R channel, * L/R ADCs need power up at the same time */ SND_SOC_DAPM_MIXER("ADC Mixer", SND_SOC_NOPM, 0, 0, NULL, 0), /* DMIC */ SND_SOC_DAPM_SUPPLY("DMIC Supply", RT5631_DIG_MIC_CTRL, RT5631_DMIC_ENA_SHIFT, 0, set_dmic_params, SND_SOC_DAPM_PRE_PMU), /* ADC Data Srouce */ SND_SOC_DAPM_SUPPLY("Left ADC Select", RT5631_INT_ST_IRQ_CTRL_2, RT5631_ADC_DATA_SEL_MIC1_SHIFT, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("Right ADC Select", RT5631_INT_ST_IRQ_CTRL_2, RT5631_ADC_DATA_SEL_MIC2_SHIFT, 0, NULL, 0), /* ADCs */ SND_SOC_DAPM_ADC("Left ADC", "HIFI Capture", RT5631_PWR_MANAG_ADD1, RT5631_PWR_ADC_L_CLK_BIT, 0), SND_SOC_DAPM_ADC("Right ADC", "HIFI Capture", RT5631_PWR_MANAG_ADD1, RT5631_PWR_ADC_R_CLK_BIT, 0), /* DAC and ADC supply power */ SND_SOC_DAPM_SUPPLY("I2S", RT5631_PWR_MANAG_ADD1, RT5631_PWR_MAIN_I2S_BIT, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("DAC REF", RT5631_PWR_MANAG_ADD1, RT5631_PWR_DAC_REF_BIT, 0, NULL, 0), /* Output Side */ /* DACs */ SND_SOC_DAPM_DAC("Left DAC", "HIFI Playback", RT5631_PWR_MANAG_ADD1, RT5631_PWR_DAC_L_CLK_BIT, 0), SND_SOC_DAPM_DAC("Right DAC", "HIFI Playback", RT5631_PWR_MANAG_ADD1, RT5631_PWR_DAC_R_CLK_BIT, 0), SND_SOC_DAPM_DAC("Voice DAC", "Voice DAC Mono Playback", SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_PGA("Voice DAC Boost", SND_SOC_NOPM, 0, 0, NULL, 0), /* DAC supply power */ SND_SOC_DAPM_SUPPLY("Left DAC To Mixer", RT5631_PWR_MANAG_ADD1, RT5631_PWR_DAC_L_TO_MIXER_BIT, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("Right DAC To Mixer", RT5631_PWR_MANAG_ADD1, RT5631_PWR_DAC_R_TO_MIXER_BIT, 0, NULL, 0), /* Left SPK Mixer */ SND_SOC_DAPM_MIXER("SPKMIXL Mixer", RT5631_PWR_MANAG_ADD2, RT5631_PWR_SPKMIXER_L_BIT, 0, &rt5631_spkmixl_mixer_controls[0], ARRAY_SIZE(rt5631_spkmixl_mixer_controls)), /* Left Out Mixer */ SND_SOC_DAPM_MIXER("OUTMIXL Mixer", RT5631_PWR_MANAG_ADD2, RT5631_PWR_OUTMIXER_L_BIT, 0, &rt5631_outmixl_mixer_controls[0], ARRAY_SIZE(rt5631_outmixl_mixer_controls)), /* Right Out Mixer */ SND_SOC_DAPM_MIXER("OUTMIXR Mixer", RT5631_PWR_MANAG_ADD2, RT5631_PWR_OUTMIXER_R_BIT, 0, &rt5631_outmixr_mixer_controls[0], ARRAY_SIZE(rt5631_outmixr_mixer_controls)), /* Right SPK Mixer */ SND_SOC_DAPM_MIXER("SPKMIXR Mixer", RT5631_PWR_MANAG_ADD2, RT5631_PWR_SPKMIXER_R_BIT, 0, &rt5631_spkmixr_mixer_controls[0], ARRAY_SIZE(rt5631_spkmixr_mixer_controls)), /* Volume Mux */ SND_SOC_DAPM_MUX("Left SPKVOL Mux", RT5631_PWR_MANAG_ADD4, RT5631_PWR_SPK_L_VOL_BIT, 0, &rt5631_spkvoll_mux_control), SND_SOC_DAPM_MUX("Left HPVOL Mux", RT5631_PWR_MANAG_ADD4, RT5631_PWR_HP_L_OUT_VOL_BIT, 0, &rt5631_hpvoll_mux_control), SND_SOC_DAPM_MUX("Left OUTVOL Mux", RT5631_PWR_MANAG_ADD4, RT5631_PWR_LOUT_VOL_BIT, 0, &rt5631_outvoll_mux_control), SND_SOC_DAPM_MUX("Right OUTVOL Mux", RT5631_PWR_MANAG_ADD4, RT5631_PWR_ROUT_VOL_BIT, 0, &rt5631_outvolr_mux_control), SND_SOC_DAPM_MUX("Right HPVOL Mux", RT5631_PWR_MANAG_ADD4, RT5631_PWR_HP_R_OUT_VOL_BIT, 0, &rt5631_hpvolr_mux_control), SND_SOC_DAPM_MUX("Right SPKVOL Mux", RT5631_PWR_MANAG_ADD4, RT5631_PWR_SPK_R_VOL_BIT, 0, &rt5631_spkvolr_mux_control), /* DAC To HP */ SND_SOC_DAPM_PGA_S("Left DAC_HP", 0, SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_PGA_S("Right DAC_HP", 0, SND_SOC_NOPM, 0, 0, NULL, 0), /* HP Depop */ SND_SOC_DAPM_PGA_S("HP Depop", 1, SND_SOC_NOPM, 0, 0, hp_event, SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMU), /* AXO1 Mixer */ SND_SOC_DAPM_MIXER("AXO1MIX Mixer", RT5631_PWR_MANAG_ADD3, RT5631_PWR_AXO1MIXER_BIT, 0, &rt5631_AXO1MIX_mixer_controls[0], ARRAY_SIZE(rt5631_AXO1MIX_mixer_controls)), /* SPOL Mixer */ SND_SOC_DAPM_MIXER("SPOLMIX Mixer", SND_SOC_NOPM, 0, 0, &rt5631_spolmix_mixer_controls[0], ARRAY_SIZE(rt5631_spolmix_mixer_controls)), /* MONO Mixer */ SND_SOC_DAPM_MIXER("MONOMIX Mixer", RT5631_PWR_MANAG_ADD3, RT5631_PWR_MONOMIXER_BIT, 0, &rt5631_monomix_mixer_controls[0], ARRAY_SIZE(rt5631_monomix_mixer_controls)), /* SPOR Mixer */ SND_SOC_DAPM_MIXER("SPORMIX Mixer", SND_SOC_NOPM, 0, 0, &rt5631_spormix_mixer_controls[0], ARRAY_SIZE(rt5631_spormix_mixer_controls)), /* AXO2 Mixer */ SND_SOC_DAPM_MIXER("AXO2MIX Mixer", RT5631_PWR_MANAG_ADD3, RT5631_PWR_AXO2MIXER_BIT, 0, &rt5631_AXO2MIX_mixer_controls[0], ARRAY_SIZE(rt5631_AXO2MIX_mixer_controls)), /* Mux */ SND_SOC_DAPM_MUX("SPOL Mux", SND_SOC_NOPM, 0, 0, &rt5631_spol_mux_control), SND_SOC_DAPM_MUX("SPOR Mux", SND_SOC_NOPM, 0, 0, &rt5631_spor_mux_control), SND_SOC_DAPM_MUX("MONO Mux", SND_SOC_NOPM, 0, 0, &rt5631_mono_mux_control), SND_SOC_DAPM_MUX("HPL Mux", SND_SOC_NOPM, 0, 0, &rt5631_hpl_mux_control), SND_SOC_DAPM_MUX("HPR Mux", SND_SOC_NOPM, 0, 0, &rt5631_hpr_mux_control), /* AMP supply */ SND_SOC_DAPM_SUPPLY("MONO Depop", RT5631_PWR_MANAG_ADD3, RT5631_PWR_MONO_DEPOP_DIS_BIT, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("Class D", RT5631_PWR_MANAG_ADD1, RT5631_PWR_CLASS_D_BIT, 0, NULL, 0), /* Output Lines */ SND_SOC_DAPM_OUTPUT("AUXO1"), SND_SOC_DAPM_OUTPUT("AUXO2"), SND_SOC_DAPM_OUTPUT("SPOL"), SND_SOC_DAPM_OUTPUT("SPOR"), SND_SOC_DAPM_OUTPUT("HPOL"), SND_SOC_DAPM_OUTPUT("HPOR"), SND_SOC_DAPM_OUTPUT("MONO"), }; static const struct snd_soc_dapm_route rt5631_dapm_routes[] = { {"MIC1 Boost", NULL, "MIC1"}, {"MIC2 Boost", NULL, "MIC2"}, {"MONOIN_RXP Boost", NULL, "MONOIN_RXP"}, {"MONOIN_RXN Boost", NULL, "MONOIN_RXN"}, {"AXIL Boost", NULL, "AXIL"}, {"AXIR Boost", NULL, "AXIR"}, {"MONO_IN", NULL, "MONOIN_RXP Boost"}, {"MONO_IN", NULL, "MONOIN_RXN Boost"}, {"RECMIXL Mixer", "OUTMIXL Capture Switch", "OUTMIXL Mixer"}, {"RECMIXL Mixer", "MIC1_BST1 Capture Switch", "MIC1 Boost"}, {"RECMIXL Mixer", "AXILVOL Capture Switch", "AXIL Boost"}, {"RECMIXL Mixer", "MONOIN_RX Capture Switch", "MONO_IN"}, {"RECMIXR Mixer", "OUTMIXR Capture Switch", "OUTMIXR Mixer"}, {"RECMIXR Mixer", "MIC2_BST2 Capture Switch", "MIC2 Boost"}, {"RECMIXR Mixer", "AXIRVOL Capture Switch", "AXIR Boost"}, {"RECMIXR Mixer", "MONOIN_RX Capture Switch", "MONO_IN"}, {"ADC Mixer", NULL, "RECMIXL Mixer"}, {"ADC Mixer", NULL, "RECMIXR Mixer"}, {"Left ADC", NULL, "ADC Mixer"}, {"Left ADC", NULL, "Left ADC Select", check_adcl_select}, {"Left ADC", NULL, "PLL1", check_sysclk1_source}, {"Left ADC", NULL, "I2S"}, {"Left ADC", NULL, "DAC REF"}, {"Right ADC", NULL, "ADC Mixer"}, {"Right ADC", NULL, "Right ADC Select", check_adcr_select}, {"Right ADC", NULL, "PLL1", check_sysclk1_source}, {"Right ADC", NULL, "I2S"}, {"Right ADC", NULL, "DAC REF"}, {"DMIC", NULL, "DMIC Supply", check_dmic_used}, {"Left ADC", NULL, "DMIC"}, {"Right ADC", NULL, "DMIC"}, {"Left DAC", NULL, "PLL1", check_sysclk1_source}, {"Left DAC", NULL, "I2S"}, {"Left DAC", NULL, "DAC REF"}, {"Right DAC", NULL, "PLL1", check_sysclk1_source}, {"Right DAC", NULL, "I2S"}, {"Right DAC", NULL, "DAC REF"}, {"Voice DAC Boost", NULL, "Voice DAC"}, {"SPKMIXL Mixer", NULL, "Left DAC To Mixer", check_dacl_to_spkmixl}, {"SPKMIXL Mixer", "RECMIXL Playback Switch", "RECMIXL Mixer"}, {"SPKMIXL Mixer", "MIC1_P Playback Switch", "MIC1"}, {"SPKMIXL Mixer", "DACL Playback Switch", "Left DAC"}, {"SPKMIXL Mixer", "OUTMIXL Playback Switch", "OUTMIXL Mixer"}, {"SPKMIXR Mixer", NULL, "Right DAC To Mixer", check_dacr_to_spkmixr}, {"SPKMIXR Mixer", "OUTMIXR Playback Switch", "OUTMIXR Mixer"}, {"SPKMIXR Mixer", "DACR Playback Switch", "Right DAC"}, {"SPKMIXR Mixer", "MIC2_P Playback Switch", "MIC2"}, {"SPKMIXR Mixer", "RECMIXR Playback Switch", "RECMIXR Mixer"}, {"OUTMIXL Mixer", NULL, "Left DAC To Mixer", check_dacl_to_outmixl}, {"OUTMIXL Mixer", "RECMIXL Playback Switch", "RECMIXL Mixer"}, {"OUTMIXL Mixer", "RECMIXR Playback Switch", "RECMIXR Mixer"}, {"OUTMIXL Mixer", "DACL Playback Switch", "Left DAC"}, {"OUTMIXL Mixer", "MIC1_BST1 Playback Switch", "MIC1 Boost"}, {"OUTMIXL Mixer", "MIC2_BST2 Playback Switch", "MIC2 Boost"}, {"OUTMIXL Mixer", "MONOIN_RXP Playback Switch", "MONOIN_RXP Boost"}, {"OUTMIXL Mixer", "AXILVOL Playback Switch", "AXIL Boost"}, {"OUTMIXL Mixer", "AXIRVOL Playback Switch", "AXIR Boost"}, {"OUTMIXL Mixer", "VDAC Playback Switch", "Voice DAC Boost"}, {"OUTMIXR Mixer", NULL, "Right DAC To Mixer", check_dacr_to_outmixr}, {"OUTMIXR Mixer", "RECMIXL Playback Switch", "RECMIXL Mixer"}, {"OUTMIXR Mixer", "RECMIXR Playback Switch", "RECMIXR Mixer"}, {"OUTMIXR Mixer", "DACR Playback Switch", "Right DAC"}, {"OUTMIXR Mixer", "MIC1_BST1 Playback Switch", "MIC1 Boost"}, {"OUTMIXR Mixer", "MIC2_BST2 Playback Switch", "MIC2 Boost"}, {"OUTMIXR Mixer", "MONOIN_RXN Playback Switch", "MONOIN_RXN Boost"}, {"OUTMIXR Mixer", "AXILVOL Playback Switch", "AXIL Boost"}, {"OUTMIXR Mixer", "AXIRVOL Playback Switch", "AXIR Boost"}, {"OUTMIXR Mixer", "VDAC Playback Switch", "Voice DAC Boost"}, {"Left SPKVOL Mux", "SPKMIXL", "SPKMIXL Mixer"}, {"Left SPKVOL Mux", "Vmid", "Vmid"}, {"Left HPVOL Mux", "OUTMIXL", "OUTMIXL Mixer"}, {"Left HPVOL Mux", "Vmid", "Vmid"}, {"Left OUTVOL Mux", "OUTMIXL", "OUTMIXL Mixer"}, {"Left OUTVOL Mux", "Vmid", "Vmid"}, {"Right OUTVOL Mux", "OUTMIXR", "OUTMIXR Mixer"}, {"Right OUTVOL Mux", "Vmid", "Vmid"}, {"Right HPVOL Mux", "OUTMIXR", "OUTMIXR Mixer"}, {"Right HPVOL Mux", "Vmid", "Vmid"}, {"Right SPKVOL Mux", "SPKMIXR", "SPKMIXR Mixer"}, {"Right SPKVOL Mux", "Vmid", "Vmid"}, {"AXO1MIX Mixer", "MIC1_BST1 Playback Switch", "MIC1 Boost"}, {"AXO1MIX Mixer", "OUTVOLL Playback Switch", "Left OUTVOL Mux"}, {"AXO1MIX Mixer", "OUTVOLR Playback Switch", "Right OUTVOL Mux"}, {"AXO1MIX Mixer", "MIC2_BST2 Playback Switch", "MIC2 Boost"}, {"AXO2MIX Mixer", "MIC1_BST1 Playback Switch", "MIC1 Boost"}, {"AXO2MIX Mixer", "OUTVOLL Playback Switch", "Left OUTVOL Mux"}, {"AXO2MIX Mixer", "OUTVOLR Playback Switch", "Right OUTVOL Mux"}, {"AXO2MIX Mixer", "MIC2_BST2 Playback Switch", "MIC2 Boost"}, {"SPOLMIX Mixer", "SPKVOLL Playback Switch", "Left SPKVOL Mux"}, {"SPOLMIX Mixer", "SPKVOLR Playback Switch", "Right SPKVOL Mux"}, {"SPORMIX Mixer", "SPKVOLL Playback Switch", "Left SPKVOL Mux"}, {"SPORMIX Mixer", "SPKVOLR Playback Switch", "Right SPKVOL Mux"}, {"MONOMIX Mixer", "OUTVOLL Playback Switch", "Left OUTVOL Mux"}, {"MONOMIX Mixer", "OUTVOLR Playback Switch", "Right OUTVOL Mux"}, {"SPOL Mux", "SPOLMIX", "SPOLMIX Mixer"}, {"SPOL Mux", "MONOIN_RX", "MONO_IN"}, {"SPOL Mux", "VDAC", "Voice DAC Boost"}, {"SPOL Mux", "DACL", "Left DAC"}, {"SPOR Mux", "SPORMIX", "SPORMIX Mixer"}, {"SPOR Mux", "MONOIN_RX", "MONO_IN"}, {"SPOR Mux", "VDAC", "Voice DAC Boost"}, {"SPOR Mux", "DACR", "Right DAC"}, {"MONO Mux", "MONOMIX", "MONOMIX Mixer"}, {"MONO Mux", "MONOIN_RX", "MONO_IN"}, {"MONO Mux", "VDAC", "Voice DAC Boost"}, {"Right DAC_HP", NULL, "Right DAC"}, {"Left DAC_HP", NULL, "Left DAC"}, {"HPL Mux", "Left HPVOL", "Left HPVOL Mux"}, {"HPL Mux", "Left DAC", "Left DAC_HP"}, {"HPR Mux", "Right HPVOL", "Right HPVOL Mux"}, {"HPR Mux", "Right DAC", "Right DAC_HP"}, {"HP Depop", NULL, "HPL Mux"}, {"HP Depop", NULL, "HPR Mux"}, {"AUXO1", NULL, "AXO1MIX Mixer"}, {"AUXO2", NULL, "AXO2MIX Mixer"}, {"SPOL", NULL, "Class D"}, {"SPOL", NULL, "SPOL Mux"}, {"SPOR", NULL, "Class D"}, {"SPOR", NULL, "SPOR Mux"}, {"HPOL", NULL, "HP Depop"}, {"HPOR", NULL, "HP Depop"}, {"MONO", NULL, "MONO Depop"}, {"MONO", NULL, "MONO Mux"}, }; struct coeff_clk_div { u32 mclk; u32 bclk; u32 rate; u16 reg_val; }; /* PLL divisors */ struct pll_div { u32 pll_in; u32 pll_out; u16 reg_val; }; static const struct pll_div codec_master_pll_div[] = { {2048000, 8192000, 0x0ea0}, {3686400, 8192000, 0x4e27}, {12000000, 8192000, 0x456b}, {13000000, 8192000, 0x495f}, {13100000, 8192000, 0x0320}, {2048000, 11289600, 0xf637}, {3686400, 11289600, 0x2f22}, {12000000, 11289600, 0x3e2f}, {13000000, 11289600, 0x4d5b}, {13100000, 11289600, 0x363b}, {2048000, 16384000, 0x1ea0}, {3686400, 16384000, 0x9e27}, {12000000, 16384000, 0x452b}, {13000000, 16384000, 0x542f}, {13100000, 16384000, 0x03a0}, {2048000, 16934400, 0xe625}, {3686400, 16934400, 0x9126}, {12000000, 16934400, 0x4d2c}, {13000000, 16934400, 0x742f}, {13100000, 16934400, 0x3c27}, {2048000, 22579200, 0x2aa0}, {3686400, 22579200, 0x2f20}, {12000000, 22579200, 0x7e2f}, {13000000, 22579200, 0x742f}, {13100000, 22579200, 0x3c27}, {2048000, 24576000, 0x2ea0}, {3686400, 24576000, 0xee27}, {12000000, 24576000, 0x2915}, {13000000, 24576000, 0x772e}, {13100000, 24576000, 0x0d20}, {26000000, 24576000, 0x2027}, {26000000, 22579200, 0x392f}, {24576000, 22579200, 0x0921}, {24576000, 24576000, 0x02a0}, }; static const struct pll_div codec_slave_pll_div[] = { {256000, 2048000, 0x46f0}, {256000, 4096000, 0x3ea0}, {352800, 5644800, 0x3ea0}, {512000, 8192000, 0x3ea0}, {1024000, 8192000, 0x46f0}, {705600, 11289600, 0x3ea0}, {1024000, 16384000, 0x3ea0}, {1411200, 22579200, 0x3ea0}, {1536000, 24576000, 0x3ea0}, {2048000, 16384000, 0x1ea0}, {2822400, 22579200, 0x1ea0}, {2822400, 45158400, 0x5ec0}, {5644800, 45158400, 0x46f0}, {3072000, 24576000, 0x1ea0}, {3072000, 49152000, 0x5ec0}, {6144000, 49152000, 0x46f0}, {705600, 11289600, 0x3ea0}, {705600, 8467200, 0x3ab0}, {24576000, 24576000, 0x02a0}, {1411200, 11289600, 0x1690}, {2822400, 11289600, 0x0a90}, {1536000, 12288000, 0x1690}, {3072000, 12288000, 0x0a90}, }; static struct coeff_clk_div coeff_div[] = { /* sysclk is 256fs */ {2048000, 8000 * 32, 8000, 0x1000}, {2048000, 8000 * 64, 8000, 0x0000}, {2822400, 11025 * 32, 11025, 0x1000}, {2822400, 11025 * 64, 11025, 0x0000}, {4096000, 16000 * 32, 16000, 0x1000}, {4096000, 16000 * 64, 16000, 0x0000}, {5644800, 22050 * 32, 22050, 0x1000}, {5644800, 22050 * 64, 22050, 0x0000}, {8192000, 32000 * 32, 32000, 0x1000}, {8192000, 32000 * 64, 32000, 0x0000}, {11289600, 44100 * 32, 44100, 0x1000}, {11289600, 44100 * 64, 44100, 0x0000}, {12288000, 48000 * 32, 48000, 0x1000}, {12288000, 48000 * 64, 48000, 0x0000}, {22579200, 88200 * 32, 88200, 0x1000}, {22579200, 88200 * 64, 88200, 0x0000}, {24576000, 96000 * 32, 96000, 0x1000}, {24576000, 96000 * 64, 96000, 0x0000}, /* sysclk is 512fs */ {4096000, 8000 * 32, 8000, 0x3000}, {4096000, 8000 * 64, 8000, 0x2000}, {5644800, 11025 * 32, 11025, 0x3000}, {5644800, 11025 * 64, 11025, 0x2000}, {8192000, 16000 * 32, 16000, 0x3000}, {8192000, 16000 * 64, 16000, 0x2000}, {11289600, 22050 * 32, 22050, 0x3000}, {11289600, 22050 * 64, 22050, 0x2000}, {16384000, 32000 * 32, 32000, 0x3000}, {16384000, 32000 * 64, 32000, 0x2000}, {22579200, 44100 * 32, 44100, 0x3000}, {22579200, 44100 * 64, 44100, 0x2000}, {24576000, 48000 * 32, 48000, 0x3000}, {24576000, 48000 * 64, 48000, 0x2000}, {45158400, 88200 * 32, 88200, 0x3000}, {45158400, 88200 * 64, 88200, 0x2000}, {49152000, 96000 * 32, 96000, 0x3000}, {49152000, 96000 * 64, 96000, 0x2000}, /* sysclk is 24.576Mhz or 22.5792Mhz */ {24576000, 8000 * 32, 8000, 0x7080}, {24576000, 8000 * 64, 8000, 0x6080}, {24576000, 16000 * 32, 16000, 0x5080}, {24576000, 16000 * 64, 16000, 0x4080}, {24576000, 24000 * 32, 24000, 0x5000}, {24576000, 24000 * 64, 24000, 0x4000}, {24576000, 32000 * 32, 32000, 0x3080}, {24576000, 32000 * 64, 32000, 0x2080}, {22579200, 11025 * 32, 11025, 0x7000}, {22579200, 11025 * 64, 11025, 0x6000}, {22579200, 22050 * 32, 22050, 0x5000}, {22579200, 22050 * 64, 22050, 0x4000}, }; static int get_coeff(int mclk, int rate, int timesofbclk) { int i; for (i = 0; i < ARRAY_SIZE(coeff_div); i++) { if (coeff_div[i].mclk == mclk && coeff_div[i].rate == rate && (coeff_div[i].bclk / coeff_div[i].rate) == timesofbclk) return i; } return -EINVAL; } static int rt5631_hifi_pcm_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; struct rt5631_priv *rt5631 = snd_soc_codec_get_drvdata(codec); int timesofbclk = 32, coeff; unsigned int iface = 0; dev_dbg(codec->dev, "enter %s\n", __func__); rt5631->bclk_rate = snd_soc_params_to_bclk(params); if (rt5631->bclk_rate < 0) { dev_err(codec->dev, "Fail to get BCLK rate\n"); return rt5631->bclk_rate; } rt5631->rx_rate = params_rate(params); if (rt5631->master) coeff = get_coeff(rt5631->sysclk, rt5631->rx_rate, rt5631->bclk_rate / rt5631->rx_rate); else coeff = get_coeff(rt5631->sysclk, rt5631->rx_rate, timesofbclk); if (coeff < 0) { dev_err(codec->dev, "Fail to get coeff\n"); return coeff; } switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: break; case SNDRV_PCM_FORMAT_S20_3LE: iface |= RT5631_SDP_I2S_DL_20; break; case SNDRV_PCM_FORMAT_S24_LE: iface |= RT5631_SDP_I2S_DL_24; break; case SNDRV_PCM_FORMAT_S8: iface |= RT5631_SDP_I2S_DL_8; break; default: return -EINVAL; } snd_soc_update_bits(codec, RT5631_SDP_CTRL, RT5631_SDP_I2S_DL_MASK, iface); snd_soc_write(codec, RT5631_STEREO_AD_DA_CLK_CTRL, coeff_div[coeff].reg_val); return 0; } static int rt5631_hifi_codec_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { struct snd_soc_codec *codec = codec_dai->codec; struct rt5631_priv *rt5631 = snd_soc_codec_get_drvdata(codec); unsigned int iface = 0; dev_dbg(codec->dev, "enter %s\n", __func__); switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBM_CFM: rt5631->master = 1; break; case SND_SOC_DAIFMT_CBS_CFS: iface |= RT5631_SDP_MODE_SEL_SLAVE; rt5631->master = 0; break; default: return -EINVAL; } switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: break; case SND_SOC_DAIFMT_LEFT_J: iface |= RT5631_SDP_I2S_DF_LEFT; break; case SND_SOC_DAIFMT_DSP_A: iface |= RT5631_SDP_I2S_DF_PCM_A; break; case SND_SOC_DAIFMT_DSP_B: iface |= RT5631_SDP_I2S_DF_PCM_B; break; default: return -EINVAL; } switch (fmt & SND_SOC_DAIFMT_INV_MASK) { case SND_SOC_DAIFMT_NB_NF: break; case SND_SOC_DAIFMT_IB_NF: iface |= RT5631_SDP_I2S_BCLK_POL_CTRL; break; default: return -EINVAL; } snd_soc_write(codec, RT5631_SDP_CTRL, iface); return 0; } static int rt5631_hifi_codec_set_dai_sysclk(struct snd_soc_dai *codec_dai, int clk_id, unsigned int freq, int dir) { struct snd_soc_codec *codec = codec_dai->codec; struct rt5631_priv *rt5631 = snd_soc_codec_get_drvdata(codec); dev_dbg(codec->dev, "enter %s, syclk=%d\n", __func__, freq); if ((freq >= (256 * 8000)) && (freq <= (512 * 96000))) { rt5631->sysclk = freq; return 0; } return -EINVAL; } static int rt5631_codec_set_dai_pll(struct snd_soc_dai *codec_dai, int pll_id, int source, unsigned int freq_in, unsigned int freq_out) { struct snd_soc_codec *codec = codec_dai->codec; struct rt5631_priv *rt5631 = snd_soc_codec_get_drvdata(codec); int i, ret = -EINVAL; dev_dbg(codec->dev, "enter %s\n", __func__); if (!freq_in || !freq_out) { dev_dbg(codec->dev, "PLL disabled\n"); snd_soc_update_bits(codec, RT5631_GLOBAL_CLK_CTRL, RT5631_SYSCLK_SOUR_SEL_MASK, RT5631_SYSCLK_SOUR_SEL_MCLK); return 0; } if (rt5631->master) { for (i = 0; i < ARRAY_SIZE(codec_master_pll_div); i++) if (freq_in == codec_master_pll_div[i].pll_in && freq_out == codec_master_pll_div[i].pll_out) { dev_info(codec->dev, "change PLL in master mode\n"); snd_soc_write(codec, RT5631_PLL_CTRL, codec_master_pll_div[i].reg_val); schedule_timeout_uninterruptible( msecs_to_jiffies(20)); snd_soc_update_bits(codec, RT5631_GLOBAL_CLK_CTRL, RT5631_SYSCLK_SOUR_SEL_MASK | RT5631_PLLCLK_SOUR_SEL_MASK, RT5631_SYSCLK_SOUR_SEL_PLL | RT5631_PLLCLK_SOUR_SEL_MCLK); ret = 0; break; } } else { for (i = 0; i < ARRAY_SIZE(codec_slave_pll_div); i++) if (freq_in == codec_slave_pll_div[i].pll_in && freq_out == codec_slave_pll_div[i].pll_out) { dev_info(codec->dev, "change PLL in slave mode\n"); snd_soc_write(codec, RT5631_PLL_CTRL, codec_slave_pll_div[i].reg_val); schedule_timeout_uninterruptible( msecs_to_jiffies(20)); snd_soc_update_bits(codec, RT5631_GLOBAL_CLK_CTRL, RT5631_SYSCLK_SOUR_SEL_MASK | RT5631_PLLCLK_SOUR_SEL_MASK, RT5631_SYSCLK_SOUR_SEL_PLL | RT5631_PLLCLK_SOUR_SEL_BCLK); ret = 0; break; } } return ret; } static int rt5631_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { struct rt5631_priv *rt5631 = snd_soc_codec_get_drvdata(codec); switch (level) { case SND_SOC_BIAS_ON: case SND_SOC_BIAS_PREPARE: snd_soc_update_bits(codec, RT5631_PWR_MANAG_ADD2, RT5631_PWR_MICBIAS1_VOL | RT5631_PWR_MICBIAS2_VOL, RT5631_PWR_MICBIAS1_VOL | RT5631_PWR_MICBIAS2_VOL); break; case SND_SOC_BIAS_STANDBY: if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) { snd_soc_update_bits(codec, RT5631_PWR_MANAG_ADD3, RT5631_PWR_VREF | RT5631_PWR_MAIN_BIAS, RT5631_PWR_VREF | RT5631_PWR_MAIN_BIAS); msleep(80); snd_soc_update_bits(codec, RT5631_PWR_MANAG_ADD3, RT5631_PWR_FAST_VREF_CTRL, RT5631_PWR_FAST_VREF_CTRL); regcache_cache_only(rt5631->regmap, false); regcache_sync(rt5631->regmap); } break; case SND_SOC_BIAS_OFF: snd_soc_write(codec, RT5631_PWR_MANAG_ADD1, 0x0000); snd_soc_write(codec, RT5631_PWR_MANAG_ADD2, 0x0000); snd_soc_write(codec, RT5631_PWR_MANAG_ADD3, 0x0000); snd_soc_write(codec, RT5631_PWR_MANAG_ADD4, 0x0000); break; default: break; } codec->dapm.bias_level = level; return 0; } static int rt5631_probe(struct snd_soc_codec *codec) { struct rt5631_priv *rt5631 = snd_soc_codec_get_drvdata(codec); unsigned int val; int ret; codec->control_data = rt5631->regmap; ret = snd_soc_codec_set_cache_io(codec, 8, 16, SND_SOC_REGMAP); if (ret != 0) { dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret); return ret; } val = rt5631_read_index(codec, RT5631_ADDA_MIXER_INTL_REG3); if (val & 0x0002) rt5631->codec_version = 1; else rt5631->codec_version = 0; rt5631_reset(codec); snd_soc_update_bits(codec, RT5631_PWR_MANAG_ADD3, RT5631_PWR_VREF | RT5631_PWR_MAIN_BIAS, RT5631_PWR_VREF | RT5631_PWR_MAIN_BIAS); msleep(80); snd_soc_update_bits(codec, RT5631_PWR_MANAG_ADD3, RT5631_PWR_FAST_VREF_CTRL, RT5631_PWR_FAST_VREF_CTRL); /* enable HP zero cross */ snd_soc_write(codec, RT5631_INT_ST_IRQ_CTRL_2, 0x0f18); /* power off ClassD auto Recovery */ if (rt5631->codec_version) snd_soc_update_bits(codec, RT5631_INT_ST_IRQ_CTRL_2, 0x2000, 0x2000); else snd_soc_update_bits(codec, RT5631_INT_ST_IRQ_CTRL_2, 0x2000, 0); /* DMIC */ if (rt5631->dmic_used_flag) { snd_soc_update_bits(codec, RT5631_GPIO_CTRL, RT5631_GPIO_PIN_FUN_SEL_MASK | RT5631_GPIO_DMIC_FUN_SEL_MASK, RT5631_GPIO_PIN_FUN_SEL_GPIO_DIMC | RT5631_GPIO_DMIC_FUN_SEL_DIMC); snd_soc_update_bits(codec, RT5631_DIG_MIC_CTRL, RT5631_DMIC_L_CH_LATCH_MASK | RT5631_DMIC_R_CH_LATCH_MASK, RT5631_DMIC_L_CH_LATCH_FALLING | RT5631_DMIC_R_CH_LATCH_RISING); } codec->dapm.bias_level = SND_SOC_BIAS_STANDBY; return 0; } static int rt5631_remove(struct snd_soc_codec *codec) { rt5631_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } #ifdef CONFIG_PM static int rt5631_suspend(struct snd_soc_codec *codec) { rt5631_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static int rt5631_resume(struct snd_soc_codec *codec) { rt5631_set_bias_level(codec, SND_SOC_BIAS_STANDBY); return 0; } #else #define rt5631_suspend NULL #define rt5631_resume NULL #endif #define RT5631_STEREO_RATES SNDRV_PCM_RATE_8000_96000 #define RT5631_FORMAT (SNDRV_PCM_FMTBIT_S16_LE | \ SNDRV_PCM_FMTBIT_S20_3LE | \ SNDRV_PCM_FMTBIT_S24_LE | \ SNDRV_PCM_FMTBIT_S8) static const struct snd_soc_dai_ops rt5631_ops = { .hw_params = rt5631_hifi_pcm_params, .set_fmt = rt5631_hifi_codec_set_dai_fmt, .set_sysclk = rt5631_hifi_codec_set_dai_sysclk, .set_pll = rt5631_codec_set_dai_pll, }; static struct snd_soc_dai_driver rt5631_dai[] = { { .name = "rt5631-hifi", .id = 1, .playback = { .stream_name = "HIFI Playback", .channels_min = 1, .channels_max = 2, .rates = RT5631_STEREO_RATES, .formats = RT5631_FORMAT, }, .capture = { .stream_name = "HIFI Capture", .channels_min = 1, .channels_max = 2, .rates = RT5631_STEREO_RATES, .formats = RT5631_FORMAT, }, .ops = &rt5631_ops, }, }; static struct snd_soc_codec_driver soc_codec_dev_rt5631 = { .probe = rt5631_probe, .remove = rt5631_remove, .suspend = rt5631_suspend, .resume = rt5631_resume, .set_bias_level = rt5631_set_bias_level, .controls = rt5631_snd_controls, .num_controls = ARRAY_SIZE(rt5631_snd_controls), .dapm_widgets = rt5631_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(rt5631_dapm_widgets), .dapm_routes = rt5631_dapm_routes, .num_dapm_routes = ARRAY_SIZE(rt5631_dapm_routes), }; static const struct i2c_device_id rt5631_i2c_id[] = { { "rt5631", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, rt5631_i2c_id); static const struct regmap_config rt5631_regmap_config = { .reg_bits = 8, .val_bits = 16, .readable_reg = rt5631_readable_register, .volatile_reg = rt5631_volatile_register, .max_register = RT5631_VENDOR_ID2, .reg_defaults = rt5631_reg, .num_reg_defaults = ARRAY_SIZE(rt5631_reg), .cache_type = REGCACHE_RBTREE, }; static int rt5631_i2c_probe(struct i2c_client *i2c, const struct i2c_device_id *id) { struct rt5631_priv *rt5631; int ret; rt5631 = devm_kzalloc(&i2c->dev, sizeof(struct rt5631_priv), GFP_KERNEL); if (NULL == rt5631) return -ENOMEM; i2c_set_clientdata(i2c, rt5631); rt5631->regmap = devm_regmap_init_i2c(i2c, &rt5631_regmap_config); if (IS_ERR(rt5631->regmap)) return PTR_ERR(rt5631->regmap); ret = snd_soc_register_codec(&i2c->dev, &soc_codec_dev_rt5631, rt5631_dai, ARRAY_SIZE(rt5631_dai)); return ret; } static int rt5631_i2c_remove(struct i2c_client *client) { snd_soc_unregister_codec(&client->dev); return 0; } static struct i2c_driver rt5631_i2c_driver = { .driver = { .name = "rt5631", .owner = THIS_MODULE, }, .probe = rt5631_i2c_probe, .remove = rt5631_i2c_remove, .id_table = rt5631_i2c_id, }; module_i2c_driver(rt5631_i2c_driver); MODULE_DESCRIPTION("ASoC RT5631 driver"); MODULE_AUTHOR("flove <[email protected]>"); MODULE_LICENSE("GPL");
{ "pile_set_name": "Github" }
$NetBSD: patch-ab,v 1.3 2000/11/17 07:36:34 rh Exp $ --- X11/xedit/xedit.h.orig Fri Nov 17 08:27:10 2000 +++ X11/xedit/xedit.h @@ -37,6 +37,8 @@ #include <X11/Xaw/Viewport.h> #include <X11/Xaw/Cardinals.h> +#include <stdio.h> + #ifndef BUFSIZ #define BUFSIZ 2048 #endif
{ "pile_set_name": "Github" }
// // VMime library (http://www.vmime.org) // Copyright (C) 2002 Vincent Richard <[email protected]> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 3 of // the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // Linking this library statically or dynamically with other modules is making // a combined work based on this library. Thus, the terms and conditions of // the GNU General Public License cover the whole combination. // // Helper function to obtain an encoder given its name static vmime::shared_ptr <vmime::utility::encoder::encoder> getEncoder( const vmime::string& name, int maxLineLength = 0, const vmime::propertySet props = vmime::propertySet() ) { vmime::shared_ptr <vmime::utility::encoder::encoder> enc = vmime::utility::encoder::encoderFactory::getInstance()->create(name); enc->getProperties() = props; if (maxLineLength != 0) { enc->getProperties()["maxlinelength"] = maxLineLength; } return enc; } // Encoding helper function static const vmime::string encode( const vmime::string& name, const vmime::string& in, int maxLineLength = 0, const vmime::propertySet props = vmime::propertySet() ) { vmime::shared_ptr <vmime::utility::encoder::encoder> enc = getEncoder(name, maxLineLength, props); vmime::utility::inputStreamStringAdapter vin(in); std::ostringstream out; vmime::utility::outputStreamAdapter vout(out); enc->encode(vin, vout); return (out.str()); } // Decoding helper function static const vmime::string decode( const vmime::string& name, const vmime::string& in, int maxLineLength = 0 ) { vmime::shared_ptr <vmime::utility::encoder::encoder> enc = getEncoder(name, maxLineLength); vmime::utility::inputStreamStringAdapter vin(in); std::ostringstream out; vmime::utility::outputStreamAdapter vout(out); enc->decode(vin, vout); return (out.str()); }
{ "pile_set_name": "Github" }
package com.objectmentor.library.offline; import com.objectmentor.library.gateways.PatronGateway; import com.objectmentor.library.models.Patron; import java.util.*; public class InMemoryPatronGateway implements PatronGateway { private static int lastId = 0; Map patrons = new HashMap(); protected static class PatronComparatorById implements Comparator { public int compare(Object arg0, Object arg1) { Patron p0 = (Patron) arg0; Patron p1 = (Patron) arg1; return p0.getId().compareTo(p1.getId()); } } public int getNextId() { return ++lastId; } public Map getPatronMap() { return patrons; } public InMemoryPatronGateway() { super(); } public List getPatronList() { ArrayList list = new ArrayList(patrons.values()); Collections.sort(list, new PatronComparatorById()); return list; } }
{ "pile_set_name": "Github" }
<?php namespace Biz\Marker\Dao; use Codeages\Biz\Framework\Dao\GeneralDaoInterface; interface QuestionMarkerDao extends GeneralDaoInterface { public function getMaxSeqByMarkerId($id); public function merge($sourceMarkerId, $targetMarkerId, $maxSeq); public function findByIds($ids); public function findByMarkerId($markerId); public function findByMarkerIds($markerIdss); public function findByQuestionId($questionId); public function waveSeqBehind($markerId, $seq); public function waveSeqForward($markerId, $seq); }
{ "pile_set_name": "Github" }
define( [ "../core", "../data/var/dataPriv", "../css/var/isHiddenWithinTree" ], function( jQuery, dataPriv, isHiddenWithinTree ) { "use strict"; var defaultDisplayMap = {}; function getDefaultDisplay( elem ) { var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[ nodeName ]; if ( display ) { return display; } temp = doc.body.appendChild( doc.createElement( nodeName ) ); display = jQuery.css( temp, "display" ); temp.parentNode.removeChild( temp ); if ( display === "none" ) { display = "block"; } defaultDisplayMap[ nodeName ] = display; return display; } function showHide( elements, show ) { var display, elem, values = [], index = 0, length = elements.length; // Determine new display value for elements that need to change for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } display = elem.style.display; if ( show ) { // Since we force visibility upon cascade-hidden elements, an immediate (and slow) // check is required in this first loop unless we have a nonempty display value (either // inline or about-to-be-restored) if ( display === "none" ) { values[ index ] = dataPriv.get( elem, "display" ) || null; if ( !values[ index ] ) { elem.style.display = ""; } } if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { values[ index ] = getDefaultDisplay( elem ); } } else { if ( display !== "none" ) { values[ index ] = "none"; // Remember what we're overwriting dataPriv.set( elem, "display", display ); } } } // Set the display of the elements in a second loop to avoid constant reflow for ( index = 0; index < length; index++ ) { if ( values[ index ] != null ) { elements[ index ].style.display = values[ index ]; } } return elements; } jQuery.fn.extend( { show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHiddenWithinTree( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); return showHide; } );
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "scale" : "1x" }, { "idiom" : "universal", "filename" : "[email protected]", "scale" : "2x" }, { "idiom" : "universal", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } }
{ "pile_set_name": "Github" }
#ifndef BOOST_SERIALIZATION_LEVEL_ENUM_HPP #define BOOST_SERIALIZATION_LEVEL_ENUM_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) # pragma once #endif /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // level_enum.hpp: // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for updates, documentation, and revision history. namespace boost { namespace serialization { // for each class used in the program, specify which level // of serialization should be implemented // names for each level enum level_type { // Don't serialize this type. An attempt to do so should // invoke a compile time assertion. not_serializable = 0, // write/read this type directly to the archive. In this case // serialization code won't be called. This is the default // case for fundamental types. It presumes a member function or // template in the archive class that can handle this type. // there is no runtime overhead associated reading/writing // instances of this level primitive_type = 1, // Serialize the objects of this type using the objects "serialize" // function or template. This permits values to be written/read // to/from archives but includes no class or version information. object_serializable = 2, /////////////////////////////////////////////////////////////////// // once an object is serialized at one of the above levels, the // corresponding archives cannot be read if the implementation level // for the archive object is changed. /////////////////////////////////////////////////////////////////// // Add class information to the archive. Class information includes // implementation level, class version and class name if available object_class_info = 3 }; } // namespace serialization } // namespace boost #endif // BOOST_SERIALIZATION_LEVEL_ENUM_HPP
{ "pile_set_name": "Github" }
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Netscape Communication Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /** File Name: lexical-031.js Corresponds To: 7.4.2-8-n.js ECMA Section: 7.4.2 Description: The following tokens are ECMAScript keywords and may not be used as identifiers in ECMAScript programs. Syntax Keyword :: one of break for new var continue function return void delete if this while else in typeof with This test verifies that the keyword cannot be used as an identifier. Functioinal tests of the keyword may be found in the section corresponding to the function of the keyword. Author: [email protected] Date: 12 november 1997 */ var SECTION = "lexical-031"; var VERSION = "JS1_4"; var TITLE = "Keywords"; startTest(); writeHeaderToLog( SECTION + " "+ TITLE); var result = "Failed"; var exception = "No exception thrown"; var expect = "Passed"; try { eval("var return;"); } catch ( e ) { result = expect; exception = e.toString(); } new TestCase( SECTION, "var return" + " (threw " + exception +")", expect, result ); test();
{ "pile_set_name": "Github" }
import numpy as np from . import _base from .so3 import SO3Matrix class SE3Matrix(_base.SEMatrixBase): """Homogeneous transformation matrix in :math:`SE(3)` using active (alibi) transformations. .. math:: SE(3) &= \\left\\{ \\mathbf{T}= \\begin{bmatrix} \\mathbf{C} & \\mathbf{r} \\\\ \\mathbf{0}^T & 1 \\end{bmatrix} \\in \\mathbb{R}^{4 \\times 4} ~\\middle|~ \\mathbf{C} \\in SO(3), \\mathbf{r} \\in \\mathbb{R}^3 \\right\\} \\\\ \\mathfrak{se}(3) &= \\left\\{ \\boldsymbol{\\Xi} = \\boldsymbol{\\xi}^\\wedge \\in \\mathbb{R}^{4 \\times 4} ~\\middle|~ \\boldsymbol{\\xi}= \\begin{bmatrix} \\boldsymbol{\\rho} \\\\ \\boldsymbol{\\phi} \\end{bmatrix} \\in \\mathbb{R}^6, \\boldsymbol{\\rho} \\in \\mathbb{R}^3, \\boldsymbol{\\phi} \\in \\mathbb{R}^3 \\right\\} :cvar ~liegroups.SE2.dim: Dimension of the rotation matrix. :cvar ~liegroups.SE2.dof: Underlying degrees of freedom (i.e., dimension of the tangent space). :ivar rot: Storage for the rotation matrix :math:`\\mathbf{C}`. :ivar trans: Storage for the translation vector :math:`\\mathbf{r}`. """ dim = 4 """Dimension of the transformation matrix.""" dof = 6 """Underlying degrees of freedom (i.e., dimension of the tangent space).""" RotationType = SO3Matrix def adjoint(self): """Adjoint matrix of the transformation. .. math:: \\text{Ad}(\\mathbf{T}) = \\begin{bmatrix} \\mathbf{C} & \\mathbf{r}^\\wedge\\mathbf{C} \\\\ \\mathbf{0} & \\mathbf{C} \\end{bmatrix} \\in \\mathbb{R}^{6 \\times 6} """ rotmat = self.rot.as_matrix() return np.vstack( [np.hstack([rotmat, self.RotationType.wedge(self.trans).dot(rotmat)]), np.hstack([np.zeros((3, 3)), rotmat])] ) @classmethod def curlyvee(cls, Psi): """:math:`SE(3)` curlyvee operator as defined by Barfoot. .. math:: \\boldsymbol{\\xi} = \\boldsymbol{\\Psi}^\\curlyvee This is the inverse operation to :meth:`~liegroups.SE3.curlywedge`. """ if Psi.ndim < 3: Psi = np.expand_dims(Psi, axis=0) if Psi.shape[1:3] != (cls.dof, cls.dof): raise ValueError("Psi must have shape ({},{}) or (N,{},{})".format( cls.dof, cls.dof, cls.dof, cls.dof)) xi = np.empty([Psi.shape[0], cls.dof]) xi[:, 0:3] = cls.RotationType.vee(Psi[:, 0:3, 3:6]) xi[:, 3:6] = cls.RotationType.vee(Psi[:, 0:3, 0:3]) return np.squeeze(xi) @classmethod def curlywedge(cls, xi): """:math:`SE(3)` curlywedge operator as defined by Barfoot. .. math:: \\boldsymbol{\\Psi} = \\boldsymbol{\\xi}^\\curlywedge = \\begin{bmatrix} \\boldsymbol{\\phi}^\\wedge & \\boldsymbol{\\rho}^\\wedge \\\\ \\mathbf{0} & \\boldsymbol{\\phi}^\\wedge \\end{bmatrix} This is the inverse operation to :meth:`~liegroups.SE3.curlyvee`. """ xi = np.atleast_2d(xi) if xi.shape[1] != cls.dof: raise ValueError( "xi must have shape ({},) or (N,{})".format(cls.dof, cls.dof)) Psi = np.zeros([xi.shape[0], cls.dof, cls.dof]) Psi[:, 0:3, 0:3] = cls.RotationType.wedge(xi[:, 3:6]) Psi[:, 0:3, 3:6] = cls.RotationType.wedge(xi[:, 0:3]) Psi[:, 3:6, 3:6] = Psi[:, 0:3, 0:3] return np.squeeze(Psi) @classmethod def exp(cls, xi): """Exponential map for :math:`SE(3)`, which computes a transformation from a tangent vector: .. math:: \\mathbf{T}(\\boldsymbol{\\xi}) = \\exp(\\boldsymbol{\\xi}^\\wedge) = \\begin{bmatrix} \\exp(\\boldsymbol{\\phi}^\\wedge) & \\mathbf{J} \\boldsymbol{\\rho} \\\\ \\mathbf{0} ^ T & 1 \\end{bmatrix} This is the inverse operation to :meth:`~liegroups.SE3.log`. """ if len(xi) != cls.dof: raise ValueError("xi must have length {}".format(cls.dof)) rho = xi[0:3] phi = xi[3:6] return cls(cls.RotationType.exp(phi), cls.RotationType.left_jacobian(phi).dot(rho)) @classmethod def left_jacobian_Q_matrix(cls, xi): """The :math:`\\mathbf{Q}` matrix used to compute :math:`\\mathcal{J}` in :meth:`~liegroups.SE3.left_jacobian` and :math:`\\mathcal{J}^{-1}` in :meth:`~liegroups.SE3.inv_left_jacobian`. .. math:: \\mathbf{Q}(\\boldsymbol{\\xi}) = \\frac{1}{2}\\boldsymbol{\\rho}^\\wedge &+ \\left( \\frac{\\phi - \\sin \\phi}{\\phi^3} \\right) \\left( \\boldsymbol{\\phi}^\\wedge \\boldsymbol{\\rho}^\\wedge + \\boldsymbol{\\rho}^\\wedge \\boldsymbol{\\phi}^\\wedge + \\boldsymbol{\\phi}^\\wedge \\boldsymbol{\\rho}^\\wedge \\boldsymbol{\\phi}^\\wedge \\right) \\\\ &+ \\left( \\frac{\\phi^2 + 2 \\cos \\phi - 2}{2 \\phi^4} \\right) \\left( \\boldsymbol{\\phi}^\\wedge \\boldsymbol{\\phi}^\\wedge \\boldsymbol{\\rho}^\\wedge + \\boldsymbol{\\rho}^\\wedge \\boldsymbol{\\phi}^\\wedge \\boldsymbol{\\phi}^\\wedge - 3 \\boldsymbol{\\phi}^\\wedge \\boldsymbol{\\rho}^\\wedge \\boldsymbol{\\phi}^\\wedge \\right) \\\\ &+ \\left( \\frac{2 \\phi - 3 \\sin \\phi + \\phi \\cos \\phi}{2 \\phi^5} \\right) \\left( \\boldsymbol{\\phi}^\\wedge \\boldsymbol{\\rho}^\\wedge \\boldsymbol{\\phi}^\\wedge \\boldsymbol{\\phi}^\\wedge + \\boldsymbol{\\phi}^\\wedge \\boldsymbol{\\phi}^\\wedge \\boldsymbol{\\rho}^\\wedge \\boldsymbol{\\phi}^\\wedge \\right) """ if len(xi) != cls.dof: raise ValueError("xi must have length {}".format(cls.dof)) rho = xi[0:3] # translation part phi = xi[3:6] # rotation part rx = cls.RotationType.wedge(rho) px = cls.RotationType.wedge(phi) ph = np.linalg.norm(phi) ph2 = ph * ph ph3 = ph2 * ph ph4 = ph3 * ph ph5 = ph4 * ph cph = np.cos(ph) sph = np.sin(ph) m1 = 0.5 m2 = (ph - sph) / ph3 m3 = (0.5 * ph2 + cph - 1.) / ph4 m4 = (ph - 1.5 * sph + 0.5 * ph * cph) / ph5 t1 = rx t2 = px.dot(rx) + rx.dot(px) + px.dot(rx).dot(px) t3 = px.dot(px).dot(rx) + rx.dot(px).dot(px) - 3. * px.dot(rx).dot(px) t4 = px.dot(rx).dot(px).dot(px) + px.dot(px).dot(rx).dot(px) return m1 * t1 + m2 * t2 + m3 * t3 + m4 * t4 @classmethod def inv_left_jacobian(cls, xi): """:math:`SE(3)` inverse left Jacobian. .. math:: \\mathcal{J}^{-1}(\\boldsymbol{\\xi}) = \\begin{bmatrix} \\mathbf{J}^{-1} & -\\mathbf{J}^{-1} \\mathbf{Q} \\mathbf{J}^{-1} \\\\ \\mathbf{0} & \\mathbf{J}^{-1} \\end{bmatrix} with :math:`\\mathbf{J}^{-1}` as in :meth:`liegroups.SO3.inv_left_jacobian` and :math:`\\mathbf{Q}` as in :meth:`~liegroups.SE3.left_jacobian_Q_matrix`. """ rho = xi[0:3] # translation part phi = xi[3:6] # rotation part # Near |phi|==0, use first order Taylor expansion if np.isclose(np.linalg.norm(phi), 0.): return np.identity(cls.dof) - 0.5 * cls.curlywedge(xi) so3_inv_jac = cls.RotationType.inv_left_jacobian(phi) Q_mat = cls.left_jacobian_Q_matrix(xi) jac = np.zeros([cls.dof, cls.dof]) jac[0:3, 0:3] = so3_inv_jac jac[0:3, 3:6] = -so3_inv_jac.dot(Q_mat).dot(so3_inv_jac) jac[3:6, 3:6] = so3_inv_jac return jac @classmethod def left_jacobian(cls, xi): """:math:`SE(3)` left Jacobian. .. math:: \\mathcal{J}(\\boldsymbol{\\xi}) = \\begin{bmatrix} \\mathbf{J} & \\mathbf{Q} \\\\ \\mathbf{0} & \\mathbf{J} \\end{bmatrix} with :math:`\\mathbf{J}` as in :meth:`liegroups.SO3.left_jacobian` and :math:`\\mathbf{Q}` as in :meth:`~liegroups.SE3.left_jacobian_Q_matrix`. """ rho = xi[0:3] # translation part phi = xi[3:6] # rotation part # Near |phi|==0, use first order Taylor expansion if np.isclose(np.linalg.norm(phi), 0.): return np.identity(cls.dof) + 0.5 * cls.curlywedge(xi) so3_jac = cls.RotationType.left_jacobian(phi) Q_mat = cls.left_jacobian_Q_matrix(xi) jac = np.zeros([cls.dof, cls.dof]) jac[0:3, 0:3] = so3_jac jac[0:3, 3:6] = Q_mat jac[3:6, 3:6] = so3_jac return jac def log(self): """Logarithmic map for :math:`SE(3)`, which computes a tangent vector from a transformation: .. math:: \\boldsymbol{\\xi}(\\mathbf{T}) = \\ln(\\mathbf{T})^\\vee = \\begin{bmatrix} \\mathbf{J} ^ {-1} \\mathbf{r} \\\\ \\ln(\\boldsymbol{C}) ^\\vee \\end{bmatrix} This is the inverse operation to :meth:`~liegroups.SE3.exp`. """ phi = self.RotationType.log(self.rot) rho = self.RotationType.inv_left_jacobian(phi).dot(self.trans) return np.hstack([rho, phi]) @classmethod def odot(cls, p, directional=False): """:math:`SE(3)` odot operator as defined by Barfoot. This is the Jacobian of a vector .. math:: \\mathbf{p} = \\begin{bmatrix} sx \\\\ sy \\\\ sz \\\\ s \\end{bmatrix} = \\begin{bmatrix} \\boldsymbol{\\epsilon} \\\\ \\eta \\end{bmatrix} with respect to a perturbation in the underlying parameters of :math:`\\mathbf{T}`. If :math:`\\mathbf{p}` is given in Euclidean coordinates and directional=False, the missing scale value :math:`\\eta` is assumed to be 1 and the Jacobian is 3x6. If directional=True, :math:`\\eta` is assumed to be 0: .. math:: \\mathbf{p}^\\odot = \\begin{bmatrix} \\eta \\mathbf{1} & -\\boldsymbol{\\epsilon}^\\wedge \\end{bmatrix} If :math:`\\mathbf{p}` is given in Homogeneous coordinates, the Jacobian is 4x6: .. math:: \\mathbf{p}^\\odot = \\begin{bmatrix} \\eta \\mathbf{1} & -\\boldsymbol{\\epsilon}^\\wedge \\\\ \\mathbf{0}^T & \\mathbf{0}^T \\end{bmatrix} """ p = np.atleast_2d(p) result = np.zeros([p.shape[0], p.shape[1], cls.dof]) if p.shape[1] == cls.dim - 1: # Assume scale parameter is 1 unless p is a direction # ptor, in which case the scale is 0 if not directional: result[:, 0:3, 0:3] = np.eye(3) result[:, 0:3, 3:6] = cls.RotationType.wedge(-p) elif p.shape[1] == cls.dim: # Broadcast magic result[:, 0:3, 0:3] = p[:, 3][:, None, None] * np.eye(3) result[:, 0:3, 3:6] = cls.RotationType.wedge(-p[:, 0:3]) else: raise ValueError("p must have shape ({},), ({},), (N,{}) or (N,{})".format( cls.dim - 1, cls.dim, cls.dim - 1, cls.dim)) return np.squeeze(result) @classmethod def vee(cls, Xi): """:math:`SE(3)` vee operator as defined by Barfoot. .. math:: \\boldsymbol{\\xi} = \\boldsymbol{\\Xi} ^\\vee This is the inverse operation to :meth:`~liegroups.SE3.wedge`. """ if Xi.ndim < 3: Xi = np.expand_dims(Xi, axis=0) if Xi.shape[1:3] != (cls.dim, cls.dim): raise ValueError("Xi must have shape ({},{}) or (N,{},{})".format( cls.dim, cls.dim, cls.dim, cls.dim)) xi = np.empty([Xi.shape[0], cls.dof]) xi[:, 0:3] = Xi[:, 0:3, 3] xi[:, 3:6] = cls.RotationType.vee(Xi[:, 0:3, 0:3]) return np.squeeze(xi) @classmethod def wedge(cls, xi): """:math:`SE(3)` wedge operator as defined by Barfoot. .. math:: \\boldsymbol{\\Xi} = \\boldsymbol{\\xi} ^\\wedge = \\begin{bmatrix} \\boldsymbol{\\phi} ^\\wedge & \\boldsymbol{\\rho} \\\\ \\mathbf{0} ^ T & 0 \\end{bmatrix} This is the inverse operation to :meth:`~liegroups.SE2.vee`. """ xi = np.atleast_2d(xi) if xi.shape[1] != cls.dof: raise ValueError( "xi must have shape ({},) or (N,{})".format(cls.dof, cls.dof)) Xi = np.zeros([xi.shape[0], cls.dim, cls.dim]) Xi[:, 0:3, 0:3] = cls.RotationType.wedge(xi[:, 3:6]) Xi[:, 0:3, 3] = xi[:, 0:3] return np.squeeze(Xi)
{ "pile_set_name": "Github" }
DROP TABLE IF EXISTS `transport_events`;
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><head> <title>CURLMOPT_PIPELINING man page</title> <meta name="generator" content="roffit"> <STYLE type="text/css"> pre { overflow: auto; margin: 0; } P.level0, pre.level0 { padding-left: 2em; } P.level1, pre.level1 { padding-left: 4em; } P.level2, pre.level2 { padding-left: 6em; } span.emphasis { font-style: italic; } span.bold { font-weight: bold; } span.manpage { font-weight: bold; } h2.nroffsh { background-color: #e0e0e0; } span.nroffip { font-weight: bold; font-size: 120%; font-family: monospace; } p.roffit { text-align: center; font-size: 80%; } </STYLE> </head><body> <p class="level0"><a name="NAME"></a><h2 class="nroffsh">NAME</h2> <p class="level0">CURLMOPT_PIPELINING - enable/disable HTTP pipelining <a name="SYNOPSIS"></a><h2 class="nroffsh">SYNOPSIS</h2> <p class="level0">&#35;include &lt;curl/curl.h&gt; <p class="level0">CURLMcode curl_multi_setopt(CURLM *handle, CURLMOPT_PIPELINING, long bits); <a name="DESCRIPTION"></a><h2 class="nroffsh">DESCRIPTION</h2> <p class="level0">Set the <span Class="bold">bits</span> parameter to 1 to make libcurl use HTTP pipelining for HTTP/1.1 transfers done using this multi handle, as far as possible. This means that if you add a second request that can use an already existing connection, the second request will be "piped" on the same connection rather than being executed in parallel. <p class="level0">When using pipelining, there are also several other related options that are interesting to tweak and adjust to alter how libcurl spreads out requests on different connections or not etc. <p class="level0">Starting in 7.43.0, the <span Class="bold">bits</span> parameter's bit 1 also has a meaning and libcurl is now offering symbol names for the bits: <p class="level0"><a name="CURLPIPENOTHING"></a><span class="nroffip">CURLPIPE_NOTHING (0)</span> <p class="level1">Default, which means doing no attempts at pipelining or multiplexing. <p class="level0"><a name="CURLPIPEHTTP1"></a><span class="nroffip">CURLPIPE_HTTP1 (1)</span> <p class="level1">If this bit is set, libcurl will try to pipeline HTTP/1.1 requests on connections that are already established and in use to hosts. <p class="level0"><a name="CURLPIPEMULTIPLEX"></a><span class="nroffip">CURLPIPE_MULTIPLEX (2)</span> <p class="level1">If this bit is set, libcurl will try to multiplex the new transfer over an existing connection if possible. This requires HTTP/2. <a name="DEFAULT"></a><h2 class="nroffsh">DEFAULT</h2> <p class="level0">0 (off) <a name="PROTOCOLS"></a><h2 class="nroffsh">PROTOCOLS</h2> <p class="level0">HTTP(S) <a name="EXAMPLE"></a><h2 class="nroffsh">EXAMPLE</h2> <p class="level0">TODO <a name="AVAILABILITY"></a><h2 class="nroffsh">AVAILABILITY</h2> <p class="level0">Added in 7.16.0. Multiplex support bit added in 7.43.0. <a name="RETURN"></a><h2 class="nroffsh">RETURN VALUE</h2> <p class="level0">Returns CURLM_OK if the option is supported, and CURLM_UNKNOWN_OPTION if not. <a name="SEE"></a><h2 class="nroffsh">SEE ALSO</h2> <p class="level0"><a Class="manpage" href="./CURLMOPT_MAX_PIPELINE_LENGTH.html">CURLMOPT_MAX_PIPELINE_LENGTH</a>, <a Class="manpage" href="./CURLMOPT_PIPELINING_SITE_BL.html">CURLMOPT_PIPELINING_SITE_BL</a>, <a Class="manpage" href="./CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE.html">CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE</a>, <a Class="manpage" href="./CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE.html">CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE</a>, <a Class="manpage" href="./CURLMOPT_MAX_HOST_CONNECTIONS.html">CURLMOPT_MAX_HOST_CONNECTIONS</a>, <a Class="manpage" href="./CURLMOPT_MAXCONNECTS.html">CURLMOPT_MAXCONNECTS</a>, <a Class="manpage" href="./CURLMOPT_MAX_HOST_CONNECTIONS.html">CURLMOPT_MAX_HOST_CONNECTIONS</a><p class="roffit"> This HTML page was made with <a href="http://daniel.haxx.se/projects/roffit/">roffit</a>. </body></html>
{ "pile_set_name": "Github" }
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_CODEGEN_TURBO_ASSEMBLER_H_ #define V8_CODEGEN_TURBO_ASSEMBLER_H_ #include <memory> #include "src/base/template-utils.h" #include "src/builtins/builtins.h" #include "src/codegen/assembler-arch.h" #include "src/roots/roots.h" namespace v8 { namespace internal { // Common base class for platform-specific TurboAssemblers containing // platform-independent bits. class V8_EXPORT_PRIVATE TurboAssemblerBase : public Assembler { public: // Constructors are declared public to inherit them in derived classes // with `using` directive. TurboAssemblerBase(Isolate* isolate, CodeObjectRequired create_code_object, std::unique_ptr<AssemblerBuffer> buffer = {}) : TurboAssemblerBase(isolate, AssemblerOptions::Default(isolate), create_code_object, std::move(buffer)) {} TurboAssemblerBase(Isolate* isolate, const AssemblerOptions& options, CodeObjectRequired create_code_object, std::unique_ptr<AssemblerBuffer> buffer = {}); Isolate* isolate() const { return isolate_; } Handle<HeapObject> CodeObject() const { DCHECK(!code_object_.is_null()); return code_object_; } bool root_array_available() const { return root_array_available_; } void set_root_array_available(bool v) { root_array_available_ = v; } bool trap_on_abort() const { return trap_on_abort_; } bool should_abort_hard() const { return hard_abort_; } void set_abort_hard(bool v) { hard_abort_ = v; } void set_builtin_index(int i) { maybe_builtin_index_ = i; } void set_has_frame(bool v) { has_frame_ = v; } bool has_frame() const { return has_frame_; } virtual void Jump(const ExternalReference& reference) = 0; // Calls the builtin given by the Smi in |builtin|. If builtins are embedded, // the trampoline Code object on the heap is not used. virtual void CallBuiltinByIndex(Register builtin_index) = 0; // Calls/jumps to the given Code object. If builtins are embedded, the // trampoline Code object on the heap is not used. virtual void CallCodeObject(Register code_object) = 0; virtual void JumpCodeObject(Register code_object) = 0; // Loads the given Code object's entry point into the destination register. virtual void LoadCodeObjectEntry(Register destination, Register code_object) = 0; // Loads the given constant or external reference without embedding its direct // pointer. The produced code is isolate-independent. void IndirectLoadConstant(Register destination, Handle<HeapObject> object); void IndirectLoadExternalReference(Register destination, ExternalReference reference); virtual void LoadFromConstantsTable(Register destination, int constant_index) = 0; // Corresponds to: destination = kRootRegister + offset. virtual void LoadRootRegisterOffset(Register destination, intptr_t offset) = 0; // Corresponds to: destination = [kRootRegister + offset]. virtual void LoadRootRelative(Register destination, int32_t offset) = 0; virtual void LoadRoot(Register destination, RootIndex index) = 0; virtual void Trap() = 0; virtual void DebugBreak() = 0; static int32_t RootRegisterOffsetForRootIndex(RootIndex root_index); static int32_t RootRegisterOffsetForBuiltinIndex(int builtin_index); // Returns the root-relative offset to reference.address(). static intptr_t RootRegisterOffsetForExternalReference( Isolate* isolate, const ExternalReference& reference); // Returns the root-relative offset to the external reference table entry, // which itself contains reference.address(). static int32_t RootRegisterOffsetForExternalReferenceTableEntry( Isolate* isolate, const ExternalReference& reference); // An address is addressable through kRootRegister if it is located within // isolate->root_register_addressable_region(). static bool IsAddressableThroughRootRegister( Isolate* isolate, const ExternalReference& reference); #ifdef V8_TARGET_OS_WIN // Minimum page size. We must touch memory once per page when expanding the // stack, to avoid access violations. static constexpr int kStackPageSize = 4 * KB; #endif protected: void RecordCommentForOffHeapTrampoline(int builtin_index); Isolate* const isolate_ = nullptr; // This handle will be patched with the code object on installation. Handle<HeapObject> code_object_; // Whether kRootRegister has been initialized. bool root_array_available_ = true; // Immediately trap instead of calling {Abort} when debug code fails. bool trap_on_abort_ = FLAG_trap_on_abort; // Emit a C call to abort instead of a runtime call. bool hard_abort_ = false; // May be set while generating builtins. int maybe_builtin_index_ = Builtins::kNoBuiltinId; bool has_frame_ = false; DISALLOW_IMPLICIT_CONSTRUCTORS(TurboAssemblerBase); }; // Avoids emitting calls to the {Builtins::kAbort} builtin when emitting debug // code during the lifetime of this scope object. For disabling debug code // entirely use the {DontEmitDebugCodeScope} instead. class HardAbortScope { public: explicit HardAbortScope(TurboAssemblerBase* assembler) : assembler_(assembler), old_value_(assembler->should_abort_hard()) { assembler_->set_abort_hard(true); } ~HardAbortScope() { assembler_->set_abort_hard(old_value_); } private: TurboAssemblerBase* assembler_; bool old_value_; }; #ifdef DEBUG struct CountIfValidRegisterFunctor { template <typename RegType> constexpr int operator()(int count, RegType reg) const { return count + (reg.is_valid() ? 1 : 0); } }; template <typename RegType, typename... RegTypes, // All arguments must be either Register or DoubleRegister. typename = typename std::enable_if< base::is_same<Register, RegType, RegTypes...>::value || base::is_same<DoubleRegister, RegType, RegTypes...>::value>::type> inline bool AreAliased(RegType first_reg, RegTypes... regs) { int num_different_regs = NumRegs(RegType::ListOf(first_reg, regs...)); int num_given_regs = base::fold(CountIfValidRegisterFunctor{}, 0, first_reg, regs...); return num_different_regs < num_given_regs; } #endif } // namespace internal } // namespace v8 #endif // V8_CODEGEN_TURBO_ASSEMBLER_H_
{ "pile_set_name": "Github" }
md.dihedral -------------- .. rubric:: Overview .. py:currentmodule:: hoomd .. autosummary:: :nosignatures: md.dihedral.harmonic md.dihedral.opls md.dihedral.table .. rubric:: Details .. automodule:: hoomd.md.dihedral :synopsis: Dihedral potentials. :members:
{ "pile_set_name": "Github" }
# - Find BOARD # Find the native BOARD includes and library # This module defines # BOARD_INCLUDE_DIR, where to find jpeglib.h, etc. # BOARD_LIBRARIES, the libraries needed to use BOARD. # BOARD_FOUND, If false, do not try to use BOARD. # also defined, but not for general use are # BOARD_LIBRARY, where to find the BOARD library. FIND_PATH(BOARD_INCLUDE_DIR board.h /usr/local/include /usr/include ) SET(BOARD_NAMES ${BOARD_NAMES} board) FIND_LIBRARY(BOARD_LIBRARY NAMES ${BOARD_NAMES} PATHS /usr/lib /usr/local/lib ) IF (BOARD_LIBRARY AND BOARD_INCLUDE_DIR) SET(BOARD_LIBRARIES ${BOARD_LIBRARY}) SET(BOARD_FOUND "YES") ELSE (BOARD_LIBRARY AND BOARD_INCLUDE_DIR) SET(BOARD_FOUND "NO") ENDIF (BOARD_LIBRARY AND BOARD_INCLUDE_DIR) IF (BOARD_FOUND) IF (NOT BOARD_FIND_QUIETLY) MESSAGE(STATUS "Found BOARD: ${BOARD_LIBRARIES}") ENDIF (NOT BOARD_FIND_QUIETLY) ELSE (BOARD_FOUND) IF (BOARD_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find BOARD library") ENDIF (BOARD_FIND_REQUIRED) ENDIF (BOARD_FOUND) # Deprecated declarations. SET (NATIVE_BOARD_INCLUDE_PATH ${BOARD_INCLUDE_DIR} ) GET_FILENAME_COMPONENT (NATIVE_BOARD_LIB_PATH ${BOARD_LIBRARY} PATH) MARK_AS_ADVANCED( BOARD_LIBRARY BOARD_INCLUDE_DIR )
{ "pile_set_name": "Github" }
<div id="search-modal" class="modal"> <div class="modal-content"> <h4>Your handy pagefinder</h4> <p> Type anything you want below. It'll match page names (like the names of your characters, locations, and so on), but also anything you've typed in any of those pages' fields as well. For example, searching "bald" will show you all your characters that you've entered "bald" in for their hair style. </p> <%= form_tag main_app.search_path, method: :get do %> <input type="search" name="q" value="" placeholder="search your notebook" /> <button type="submit" class="btn btn-primary blue">Search everything</button> <% end %> </div> <div class="modal-footer"> <a href="#!" class="modal-close waves-effect waves-green btn-flat">Cancel</a> </div> </div>
{ "pile_set_name": "Github" }
// // TicketConstants.swift // 12306ForMac // // Created by fancymax on 16/9/10. // Copyright © 2016年 fancy. All rights reserved. // import Foundation //let cardTypeNameDic = ["二代身份证": "1", "一代身份证": "2", "港澳通行证": "C", "台湾通行证": "G", "护照": "B"] let SEAT_TYPE_ARRAY = ["商务座", "特等座", "一等座", "二等座", "高级软卧", "软卧", "硬卧", "软座", "硬座", "无座"] //动车 let D_SEAT_TYPE_NAME_DIC = ["高级软卧":"A","商务座": "9", "特等座": "P", "一等座": "M", "二等座": "O","软卧": "F", "无座": "O"] let D_SEAT_TYPE_KEYPATH_DIC = ["高级软卧": "Gr_Num","商务座": "Swz_Num", "特等座": "Tz_Num", "一等座": "Zy_Num", "二等座": "Ze_Num","软卧": "Rw_Num", "无座": "Wz_Num"] //普通车 let K_SEAT_TYPE_NAME_DIC = ["高级软卧": "6","软卧": "4", "硬卧": "3", "软座": "2", "硬座": "1", "无座": "1"] let K_SEAT_TYPE_KEYPATH_DIC = ["高级软卧": "Gr_Num","软卧": "Rw_Num", "硬卧": "Yw_Num", "软座": "Rz_Num", "硬座": "Yz_Num", "无座": "Wz_Num"] func G_QuerySeatTypeNameDicBy(_ trainCode:String)->[String:String] { if (trainCode.contains("G"))||(trainCode.contains("D")||(trainCode.contains("C"))) { return D_SEAT_TYPE_NAME_DIC; } else { return K_SEAT_TYPE_NAME_DIC; } } func G_QuerySeatTypeKeyPathDicBy(_ trainCode:String)->[String:String] { if (trainCode.contains("G"))||(trainCode.contains("D")||(trainCode.contains("C"))) { return D_SEAT_TYPE_KEYPATH_DIC; } else { return K_SEAT_TYPE_KEYPATH_DIC; } } //20160502->2016-05-02 func G_Convert2StartTrainDateStr(_ dateStr: String)->String{ var formateStr = dateStr var index = dateStr.characters.index(dateStr.startIndex, offsetBy: 4) formateStr.insert("-", at: index) index = dateStr.characters.index(dateStr.startIndex, offsetBy: 7) formateStr.insert("-", at: index) return formateStr }
{ "pile_set_name": "Github" }
package com.avito.ci.steps import com.avito.cd.CdBuildConfig import com.avito.cd.CdBuildConfig.Deployment import com.avito.cd.cdBuildConfig import com.avito.plugin.qappsTaskProvider import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.tasks.TaskProvider import java.io.File @Suppress("UnstableApiUsage") class UploadToQapps( context: String, artifactsConfiguration: ArtifactsConfiguration, name: String ) : UploadArtifactsStep(context, artifactsConfiguration, name) { override fun provideTask( project: Project, artifactsMap: Map<String, Output> ): List<TaskProvider<out Task>> { val plugin = "com.avito.android.qapps" require(project.plugins.hasPlugin(plugin)) { "${this.javaClass.simpleName} check requires $plugin being applied to project" } val uploadCondition = UploadToQappsCondition(project.cdBuildConfig.orNull) return artifactsMap.map { (_, output) -> when (output) { is Output.ApkOutput -> project.tasks.qappsTaskProvider(output.variantName) .apply { configure { it.getApk().set(File(output.path)) it.releaseChain.set(uploadCondition.isReleaseChain()) it.onlyIf { uploadCondition.canUpload() } } } else -> error("QApps upload doesn't support that type of artifact: $output") } } } } internal class UploadToQappsCondition( val config: CdBuildConfig? ) { fun isReleaseChain(): Boolean { return findDeployment()?.isRelease ?: false } fun canUpload(): Boolean { if (config == null) return true return findDeployment() != null } private fun findDeployment(): Deployment.Qapps? { if (config == null) return null return config.deployments .firstOrNull { it is Deployment.Qapps } as Deployment.Qapps? } }
{ "pile_set_name": "Github" }
import System.Environment import System.Process import Data.Maybe main = do [ghc] <- getArgs info <- readProcess ghc ["+RTS", "--info"] "" let fields = read info :: [(String,String)] getGhcFieldOrFail fields "HostOS" "Host OS" getGhcFieldOrFail fields "WORDSIZE" "Word size" getGhcFieldOrFail fields "TARGETPLATFORM" "Target platform" getGhcFieldOrFail fields "TargetOS_CPP" "Target OS" getGhcFieldOrFail fields "TargetARCH_CPP" "Target architecture" info <- readProcess ghc ["--info"] "" let fields = read info :: [(String,String)] getGhcFieldOrFail fields "GhcStage" "Stage" getGhcFieldOrFail fields "GhcDebugged" "Debug on" getGhcFieldOrFail fields "GhcWithNativeCodeGen" "Have native code generator" getGhcFieldOrFail fields "GhcWithInterpreter" "Have interpreter" getGhcFieldOrFail fields "GhcUnregisterised" "Unregisterised" getGhcFieldOrFail fields "GhcWithSMP" "Support SMP" getGhcFieldOrFail fields "GhcRTSWays" "RTS ways" getGhcFieldOrFail fields "GhcLeadingUnderscore" "Leading underscore" getGhcFieldOrDefault fields "GhcDynamicByDefault" "Dynamic by default" "NO" getGhcFieldOrDefault fields "GhcDynamic" "GHC Dynamic" "NO" getGhcFieldOrDefault fields "GhcProfiled" "GHC Profiled" "NO" getGhcFieldProgWithDefault fields "AR" "ar command" "ar" getGhcFieldProgWithDefault fields "CLANG" "LLVM clang command" "clang" getGhcFieldProgWithDefault fields "LLC" "LLVM llc command" "llc" getGhcFieldProgWithDefault fields "TEST_CC" "C compiler command" "gcc" let pkgdb_flag = case lookup "Project version" fields of Just v | parseVersion v >= [7,5] -> "package-db" _ -> "package-conf" putStrLn $ "GhcPackageDbFlag" ++ '=':pkgdb_flag let minGhcVersion711 = case lookup "Project version" fields of Just v | parseVersion v >= [7,11] -> "YES" _ -> "NO" putStrLn $ "MinGhcVersion711" ++ '=':minGhcVersion711 let minGhcVersion801 = case lookup "Project version" fields of Just v | parseVersion v >= [8,1] -> "YES" _ -> "NO" putStrLn $ "MinGhcVersion801" ++ '=':minGhcVersion801 getGhcFieldOrFail :: [(String,String)] -> String -> String -> IO () getGhcFieldOrFail fields mkvar key = getGhcField fields mkvar key id (fail ("No field: " ++ key)) getGhcFieldOrDefault :: [(String,String)] -> String -> String -> String -> IO () getGhcFieldOrDefault fields mkvar key deflt = getGhcField fields mkvar key id on_fail where on_fail = putStrLn (mkvar ++ '=' : deflt) getGhcFieldProgWithDefault :: [(String,String)] -> String -> String -> String -> IO () getGhcFieldProgWithDefault fields mkvar key deflt = getGhcField fields mkvar key fix on_fail where fix val = fixSlashes (fixTopdir topdir val) topdir = fromMaybe "" (lookup "LibDir" fields) on_fail = putStrLn (mkvar ++ '=' : deflt) getGhcField :: [(String,String)] -> String -> String -> (String -> String) -> IO () -> IO () getGhcField fields mkvar key fix on_fail = case lookup key fields of Nothing -> on_fail Just val -> putStrLn (mkvar ++ '=' : fix val) fixTopdir :: String -> String -> String fixTopdir t "" = "" fixTopdir t ('$':'t':'o':'p':'d':'i':'r':s) = t ++ s fixTopdir t (c:s) = c : fixTopdir t s fixSlashes :: FilePath -> FilePath fixSlashes = map f where f '\\' = '/' f c = c parseVersion :: String -> [Int] parseVersion v = case break (== '.') v of (n, rest) -> read n : case rest of [] -> [] ('.':v') -> parseVersion v' _ -> error "bug in parseVersion"
{ "pile_set_name": "Github" }
# Historically 'as' treats '.' as a reference to the current location in # arbitrary contexts. We don't support this in general. # RUN: not llvm-mc -triple i386-unknown-unknown %s 2> %t # RUN: FileCheck -input-file %t %s # CHECK: invalid use of pseudo-symbol '.' as a label .: .long 0
{ "pile_set_name": "Github" }
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2020 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { #if ! JUCE_ANDROID // We currently don't request runtime permissions on any other platform // than Android, so this file contains a dummy implementation for those. // This may change in the future. void RuntimePermissions::request (PermissionID, Callback callback) { callback (true); } bool RuntimePermissions::isRequired (PermissionID) { return false; } bool RuntimePermissions::isGranted (PermissionID) { return true; } #endif } // namespace juce
{ "pile_set_name": "Github" }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from aliyunsdkcore.request import RpcRequest from aliyunsdkopenanalytics_open.endpoint import endpoint_data class GetConsolePermissionRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'openanalytics-open', '2018-06-19', 'GetConsolePermission','openanalytics') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
{ "pile_set_name": "Github" }
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: | Refer 12.6.3; The production IterationStatement : for ( var VariableDeclarationListNoIn ; Expressionopt ; Expressionopt ) Statement is evaluated as follows: es5id: 12.6.3_2-3-a-ii-9 description: > The for Statement - (normal, V, empty) will be returned when first Expression is a String object (value is 'null') ---*/ var accessed = false; var strObj = new String("null"); for (var i = 0; strObj;) { accessed = true; break; } assert(accessed, 'accessed !== true');
{ "pile_set_name": "Github" }
# Contributing to Ant Design Mobile The following is a set of guidelines for contributing to Ant Design Mobile. Please spend several minutes in reading these guidelines before you create an issue or pull request. Anyway, these are just guidelines, not rules, use your best judgment and feel free to propose changes to this document in a pull request. ## Do your homework before asking a question It's a great idea to read Eric Steven Raymond's [How To Ask Questions The Smart Way](http://www.catb.org/esr/faqs/smart-questions.html) twice before asking a question. But if you are busy now, I recommend to read [Don't post homework questions](http://www.catb.org/esr/faqs/smart-questions.html#homework) first. The following guidelines are about *How to avoid Homework Questions*. ### 1. Read the documentation. It sad but true that someone just glance(not read) [Ant Design Mobile's documentation](http://mobile.ant.design/). Please read the documentation closely. Tips: choose the corresponding documentation with versions selector which in the bottom-right corner. ### 2. Make sure that your question is about Ant Design Mobile, not React Someone may think all of the questions that he/she meets in developing are about Ant Design Mobile, but it's not true. So, please read [React's documentaion](http://facebook.github.io/react/docs/getting-started.html) or just Google(not Baidu, seriously) your questions with keywork *React* first. If you are sure that your question is about Ant Design Mobile, go ahead. ### 3. Read the FAQ and search the issues list of Ant Design Mobile Your questions may be asked and solved by others. So please spend several minutes on searching. Remember [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself), both code and questions. P.S. 1. [FAQ](https://github.com/ant-design/ant-design-mobile/wiki/FAQ) 1. [Issues list](https://github.com/ant-design/ant-design-mobile/issues) ## Close your issue if it's solved It is a good habit which will save maintainers' time. Thank you! ## Providing a demo while reporting a bug It would be helpful to provide a demo which can re-produce the bug 100%. Please give us the steps in detail that can help us re-producing the bug you met. Then, create an issue. The most important thing is: double check before claiming that you have found a bug. ## Tips about Feature Request If you believe that Ant Design Mobile should provide some features, but it does not. You could create an issue to discuss. However, Ant Design Mobile is not Swiss Army Knife, there are some features which Ant Design Mobile will not support: 1. Request or operate data ## Tips about Pull Request It's welcomed to pull request. And there are some tips about that: 1. It is a good habit to create a feature request issue to disscuss whether the feature is necessary before you implement it. However, it's unnecessary to create an issue to claim that you found a typo or improved the readability of documentaion, just create a pull request. 1. Run `npm run lint` and fix those errors before committing in order to keep consistent code style. 1. Rebase before creating a PR to keep commit history clear. 1. Add some descriptions and refer relative issues for you PR.
{ "pile_set_name": "Github" }
changed in both base 100644 29c55f1e4398c37e27660f4ece9976cf551cd804 src/vs/platform/node/product.ts our 100644 dbb84fd473f8212ea96a20a8f12d66c5b703786a src/vs/platform/node/product.ts their 100644 c2d0ab485103b0decd8479198b2da31682ec534f src/vs/platform/node/product.ts @@ -36,7 +36,11 @@ }; extensionTips: { [id: string]: string; }; extensionImportantTips: { [id: string]: { name: string; pattern: string; }; }; +<<<<<<< .our exeBasedExtensionTips: { [id: string]: { friendlyName: string, windowsPath?: string, recommendations: string[] }; }; +======= + exeBasedExtensionTips: { [id: string]: any; }; +>>>>>>> .their extensionKeywords: { [extension: string]: string[]; }; extensionAllowedBadgeProviders: string[]; extensionAllowedProposedApi: string[]; changed in both base 100644 3918fe5f9f03c9ec1cd687a7caf8069a54a87775 src/vs/workbench/parts/extensions/electron-browser/extensionTipsService.ts our 100644 6f9d4a74f5feb07a450341f183980ee0a10455a9 src/vs/workbench/parts/extensions/electron-browser/extensionTipsService.ts their 100644 869c71175a9d30718bd642261ff65e81f9459f3b src/vs/workbench/parts/extensions/electron-browser/extensionTipsService.ts @@ -28,6 +28,7 @@ import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import * as pfs from 'vs/base/node/pfs'; import * as os from 'os'; +<<<<<<< .our import { flatten, distinct, shuffle, coalesce } from 'vs/base/common/arrays'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { guessMimeTypes, MIME_UNKNOWN } from 'vs/base/common/mime'; @@ -43,6 +44,9 @@ import URI from 'vs/base/common/uri'; import { areSameExtensions, getGalleryExtensionIdFromLocal } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { IExperimentService, ExperimentActionType, ExperimentState } from 'vs/workbench/parts/experiments/node/experimentService'; +======= +import { flatten, distinct } from 'vs/base/common/arrays'; +>>>>>>> .their const milliSecondsInADay = 1000 * 60 * 60 * 24; const choiceNever = localize('neverShowAgain', "Don't Show Again"); @@ -113,9 +117,19 @@ return; } +<<<<<<< .our if (product.extensionsGallery && product.extensionsGallery.recommendationsUrl) { this._extensionsRecommendationsUrl = product.extensionsGallery.recommendationsUrl; } +======= + this._suggestTips(); + this._suggestWorkspaceRecommendations(); + + // Executable based recommendations carry out a lot of file stats, so run them after 10 secs + // So that the startup is not affected + setTimeout(() => this._suggestBasedOnExecutables(this._exeBasedRecommendations), 10000); + } +>>>>>>> .their this.sessionSeed = +new Date(); @@ -286,6 +300,7 @@ })); } +<<<<<<< .our private fetchExtensionRecommendationContents(): TPromise<{ contents: IExtensionsConfigContent, source: ExtensionRecommendationSource }[]> { const workspace = this.contextService.getWorkspace(); return TPromise.join<{ contents: IExtensionsConfigContent, source: ExtensionRecommendationSource }>([ @@ -293,6 +308,9 @@ ...workspace.folders.map(workspaceFolder => this.resolveWorkspaceFolderExtensionConfig(workspaceFolder).then(contents => contents ? { contents, source: workspaceFolder } : null)) ]).then(contents => coalesce(contents)); } +======= + const exeBased = distinct(this._exeBasedRecommendations); +>>>>>>> .their private resolveWorkspaceExtensionConfig(workspace: IWorkspace): TPromise<IExtensionsConfigContent | null> { if (!workspace.configuration) { @@ -801,6 +819,7 @@ ); } +<<<<<<< .our private fetchExecutableRecommendations(): TPromise<any> { const homeDir = os.homedir(); let foundExecutables: Set<string> = new Set<string>(); @@ -815,11 +834,25 @@ this._exeBasedRecommendations[extensionId.toLowerCase()] = product.exeBasedExtensionTips[exeName]['friendlyName']; } }); +======= + private _suggestBasedOnExecutables(recommendations: string[]): void { + const homeDir = os.homedir(); + let foundExecutables: Set<string> = new Set<string>(); + + let findExecutable = (exeName, path) => { + return pfs.fileExists(path).then(exists => { + if (!foundExecutables.has(exeName)) { + foundExecutables.add(exeName); + recommendations.push(...product.exeBasedExtensionTips[exeName]['recommendations']); +>>>>>>> .their } }); }; +<<<<<<< .our let promises: TPromise<any>[] = []; +======= +>>>>>>> .their // Loop through recommended extensions forEach(product.exeBasedExtensionTips, entry => { if (typeof entry.value !== 'object' || !Array.isArray(entry.value['recommendations'])) { @@ -832,6 +865,7 @@ if (!windowsPath || typeof windowsPath !== 'string') { return; } +<<<<<<< .our windowsPath = windowsPath.replace('%USERPROFILE%', process.env['USERPROFILE']) .replace('%ProgramFiles(x86)%', process.env['ProgramFiles(x86)']) .replace('%ProgramFiles%', process.env['ProgramFiles']) @@ -844,6 +878,15 @@ }); return TPromise.join(promises); +======= + windowsPath = windowsPath.replace('%USERPROFILE%', process.env['USERPROFILE']); + findExecutable(exeName, windowsPath); + } else { + findExecutable(exeName, paths.join('/usr/local/bin', exeName)); + findExecutable(exeName, paths.join(homeDir, exeName)); + } + }); +>>>>>>> .their } private setIgnoreRecommendationsConfig(configVal: boolean) {
{ "pile_set_name": "Github" }
using System; using Mono.Cecil; using Mono.Tuner; namespace Xamarin.Linker { public class MobileRemoveAttributes : RemoveAttributesBase { protected virtual bool DebugBuild { get { return context.LinkSymbols; } } protected override bool IsRemovedAttribute (CustomAttribute attribute) { // note: this also avoid calling FullName (which allocates a string) var attr_type = attribute.Constructor.DeclaringType; switch (attr_type.Name) { case "ObsoleteAttribute": // System.Mono*Attribute from mono/mcs/build/common/MonoTODOAttribute.cs case "MonoLimitationAttribute": case "MonoNotSupportedAttribute": case "MonoTODOAttribute": return attr_type.Namespace == "System"; // remove debugging-related attributes if we're not linking symbols (i.e. we're building release builds) case "DebuggableAttribute": case "DebuggerBrowsableAttribute": case "DebuggerDisplayAttribute": case "DebuggerHiddenAttribute": case "DebuggerNonUserCodeAttribute": case "DebuggerStepperBoundaryAttribute": case "DebuggerStepThroughAttribute": case "DebuggerTypeProxyAttribute": case "DebuggerVisualizerAttribute": return !DebugBuild && attr_type.Namespace == "System.Diagnostics"; // compiler nullability attributes are not used at runtime so they can be removed by the linker case "NullableAttribute": case "NullableContextAttribute": case "NullablePublicOnlyAttribute": return attr_type.Namespace == "System.Runtime.CompilerServices"; // _manual_ nullability attributes are not used at runtime so they can be removed by the linker case "AllowNullAttribute": case "DisallowNullAttribute": case "DoesNotReturnAttribute": case "DoesNotReturnIfAttribute": case "ExcludeFromCodeCoverageAttribute": case "MaybeNullAttribute": case "MaybeNullWhenAttribute": case "NotNullAttribute": case "NotNullIfNotNullAttribute": case "NotNullWhenAttribute": return attr_type.Namespace == "System.Diagnostics.CodeAnalysis"; // decorate the internalattributes (like nullability) that Roslyn inject into assemblies case "EmbeddedAttribute": return attr_type.Namespace == "Microsoft.CodeAnalysis"; default: return false; } } } }
{ "pile_set_name": "Github" }
<?php namespace Vinelab\NeoEloquent\Schema; use Closure; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\Schema\Grammars\Grammar as IlluminateSchemaGrammar; use Illuminate\Support\Fluent; class Blueprint { /** * The label the blueprint describes. * * @var string */ protected $label; /** * The commands that should be run for the label. * * @var array */ protected $commands = []; /** * @param string $label * @param Closure $callback * @return void */ public function __construct($label, Closure $callback = null) { $this->label = $label; if ( ! is_null($callback)) { $callback($this); } } /** * Execute the blueprint against the label. * * @param \Illuminate\Database\ConnectionInterface $connection * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar * @return void */ public function build(ConnectionInterface $connection, IlluminateSchemaGrammar $grammar) { foreach ($this->toCypher($connection, $grammar) as $statement) { $connection->statement($statement); } } /** * Get the raw Cypher statements for the blueprint. * * @param \Illuminate\Database\ConnectionInterface $connection * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar * @return array */ public function toCypher(ConnectionInterface $connection, IlluminateSchemaGrammar $grammar) { $statements = []; // Each type of command has a corresponding compiler function on the schema // grammar which is used to build the necessary SQL statements to build // the blueprint element, so we'll just call that compilers function. foreach ($this->commands as $command) { $method = 'compile'.ucfirst($command->name); if (method_exists($grammar, $method)) { if ( ! is_null($cypher = $grammar->$method($this, $command, $connection))) { $statements = array_merge($statements, (array) $cypher); } } } return $statements; } /** * Indicate that the label should be dropped. * * @return \Illuminate\Support\Fluent */ public function drop() { return $this->addCommand('drop'); } /** * Indicate that the label should be dropped if it exists. * * @return \Illuminate\Support\Fluent */ public function dropIfExists() { return $this->addCommand('dropIfExists'); } /** * Rename the label to a given name. * * @param string $to * @return \Illuminate\Support\Fluent */ public function renameLabel($to) { return $this->addCommand('renameLabel', compact('to')); } /** * Indicate that the given unique constraint on labels properties should be dropped. * * @param string|array $properties * @return \Illuminate\Support\Fluent */ public function dropUnique($properties) { $properties = (array) $properties; foreach ($properties as $property) { $this->indexCommand('dropUnique', $property); } } /** * Indicate that the given index on label's properties should be dropped. * * @param string|array $properties * @return \Illuminate\Support\Fluent */ public function dropIndex($properties) { $properties = (array) $properties; foreach ($properties as $property) { $this->indexCommand('dropIndex', $property); } } /** * Specify a unique contraint for label's properties. * * @param string|array $properties * @return \Illuminate\Support\Fluent */ public function unique($properties) { $properties = (array) $properties; foreach ($properties as $property) { $this->addCommand('unique', ['property' => $property]); } } /** * Specify an index for the label properties. * * @param string|array $properties * @return \Illuminate\Support\Fluent */ public function index($properties) { $properties = (array) $properties; foreach ($properties as $property) { $this->addCommand('index', ['property' => $property]); } } /** * Add a new command to the blueprint. * * @param string $name * @param array $parameters * @return \Illuminate\Support\Fluent */ protected function addCommand($name, array $parameters = []) { $this->commands[] = $command = $this->createCommand($name, $parameters); return $command; } /** * Create a new Fluent command. * * @param string $name * @param array $parameters * @return \Illuminate\Support\Fluent */ protected function createCommand($name, array $parameters = []) { return new Fluent( array_merge( compact('name'), $parameters) ); } /** * Add a new index command to the blueprint. * * @param string $type * @param string|array $property * @param string $index * @return \Illuminate\Support\Fluent */ protected function indexCommand($type, $property) { return $this->addCommand($type, compact('property')); } /** * Set the label that blueprint describes. * * @return string */ public function setLabel($label) { $this->label = $label; } /** * Get the label that blueprint describes. * * @return string */ public function getLabel() { return $this->label; } /** * Get the commands on the blueprint. * * @return array */ public function getCommands() { return $this->commands; } /** * Return the label that blueprint describes. * * @return string */ public function __toString() { return $this->getLabel(); } }
{ "pile_set_name": "Github" }
[/ / Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com) / / Distributed under the Boost Software License, Version 1.0. (See accompanying / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /] [section:InternetProtocol Internet protocol requirements] An internet protocol must meet the requirements for a [link asio.reference.Protocol protocol] as well as the additional requirements listed below. In the table below, `X` denotes an internet protocol class, `a` denotes a value of type `X`, and `b` denotes a value of type `X`. [table InternetProtocol requirements [[expression] [return type] [assertion/note\npre/post-conditions]] [ [`X::resolver`] [`ip::basic_resolver<X>`] [The type of a resolver for the protocol.] ] [ [`X::v4()`] [`X`] [Returns an object representing the IP version 4 protocol.] ] [ [`X::v6()`] [`X`] [Returns an object representing the IP version 6 protocol.] ] [ [`a == b`] [convertible to `bool`] [Returns whether two protocol objects are equal.] ] [ [`a != b`] [convertible to `bool`] [Returns `!(a == b)`.] ] ] [endsect]
{ "pile_set_name": "Github" }
/* Copyright 2005-2006 Tim Fennell * * 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 net.sourceforge.stripes.mock; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.servlet.Filter; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.action.Message; import net.sourceforge.stripes.controller.ActionResolver; import net.sourceforge.stripes.controller.AnnotatedClassActionResolver; import net.sourceforge.stripes.controller.StripesConstants; import net.sourceforge.stripes.controller.StripesFilter; import net.sourceforge.stripes.controller.UrlBindingFactory; import net.sourceforge.stripes.util.CryptoUtil; import net.sourceforge.stripes.validation.ValidationErrors; /** * <p> * Mock object that attempts to make it easier to use the other Mock objects in * this package to interact with Stripes and to interrogate the results. * Everything that is done in this class is do-able without this class! It * simply exists to make things a bit easier. As a result all the methods in * this class simply manipulate one or more of the underlying Mock objects. If * some needed capability is not exposed through the MockRoundtrip it is always * possible to fetch the underlying request, response and context and interact * with them directly.</p> * * <p> * It is worth noting that the Mock system <b>does not process forwards, * includes and redirects</b>. When an ActionBean (or other object) invokes the * servlet APIs for any of these actions it is recorded so that it can be * reported and verified later. In the majority of cases it should be sufficient * to test ActionBeans in isolation and verify that they produced the expected * output data and/or forward/redirect. If your ActionBeans depend on being able * to include other resources before continuing, sorry - you're on your own!</p> * * <p> * An example usage of this class might look like:</p> * * <pre> * MockServletContext context = ...; * MockRoundtrip trip = new MockRoundtrip(context, CalculatorActionBean.class); * trip.setParameter("numberOne", "2"); * trip.setParameter("numberTwo", "2"); * trip.execute(); * CalculatorActionBean bean = trip.getActionBean(CalculatorActionBean.class); * Assert.assertEquals(bean.getResult(), 4, "two plus two should equal four"); * Assert.assertEquals(trip.getDestination(), ""/quickstart/index.jsp"); * </pre> * * @author Tim Fennell * @since Stripes 1.1.1 */ public class MockRoundtrip { /** * Default value for the source page that generated this round trip request. */ public static final String DEFAULT_SOURCE_PAGE = "_default_source_page_"; private MockHttpServletRequest request; private MockHttpServletResponse response; private MockServletContext context; /** * Preferred constructor that will manufacture a request. Uses the * ServletContext to ensure that the request's context path matches. Pulls * the UrlBinding of the ActionBean and uses that as the requst URL. * Constructs a new session for the request. * * @param context the MockServletContext that will receive this request * @param beanType a Class object representing the ActionBean that should * receive the request */ public MockRoundtrip(MockServletContext context, Class<? extends ActionBean> beanType) { this(context, beanType, new MockHttpSession(context)); } /** * Preferred constructor that will manufacture a request. Uses the * ServletContext to ensure that the request's context path matches. Pulls * the UrlBinding of the ActionBean and uses that as the requst URL. * Constructs a new session for the request. * * @param context the MockServletContext that will receive this request * @param beanType a Class object representing the ActionBean that should * receive the request * @param session */ public MockRoundtrip(MockServletContext context, Class<? extends ActionBean> beanType, MockHttpSession session) { this(context, getUrlBindingStub(beanType, context), session); } /** * Constructor that will create a request suitable for the provided servlet * context and URL. Note that in general the constructors that take an * ActionBean Class object are preferred over those that take a URL. * Constructs a new session for the request. * * @param context the MockServletContext that will receive this request * @param actionBeanUrl the url binding of the action bean */ public MockRoundtrip(MockServletContext context, String actionBeanUrl) { this(context, actionBeanUrl, new MockHttpSession(context)); } /** * Constructor that will create a request suitable for the provided servlet * context and URL. Note that in general the contructors that take an * ActionBean Class object are preferred over those that take a URL. The * request will use the provided session instead of creating a new one. * * @param context the MockServletContext that will receive this request * @param actionBeanUrl the url binding of the action bean * @param session an instance of MockHttpSession to use for the request */ public MockRoundtrip(MockServletContext context, String actionBeanUrl, MockHttpSession session) { // Look for a query string and parse out the parameters if one is present String path = actionBeanUrl; SortedMap<String, List<String>> parameters = null; int qmark = actionBeanUrl.indexOf("?"); if (qmark > 0) { path = actionBeanUrl.substring(0, qmark); if (qmark < actionBeanUrl.length()) { String query = actionBeanUrl.substring(qmark + 1); if (query != null && query.length() > 0) { parameters = new TreeMap<String, List<String>>(); for (String kv : query.split("&")) { String[] parts = kv.split("="); String key, value; if (parts.length == 1) { key = parts[0]; value = null; } else if (parts.length == 2) { key = parts[0]; value = parts[1]; } else { key = value = null; } if (key != null) { List<String> values = parameters.get(key); if (values == null) { values = new ArrayList<String>(); } values.add(value); parameters.put(key, values); } } } } } this.context = context; this.request = new MockHttpServletRequest("/" + context.getServletContextName(), path); this.request.setSession(session); this.response = new MockHttpServletResponse(); setSourcePage(DEFAULT_SOURCE_PAGE); // Add any parameters that were embedded in the given URL if (parameters != null) { for (Map.Entry<String, List<String>> entry : parameters.entrySet()) { for (String value : entry.getValue()) { addParameter(entry.getKey(), value); } } } } /** * Get the servlet request object to be used by this round trip * @return */ public MockHttpServletRequest getRequest() { return request; } /** * Set the servlet request object to be used by this round trip * @param request */ protected void setRequest(MockHttpServletRequest request) { this.request = request; } /** * Get the servlet response object to be used by this round trip * @return */ public MockHttpServletResponse getResponse() { return response; } /** * Set the servlet response object to be used by this round trip * @param response */ protected void setResponse(MockHttpServletResponse response) { this.response = response; } /** * Get the ActionBean context to be used by this round trip * @return */ public MockServletContext getContext() { return context; } /** * Set the ActionBean context to be used by this round trip * @param context */ protected void setContext(MockServletContext context) { this.context = context; } /** * Sets the named request parameter to the value or values provided. Any * existing values are wiped out and replaced with the value(s) provided. * @param name * @param value */ public void setParameter(String name, String... value) { this.request.getParameterMap().put(name, value); } /** * Adds the value provided to the set of values for the named request * parameter. If one or more values already exist they will be retained, and * the new value will be appended to the set of values. * @param name * @param value */ public void addParameter(String name, String... value) { if (this.request.getParameterValues(name) == null) { setParameter(name, value); } else { String[] oldValues = this.request.getParameterMap().get(name); String[] combined = new String[oldValues.length + value.length]; System.arraycopy(oldValues, 0, combined, 0, oldValues.length); System.arraycopy(value, 0, combined, oldValues.length, value.length); setParameter(name, combined); } } /** * All requests to Stripes that can generate validation errors are required * to supply a request parameter telling Stripes where the request came * from. If you do not supply a value for this parameter then the value of * MockRoundTrip.DEFAULT_SOURCE_PAGE will be used. * @param url */ public void setSourcePage(String url) { if (url != null) { url = CryptoUtil.encrypt(url); } setParameter(StripesConstants.URL_KEY_SOURCE_PAGE, url); } /** * Executes the request in the servlet context that was provided in the * constructor. If the request throws an Exception then that will be thrown * from this method. Otherwise, once the execution has completed you can use * the other methods on this class to examine the outcome. * @throws java.lang.Exception */ public void execute() throws Exception { this.context.acceptRequest(this.request, this.response); } /** * Executes the request in the servlet context that was provided in the * constructor. Sets up the request so that it mimics the submission of a * specific event, named by the 'event' parameter to this method. If the * request throws an Exception then that will be thrown from this method. * Otherwise, once the execution has completed you can use the other methods * on this class to examine the outcome. * @param event * @throws java.lang.Exception */ public void execute(String event) throws Exception { setParameter(event, ""); execute(); } /** * Gets the instance of the ActionBean type provided that was instantiated * by Stripes to handle the request. If a bean of this type was not * instantiated, this method will return null. * * @param <A> * @param type the Class object representing the ActionBean type expected * @return the instance of the ActionBean that was created by Stripes */ @SuppressWarnings("unchecked") public <A extends ActionBean> A getActionBean(Class<A> type) { A bean = (A) this.request.getAttribute(getUrlBinding(type, this.context)); if (bean == null) { bean = (A) this.request.getSession().getAttribute(getUrlBinding(type, this.context)); } return bean; } /** * Gets the (potentially empty) set of Validation Errors that were produced * by the request. * @return */ public ValidationErrors getValidationErrors() { ActionBean bean = (ActionBean) this.request.getAttribute(StripesConstants.REQ_ATTR_ACTION_BEAN); return bean.getContext().getValidationErrors(); } /** * Gets the {@link List} of {@link Message}s that were produced by the * request. This should be used instead of obtaining the messages from the * {@link net.sourceforge.stripes.action.ActionBeanContext} as the context * is bound to the {@link net.sourceforge.stripes.controller.FlashScope}. * * @return */ public List<Message> getMessages() { Object attribute = this.request.getAttribute(StripesConstants.REQ_ATTR_MESSAGES); if (attribute == null) { return null; } return (List<Message>) attribute; } /** * Gets, as bytes, any data that was written to the output stream associated * with the request. Note that since the Mock system does not write standard * HTTP response information (headers etc.) to the output stream, this will * be exactly what was written by the ActionBean. * @return */ public byte[] getOutputBytes() { return this.response.getOutputBytes(); } /** * Gets, as a String, any data that was written to the output stream * associated with the request. Note that since the Mock system does not * write standard HTTP response information (headers etc.) to the output * stream, this will be exactly what was written by the ActionBean. * @return */ public String getOutputString() { return this.response.getOutputString(); } /** * Gets the URL to which Stripes was directed after invoking the ActionBean. * Assumes that the request was either forwarded or redirected exactly once. * If the request was forwarded then the forwarded URL will be returned * verbatim. If the response was redirected and the redirect URL was within * the same web application, then the URL returned will exclude the context * path. I.e. the URL returned will be the same regardless of whether the * page was forwarded to or redirected to. * @return */ public String getDestination() { String forward = this.request.getForwardUrl(); String redirect = this.response.getRedirectUrl(); if (forward != null) { return forward; } else if (redirect != null) { String contextPath = this.request.getContextPath(); if (contextPath.length() > 1 && redirect.startsWith(contextPath + '/')) { redirect = redirect.substring(contextPath.length()); } } return redirect; } /** * If the request resulted in a forward, returns the URL that was forwarded * to. * @return */ public String getForwardUrl() { return this.request.getForwardUrl(); } /** * If the request resulted in a redirect, returns the URL that was * redirected to. Unlike getDestination(), the URL in this case will be the * exact URL that would have been sent to the browser (i.e. including the * servlet context). * @return */ public String getRedirectUrl() { return this.response.getRedirectUrl(); } /** * Find and return the {@link AnnotatedClassActionResolver} for the given * context. */ private static AnnotatedClassActionResolver getActionResolver(MockServletContext context) { for (Filter filter : context.getFilters()) { if (filter instanceof StripesFilter) { ActionResolver resolver = ((StripesFilter) filter).getInstanceConfiguration() .getActionResolver(); if (resolver instanceof AnnotatedClassActionResolver) { return (AnnotatedClassActionResolver) resolver; } } } return null; } /** * Find and return the {@link UrlBindingFactory} for the given context. */ private static UrlBindingFactory getUrlBindingFactory(MockServletContext context) { ActionResolver resolver = getActionResolver(context); if (resolver instanceof AnnotatedClassActionResolver) { return ((AnnotatedClassActionResolver) resolver).getUrlBindingFactory(); } return null; } /** * A helper method that fetches the UrlBinding of a class in the manner it * would be interpreted by the current context configuration. */ private static String getUrlBinding(Class<? extends ActionBean> clazz, MockServletContext context) { return getActionResolver(context).getUrlBinding(clazz); } /** * Get the URL binding for an {@link ActionBean} class up to the first * parameter. */ private static String getUrlBindingStub(Class<? extends ActionBean> clazz, MockServletContext context) { return getUrlBindingFactory(context).getBindingPrototype(clazz).getPath(); } }
{ "pile_set_name": "Github" }
"""Vera tests.""" import pyvera as pv from homeassistant.core import HomeAssistant from .common import ComponentFactory, new_simple_controller_config from tests.async_mock import MagicMock async def test_binary_sensor( hass: HomeAssistant, vera_component_factory: ComponentFactory ) -> None: """Test function.""" vera_device = MagicMock(spec=pv.VeraBinarySensor) # type: pv.VeraBinarySensor vera_device.device_id = 1 vera_device.vera_device_id = vera_device.device_id vera_device.name = "dev1" vera_device.is_tripped = False entity_id = "binary_sensor.dev1_1" component_data = await vera_component_factory.configure_component( hass=hass, controller_config=new_simple_controller_config(devices=(vera_device,)), ) update_callback = component_data.controller_data[0].update_callback vera_device.is_tripped = False update_callback(vera_device) await hass.async_block_till_done() assert hass.states.get(entity_id).state == "off" vera_device.is_tripped = True update_callback(vera_device) await hass.async_block_till_done() assert hass.states.get(entity_id).state == "on"
{ "pile_set_name": "Github" }
// NOTE: cgo can't generate struct Stat_t and struct Statfs_t yet // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_darwin.go // +build arm,darwin package unix const ( SizeofPtr = 0x4 SizeofShort = 0x2 SizeofInt = 0x4 SizeofLong = 0x4 SizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timeval32 [0]byte type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev int32 Mode uint16 Nlink uint16 Ino uint64 Uid uint32 Gid uint32 Rdev int32 Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Qspare [2]int64 } type Statfs_t struct { Bsize uint32 Iosize int32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Owner uint32 Type uint32 Flags uint32 Fssubtype uint32 Fstypename [16]int8 Mntonname [1024]int8 Mntfromname [1024]int8 Reserved [8]uint32 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Fstore_t struct { Flags uint32 Posmode int32 Offset int64 Length int64 Bytesalloc int64 } type Radvisory_t struct { Offset int64 Count int32 } type Fbootstraptransfer_t struct { Offset int64 Length uint32 Buffer *byte } type Log2phys_t struct { Flags uint32 Contigbytes int64 Devoffset int64 } type Fsid struct { Val [2]int32 } type Dirent struct { Ino uint64 Seekoff uint64 Reclen uint16 Namlen uint16 Type uint8 Name [1024]int8 _ [3]byte } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint32 Filter int16 Flags uint16 Fflags uint32 Data int32 Udata *byte } type FdSet struct { Bits [32]int32 } const ( SizeofIfMsghdr = 0x70 SizeofIfData = 0x60 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c SizeofRtMetrics = 0x38 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Data IfData } type IfData struct { Type uint8 Typelen uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 Unused1 uint8 Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Recvtiming uint32 Xmittiming uint32 Lastchange Timeval Unused2 uint32 Hwassist uint32 Reserved1 uint32 Reserved2 uint32 } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte } type IfmaMsghdr2 struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Refcount int32 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 _ [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire int32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 Filler [4]uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x8 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval Caplen uint32 Datalen uint32 Hdrlen uint16 _ [2]byte } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x2 AT_REMOVEDIR = 0x80 AT_SYMLINK_FOLLOW = 0x40 AT_SYMLINK_NOFOLLOW = 0x20 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLERR = 0x8 POLLHUP = 0x10 POLLIN = 0x1 POLLNVAL = 0x20 POLLOUT = 0x4 POLLPRI = 0x2 POLLRDBAND = 0x80 POLLRDNORM = 0x40 POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) type Utsname struct { Sysname [256]byte Nodename [256]byte Release [256]byte Version [256]byte Machine [256]byte }
{ "pile_set_name": "Github" }
DEFINED_PHASES=install preinst pretend DESCRIPTION=Group for app-emulation/lxd EAPI=7 KEYWORDS=alpha amd64 arm arm64 hppa ia64 m68k ~mips ppc ppc64 ~riscv s390 sparc x86 ~ppc-aix ~x64-cygwin ~amd64-linux ~x86-linux ~ppc-macos ~x64-macos ~x86-macos ~m68k-mint ~sparc-solaris ~sparc64-solaris ~x64-solaris ~x86-solaris SLOT=0 _eclasses_=acct-group c7c2102da2c8db70657be99a7add9c06 user 7b7fc6ec5eb1c1eee55b0609f01e7362 user-info a2abd4e2f4c3b9b06d64bf1329359a02 _md5_=4e17f1595d1bd56d16a02fbb18c9afff
{ "pile_set_name": "Github" }
(function() { if ( typeof self !== 'undefined' && !self.Prism || typeof global !== 'undefined' && !global.Prism ) { return; } var languages = { 'css': true, 'less': true, 'markup': { lang: 'markup', before: 'punctuation', inside: 'inside', root: Prism.languages.markup && Prism.languages.markup['tag'].inside['attr-value'] }, 'sass': [ { lang: 'sass', inside: 'inside', root: Prism.languages.sass && Prism.languages.sass['property-line'] }, { lang: 'sass', before: 'operator', inside: 'inside', root: Prism.languages.sass && Prism.languages.sass['variable-line'] } ], 'scss': true, 'stylus': [ { lang: 'stylus', before: 'hexcode', inside: 'rest', root: Prism.languages.stylus && Prism.languages.stylus['property-declaration'].inside }, { lang: 'stylus', before: 'hexcode', inside: 'rest', root: Prism.languages.stylus && Prism.languages.stylus['variable-declaration'].inside } ] }; Prism.hooks.add('before-highlight', function (env) { if (env.language && languages[env.language] && !languages[env.language].initialized) { var lang = languages[env.language]; if (Prism.util.type(lang) !== 'Array') { lang = [lang]; } lang.forEach(function(lang) { var before, inside, root, skip; if (lang === true) { before = 'important'; inside = env.language; lang = env.language; } else { before = lang.before || 'important'; inside = lang.inside || lang.lang; root = lang.root || Prism.languages; skip = lang.skip; lang = env.language; } if (!skip && Prism.languages[lang]) { Prism.languages.insertBefore(inside, before, { 'time': /(?:\b|\B-|(?=\B\.))\d*\.?\d+m?s\b/i }, root); env.grammar = Prism.languages[lang]; languages[env.language] = {initialized: true}; } }); } }); if (Prism.plugins.Previewer) { new Prism.plugins.Previewer('time', function(value) { var num = parseFloat(value); var unit = value.match(/[a-z]+$/i); if (!num || !unit) { return false; } unit = unit[0]; this.querySelector('circle').style.animationDuration = 2 * num + unit; return true; }, '*', function () { this._elt.innerHTML = '<svg viewBox="0 0 64 64">' + '<circle r="16" cy="32" cx="32"></circle>' + '</svg>'; }); } }());
{ "pile_set_name": "Github" }
// Compiled by ClojureScript to Go 0.0-2411 // clojure.zip // Functional hierarchical zipper, with navigation, editing, // and enumeration. See Huet // Author: Rich Hickey package zip import cljs_core "github.com/hraberg/cljs2go/cljs/core" func init() { Zipper = func(zipper *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(zipper, 4, func(branch_QMARK_ interface{}, children interface{}, make_node interface{}, root interface{}) interface{} { return cljs_core.With_meta.X_invoke_Arity2((&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{root, nil}, nil}), (&cljs_core.CljsCorePersistentArrayMap{nil, float64(3), []interface{}{(&cljs_core.CljsCoreKeyword{Ns: "zip", Name: "make-node", Fqn: "zip/make-node", X_hash: float64(1103800591)}), make_node, (&cljs_core.CljsCoreKeyword{Ns: "zip", Name: "children", Fqn: "zip/children", X_hash: float64(-940194589)}), children, (&cljs_core.CljsCoreKeyword{Ns: "zip", Name: "branch?", Fqn: "zip/branch?", X_hash: float64(-998880862)}), branch_QMARK_}, nil})) }) }(&cljs_core.AFn{}) Seq_zip = func(seq_zip *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(seq_zip, 1, func(root interface{}) interface{} { return Zipper.X_invoke_Arity4(cljs_core.Seq_QMARK_, cljs_core.Identity, func(G__1 *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(G__1, 2, func(node interface{}, children interface{}) interface{} { return cljs_core.With_meta.X_invoke_Arity2(children, cljs_core.Meta.X_invoke_Arity1(node)) }) }(&cljs_core.AFn{}), root) }) }(&cljs_core.AFn{}) Vector_zip = func(vector_zip *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(vector_zip, 1, func(root interface{}) interface{} { return Zipper.X_invoke_Arity4(cljs_core.Vector_QMARK_, cljs_core.Seq, func(G__2 *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(G__2, 2, func(node interface{}, children interface{}) interface{} { return cljs_core.With_meta.X_invoke_Arity2(cljs_core.Vec.X_invoke_Arity1(children), cljs_core.Meta.X_invoke_Arity1(node)) }) }(&cljs_core.AFn{}), root) }) }(&cljs_core.AFn{}) Xml_zip = func(xml_zip *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(xml_zip, 1, func(root interface{}) interface{} { return Zipper.X_invoke_Arity4(cljs_core.Complement.X_invoke_Arity1(cljs_core.String_QMARK_).(cljs_core.CljsCoreIFn), cljs_core.Comp.X_invoke_Arity2(cljs_core.Seq, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "content", Fqn: "content", X_hash: float64(15833224)})).(cljs_core.CljsCoreIFn), func(G__3 *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(G__3, 2, func(node interface{}, children interface{}) interface{} { return cljs_core.Assoc.X_invoke_Arity3(node, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "content", Fqn: "content", X_hash: float64(15833224)}), func() interface{} { var and__159__auto__ = children _ = and__159__auto__ if cljs_core.Truth_(and__159__auto__) { return cljs_core.Apply.X_invoke_Arity2(cljs_core.Vector, children) } else { return and__159__auto__ } }()) }) }(&cljs_core.AFn{}), root) }) }(&cljs_core.AFn{}) Node = func(node *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(node, 1, func(loc interface{}) interface{} { { var G__5 = float64(0) _ = G__5 return loc.(cljs_core.CljsCoreIFn).X_invoke_Arity1(G__5) } }) }(&cljs_core.AFn{}) Branch_QMARK_ = func(branch_QMARK_ *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(branch_QMARK_, 1, func(loc interface{}) interface{} { return (&cljs_core.CljsCoreKeyword{Ns: "zip", Name: "branch?", Fqn: "zip/branch?", X_hash: float64(-998880862)}).X_invoke_Arity1(cljs_core.Meta.X_invoke_Arity1(loc)).(cljs_core.CljsCoreIFn).X_invoke_Arity1(Node.X_invoke_Arity1(loc)) }) }(&cljs_core.AFn{}) Children = func(children *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(children, 1, func(loc interface{}) interface{} { if cljs_core.Truth_(Branch_QMARK_.X_invoke_Arity1(loc)) { return (&cljs_core.CljsCoreKeyword{Ns: "zip", Name: "children", Fqn: "zip/children", X_hash: float64(-940194589)}).X_invoke_Arity1(cljs_core.Meta.X_invoke_Arity1(loc)).(cljs_core.CljsCoreIFn).X_invoke_Arity1(Node.X_invoke_Arity1(loc)) } else { panic("called children on a leaf node") } }) }(&cljs_core.AFn{}) Make_node = func(make_node *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(make_node, 3, func(loc interface{}, node interface{}, children interface{}) interface{} { return (&cljs_core.CljsCoreKeyword{Ns: "zip", Name: "make-node", Fqn: "zip/make-node", X_hash: float64(1103800591)}).X_invoke_Arity1(cljs_core.Meta.X_invoke_Arity1(loc)).(cljs_core.CljsCoreIFn).X_invoke_Arity2(node, children) }) }(&cljs_core.AFn{}) Path = func(path *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(path, 1, func(loc interface{}) interface{} { return (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "pnodes", Fqn: "pnodes", X_hash: float64(1739080565)}).X_invoke_Arity1(func() interface{} { var G__7 = float64(1) _ = G__7 return loc.(cljs_core.CljsCoreIFn).X_invoke_Arity1(G__7) }()) }) }(&cljs_core.AFn{}) Lefts = func(lefts *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(lefts, 1, func(loc interface{}) interface{} { return cljs_core.Seq.Arity1IQ((&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)}).X_invoke_Arity1(func() interface{} { var G__9 = float64(1) _ = G__9 return loc.(cljs_core.CljsCoreIFn).X_invoke_Arity1(G__9) }())) }) }(&cljs_core.AFn{}) Rights = func(rights *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(rights, 1, func(loc interface{}) interface{} { return (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)}).X_invoke_Arity1(func() interface{} { var G__11 = float64(1) _ = G__11 return loc.(cljs_core.CljsCoreIFn).X_invoke_Arity1(G__11) }()) }) }(&cljs_core.AFn{}) Down = func(down *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(down, 1, func(loc interface{}) interface{} { if cljs_core.Truth_(Branch_QMARK_.X_invoke_Arity1(loc)) { { var vec__14 = loc var node = cljs_core.Nth.X_invoke_Arity3(vec__14, float64(0), nil) var path = cljs_core.Nth.X_invoke_Arity3(vec__14, float64(1), nil) var vec__15 = Children.X_invoke_Arity1(loc) var c = cljs_core.Nth.X_invoke_Arity3(vec__15, float64(0), nil) var cnext = cljs_core.Seq_(cljs_core.Nthnext.X_invoke_Arity2(vec__15, float64(1))) var cs = vec__15 _, _, _, _, _, _, _ = vec__14, node, path, vec__15, c, cnext, cs if cljs_core.Truth_(cs) { return cljs_core.With_meta.X_invoke_Arity2((&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{c, (&cljs_core.CljsCorePersistentArrayMap{nil, float64(4), []interface{}{(&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)}), cljs_core.CljsCorePersistentVector_EMPTY, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "pnodes", Fqn: "pnodes", X_hash: float64(1739080565)}), func() interface{} { if cljs_core.Truth_(path) { return cljs_core.Conj.X_invoke_Arity2((&cljs_core.CljsCoreKeyword{Ns: nil, Name: "pnodes", Fqn: "pnodes", X_hash: float64(1739080565)}).X_invoke_Arity1(path), node) } else { return (&cljs_core.CljsCorePersistentVector{nil, float64(1), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{node}, nil}) } }(), (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "ppath", Fqn: "ppath", X_hash: float64(-1758182784)}), path, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)}), cnext}, nil})}, nil}), cljs_core.Meta.X_invoke_Arity1(loc)) } else { return nil } } } else { return nil } }) }(&cljs_core.AFn{}) Up = func(up *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(up, 1, func(loc interface{}) interface{} { { var vec__18 = loc var node = cljs_core.Nth.X_invoke_Arity3(vec__18, float64(0), nil) var map__19 = cljs_core.Nth.X_invoke_Arity3(vec__18, float64(1), nil) var map__19___1 = func() interface{} { if cljs_core.Seq_QMARK_.Arity1IB(map__19) { return cljs_core.Apply.X_invoke_Arity2(cljs_core.Hash_map, map__19) } else { return map__19 } }() var path = map__19___1 var l = cljs_core.Get.X_invoke_Arity2(map__19___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)})) var ppath = cljs_core.Get.X_invoke_Arity2(map__19___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "ppath", Fqn: "ppath", X_hash: float64(-1758182784)})) var pnodes = cljs_core.Get.X_invoke_Arity2(map__19___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "pnodes", Fqn: "pnodes", X_hash: float64(1739080565)})) var r = cljs_core.Get.X_invoke_Arity2(map__19___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)})) var changed_QMARK_ = cljs_core.Get.X_invoke_Arity2(map__19___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "changed?", Fqn: "changed?", X_hash: float64(-437828330)})) _, _, _, _, _, _, _, _, _, _ = vec__18, node, map__19, map__19___1, path, l, ppath, pnodes, r, changed_QMARK_ if cljs_core.Truth_(pnodes) { { var pnode = cljs_core.Peek.X_invoke_Arity1(pnodes) _ = pnode return cljs_core.With_meta.X_invoke_Arity2(func() cljs_core.CljsCoreIVector { if cljs_core.Truth_(changed_QMARK_) { return (&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{Make_node.X_invoke_Arity3(loc, pnode, cljs_core.Concat.X_invoke_Arity2(l, cljs_core.Cons.X_invoke_Arity2(node, r).(*cljs_core.CljsCoreCons)).(*cljs_core.CljsCoreLazySeq)), func() interface{} { var and__159__auto__ = ppath _ = and__159__auto__ if cljs_core.Truth_(and__159__auto__) { return cljs_core.Assoc.X_invoke_Arity3(ppath, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "changed?", Fqn: "changed?", X_hash: float64(-437828330)}), true) } else { return and__159__auto__ } }()}, nil}) } else { return (&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{pnode, ppath}, nil}) } }(), cljs_core.Meta.X_invoke_Arity1(loc)) } } else { return nil } } }) }(&cljs_core.AFn{}) Root = func(root *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(root, 1, func(loc interface{}) interface{} { for { if cljs_core.X_EQ_.Arity2IIB((&cljs_core.CljsCoreKeyword{Ns: nil, Name: "end", Fqn: "end", X_hash: float64(-268185958)}), func() interface{} { var G__21 = float64(1) _ = G__21 return loc.(cljs_core.CljsCoreIFn).X_invoke_Arity1(G__21) }()) { return Node.X_invoke_Arity1(loc) } else { { var p = Up.X_invoke_Arity1(loc) _ = p if cljs_core.Truth_(p) { loc = p continue } else { return Node.X_invoke_Arity1(loc) } } } } }) }(&cljs_core.AFn{}) Right = func(right *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(right, 1, func(loc interface{}) interface{} { { var vec__25 = loc var node = cljs_core.Nth.X_invoke_Arity3(vec__25, float64(0), nil) var map__26 = cljs_core.Nth.X_invoke_Arity3(vec__25, float64(1), nil) var map__26___1 = func() interface{} { if cljs_core.Seq_QMARK_.Arity1IB(map__26) { return cljs_core.Apply.X_invoke_Arity2(cljs_core.Hash_map, map__26) } else { return map__26 } }() var path = map__26___1 var l = cljs_core.Get.X_invoke_Arity2(map__26___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)})) var vec__27 = cljs_core.Get.X_invoke_Arity2(map__26___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)})) var r = cljs_core.Nth.X_invoke_Arity3(vec__27, float64(0), nil) var rnext = cljs_core.Seq_(cljs_core.Nthnext.X_invoke_Arity2(vec__27, float64(1))) var rs = vec__27 _, _, _, _, _, _, _, _, _, _ = vec__25, node, map__26, map__26___1, path, l, vec__27, r, rnext, rs if cljs_core.Truth_(func() interface{} { var and__159__auto__ = path _ = and__159__auto__ if cljs_core.Truth_(and__159__auto__) { return rs } else { return and__159__auto__ } }()) { return cljs_core.With_meta.X_invoke_Arity2((&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{r, cljs_core.Assoc.X_invoke_ArityVariadic(path, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)}), cljs_core.Conj.X_invoke_Arity2(l, node), cljs_core.Array_seq.X_invoke_Arity1([]interface{}{(&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)}), rnext}))}, nil}), cljs_core.Meta.X_invoke_Arity1(loc)) } else { return nil } } }) }(&cljs_core.AFn{}) Rightmost = func(rightmost *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(rightmost, 1, func(loc interface{}) interface{} { { var vec__30 = loc var node = cljs_core.Nth.X_invoke_Arity3(vec__30, float64(0), nil) var map__31 = cljs_core.Nth.X_invoke_Arity3(vec__30, float64(1), nil) var map__31___1 = func() interface{} { if cljs_core.Seq_QMARK_.Arity1IB(map__31) { return cljs_core.Apply.X_invoke_Arity2(cljs_core.Hash_map, map__31) } else { return map__31 } }() var path = map__31___1 var l = cljs_core.Get.X_invoke_Arity2(map__31___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)})) var r = cljs_core.Get.X_invoke_Arity2(map__31___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)})) _, _, _, _, _, _, _ = vec__30, node, map__31, map__31___1, path, l, r if cljs_core.Truth_(func() interface{} { var and__159__auto__ = path _ = and__159__auto__ if cljs_core.Truth_(and__159__auto__) { return r } else { return and__159__auto__ } }()) { return cljs_core.With_meta.X_invoke_Arity2((&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{cljs_core.Last.X_invoke_Arity1(r), cljs_core.Assoc.X_invoke_ArityVariadic(path, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)}), cljs_core.Apply.X_invoke_Arity4(cljs_core.Conj, l, node, cljs_core.Seq_(cljs_core.Butlast.X_invoke_Arity1(r))), cljs_core.Array_seq.X_invoke_Arity1([]interface{}{(&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)}), nil}))}, nil}), cljs_core.Meta.X_invoke_Arity1(loc)) } else { return loc } } }) }(&cljs_core.AFn{}) Left = func(left *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(left, 1, func(loc interface{}) interface{} { { var vec__34 = loc var node = cljs_core.Nth.X_invoke_Arity3(vec__34, float64(0), nil) var map__35 = cljs_core.Nth.X_invoke_Arity3(vec__34, float64(1), nil) var map__35___1 = func() interface{} { if cljs_core.Seq_QMARK_.Arity1IB(map__35) { return cljs_core.Apply.X_invoke_Arity2(cljs_core.Hash_map, map__35) } else { return map__35 } }() var path = map__35___1 var l = cljs_core.Get.X_invoke_Arity2(map__35___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)})) var r = cljs_core.Get.X_invoke_Arity2(map__35___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)})) _, _, _, _, _, _, _ = vec__34, node, map__35, map__35___1, path, l, r if cljs_core.Truth_(func() interface{} { var and__159__auto__ = path _ = and__159__auto__ if cljs_core.Truth_(and__159__auto__) { return cljs_core.Seq.Arity1IQ(l) } else { return and__159__auto__ } }()) { return cljs_core.With_meta.X_invoke_Arity2((&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{cljs_core.Peek.X_invoke_Arity1(l), cljs_core.Assoc.X_invoke_ArityVariadic(path, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)}), cljs_core.Pop.X_invoke_Arity1(l), cljs_core.Array_seq.X_invoke_Arity1([]interface{}{(&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)}), cljs_core.Cons.X_invoke_Arity2(node, r).(*cljs_core.CljsCoreCons)}))}, nil}), cljs_core.Meta.X_invoke_Arity1(loc)) } else { return nil } } }) }(&cljs_core.AFn{}) Leftmost = func(leftmost *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(leftmost, 1, func(loc interface{}) interface{} { { var vec__38 = loc var node = cljs_core.Nth.X_invoke_Arity3(vec__38, float64(0), nil) var map__39 = cljs_core.Nth.X_invoke_Arity3(vec__38, float64(1), nil) var map__39___1 = func() interface{} { if cljs_core.Seq_QMARK_.Arity1IB(map__39) { return cljs_core.Apply.X_invoke_Arity2(cljs_core.Hash_map, map__39) } else { return map__39 } }() var path = map__39___1 var l = cljs_core.Get.X_invoke_Arity2(map__39___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)})) var r = cljs_core.Get.X_invoke_Arity2(map__39___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)})) _, _, _, _, _, _, _ = vec__38, node, map__39, map__39___1, path, l, r if cljs_core.Truth_(func() interface{} { var and__159__auto__ = path _ = and__159__auto__ if cljs_core.Truth_(and__159__auto__) { return cljs_core.Seq.Arity1IQ(l) } else { return and__159__auto__ } }()) { return cljs_core.With_meta.X_invoke_Arity2((&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{cljs_core.First.X_invoke_Arity1(l), cljs_core.Assoc.X_invoke_ArityVariadic(path, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)}), cljs_core.CljsCorePersistentVector_EMPTY, cljs_core.Array_seq.X_invoke_Arity1([]interface{}{(&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)}), cljs_core.Concat.X_invoke_ArityVariadic(cljs_core.Rest.Arity1IQ(l), (&cljs_core.CljsCorePersistentVector{nil, float64(1), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{node}, nil}), cljs_core.Array_seq.X_invoke_Arity1([]interface{}{r})).(*cljs_core.CljsCoreLazySeq)}))}, nil}), cljs_core.Meta.X_invoke_Arity1(loc)) } else { return loc } } }) }(&cljs_core.AFn{}) Insert_left = func(insert_left *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(insert_left, 2, func(loc interface{}, item interface{}) interface{} { { var vec__42 = loc var node = cljs_core.Nth.X_invoke_Arity3(vec__42, float64(0), nil) var map__43 = cljs_core.Nth.X_invoke_Arity3(vec__42, float64(1), nil) var map__43___1 = func() interface{} { if cljs_core.Seq_QMARK_.Arity1IB(map__43) { return cljs_core.Apply.X_invoke_Arity2(cljs_core.Hash_map, map__43) } else { return map__43 } }() var path = map__43___1 var l = cljs_core.Get.X_invoke_Arity2(map__43___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)})) _, _, _, _, _, _ = vec__42, node, map__43, map__43___1, path, l if cljs_core.Nil_(path) { panic("Insert at top") } else { return cljs_core.With_meta.X_invoke_Arity2((&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{node, cljs_core.Assoc.X_invoke_ArityVariadic(path, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)}), cljs_core.Conj.X_invoke_Arity2(l, item), cljs_core.Array_seq.X_invoke_Arity1([]interface{}{(&cljs_core.CljsCoreKeyword{Ns: nil, Name: "changed?", Fqn: "changed?", X_hash: float64(-437828330)}), true}))}, nil}), cljs_core.Meta.X_invoke_Arity1(loc)) } } }) }(&cljs_core.AFn{}) Insert_right = func(insert_right *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(insert_right, 2, func(loc interface{}, item interface{}) interface{} { { var vec__46 = loc var node = cljs_core.Nth.X_invoke_Arity3(vec__46, float64(0), nil) var map__47 = cljs_core.Nth.X_invoke_Arity3(vec__46, float64(1), nil) var map__47___1 = func() interface{} { if cljs_core.Seq_QMARK_.Arity1IB(map__47) { return cljs_core.Apply.X_invoke_Arity2(cljs_core.Hash_map, map__47) } else { return map__47 } }() var path = map__47___1 var r = cljs_core.Get.X_invoke_Arity2(map__47___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)})) _, _, _, _, _, _ = vec__46, node, map__47, map__47___1, path, r if cljs_core.Nil_(path) { panic("Insert at top") } else { return cljs_core.With_meta.X_invoke_Arity2((&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{node, cljs_core.Assoc.X_invoke_ArityVariadic(path, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)}), cljs_core.Cons.X_invoke_Arity2(item, r).(*cljs_core.CljsCoreCons), cljs_core.Array_seq.X_invoke_Arity1([]interface{}{(&cljs_core.CljsCoreKeyword{Ns: nil, Name: "changed?", Fqn: "changed?", X_hash: float64(-437828330)}), true}))}, nil}), cljs_core.Meta.X_invoke_Arity1(loc)) } } }) }(&cljs_core.AFn{}) Replace = func(replace *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(replace, 2, func(loc interface{}, node interface{}) interface{} { { var vec__49 = loc var ___ = cljs_core.Nth.X_invoke_Arity3(vec__49, float64(0), nil) var path = cljs_core.Nth.X_invoke_Arity3(vec__49, float64(1), nil) _, _, _ = vec__49, ___, path return cljs_core.With_meta.X_invoke_Arity2((&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{node, cljs_core.Assoc.X_invoke_Arity3(path, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "changed?", Fqn: "changed?", X_hash: float64(-437828330)}), true)}, nil}), cljs_core.Meta.X_invoke_Arity1(loc)) } }) }(&cljs_core.AFn{}) Edit = func(edit *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(edit, 2, func(loc_f_args__ ...interface{}) interface{} { var loc = loc_f_args__[0] var f = loc_f_args__[1] var args = cljs_core.Seq.Arity1IQ(loc_f_args__[2]) _, _, _ = loc, f, args return Replace.X_invoke_Arity2(loc, cljs_core.Apply.X_invoke_Arity3(f, Node.X_invoke_Arity1(loc), args)) }) }(&cljs_core.AFn{}) Insert_child = func(insert_child *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(insert_child, 2, func(loc interface{}, item interface{}) interface{} { return Replace.X_invoke_Arity2(loc, Make_node.X_invoke_Arity3(loc, Node.X_invoke_Arity1(loc), cljs_core.Cons.X_invoke_Arity2(item, Children.X_invoke_Arity1(loc)).(*cljs_core.CljsCoreCons))) }) }(&cljs_core.AFn{}) Append_child = func(append_child *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(append_child, 2, func(loc interface{}, item interface{}) interface{} { return Replace.X_invoke_Arity2(loc, Make_node.X_invoke_Arity3(loc, Node.X_invoke_Arity1(loc), cljs_core.Concat.X_invoke_Arity2(Children.X_invoke_Arity1(loc), (&cljs_core.CljsCorePersistentVector{nil, float64(1), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{item}, nil})).(*cljs_core.CljsCoreLazySeq))) }) }(&cljs_core.AFn{}) Next = func(next *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(next, 1, func(loc interface{}) interface{} { if cljs_core.X_EQ_.Arity2IIB((&cljs_core.CljsCoreKeyword{Ns: nil, Name: "end", Fqn: "end", X_hash: float64(-268185958)}), func() interface{} { var G__51 = float64(1) _ = G__51 return loc.(cljs_core.CljsCoreIFn).X_invoke_Arity1(G__51) }()) { return loc } else { { var or__171__auto__ = func() interface{} { var and__159__auto__ = Branch_QMARK_.X_invoke_Arity1(loc) _ = and__159__auto__ if cljs_core.Truth_(and__159__auto__) { return Down.X_invoke_Arity1(loc) } else { return and__159__auto__ } }() _ = or__171__auto__ if cljs_core.Truth_(or__171__auto__) { return or__171__auto__ } else { { var or__171__auto_____1 = Right.X_invoke_Arity1(loc) _ = or__171__auto_____1 if cljs_core.Truth_(or__171__auto_____1) { return or__171__auto_____1 } else { { var p interface{} = loc _ = p for { if cljs_core.Truth_(Up.X_invoke_Arity1(p)) { { var or__171__auto_____2 = Right.X_invoke_Arity1(Up.X_invoke_Arity1(p)) _ = or__171__auto_____2 if cljs_core.Truth_(or__171__auto_____2) { return or__171__auto_____2 } else { p = Up.X_invoke_Arity1(p) continue } } } else { return (&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{Node.X_invoke_Arity1(p), (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "end", Fqn: "end", X_hash: float64(-268185958)})}, nil}) } } } } } } } } }) }(&cljs_core.AFn{}) Prev = func(prev *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(prev, 1, func(loc interface{}) interface{} { { var temp__4386__auto__ = Left.X_invoke_Arity1(loc) _ = temp__4386__auto__ if cljs_core.Truth_(temp__4386__auto__) { { var lloc = temp__4386__auto__ _ = lloc { var loc___1 interface{} = lloc _ = loc___1 for { { var temp__4386__auto_____1 = func() interface{} { var and__159__auto__ = Branch_QMARK_.X_invoke_Arity1(loc___1) _ = and__159__auto__ if cljs_core.Truth_(and__159__auto__) { return Down.X_invoke_Arity1(loc___1) } else { return and__159__auto__ } }() _ = temp__4386__auto_____1 if cljs_core.Truth_(temp__4386__auto_____1) { { var child = temp__4386__auto_____1 _ = child loc___1 = Rightmost.X_invoke_Arity1(child) continue } } else { return loc___1 } } } } } } else { return Up.X_invoke_Arity1(loc) } } }) }(&cljs_core.AFn{}) End_QMARK_ = func(end_QMARK_ *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(end_QMARK_, 1, func(loc interface{}) interface{} { return cljs_core.X_EQ_.Arity2IIB((&cljs_core.CljsCoreKeyword{Ns: nil, Name: "end", Fqn: "end", X_hash: float64(-268185958)}), func() interface{} { var G__53 = float64(1) _ = G__53 return loc.(cljs_core.CljsCoreIFn).X_invoke_Arity1(G__53) }()) }) }(&cljs_core.AFn{}) Remove = func(remove *cljs_core.AFn) *cljs_core.AFn { return cljs_core.Fn(remove, 1, func(loc interface{}) interface{} { { var vec__56 = loc var node = cljs_core.Nth.X_invoke_Arity3(vec__56, float64(0), nil) var map__57 = cljs_core.Nth.X_invoke_Arity3(vec__56, float64(1), nil) var map__57___1 = func() interface{} { if cljs_core.Seq_QMARK_.Arity1IB(map__57) { return cljs_core.Apply.X_invoke_Arity2(cljs_core.Hash_map, map__57) } else { return map__57 } }() var path = map__57___1 var l = cljs_core.Get.X_invoke_Arity2(map__57___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)})) var ppath = cljs_core.Get.X_invoke_Arity2(map__57___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "ppath", Fqn: "ppath", X_hash: float64(-1758182784)})) var pnodes = cljs_core.Get.X_invoke_Arity2(map__57___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "pnodes", Fqn: "pnodes", X_hash: float64(1739080565)})) var rs = cljs_core.Get.X_invoke_Arity2(map__57___1, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "r", Fqn: "r", X_hash: float64(-471384190)})) _, _, _, _, _, _, _, _, _ = vec__56, node, map__57, map__57___1, path, l, ppath, pnodes, rs if cljs_core.Nil_(path) { panic("Remove at top") } else { if cljs_core.Count.X_invoke_Arity1(l).(float64) > float64(0) { { var loc___1 interface{} = cljs_core.With_meta.X_invoke_Arity2((&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{cljs_core.Peek.X_invoke_Arity1(l), cljs_core.Assoc.X_invoke_ArityVariadic(path, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "l", Fqn: "l", X_hash: float64(1395893423)}), cljs_core.Pop.X_invoke_Arity1(l), cljs_core.Array_seq.X_invoke_Arity1([]interface{}{(&cljs_core.CljsCoreKeyword{Ns: nil, Name: "changed?", Fqn: "changed?", X_hash: float64(-437828330)}), true}))}, nil}), cljs_core.Meta.X_invoke_Arity1(loc)) _ = loc___1 for { { var temp__4386__auto__ = func() interface{} { var and__159__auto__ = Branch_QMARK_.X_invoke_Arity1(loc___1) _ = and__159__auto__ if cljs_core.Truth_(and__159__auto__) { return Down.X_invoke_Arity1(loc___1) } else { return and__159__auto__ } }() _ = temp__4386__auto__ if cljs_core.Truth_(temp__4386__auto__) { { var child = temp__4386__auto__ _ = child loc___1 = Rightmost.X_invoke_Arity1(child) continue } } else { return loc___1 } } } } } else { return cljs_core.With_meta.X_invoke_Arity2((&cljs_core.CljsCorePersistentVector{nil, float64(2), float64(5), cljs_core.CljsCorePersistentVector_EMPTY_NODE, []interface{}{Make_node.X_invoke_Arity3(loc, cljs_core.Peek.X_invoke_Arity1(pnodes), rs), func() interface{} { var and__159__auto__ = ppath _ = and__159__auto__ if cljs_core.Truth_(and__159__auto__) { return cljs_core.Assoc.X_invoke_Arity3(ppath, (&cljs_core.CljsCoreKeyword{Ns: nil, Name: "changed?", Fqn: "changed?", X_hash: float64(-437828330)}), true) } else { return and__159__auto__ } }()}, nil}), cljs_core.Meta.X_invoke_Arity1(loc)) } } } }) }(&cljs_core.AFn{}) } // Creates a new zipper structure. // // branch? is a fn that, given a node, returns true if can have // children, even if it currently doesn't. // // children is a fn that, given a branch node, returns a seq of its // children. // // make-node is a fn that, given an existing node and a seq of // children, returns a new branch node with the supplied children. // root is the root node. var Zipper *cljs_core.AFn // Returns a zipper for nested sequences, given a root sequence var Seq_zip *cljs_core.AFn // Returns a zipper for nested vectors, given a root vector var Vector_zip *cljs_core.AFn // Returns a zipper for xml elements (as from xml/parse), // given a root element var Xml_zip *cljs_core.AFn // Returns the node at loc var Node *cljs_core.AFn // Returns true if the node at loc is a branch var Branch_QMARK_ *cljs_core.AFn // Returns a seq of the children of node at loc, which must be a branch var Children *cljs_core.AFn // Returns a new branch node, given an existing node and new // children. The loc is only used to supply the constructor. var Make_node *cljs_core.AFn // Returns a seq of nodes leading to this loc var Path *cljs_core.AFn // Returns a seq of the left siblings of this loc var Lefts *cljs_core.AFn // Returns a seq of the right siblings of this loc var Rights *cljs_core.AFn // Returns the loc of the leftmost child of the node at this loc, or // nil if no children var Down *cljs_core.AFn // Returns the loc of the parent of the node at this loc, or nil if at // the top var Up *cljs_core.AFn // zips all the way up and returns the root node, reflecting any // changes. var Root *cljs_core.AFn // Returns the loc of the right sibling of the node at this loc, or nil var Right *cljs_core.AFn // Returns the loc of the rightmost sibling of the node at this loc, or self var Rightmost *cljs_core.AFn // Returns the loc of the left sibling of the node at this loc, or nil var Left *cljs_core.AFn // Returns the loc of the leftmost sibling of the node at this loc, or self var Leftmost *cljs_core.AFn // Inserts the item as the left sibling of the node at this loc, // without moving var Insert_left *cljs_core.AFn // Inserts the item as the right sibling of the node at this loc, // without moving var Insert_right *cljs_core.AFn // Replaces the node at this loc, without moving var Replace *cljs_core.AFn // Replaces the node at this loc with the value of (f node args) // @param {...*} var_args var Edit *cljs_core.AFn // Inserts the item as the leftmost child of the node at this loc, // without moving var Insert_child *cljs_core.AFn // Inserts the item as the rightmost child of the node at this loc, // without moving var Append_child *cljs_core.AFn // Moves to the next loc in the hierarchy, depth-first. When reaching // the end, returns a distinguished loc detectable via end?. If already // at the end, stays there. var Next *cljs_core.AFn // Moves to the previous loc in the hierarchy, depth-first. If already // at the root, returns nil. var Prev *cljs_core.AFn // Returns true if loc represents the end of a depth-first walk var End_QMARK_ *cljs_core.AFn // Removes the node at loc, returning the loc that would have preceded // it in a depth-first walk. var Remove *cljs_core.AFn
{ "pile_set_name": "Github" }
package deployer import ( "github.com/coinbase/step/aws" "github.com/coinbase/step/handler" "github.com/coinbase/step/machine" ) // StateMachine returns the StateMachine for the deployer func StateMachine() (*machine.StateMachine, error) { return machine.FromJSON([]byte(`{ "Comment": "Step Function Deployer", "StartAt": "Validate", "States": { "Validate": { "Type": "TaskFn", "Resource": "arn:aws:lambda:{{aws_region}}:{{aws_account}}:function:{{lambda_name}}", "Comment": "Validate and Set Defaults", "Next": "Lock", "Catch": [ { "Comment": "Bad Release or Error GoTo end", "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "FailureClean" } ] }, "Lock": { "Type": "TaskFn", "Resource": "arn:aws:lambda:{{aws_region}}:{{aws_account}}:function:{{lambda_name}}", "Comment": "Grab Lock", "Next": "ValidateResources", "Catch": [ { "Comment": "Something else is deploying", "ErrorEquals": ["LockExistsError"], "ResultPath": "$.error", "Next": "FailureClean" }, { "Comment": "Try Release Lock Then Fail", "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "ReleaseLockFailure" } ] }, "ValidateResources": { "Type": "TaskFn", "Resource": "arn:aws:lambda:{{aws_region}}:{{aws_account}}:function:{{lambda_name}}", "Comment": "ValidateResources", "Next": "Deploy", "Catch": [ { "Comment": "Try Release Lock Then Fail", "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "ReleaseLockFailure" } ] }, "Deploy": { "Type": "TaskFn", "Resource": "arn:aws:lambda:{{aws_region}}:{{aws_account}}:function:{{lambda_name}}", "Comment": "Upload Step-Function and Lambda", "Next": "Success", "Catch": [ { "Comment": "Unsure of State, Leave Lock and Fail", "ErrorEquals": ["DeploySFNError"], "ResultPath": "$.error", "Next": "ReleaseLockFailure" }, { "Comment": "Unsure of State, Leave Lock and Fail", "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "FailureDirty" } ] }, "ReleaseLockFailure": { "Type": "TaskFn", "Resource": "arn:aws:lambda:{{aws_region}}:{{aws_account}}:function:{{lambda_name}}", "Comment": "Release the Lock and Fail", "Next": "FailureClean", "Retry": [ { "Comment": "Keep trying to Release", "ErrorEquals": ["States.ALL"], "MaxAttempts": 3, "IntervalSeconds": 30 }], "Catch": [{ "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "FailureDirty" }] }, "FailureClean": { "Comment": "Deploy Failed Cleanly", "Type": "Fail", "Error": "NotifyError" }, "FailureDirty": { "Comment": "Deploy Failed, Resources left in Bad State, ALERT!", "Type": "Fail", "Error": "AlertError" }, "Success": { "Type": "Succeed" } } }`)) } // TaskHandlers returns func TaskHandlers() *handler.TaskHandlers { return CreateTaskFunctions(&aws.Clients{}) } // CreateTaskFunctions returns func CreateTaskFunctions(awsc aws.AwsClients) *handler.TaskHandlers { tm := handler.TaskHandlers{} tm["Validate"] = ValidateHandler(awsc) tm["Lock"] = LockHandler(awsc) tm["ValidateResources"] = ValidateResourcesHandler(awsc) tm["Deploy"] = DeployHandler(awsc) tm["ReleaseLockFailure"] = ReleaseLockFailureHandler(awsc) return &tm }
{ "pile_set_name": "Github" }
#include "CondFormats/RPCObjects/interface/RPCDCCLinkMap.h" RPCDCCLinkMap::RPCDCCLinkMap() {}
{ "pile_set_name": "Github" }
#!/bin/sh cleandig google-alias.example.com A hidettl cleandig google-alias.example.com AAAA hidettl cleandig google-alias.example.com A hidettl tcp cleandig google-alias.example.com AAAA hidettl tcp
{ "pile_set_name": "Github" }
package org.orcid.core.manager.read_only; import java.util.Optional; import org.orcid.jaxb.model.groupid_v2.GroupIdRecord; import org.orcid.jaxb.model.groupid_v2.GroupIdRecords; public interface GroupIdRecordManagerReadOnly { GroupIdRecord getGroupIdRecord(Long putCode); GroupIdRecords getGroupIdRecords(String pageSize, String pageNum); boolean exists(String groupId); Optional<GroupIdRecord> findByGroupId(String groupId); Optional<GroupIdRecord> findGroupIdRecordByName(String name); }
{ "pile_set_name": "Github" }
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ #include "apr.h" #include "apr_strings.h" #include "apr_private.h" #include "apr_lib.h" #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_STRING_H #include <string.h> #endif #if APR_HAVE_CTYPE_H #include <ctype.h> #endif /* * Apache's "replacement" for the strncpy() function. We roll our * own to implement these specific changes: * (1) strncpy() doesn't always null terminate and we want it to. * (2) strncpy() null fills, which is bogus, esp. when copy 8byte * strings into 8k blocks. * (3) Instead of returning the pointer to the beginning of * the destination string, we return a pointer to the * terminating '\0' to allow us to "check" for truncation * * apr_cpystrn() follows the same call structure as strncpy(). */ APR_DECLARE(char *) apr_cpystrn(char *dst, const char *src, apr_size_t dst_size) { char *d, *end; if (dst_size == 0) { return (dst); } d = dst; end = dst + dst_size - 1; for (; d < end; ++d, ++src) { if (!(*d = *src)) { return (d); } } *d = '\0'; /* always null terminate */ return (d); } /* * This function provides a way to parse a generic argument string * into a standard argv[] form of argument list. It respects the * usual "whitespace" and quoteing rules. In the future this could * be expanded to include support for the apr_call_exec command line * string processing (including converting '+' to ' ' and doing the * url processing. It does not currently support this function. * * token_context: Context from which pool allocations will occur. * arg_str: Input argument string for conversion to argv[]. * argv_out: Output location. This is a pointer to an array * of pointers to strings (ie. &(char *argv[]). * This value will be allocated from the contexts * pool and filled in with copies of the tokens * found during parsing of the arg_str. */ APR_DECLARE(apr_status_t) apr_tokenize_to_argv(const char *arg_str, char ***argv_out, apr_pool_t *token_context) { const char *cp; const char *ct; char *cleaned, *dirty; int escaped; int isquoted, numargs = 0, argnum; #define SKIP_WHITESPACE(cp) \ for ( ; *cp == ' ' || *cp == '\t'; ) { \ cp++; \ }; #define CHECK_QUOTATION(cp,isquoted) \ isquoted = 0; \ if (*cp == '"') { \ isquoted = 1; \ cp++; \ } \ else if (*cp == '\'') { \ isquoted = 2; \ cp++; \ } /* DETERMINE_NEXTSTRING: * At exit, cp will point to one of the following: NULL, SPACE, TAB or QUOTE. * NULL implies the argument string has been fully traversed. */ #define DETERMINE_NEXTSTRING(cp,isquoted) \ for ( ; *cp != '\0'; cp++) { \ if ( (*cp == '\\' && (*(cp+1) == ' ' || *(cp+1) == '\t' || \ *(cp+1) == '"' || *(cp+1) == '\''))) { \ cp++; \ continue; \ } \ if ( (!isquoted && (*cp == ' ' || *cp == '\t')) \ || (isquoted == 1 && *cp == '"') \ || (isquoted == 2 && *cp == '\'') ) { \ break; \ } \ } /* REMOVE_ESCAPE_CHARS: * Compresses the arg string to remove all of the '\' escape chars. * The final argv strings should not have any extra escape chars in it. */ #define REMOVE_ESCAPE_CHARS(cleaned, dirty, escaped) \ escaped = 0; \ while(*dirty) { \ if (!escaped && *dirty == '\\') { \ escaped = 1; \ } \ else { \ escaped = 0; \ *cleaned++ = *dirty; \ } \ ++dirty; \ } \ *cleaned = 0; /* last line of macro... */ cp = arg_str; SKIP_WHITESPACE(cp); ct = cp; /* This is ugly and expensive, but if anyone wants to figure a * way to support any number of args without counting and * allocating, please go ahead and change the code. * * Must account for the trailing NULL arg. */ numargs = 1; while (*ct != '\0') { CHECK_QUOTATION(ct, isquoted); DETERMINE_NEXTSTRING(ct, isquoted); if (*ct != '\0') { ct++; } numargs++; SKIP_WHITESPACE(ct); } *argv_out = apr_palloc(token_context, numargs * sizeof(char*)); /* determine first argument */ for (argnum = 0; argnum < (numargs-1); argnum++) { SKIP_WHITESPACE(cp); CHECK_QUOTATION(cp, isquoted); ct = cp; DETERMINE_NEXTSTRING(cp, isquoted); cp++; (*argv_out)[argnum] = apr_palloc(token_context, cp - ct); apr_cpystrn((*argv_out)[argnum], ct, cp - ct); cleaned = dirty = (*argv_out)[argnum]; REMOVE_ESCAPE_CHARS(cleaned, dirty, escaped); } (*argv_out)[argnum] = NULL; return APR_SUCCESS; } /* Filepath_name_get returns the final element of the pathname. * Using the current platform's filename syntax. * "/foo/bar/gum" -> "gum" * "/foo/bar/gum/" -> "" * "gum" -> "gum" * "wi\\n32\\stuff" -> "stuff * * Corrected Win32 to accept "a/b\\stuff", "a:stuff" */ APR_DECLARE(const char *) apr_filepath_name_get(const char *pathname) { const char path_separator = '/'; const char *s = strrchr(pathname, path_separator); #ifdef WIN32 const char path_separator_win = '\\'; const char drive_separator_win = ':'; const char *s2 = strrchr(pathname, path_separator_win); if (s2 > s) s = s2; if (!s) s = strrchr(pathname, drive_separator_win); #endif return s ? ++s : pathname; } /* length of dest assumed >= length of src * collapse in place (src == dest) is legal. * returns terminating null ptr to dest string. */ APR_DECLARE(char *) apr_collapse_spaces(char *dest, const char *src) { while (*src) { if (!apr_isspace(*src)) *dest++ = *src; ++src; } *dest = 0; return (dest); } #if !APR_HAVE_STRDUP char *strdup(const char *str) { char *sdup; size_t len = strlen(str) + 1; sdup = (char *) malloc(len); memcpy(sdup, str, len); return sdup; } #endif /* The following two routines were donated for SVR4 by Andreas Vogel */ #if (!APR_HAVE_STRCASECMP && !APR_HAVE_STRICMP) int strcasecmp(const char *a, const char *b) { const char *p = a; const char *q = b; for (p = a, q = b; *p && *q; p++, q++) { int diff = apr_tolower(*p) - apr_tolower(*q); if (diff) return diff; } if (*p) return 1; /* p was longer than q */ if (*q) return -1; /* p was shorter than q */ return 0; /* Exact match */ } #endif #if (!APR_HAVE_STRNCASECMP && !APR_HAVE_STRNICMP) int strncasecmp(const char *a, const char *b, size_t n) { const char *p = a; const char *q = b; for (p = a, q = b; /*NOTHING */ ; p++, q++) { int diff; if (p == a + n) return 0; /* Match up to n characters */ if (!(*p && *q)) return *p - *q; diff = apr_tolower(*p) - apr_tolower(*q); if (diff) return diff; } /*NOTREACHED */ } #endif /* The following routine was donated for UTS21 by [email protected] */ #if (!APR_HAVE_STRSTR) char *strstr(char *s1, char *s2) { char *p1, *p2; if (*s2 == '\0') { /* an empty s2 */ return(s1); } while((s1 = strchr(s1, *s2)) != NULL) { /* found first character of s2, see if the rest matches */ p1 = s1; p2 = s2; while (*++p1 == *++p2) { if (*p1 == '\0') { /* both strings ended together */ return(s1); } } if (*p2 == '\0') { /* second string ended, a match */ break; } /* didn't find a match here, try starting at next character in s1 */ s1++; } return(s1); } #endif
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- import sys from io import StringIO from typing import Dict, Set, Type # noqa from django.test import TestCase from django_extensions.management.commands import shell_plus class AutomaticShellPlusImportsTestCase(TestCase): def setUp(self): super().setUp() sys.stdout = StringIO() sys.stderr = StringIO() self.imported_objects = {} # type: Dict[str, Type] self.output = "" def get_all_names_for_class(self, model_to_find_occurrences): # type: (Type) -> Set[str] """ Returns all names under current class is imported. :param model_to_find_occurrences: class to find names :return: set of names under class is imported. """ result = set() for name, model_class in self.imported_objects.items(): if model_class == model_to_find_occurrences: result.add(name) return result def assert_imported_under_names(self, model_class, names_under_model_is_available): # type: (Type, Set[str]) -> () """ Function which asserts that class is available under given names and not available under any other name. :param model_class: class to assert availability. :param names_under_model_is_available: names under which class should be available. """ self.assertSetEqual(self.get_all_names_for_class(model_class), names_under_model_is_available) imports_output = self.output.split("from ") for line in imports_output: if line.startswith(model_class.__module__): for name in names_under_model_is_available: # assert that in print imports this model occurs only under names from parameter if name == model_class.__name__: expected_output = name else: expected_output = "%s (as %s)" % (model_class.__name__, name) line = line.replace(expected_output, '', 1) self.assertNotIn(line, model_class.__name__) def run_shell_plus(self): command = shell_plus.Command() self.imported_objects = command.get_imported_objects({}) self.output = sys.stdout.getvalue()
{ "pile_set_name": "Github" }
"""Matplotlib Posterior predictive plot.""" import logging import platform import matplotlib.pyplot as plt import numpy as np from matplotlib import animation, get_backend from ....stats.density_utils import get_bins, histogram, kde from ...kdeplot import plot_kde from ...plot_utils import _scale_fig_size, make_label from . import backend_kwarg_defaults, backend_show, create_axes_grid _log = logging.getLogger(__name__) def plot_ppc( ax, length_plotters, rows, cols, figsize, animated, obs_plotters, pp_plotters, predictive_dataset, pp_sample_ix, kind, alpha, color, textsize, mean, jitter, total_pp_samples, legend, group, animation_kwargs, num_pp_samples, backend_kwargs, show, ): """Matplotlib ppc plot.""" if backend_kwargs is None: backend_kwargs = {} backend_kwargs = { **backend_kwarg_defaults(), **backend_kwargs, } if animation_kwargs is None: animation_kwargs = {} if platform.system() == "Linux": animation_kwargs.setdefault("blit", True) else: animation_kwargs.setdefault("blit", False) if alpha is None: if animated: alpha = 1 else: if kind.lower() == "scatter": alpha = 0.7 else: alpha = 0.2 if jitter is None: jitter = 0.0 if jitter < 0.0: raise ValueError("jitter must be >=0") if animated: try: shell = get_ipython().__class__.__name__ if shell == "ZMQInteractiveShell" and get_backend() != "nbAgg": raise Warning( "To run animations inside a notebook you have to use the nbAgg backend. " "Try with `%matplotlib notebook` or `%matplotlib nbAgg`. You can switch " "back to the default backend with `%matplotlib inline` or " "`%matplotlib auto`." ) except NameError: pass if animation_kwargs["blit"] and platform.system() != "Linux": _log.warning( "If you experience problems rendering the animation try setting " "`animation_kwargs({'blit':False}) or changing the plotting backend " "(e.g. to TkAgg)" ) (figsize, ax_labelsize, _, xt_labelsize, linewidth, markersize) = _scale_fig_size( figsize, textsize, rows, cols ) backend_kwargs.setdefault("figsize", figsize) backend_kwargs.setdefault("squeeze", True) if ax is None: fig, axes = create_axes_grid(length_plotters, rows, cols, backend_kwargs=backend_kwargs) else: axes = np.ravel(ax) if len(axes) != length_plotters: raise ValueError( "Found {} variables to plot but {} axes instances. They must be equal.".format( length_plotters, len(axes) ) ) if animated: fig = axes[0].get_figure() if not all([ax.get_figure() is fig for ax in axes]): raise ValueError("All axes must be on the same figure for animation to work") for i, ax_i in enumerate(np.ravel(axes)[:length_plotters]): var_name, selection, obs_vals = obs_plotters[i] pp_var_name, _, pp_vals = pp_plotters[i] dtype = predictive_dataset[pp_var_name].dtype.kind # flatten non-specified dimensions obs_vals = obs_vals.flatten() pp_vals = pp_vals.reshape(total_pp_samples, -1) pp_sampled_vals = pp_vals[pp_sample_ix] if kind == "kde": plot_kwargs = {"color": color, "alpha": alpha, "linewidth": 0.5 * linewidth} if dtype == "i": plot_kwargs["drawstyle"] = "steps-pre" ax_i.plot( [], color=color, label="{} predictive {}".format(group.capitalize(), pp_var_name) ) if dtype == "f": plot_kde( obs_vals, label="Observed {}".format(var_name), plot_kwargs={"color": "k", "linewidth": linewidth, "zorder": 3}, fill_kwargs={"alpha": 0}, ax=ax_i, legend=legend, ) else: bins = get_bins(obs_vals) _, hist, bin_edges = histogram(obs_vals, bins=bins) hist = np.concatenate((hist[:1], hist)) ax_i.plot( bin_edges, hist, label="Observed {}".format(var_name), color="k", linewidth=linewidth, zorder=3, drawstyle=plot_kwargs["drawstyle"], ) pp_densities = [] pp_xs = [] for vals in pp_sampled_vals: vals = np.array([vals]).flatten() if dtype == "f": pp_x, pp_density = kde(vals) pp_densities.append(pp_density) pp_xs.append(pp_x) else: bins = get_bins(vals) _, hist, bin_edges = histogram(vals, bins=bins) hist = np.concatenate((hist[:1], hist)) pp_densities.append(hist) pp_xs.append(bin_edges) if animated: animate, init = _set_animation( pp_sampled_vals, ax_i, dtype=dtype, kind=kind, plot_kwargs=plot_kwargs ) else: if dtype == "f": ax_i.plot(np.transpose(pp_xs), np.transpose(pp_densities), **plot_kwargs) else: for x_s, y_s in zip(pp_xs, pp_densities): ax_i.plot(x_s, y_s, **plot_kwargs) if mean: label = "{} predictive mean {}".format(group.capitalize(), pp_var_name) if dtype == "f": rep = len(pp_densities) len_density = len(pp_densities[0]) new_x = np.linspace(np.min(pp_xs), np.max(pp_xs), len_density) new_d = np.zeros((rep, len_density)) bins = np.digitize(pp_xs, new_x, right=True) new_x -= (new_x[1] - new_x[0]) / 2 for irep in range(rep): new_d[irep][bins[irep]] = pp_densities[irep] ax_i.plot( new_x, new_d.mean(0), color=color, linestyle="--", linewidth=linewidth * 1.5, zorder=2, label=label, ) else: vals = pp_vals.flatten() bins = get_bins(vals) _, hist, bin_edges = histogram(vals, bins=bins) hist = np.concatenate((hist[:1], hist)) ax_i.plot( bin_edges, hist, color=color, linewidth=linewidth * 1.5, label=label, zorder=2, linestyle="--", drawstyle=plot_kwargs["drawstyle"], ) ax_i.tick_params(labelsize=xt_labelsize) ax_i.set_yticks([]) elif kind == "cumulative": drawstyle = "default" if dtype == "f" else "steps-pre" ax_i.plot( *_empirical_cdf(obs_vals), color=color, linewidth=linewidth, label="Observed {}".format(var_name), drawstyle=drawstyle, zorder=3 ) if animated: animate, init = _set_animation( pp_sampled_vals, ax_i, kind=kind, alpha=alpha, drawstyle=drawstyle, linewidth=linewidth, ) else: pp_densities = np.empty((2 * len(pp_sampled_vals), pp_sampled_vals[0].size)) for idx, vals in enumerate(pp_sampled_vals): vals = np.array([vals]).flatten() pp_x, pp_density = _empirical_cdf(vals) pp_densities[2 * idx] = pp_x pp_densities[2 * idx + 1] = pp_density ax_i.plot( *pp_densities, alpha=alpha, color=color, drawstyle=drawstyle, linewidth=linewidth ) ax_i.plot([], color=color, label="Posterior predictive {}".format(pp_var_name)) if mean: ax_i.plot( *_empirical_cdf(pp_vals.flatten()), color=color, linestyle="--", linewidth=linewidth * 1.5, drawstyle=drawstyle, label="Posterior predictive mean {}".format(pp_var_name) ) ax_i.set_yticks([0, 0.5, 1]) elif kind == "scatter": if mean: if dtype == "f": plot_kde( pp_vals.flatten(), plot_kwargs={ "color": color, "linestyle": "--", "linewidth": linewidth * 1.5, "zorder": 3, }, label="Posterior predictive mean {}".format(pp_var_name), ax=ax_i, legend=legend, ) else: vals = pp_vals.flatten() bins = get_bins(vals) _, hist, bin_edges = histogram(vals, bins=bins) hist = np.concatenate((hist[:1], hist)) ax_i.plot( bin_edges, hist, color=color, linewidth=linewidth * 1.5, label="Posterior predictive mean {}".format(pp_var_name), zorder=3, linestyle="--", drawstyle="steps-pre", ) _, limit = ax_i.get_ylim() limit *= 1.05 y_rows = np.linspace(0, limit, num_pp_samples + 1) jitter_scale = y_rows[1] - y_rows[0] scale_low = 0 scale_high = jitter_scale * jitter obs_yvals = np.zeros_like(obs_vals, dtype=np.float64) if jitter: obs_yvals += np.random.uniform(low=scale_low, high=scale_high, size=len(obs_vals)) ax_i.plot( obs_vals, obs_yvals, "o", color=color, markersize=markersize, alpha=alpha, label="Observed {}".format(var_name), zorder=4, ) if animated: animate, init = _set_animation( pp_sampled_vals, ax_i, kind=kind, color=color, height=y_rows.mean() * 0.5, markersize=markersize, ) else: for vals, y in zip(pp_sampled_vals, y_rows[1:]): vals = np.ravel(vals) yvals = np.full_like(vals, y, dtype=np.float64) if jitter: yvals += np.random.uniform(low=scale_low, high=scale_high, size=len(vals)) ax_i.plot( vals, yvals, "o", zorder=2, color=color, markersize=markersize, alpha=alpha ) ax_i.plot( [], color=color, marker="o", label="Posterior predictive {}".format(pp_var_name) ) ax_i.set_yticks([]) if var_name != pp_var_name: xlabel = "{} / {}".format(var_name, pp_var_name) else: xlabel = var_name ax_i.set_xlabel(make_label(xlabel, selection), fontsize=ax_labelsize) if legend: if i == 0: ax_i.legend(fontsize=xt_labelsize * 0.75) else: ax_i.legend([]) if backend_show(show): plt.show() if animated: ani = animation.FuncAnimation( fig, animate, np.arange(0, num_pp_samples), init_func=init, **animation_kwargs ) return axes, ani else: return axes def _set_animation( pp_sampled_vals, ax, dtype=None, kind="density", alpha=None, color=None, drawstyle=None, linewidth=None, height=None, markersize=None, plot_kwargs=None, ): if kind == "kde": length = len(pp_sampled_vals) if dtype == "f": x_vals, y_vals = kde(pp_sampled_vals[0]) max_max = max([max(kde(pp_sampled_vals[i])[1]) for i in range(length)]) ax.set_ylim(0, max_max) (line,) = ax.plot(x_vals, y_vals, **plot_kwargs) def animate(i): x_vals, y_vals = kde(pp_sampled_vals[i]) line.set_data(x_vals, y_vals) return (line,) else: vals = pp_sampled_vals[0] _, y_vals, x_vals = histogram(vals, bins="auto") (line,) = ax.plot(x_vals[:-1], y_vals, **plot_kwargs) max_max = max( [max(histogram(pp_sampled_vals[i], bins="auto")[1]) for i in range(length)] ) ax.set_ylim(0, max_max) def animate(i): _, y_vals, x_vals = histogram(pp_sampled_vals[i], bins="auto") line.set_data(x_vals[:-1], y_vals) return (line,) elif kind == "cumulative": x_vals, y_vals = _empirical_cdf(pp_sampled_vals[0]) (line,) = ax.plot( x_vals, y_vals, alpha=alpha, color=color, drawstyle=drawstyle, linewidth=linewidth ) def animate(i): x_vals, y_vals = _empirical_cdf(pp_sampled_vals[i]) line.set_data(x_vals, y_vals) return (line,) elif kind == "scatter": x_vals = pp_sampled_vals[0] y_vals = np.full_like(x_vals, height, dtype=np.float64) (line,) = ax.plot( x_vals, y_vals, "o", zorder=2, color=color, markersize=markersize, alpha=alpha ) def animate(i): line.set_xdata(np.ravel(pp_sampled_vals[i])) return (line,) def init(): if kind != "scatter": line.set_data([], []) else: line.set_xdata([]) return (line,) return animate, init def _empirical_cdf(data): """Compute empirical cdf of a numpy array. Parameters ---------- data : np.array 1d array Returns ------- np.array, np.array x and y coordinates for the empirical cdf of the data """ return np.sort(data), np.linspace(0, 1, len(data))
{ "pile_set_name": "Github" }
wakefield ============ [![Project Status: Active - The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/0.1.0/active.svg)](https://www.repostatus.org/#active) [![Build Status](https://travis-ci.org/trinker/wakefield.svg?branch=master)](https://travis-ci.org/trinker/wakefield) [![Coverage Status](https://s3.amazonaws.com/assets.coveralls.io/badges/coveralls_0.svg)](https://coveralls.io/github/trinker/wakefield) [![DOI](https://zenodo.org/badge/5398/trinker/wakefield.svg)](https://dx.doi.org/10.5281/zenodo.17172) [![](https://cranlogs.r-pkg.org/badges/wakefield)](https://cran.r-project.org/package=wakefield) **wakefield** is designed to quickly generate random data sets. The user passes `n` (number of rows) and predefined vectors to the `r_data_frame` function to produce a `dplyr::tbl_df` object. ![](tools/wakefield_logo/r_wakefield.png) Table of Contents ============ - [Installation](#installation) - [Contact](#contact) - [Demonstration](#demonstration) - [Getting Started](#getting-started) - [Random Missing Observations](#random-missing-observations) - [Repeated Measures & Time Series](#repeated-measures-time-series) - [Related Series](#related-series) - [Some Examples With Variation](#some-examples-with-variation) - [Adjust Correlations](#adjust-correlations) - [Visualize the Relationship](#visualize-the-relationship) - [Expanded Dummy Coding](#expanded-dummy-coding) - [Visualizing Column Types](#visualizing-column-types) Installation ============ To download the development version of **wakefield**: Download the [zip ball](https://github.com/trinker/wakefield/zipball/master) or [tar ball](https://github.com/trinker/wakefield/tarball/master), decompress and run `R CMD INSTALL` on it, or use the **pacman** package to install the development version: if (!require("pacman")) install.packages("pacman") pacman::p_load_gh("trinker/wakefield") pacman::p_load(dplyr, tidyr, ggplot2) Contact ======= You are welcome to: \* submit suggestions and bug-reports at: <a href="https://github.com/trinker/wakefield/issues" class="uri">https://github.com/trinker/wakefield/issues</a> \* send a pull request on: <a href="https://github.com/trinker/wakefield/" class="uri">https://github.com/trinker/wakefield/</a> \* compose a friendly e-mail to: <a href="mailto:[email protected]" class="email">[email protected]</a> Demonstration ============= Getting Started --------------- The `r_data_frame` function (random data frame) takes `n` (the number of rows) and any number of variables (columns). These columns are typically produced from a **wakefield** variable function. Each of these variable functions has a pre-set behavior that produces a named vector of n length, allowing the user to lazily pass unnamed functions (optionally, without call parenthesis). The column name is hidden as a `varname` attribute. For example here we see the `race` variable function: race(n=10) ## [1] Bi-Racial White Bi-Racial Native White White White Asian White Hispanic ## Levels: White Hispanic Black Asian Bi-Racial Native Other Hawaiian attributes(race(n=10)) ## $levels ## [1] "White" "Hispanic" "Black" "Asian" "Bi-Racial" "Native" "Other" "Hawaiian" ## ## $class ## [1] "variable" "factor" ## ## $varname ## [1] "Race" When this variable is used inside of `r_data_frame` the `varname` is used as a column name. Additionally, the `n` argument is not set within variable functions but is set once in `r_data_frame`: r_data_frame( n = 500, race ) ## Warning: `tbl_df()` is deprecated as of dplyr 1.0.0. ## Please use `tibble::as_tibble()` instead. ## This warning is displayed once every 8 hours. ## Call `lifecycle::last_warnings()` to see where this warning was generated. ## # A tibble: 500 x 1 ## Race ## <fct> ## 1 White ## 2 White ## 3 White ## 4 White ## 5 Black ## 6 Black ## 7 White ## 8 White ## 9 Hispanic ## 10 White ## # ... with 490 more rows The power of `r_data_frame` is apparent when we use many modular variable functions: r_data_frame( n = 500, id, race, age, sex, hour, iq, height, died ) ## # A tibble: 500 x 8 ## ID Race Age Sex Hour IQ Height Died ## <chr> <fct> <int> <fct> <times> <dbl> <dbl> <lgl> ## 1 001 White 25 Female 00:00:00 93 69 TRUE ## 2 002 White 80 Male 00:00:00 87 59 FALSE ## 3 003 White 60 Female 00:00:00 119 74 TRUE ## 4 004 Bi-Racial 54 Female 00:00:00 109 72 FALSE ## 5 005 White 75 Female 00:00:00 106 70 FALSE ## 6 006 White 54 Male 00:00:00 89 67 TRUE ## 7 007 Hispanic 67 Male 00:00:00 94 73 TRUE ## 8 008 Bi-Racial 86 Female 00:00:00 100 65 TRUE ## 9 009 Hispanic 56 Male 00:00:00 92 76 FALSE ## 10 010 Hispanic 52 Female 00:00:00 104 71 FALSE ## # ... with 490 more rows There are 49 **wakefield** based variable functions to chose from, spanning **R**’s various data types (see `?variables` for details). <!-- html table generated in R 4.0.2 by xtable 1.8-4 package --> <!-- Sat Sep 12 11:46:45 2020 --> <table> <tr> <td> age </td> <td> dice </td> <td> hair </td> <td> military </td> <td> sex\_inclusive </td> </tr> <tr> <td> animal </td> <td> dna </td> <td> height </td> <td> month </td> <td> smokes </td> </tr> <tr> <td> answer </td> <td> dob </td> <td> income </td> <td> name </td> <td> speed </td> </tr> <tr> <td> area </td> <td> dummy </td> <td> internet\_browser </td> <td> normal </td> <td> state </td> </tr> <tr> <td> car </td> <td> education </td> <td> iq </td> <td> political </td> <td> string </td> </tr> <tr> <td> children </td> <td> employment </td> <td> language </td> <td> race </td> <td> upper </td> </tr> <tr> <td> coin </td> <td> eye </td> <td> level </td> <td> religion </td> <td> valid </td> </tr> <tr> <td> color </td> <td> grade </td> <td> likert </td> <td> sat </td> <td> year </td> </tr> <tr> <td> date\_stamp </td> <td> grade\_level </td> <td> lorem\_ipsum </td> <td> sentence </td> <td> zip\_code </td> </tr> <tr> <td> death </td> <td> group </td> <td> marital </td> <td> sex </td> <td> </td> </tr> </table> <p class="caption"> <b><em>Available Variable Functions</em></b> </p> However, the user may also pass their own vector producing functions or vectors to `r_data_frame`. Those with an `n` argument can be set by `r_data_frame`: r_data_frame( n = 500, id, Scoring = rnorm, Smoker = valid, race, age, sex, hour, iq, height, died ) ## # A tibble: 500 x 10 ## ID Scoring Smoker Race Age Sex Hour IQ Height Died ## <chr> <dbl> <lgl> <fct> <int> <fct> <times> <dbl> <dbl> <lgl> ## 1 001 0.833 FALSE White 20 Female 00:00:00 92 69 TRUE ## 2 002 -0.529 TRUE Hispanic 83 Female 00:00:00 99 74 TRUE ## 3 003 -0.704 TRUE Hispanic 24 Male 00:00:00 115 62 TRUE ## 4 004 -0.839 TRUE Asian 19 Female 00:00:00 113 69 TRUE ## 5 005 0.606 TRUE White 70 Male 00:00:00 95 68 FALSE ## 6 006 1.46 FALSE Other 45 Female 00:00:00 110 78 FALSE ## 7 007 -0.681 TRUE Black 47 Female 00:00:00 98 64 TRUE ## 8 008 0.541 FALSE White 88 Male 00:30:00 75 70 TRUE ## 9 009 -0.294 FALSE Hispanic 89 Male 00:30:00 104 63 FALSE ## 10 010 0.0749 FALSE Hispanic 74 Female 00:30:00 105 69 TRUE ## # ... with 490 more rows r_data_frame( n = 500, id, age, age, age, grade, grade, grade ) ## # A tibble: 500 x 7 ## ID Age_1 Age_2 Age_3 Grade_1 Grade_2 Grade_3 ## <chr> <int> <int> <int> <dbl> <dbl> <dbl> ## 1 001 67 24 89 82.4 86.8 90.6 ## 2 002 55 76 27 87.3 85.4 89.8 ## 3 003 60 61 22 82.2 87 90.1 ## 4 004 50 19 56 96.4 86.6 95.6 ## 5 005 83 77 71 88.8 87.5 84.4 ## 6 006 55 71 76 87.3 96.5 86.5 ## 7 007 88 36 75 92.1 91.6 93.4 ## 8 008 71 48 81 87.9 91.4 80.9 ## 9 009 76 78 21 86.9 93.6 84.3 ## 10 010 49 68 47 85.5 93 86.6 ## # ... with 490 more rows While passing variable functions to `r_data_frame` without call parenthesis is handy, the user may wish to set arguments. This can be done through call parenthesis as we do with `data.frame` or `dplyr::data_frame`: r_data_frame( n = 500, id, Scoring = rnorm, Smoker = valid, `Reading(mins)` = rpois(lambda=20), race, age(x = 8:14), sex, hour, iq, height(mean=50, sd = 10), died ) ## # A tibble: 500 x 11 ## ID Scoring Smoker `Reading(mins)` Race Age Sex Hour IQ Height Died ## <chr> <dbl> <lgl> <int> <fct> <int> <fct> <times> <dbl> <dbl> <lgl> ## 1 001 2.48 FALSE 10 White 9 Male 00:00:00 93 44 TRUE ## 2 002 0.566 FALSE 14 Hispanic 10 Male 00:00:00 116 58 FALSE ## 3 003 -0.563 FALSE 19 Hispanic 8 Female 00:00:00 97 64 TRUE ## 4 004 0.0187 TRUE 19 White 9 Male 00:00:00 104 58 TRUE ## 5 005 -0.462 FALSE 17 Hispanic 11 Male 00:00:00 96 53 FALSE ## 6 006 -1.13 FALSE 17 White 10 Male 00:00:00 91 66 TRUE ## 7 007 -0.673 TRUE 15 White 13 Female 00:00:00 99 61 FALSE ## 8 008 0.164 TRUE 22 White 11 Male 00:00:00 106 47 FALSE ## 9 009 -0.227 FALSE 21 White 12 Female 00:00:00 101 54 TRUE ## 10 010 0.762 TRUE 22 White 8 Male 00:00:00 107 50 FALSE ## # ... with 490 more rows Random Missing Observations --------------------------- Often data contains missing values. **wakefield** allows the user to add a proportion of missing values per column/vector via the `r_na` (random `NA`). This works nicely within a **dplyr**/**magrittr** `%>%` *then* pipeline: r_data_frame( n = 30, id, race, age, sex, hour, iq, height, died, Scoring = rnorm, Smoker = valid ) %>% r_na(prob=.4) ## # A tibble: 30 x 10 ## ID Race Age Sex Hour IQ Height Died Scoring Smoker ## <chr> <fct> <int> <fct> <times> <dbl> <dbl> <lgl> <dbl> <lgl> ## 1 01 Hispanic 24 Female 01:30:00 92 70 NA NA NA ## 2 02 White NA Female <NA> NA NA FALSE 0.696 TRUE ## 3 03 Hispanic NA Female 02:00:00 107 68 FALSE -0.113 TRUE ## 4 04 Black 29 Female <NA> 93 75 TRUE -1.64 TRUE ## 5 05 <NA> 43 Female 03:30:00 NA NA NA -0.705 FALSE ## 6 06 Black NA <NA> 04:00:00 93 NA TRUE NA NA ## 7 07 Hispanic 60 <NA> <NA> NA NA TRUE NA NA ## 8 08 Hispanic NA <NA> <NA> NA NA TRUE NA FALSE ## 9 09 <NA> 34 <NA> 05:30:00 NA 70 NA -1.44 TRUE ## 10 10 White 88 <NA> <NA> NA NA NA NA NA ## # ... with 20 more rows Repeated Measures & Time Series ------------------------------- The `r_series` function allows the user to pass a single **wakefield** function and dictate how many columns (`j`) to produce. set.seed(10) r_series(likert, j = 3, n=10) ## # A tibble: 10 x 3 ## Likert_1 Likert_2 Likert_3 ## * <ord> <ord> <ord> ## 1 Neutral Agree Agree ## 2 Strongly Agree Strongly Disagree Strongly Agree ## 3 Agree Strongly Disagree Agree ## 4 Disagree Strongly Disagree Agree ## 5 Neutral Strongly Agree Strongly Agree ## 6 Agree Disagree Disagree ## 7 Agree Agree Strongly Disagree ## 8 Agree Strongly Disagree Agree ## 9 Strongly Disagree Agree Neutral ## 10 Neutral Strongly Disagree Neutral Often the user wants a numeric score for Likert type columns and similar variables. For series with multiple factors the `as_integer` converts all columns to integer values. Additionally, we may want to specify column name prefixes. This can be accomplished via the variable function’s `name` argument. Both of these features are demonstrated here. set.seed(10) as_integer(r_series(likert, j = 5, n=10, name = "Item")) ## # A tibble: 10 x 5 ## Item_1 Item_2 Item_3 Item_4 Item_5 ## <int> <int> <int> <int> <int> ## 1 3 4 4 4 5 ## 2 5 1 5 3 1 ## 3 4 1 4 5 4 ## 4 2 1 4 4 5 ## 5 3 5 5 2 5 ## 6 4 2 2 3 4 ## 7 4 4 1 4 1 ## 8 4 1 4 1 2 ## 9 1 4 3 5 3 ## 10 3 1 3 5 5 `r_series` can be used within a `r_data_frame` as well. set.seed(10) r_data_frame(n=100, id, age, sex, r_series(likert, 3, name = "Question") ) ## # A tibble: 100 x 6 ## ID Age Sex Question_1 Question_2 Question_3 ## <chr> <int> <fct> <ord> <ord> <ord> ## 1 001 26 Male Strongly Agree Disagree Disagree ## 2 002 72 Male Disagree Agree Strongly Disagree ## 3 003 89 Male Strongly Disagree Strongly Disagree Strongly Agree ## 4 004 71 Female Agree Strongly Agree Disagree ## 5 005 56 Female Strongly Disagree Disagree Neutral ## 6 006 32 Female Strongly Disagree Strongly Agree Disagree ## 7 007 32 Female Strongly Disagree Strongly Agree Strongly Disagree ## 8 008 59 Female Neutral Strongly Agree Strongly Disagree ## 9 009 88 Male Agree Agree Agree ## 10 010 51 Male Agree Disagree Neutral ## # ... with 90 more rows set.seed(10) r_data_frame(n=100, id, age, sex, r_series(likert, 5, name = "Item", integer = TRUE) ) ## # A tibble: 100 x 8 ## ID Age Sex Item_1 Item_2 Item_3 Item_4 Item_5 ## <chr> <int> <fct> <int> <int> <int> <int> <int> ## 1 001 26 Male 5 2 2 4 5 ## 2 002 72 Male 2 4 1 4 3 ## 3 003 89 Male 1 1 5 4 4 ## 4 004 71 Female 4 5 2 1 2 ## 5 005 56 Female 1 2 3 3 2 ## 6 006 32 Female 1 5 2 5 1 ## 7 007 32 Female 1 5 1 1 5 ## 8 008 59 Female 3 5 1 4 1 ## 9 009 88 Male 4 4 4 3 2 ## 10 010 51 Male 4 2 3 1 3 ## # ... with 90 more rows ### Related Series The user can also create related series via the `relate` argument in `r_series`. It allows the user to specify the relationship between columns. `relate` may be a named list of or a short hand string of the form of `"fM_sd"` where: - `f` is one of (+, -, \*, /) - `M` is a mean value - `sd` is a standard deviation of the mean value For example you may use `relate = "*4_1"`. If `relate = NULL` no relationship is generated between columns. I will use the short hand string form here. #### Some Examples With Variation r_series(grade, j = 5, n = 100, relate = "+1_6") ## # A tibble: 100 x 5 ## Grade_1 Grade_2 Grade_3 Grade_4 Grade_5 ## * <variable> <variable> <variable> <variable> <variable> ## 1 90.0 98.7 98.6 104.6 114.1 ## 2 96.3 97.9 98.4 102.7 103.9 ## 3 96.6 92.6 94.9 92.7 98.8 ## 4 84.5 89.5 81.9 87.4 83.4 ## 5 86.8 84.1 82.2 82.8 94.0 ## 6 82.1 77.9 74.3 76.4 73.0 ## 7 90.9 96.1 107.5 120.2 126.8 ## 8 86.7 88.6 90.3 89.0 83.8 ## 9 86.1 84.1 88.9 90.1 72.6 ## 10 86.4 92.3 88.5 94.6 99.0 ## # ... with 90 more rows r_series(age, 5, 100, relate = "+5_0") ## # A tibble: 100 x 5 ## Age_1 Age_2 Age_3 Age_4 Age_5 ## * <variable> <variable> <variable> <variable> <variable> ## 1 83 88 93 98 103 ## 2 48 53 58 63 68 ## 3 80 85 90 95 100 ## 4 46 51 56 61 66 ## 5 33 38 43 48 53 ## 6 53 58 63 68 73 ## 7 34 39 44 49 54 ## 8 31 36 41 46 51 ## 9 81 86 91 96 101 ## 10 50 55 60 65 70 ## # ... with 90 more rows r_series(likert, 5, 100, name ="Item", relate = "-.5_.1") ## # A tibble: 100 x 5 ## Item_1 Item_2 Item_3 Item_4 Item_5 ## * <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 1 0 -1 -1 -2 ## 2 3 3 2 2 2 ## 3 4 3 3 3 3 ## 4 3 2 1 0 0 ## 5 3 3 3 3 3 ## 6 5 4 3 2 1 ## 7 4 3 2 1 1 ## 8 1 0 -1 -2 -2 ## 9 3 2 1 1 1 ## 10 1 0 0 -1 -2 ## # ... with 90 more rows r_series(grade, j = 5, n = 100, relate = "*1.05_.1") ## # A tibble: 100 x 5 ## Grade_1 Grade_2 Grade_3 Grade_4 Grade_5 ## * <variable> <variable> <variable> <variable> <variable> ## 1 90.8 90.80 99.880 109.8680 109.8680 ## 2 89.8 80.82 80.820 64.6560 58.1904 ## 3 90.3 99.33 109.263 109.2630 98.3367 ## 4 95.2 76.16 91.392 91.3920 100.5312 ## 5 89.1 98.01 117.612 105.8508 105.8508 ## 6 86.8 95.48 95.480 114.5760 160.4064 ## 7 93.4 93.40 93.400 102.7400 123.2880 ## 8 92.7 83.43 91.773 110.1276 121.1404 ## 9 84.9 93.39 93.390 102.7290 113.0019 ## 10 84.7 84.70 93.170 93.1700 111.8040 ## # ... with 90 more rows #### Adjust Correlations Use the `sd` command to adjust correlations. round(cor(r_series(grade, 8, 10, relate = "+1_2")), 2) ## Grade_1 Grade_2 Grade_3 Grade_4 Grade_5 Grade_6 Grade_7 Grade_8 ## Grade_1 1.00 0.84 0.57 0.41 0.31 0.30 0.16 0.15 ## Grade_2 0.84 1.00 0.86 0.73 0.71 0.70 0.52 0.50 ## Grade_3 0.57 0.86 1.00 0.93 0.92 0.90 0.77 0.71 ## Grade_4 0.41 0.73 0.93 1.00 0.93 0.89 0.76 0.66 ## Grade_5 0.31 0.71 0.92 0.93 1.00 0.93 0.83 0.79 ## Grade_6 0.30 0.70 0.90 0.89 0.93 1.00 0.93 0.92 ## Grade_7 0.16 0.52 0.77 0.76 0.83 0.93 1.00 0.95 ## Grade_8 0.15 0.50 0.71 0.66 0.79 0.92 0.95 1.00 round(cor(r_series(grade, 8, 10, relate = "+1_0")), 2) ## Grade_1 Grade_2 Grade_3 Grade_4 Grade_5 Grade_6 Grade_7 Grade_8 ## Grade_1 1 1 1 1 1 1 1 1 ## Grade_2 1 1 1 1 1 1 1 1 ## Grade_3 1 1 1 1 1 1 1 1 ## Grade_4 1 1 1 1 1 1 1 1 ## Grade_5 1 1 1 1 1 1 1 1 ## Grade_6 1 1 1 1 1 1 1 1 ## Grade_7 1 1 1 1 1 1 1 1 ## Grade_8 1 1 1 1 1 1 1 1 round(cor(r_series(grade, 8, 10, relate = "+1_20")), 2) ## Grade_1 Grade_2 Grade_3 Grade_4 Grade_5 Grade_6 Grade_7 Grade_8 ## Grade_1 1.00 -0.11 0.14 -0.21 -0.42 -0.29 -0.30 -0.27 ## Grade_2 -0.11 1.00 0.49 0.44 0.18 0.24 0.23 0.51 ## Grade_3 0.14 0.49 1.00 0.86 0.48 0.59 0.70 0.81 ## Grade_4 -0.21 0.44 0.86 1.00 0.63 0.76 0.76 0.87 ## Grade_5 -0.42 0.18 0.48 0.63 1.00 0.92 0.85 0.79 ## Grade_6 -0.29 0.24 0.59 0.76 0.92 1.00 0.91 0.89 ## Grade_7 -0.30 0.23 0.70 0.76 0.85 0.91 1.00 0.93 ## Grade_8 -0.27 0.51 0.81 0.87 0.79 0.89 0.93 1.00 round(cor(r_series(grade, 8, 10, relate = "+15_20")), 2) ## Grade_1 Grade_2 Grade_3 Grade_4 Grade_5 Grade_6 Grade_7 Grade_8 ## Grade_1 1.00 0.48 0.47 0.63 0.58 0.66 0.35 0.18 ## Grade_2 0.48 1.00 0.90 0.87 0.54 0.43 0.67 0.23 ## Grade_3 0.47 0.90 1.00 0.81 0.63 0.53 0.74 0.30 ## Grade_4 0.63 0.87 0.81 1.00 0.75 0.72 0.71 0.47 ## Grade_5 0.58 0.54 0.63 0.75 1.00 0.88 0.57 0.42 ## Grade_6 0.66 0.43 0.53 0.72 0.88 1.00 0.68 0.54 ## Grade_7 0.35 0.67 0.74 0.71 0.57 0.68 1.00 0.77 ## Grade_8 0.18 0.23 0.30 0.47 0.42 0.54 0.77 1.00 #### Visualize the Relationship dat <- r_data_frame(12, name, r_series(grade, 100, relate = "+1_6") ) dat %>% gather(Time, Grade, -c(Name)) %>% mutate(Time = as.numeric(gsub("\\D", "", Time))) %>% ggplot(aes(x = Time, y = Grade, color = Name, group = Name)) + geom_line(size=.8) + theme_bw() ![](tools/figure/unnamed-chunk-17-1.png) Expanded Dummy Coding --------------------- The user may wish to expand a `factor` into `j` dummy coded columns. The `r_dummy` function expands a factor into `j` columns and works similar to the `r_series` function. The user may wish to use the original factor name as the prefix to the `j` columns. Setting `prefix = TRUE` within `r_dummy` accomplishes this. set.seed(10) r_data_frame(n=100, id, age, r_dummy(sex, prefix = TRUE), r_dummy(political) ) ## # A tibble: 100 x 8 ## ID Age Sex_Male Sex_Female Democrat Republican Libertarian Green ## <chr> <int> <int> <int> <int> <int> <int> <int> ## 1 001 26 1 0 0 0 1 0 ## 2 002 72 1 0 1 0 0 0 ## 3 003 89 1 0 0 1 0 0 ## 4 004 71 0 1 1 0 0 0 ## 5 005 56 0 1 0 1 0 0 ## 6 006 32 0 1 0 1 0 0 ## 7 007 32 0 1 1 0 0 0 ## 8 008 59 0 1 0 1 0 0 ## 9 009 88 1 0 0 1 0 0 ## 10 010 51 1 0 0 1 0 0 ## # ... with 90 more rows Visualizing Column Types ------------------------ It is helpful to see the column types and `NA`s as a visualization. The `table_heat` (also the `plot` method assigned to `tbl_df` as well) can provide visual glimpse of data types and missing cells. set.seed(10) r_data_frame(n=100, id, dob, animal, grade, grade, death, dummy, grade_letter, gender, paragraph, sentence ) %>% r_na() %>% plot(palette = "Set1") ![](tools/figure/unnamed-chunk-19-1.png)
{ "pile_set_name": "Github" }
#ifndef sgb_h #define sgb_h #include "gb_struct_def.h" #include <stdint.h> #include <stdbool.h> typedef struct GB_sgb_s GB_sgb_t; typedef struct { uint8_t tiles[0x100 * 8 * 8]; /* High nibble not used*/ union { struct { uint16_t map[32 * 32]; uint16_t palette[16 * 4]; }; uint16_t raw_data[0x440]; }; } GB_sgb_border_t; #ifdef GB_INTERNAL struct GB_sgb_s { uint8_t command[16 * 7]; uint16_t command_write_index; bool ready_for_pulse; bool ready_for_write; bool ready_for_stop; bool disable_commands; /* Screen buffer */ uint8_t screen_buffer[160 * 144]; // Live image from the Game Boy uint8_t effective_screen_buffer[160 * 144]; // Image actually rendered to the screen /* Multiplayer Input */ uint8_t player_count, current_player; /* Mask */ uint8_t mask_mode; /* Data Transfer */ uint8_t vram_transfer_countdown, transfer_dest; /* Border */ GB_sgb_border_t border, pending_border; uint8_t border_animation; /* Colorization */ uint16_t effective_palettes[4 * 4]; uint16_t ram_palettes[4 * 512]; uint8_t attribute_map[20 * 18]; uint8_t attribute_files[0xFE0]; /* Intro */ int16_t intro_animation; /* GB Header */ uint8_t received_header[0x54]; /* Multiplayer (cont) */ bool mlt_lock; }; void GB_sgb_write(GB_gameboy_t *gb, uint8_t value); void GB_sgb_render(GB_gameboy_t *gb); void GB_sgb_load_default_data(GB_gameboy_t *gb); #endif #endif
{ "pile_set_name": "Github" }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.waveprotocol.box.webclient.stat.gwtevent; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.user.client.rpc.impl.RemoteServiceProxy; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Stats event dispatcher that uses the GWT global stats function to dispatch * events. */ public class GwtStatisticsEventDispatcher implements StatisticsEventDispatcher { //@Override public boolean enabled() { return RemoteServiceProxy.isStatsAvailable(); } //@Override public StatisticsEvent newEvent(String system, String group, double millis, String type) { Event event = new Event(GWT.getModuleName(), system, group, millis); if (type != null) { setExtraParameter(event, "type", type); } return event; } //@Override public void setExtraParameter(StatisticsEvent event, String name, String value) { ((Event) event).set(name, value); } //@Override public void setExtraParameter(StatisticsEvent event, String name, JavaScriptObject value) { ((Event) event).set(name, value); } //@Override public void dispatch(StatisticsEvent event) { dispatch0(GwtStatisticsEvent.fromEvent(event)); } private native void dispatch0(JavaScriptObject event) /*-{ $stats && $stats(event); }-*/; private static class Event implements StatisticsEvent { private String module; private String system; private String group; private double millis; private Map<String, Object> params; public Event(String module, String system, String group, double millis) { this.module = module; this.system = system; this.group = group; this.millis = millis; this.params = new HashMap<String, Object>(); } //@Override public String getModuleName() { return module; } //@Override public String getSubSystem() { return system; } //@Override public String getEventGroupKey() { return group; } //@Override public double getMillis() { return millis; } //@Override public Iterator<String> getExtraParameterNames() { return params.keySet().iterator(); } //@Override public Object getExtraParameter(String name) { return params.get(name); } protected void set(String name, Object value) { params.put(name, value); } } }
{ "pile_set_name": "Github" }
## @file # This library instance provides IP services upon EFI IPv4/IPv6 Protocols. # # Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR> # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## [Defines] INF_VERSION = 0x00010005 BASE_NAME = DxeIpIoLib MODULE_UNI_FILE = DxeIpIoLib.uni FILE_GUID = A302F877-8625-425c-B1EC-7487B62C4FDA MODULE_TYPE = DXE_DRIVER VERSION_STRING = 1.0 LIBRARY_CLASS = IpIoLib|DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER UEFI_APPLICATION UEFI_DRIVER # # The following information is for reference only and not required by the build tools. # # VALID_ARCHITECTURES = IA32 X64 EBC # [Sources] DxeIpIoLib.c [Packages] MdePkg/MdePkg.dec MdeModulePkg/MdeModulePkg.dec [LibraryClasses] BaseLib DebugLib UefiBootServicesTableLib MemoryAllocationLib BaseMemoryLib DpcLib [Protocols] gEfiIp4ProtocolGuid ## SOMETIMES_CONSUMES gEfiIp4ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES gEfiIp6ProtocolGuid ## SOMETIMES_CONSUMES gEfiIp6ServiceBindingProtocolGuid ## SOMETIMES_CONSUMES
{ "pile_set_name": "Github" }
/* Copyright Rene Rivera 2008-2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_PREDEF_COMPILER_GCC_XML_H #define BOOST_PREDEF_COMPILER_GCC_XML_H #include <boost/predef/version_number.h> #include <boost/predef/make.h> /*` [heading `BOOST_COMP_GCCXML`] [@http://www.gccxml.org/ GCC XML] compiler. [table [[__predef_symbol__] [__predef_version__]] [[`__GCCXML__`] [__predef_detection__]] ] */ #define BOOST_COMP_GCCXML BOOST_VERSION_NUMBER_NOT_AVAILABLE #if defined(__GCCXML__) # define BOOST_COMP_GCCXML_DETECTION BOOST_VERSION_NUMBER_AVAILABLE #endif #ifdef BOOST_COMP_GCCXML_DETECTION # if defined(BOOST_PREDEF_DETAIL_COMP_DETECTED) # define BOOST_COMP_GCCXML_EMULATED BOOST_COMP_GCCXML_DETECTION # else # undef BOOST_COMP_GCCXML # define BOOST_COMP_GCCXML BOOST_COMP_GCCXML_DETECTION # endif # define BOOST_COMP_GCCXML_AVAILABLE # include <boost/predef/detail/comp_detected.h> #endif #define BOOST_COMP_GCCXML_NAME "GCC XML" #endif #include <boost/predef/detail/test.h> BOOST_PREDEF_DECLARE_TEST(BOOST_COMP_GCCXML,BOOST_COMP_GCCXML_NAME) #ifdef BOOST_COMP_GCCXML_EMULATED #include <boost/predef/detail/test.h> BOOST_PREDEF_DECLARE_TEST(BOOST_COMP_GCCXML_EMULATED,BOOST_COMP_GCCXML_NAME) #endif
{ "pile_set_name": "Github" }
// Copyright (C) Christof Meerwald 2003 // Copyright (C) Dan Watkins 2003 // // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // Digital Mars C++ compiler setup: #define BOOST_COMPILER __DMC_VERSION_STRING__ #define BOOST_HAS_LONG_LONG #define BOOST_HAS_PRAGMA_ONCE #if !defined(BOOST_STRICT_CONFIG) #define BOOST_NO_MEMBER_TEMPLATE_FRIENDS #define BOOST_NO_OPERATORS_IN_NAMESPACE #define BOOST_NO_UNREACHABLE_RETURN_DETECTION #define BOOST_NO_SFINAE #define BOOST_NO_USING_TEMPLATE #define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL #endif // // has macros: #define BOOST_HAS_DIRENT_H #define BOOST_HAS_STDINT_H #define BOOST_HAS_WINTHREADS #if (__DMC__ >= 0x847) #define BOOST_HAS_EXPM1 #define BOOST_HAS_LOG1P #endif // // Is this really the best way to detect whether the std lib is in namespace std? // #ifdef __cplusplus #include <cstddef> #endif #if !defined(__STL_IMPORT_VENDOR_CSTD) && !defined(_STLP_IMPORT_VENDOR_CSTD) # define BOOST_NO_STDC_NAMESPACE #endif // check for exception handling support: #if !defined(_CPPUNWIND) && !defined(BOOST_NO_EXCEPTIONS) # define BOOST_NO_EXCEPTIONS #endif // // C++0x features // #define BOOST_NO_CXX11_AUTO_DECLARATIONS #define BOOST_NO_CXX11_AUTO_MULTIDECLARATIONS #define BOOST_NO_CXX11_CHAR16_T #define BOOST_NO_CXX11_CHAR32_T #define BOOST_NO_CXX11_CONSTEXPR #define BOOST_NO_CXX11_DECLTYPE #define BOOST_NO_CXX11_DECLTYPE_N3276 #define BOOST_NO_CXX11_DEFAULTED_FUNCTIONS #define BOOST_NO_CXX11_DELETED_FUNCTIONS #define BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS #define BOOST_NO_CXX11_EXTERN_TEMPLATE #define BOOST_NO_CXX11_HDR_INITIALIZER_LIST #define BOOST_NO_CXX11_LAMBDAS #define BOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS #define BOOST_NO_CXX11_NOEXCEPT #define BOOST_NO_CXX11_NULLPTR #define BOOST_NO_CXX11_RANGE_BASED_FOR #define BOOST_NO_CXX11_RAW_LITERALS #define BOOST_NO_CXX11_RVALUE_REFERENCES #define BOOST_NO_CXX11_SCOPED_ENUMS #define BOOST_NO_SFINAE_EXPR #define BOOST_NO_CXX11_STATIC_ASSERT #define BOOST_NO_CXX11_TEMPLATE_ALIASES #define BOOST_NO_CXX11_UNICODE_LITERALS #define BOOST_NO_CXX11_VARIADIC_TEMPLATES #define BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX #define BOOST_NO_CXX11_USER_DEFINED_LITERALS #define BOOST_NO_CXX11_ALIGNAS #define BOOST_NO_CXX11_TRAILING_RESULT_TYPES #define BOOST_NO_CXX11_INLINE_NAMESPACES #define BOOST_NO_CXX11_REF_QUALIFIERS #define BOOST_NO_CXX11_FINAL // C++ 14: #if !defined(__cpp_aggregate_nsdmi) || (__cpp_aggregate_nsdmi < 201304) # define BOOST_NO_CXX14_AGGREGATE_NSDMI #endif #if !defined(__cpp_binary_literals) || (__cpp_binary_literals < 201304) # define BOOST_NO_CXX14_BINARY_LITERALS #endif #if !defined(__cpp_constexpr) || (__cpp_constexpr < 201304) # define BOOST_NO_CXX14_CONSTEXPR #endif #if !defined(__cpp_decltype_auto) || (__cpp_decltype_auto < 201304) # define BOOST_NO_CXX14_DECLTYPE_AUTO #endif #if (__cplusplus < 201304) // There's no SD6 check for this.... # define BOOST_NO_CXX14_DIGIT_SEPARATORS #endif #if !defined(__cpp_generic_lambdas) || (__cpp_generic_lambdas < 201304) # define BOOST_NO_CXX14_GENERIC_LAMBDAS #endif #if !defined(__cpp_init_captures) || (__cpp_init_captures < 201304) # define BOOST_NO_CXX14_INITIALIZED_LAMBDA_CAPTURES #endif #if !defined(__cpp_return_type_deduction) || (__cpp_return_type_deduction < 201304) # define BOOST_NO_CXX14_RETURN_TYPE_DEDUCTION #endif #if !defined(__cpp_variable_templates) || (__cpp_variable_templates < 201304) # define BOOST_NO_CXX14_VARIABLE_TEMPLATES #endif #if (__DMC__ <= 0x840) #error "Compiler not supported or configured - please reconfigure" #endif // // last known and checked version is ...: #if (__DMC__ > 0x848) # if defined(BOOST_ASSERT_CONFIG) # error "Unknown compiler version - please run the configure tests and report the results" # endif #endif
{ "pile_set_name": "Github" }
.. This data file has been placed in the public domain. .. Derived from the Unicode character mappings available from <http://www.w3.org/2003/entities/xml/>. Processed by unicode2rstsubs.py, part of Docutils: <http://docutils.sourceforge.net>. .. |af| unicode:: U+02061 .. FUNCTION APPLICATION .. |aopf| unicode:: U+1D552 .. MATHEMATICAL DOUBLE-STRUCK SMALL A .. |asympeq| unicode:: U+0224D .. EQUIVALENT TO .. |bopf| unicode:: U+1D553 .. MATHEMATICAL DOUBLE-STRUCK SMALL B .. |copf| unicode:: U+1D554 .. MATHEMATICAL DOUBLE-STRUCK SMALL C .. |Cross| unicode:: U+02A2F .. VECTOR OR CROSS PRODUCT .. |DD| unicode:: U+02145 .. DOUBLE-STRUCK ITALIC CAPITAL D .. |dd| unicode:: U+02146 .. DOUBLE-STRUCK ITALIC SMALL D .. |dopf| unicode:: U+1D555 .. MATHEMATICAL DOUBLE-STRUCK SMALL D .. |DownArrowBar| unicode:: U+02913 .. DOWNWARDS ARROW TO BAR .. |DownBreve| unicode:: U+00311 .. COMBINING INVERTED BREVE .. |DownLeftRightVector| unicode:: U+02950 .. LEFT BARB DOWN RIGHT BARB DOWN HARPOON .. |DownLeftTeeVector| unicode:: U+0295E .. LEFTWARDS HARPOON WITH BARB DOWN FROM BAR .. |DownLeftVectorBar| unicode:: U+02956 .. LEFTWARDS HARPOON WITH BARB DOWN TO BAR .. |DownRightTeeVector| unicode:: U+0295F .. RIGHTWARDS HARPOON WITH BARB DOWN FROM BAR .. |DownRightVectorBar| unicode:: U+02957 .. RIGHTWARDS HARPOON WITH BARB DOWN TO BAR .. |ee| unicode:: U+02147 .. DOUBLE-STRUCK ITALIC SMALL E .. |EmptySmallSquare| unicode:: U+025FB .. WHITE MEDIUM SQUARE .. |EmptyVerySmallSquare| unicode:: U+025AB .. WHITE SMALL SQUARE .. |eopf| unicode:: U+1D556 .. MATHEMATICAL DOUBLE-STRUCK SMALL E .. |Equal| unicode:: U+02A75 .. TWO CONSECUTIVE EQUALS SIGNS .. |FilledSmallSquare| unicode:: U+025FC .. BLACK MEDIUM SQUARE .. |FilledVerySmallSquare| unicode:: U+025AA .. BLACK SMALL SQUARE .. |fopf| unicode:: U+1D557 .. MATHEMATICAL DOUBLE-STRUCK SMALL F .. |gopf| unicode:: U+1D558 .. MATHEMATICAL DOUBLE-STRUCK SMALL G .. |GreaterGreater| unicode:: U+02AA2 .. DOUBLE NESTED GREATER-THAN .. |Hat| unicode:: U+0005E .. CIRCUMFLEX ACCENT .. |hopf| unicode:: U+1D559 .. MATHEMATICAL DOUBLE-STRUCK SMALL H .. |HorizontalLine| unicode:: U+02500 .. BOX DRAWINGS LIGHT HORIZONTAL .. |ic| unicode:: U+02063 .. INVISIBLE SEPARATOR .. |ii| unicode:: U+02148 .. DOUBLE-STRUCK ITALIC SMALL I .. |iopf| unicode:: U+1D55A .. MATHEMATICAL DOUBLE-STRUCK SMALL I .. |it| unicode:: U+02062 .. INVISIBLE TIMES .. |jopf| unicode:: U+1D55B .. MATHEMATICAL DOUBLE-STRUCK SMALL J .. |kopf| unicode:: U+1D55C .. MATHEMATICAL DOUBLE-STRUCK SMALL K .. |larrb| unicode:: U+021E4 .. LEFTWARDS ARROW TO BAR .. |LeftDownTeeVector| unicode:: U+02961 .. DOWNWARDS HARPOON WITH BARB LEFT FROM BAR .. |LeftDownVectorBar| unicode:: U+02959 .. DOWNWARDS HARPOON WITH BARB LEFT TO BAR .. |LeftRightVector| unicode:: U+0294E .. LEFT BARB UP RIGHT BARB UP HARPOON .. |LeftTeeVector| unicode:: U+0295A .. LEFTWARDS HARPOON WITH BARB UP FROM BAR .. |LeftTriangleBar| unicode:: U+029CF .. LEFT TRIANGLE BESIDE VERTICAL BAR .. |LeftUpDownVector| unicode:: U+02951 .. UP BARB LEFT DOWN BARB LEFT HARPOON .. |LeftUpTeeVector| unicode:: U+02960 .. UPWARDS HARPOON WITH BARB LEFT FROM BAR .. |LeftUpVectorBar| unicode:: U+02958 .. UPWARDS HARPOON WITH BARB LEFT TO BAR .. |LeftVectorBar| unicode:: U+02952 .. LEFTWARDS HARPOON WITH BARB UP TO BAR .. |LessLess| unicode:: U+02AA1 .. DOUBLE NESTED LESS-THAN .. |lopf| unicode:: U+1D55D .. MATHEMATICAL DOUBLE-STRUCK SMALL L .. |mapstodown| unicode:: U+021A7 .. DOWNWARDS ARROW FROM BAR .. |mapstoleft| unicode:: U+021A4 .. LEFTWARDS ARROW FROM BAR .. |mapstoup| unicode:: U+021A5 .. UPWARDS ARROW FROM BAR .. |MediumSpace| unicode:: U+0205F .. MEDIUM MATHEMATICAL SPACE .. |mopf| unicode:: U+1D55E .. MATHEMATICAL DOUBLE-STRUCK SMALL M .. |nbump| unicode:: U+0224E U+00338 .. GEOMETRICALLY EQUIVALENT TO with slash .. |nbumpe| unicode:: U+0224F U+00338 .. DIFFERENCE BETWEEN with slash .. |nesim| unicode:: U+02242 U+00338 .. MINUS TILDE with slash .. |NewLine| unicode:: U+0000A .. LINE FEED (LF) .. |NoBreak| unicode:: U+02060 .. WORD JOINER .. |nopf| unicode:: U+1D55F .. MATHEMATICAL DOUBLE-STRUCK SMALL N .. |NotCupCap| unicode:: U+0226D .. NOT EQUIVALENT TO .. |NotHumpEqual| unicode:: U+0224F U+00338 .. DIFFERENCE BETWEEN with slash .. |NotLeftTriangleBar| unicode:: U+029CF U+00338 .. LEFT TRIANGLE BESIDE VERTICAL BAR with slash .. |NotNestedGreaterGreater| unicode:: U+02AA2 U+00338 .. DOUBLE NESTED GREATER-THAN with slash .. |NotNestedLessLess| unicode:: U+02AA1 U+00338 .. DOUBLE NESTED LESS-THAN with slash .. |NotRightTriangleBar| unicode:: U+029D0 U+00338 .. VERTICAL BAR BESIDE RIGHT TRIANGLE with slash .. |NotSquareSubset| unicode:: U+0228F U+00338 .. SQUARE IMAGE OF with slash .. |NotSquareSuperset| unicode:: U+02290 U+00338 .. SQUARE ORIGINAL OF with slash .. |NotSucceedsTilde| unicode:: U+0227F U+00338 .. SUCCEEDS OR EQUIVALENT TO with slash .. |oopf| unicode:: U+1D560 .. MATHEMATICAL DOUBLE-STRUCK SMALL O .. |OverBar| unicode:: U+000AF .. MACRON .. |OverBrace| unicode:: U+0FE37 .. PRESENTATION FORM FOR VERTICAL LEFT CURLY BRACKET .. |OverBracket| unicode:: U+023B4 .. TOP SQUARE BRACKET .. |OverParenthesis| unicode:: U+0FE35 .. PRESENTATION FORM FOR VERTICAL LEFT PARENTHESIS .. |planckh| unicode:: U+0210E .. PLANCK CONSTANT .. |popf| unicode:: U+1D561 .. MATHEMATICAL DOUBLE-STRUCK SMALL P .. |Product| unicode:: U+0220F .. N-ARY PRODUCT .. |qopf| unicode:: U+1D562 .. MATHEMATICAL DOUBLE-STRUCK SMALL Q .. |rarrb| unicode:: U+021E5 .. RIGHTWARDS ARROW TO BAR .. |RightDownTeeVector| unicode:: U+0295D .. DOWNWARDS HARPOON WITH BARB RIGHT FROM BAR .. |RightDownVectorBar| unicode:: U+02955 .. DOWNWARDS HARPOON WITH BARB RIGHT TO BAR .. |RightTeeVector| unicode:: U+0295B .. RIGHTWARDS HARPOON WITH BARB UP FROM BAR .. |RightTriangleBar| unicode:: U+029D0 .. VERTICAL BAR BESIDE RIGHT TRIANGLE .. |RightUpDownVector| unicode:: U+0294F .. UP BARB RIGHT DOWN BARB RIGHT HARPOON .. |RightUpTeeVector| unicode:: U+0295C .. UPWARDS HARPOON WITH BARB RIGHT FROM BAR .. |RightUpVectorBar| unicode:: U+02954 .. UPWARDS HARPOON WITH BARB RIGHT TO BAR .. |RightVectorBar| unicode:: U+02953 .. RIGHTWARDS HARPOON WITH BARB UP TO BAR .. |ropf| unicode:: U+1D563 .. MATHEMATICAL DOUBLE-STRUCK SMALL R .. |RoundImplies| unicode:: U+02970 .. RIGHT DOUBLE ARROW WITH ROUNDED HEAD .. |RuleDelayed| unicode:: U+029F4 .. RULE-DELAYED .. |sopf| unicode:: U+1D564 .. MATHEMATICAL DOUBLE-STRUCK SMALL S .. |Tab| unicode:: U+00009 .. CHARACTER TABULATION .. |ThickSpace| unicode:: U+02009 U+0200A U+0200A .. space of width 5/18 em .. |topf| unicode:: U+1D565 .. MATHEMATICAL DOUBLE-STRUCK SMALL T .. |UnderBar| unicode:: U+00332 .. COMBINING LOW LINE .. |UnderBrace| unicode:: U+0FE38 .. PRESENTATION FORM FOR VERTICAL RIGHT CURLY BRACKET .. |UnderBracket| unicode:: U+023B5 .. BOTTOM SQUARE BRACKET .. |UnderParenthesis| unicode:: U+0FE36 .. PRESENTATION FORM FOR VERTICAL RIGHT PARENTHESIS .. |uopf| unicode:: U+1D566 .. MATHEMATICAL DOUBLE-STRUCK SMALL U .. |UpArrowBar| unicode:: U+02912 .. UPWARDS ARROW TO BAR .. |Upsilon| unicode:: U+003A5 .. GREEK CAPITAL LETTER UPSILON .. |VerticalLine| unicode:: U+0007C .. VERTICAL LINE .. |VerticalSeparator| unicode:: U+02758 .. LIGHT VERTICAL BAR .. |vopf| unicode:: U+1D567 .. MATHEMATICAL DOUBLE-STRUCK SMALL V .. |wopf| unicode:: U+1D568 .. MATHEMATICAL DOUBLE-STRUCK SMALL W .. |xopf| unicode:: U+1D569 .. MATHEMATICAL DOUBLE-STRUCK SMALL X .. |yopf| unicode:: U+1D56A .. MATHEMATICAL DOUBLE-STRUCK SMALL Y .. |ZeroWidthSpace| unicode:: U+0200B .. ZERO WIDTH SPACE .. |zopf| unicode:: U+1D56B .. MATHEMATICAL DOUBLE-STRUCK SMALL Z
{ "pile_set_name": "Github" }
'use strict'; exports.__esModule = true; exports.default = { el: { colorpicker: { confirm: 'OK', clear: 'Leeren' }, datepicker: { now: 'Jetzt', today: 'Heute', cancel: 'Abbrechen', clear: 'Leeren', confirm: 'OK', selectDate: 'Datum wählen', selectTime: 'Uhrzeit wählen', startDate: 'Startdatum', startTime: 'Startzeit', endDate: 'Enddatum', endTime: 'Endzeit', prevYear: 'Letztes Jahr', nextYear: 'Nächtes Jahr', prevMonth: 'Letzter Monat', nextMonth: 'Nächster Monat', day: 'Tag', week: 'Woche', month: 'Monat', year: '', month1: 'Januar', month2: 'Februar', month3: 'März', month4: 'April', month5: 'Mai', month6: 'Juni', month7: 'Juli', month8: 'August', month9: 'September', month10: 'Oktober', month11: 'November', month12: 'Dezember', weeks: { sun: 'So', mon: 'Mo', tue: 'Di', wed: 'Mi', thu: 'Do', fri: 'Fr', sat: 'Sa' }, months: { jan: 'Jan', feb: 'Feb', mar: 'Mär', apr: 'Apr', may: 'Mai', jun: 'Jun', jul: 'Jul', aug: 'Aug', sep: 'Sep', oct: 'Okt', nov: 'Nov', dec: 'Dez' } }, select: { loading: 'Lädt.', noMatch: 'Nichts gefunden.', noData: 'Keine Daten', placeholder: 'Daten wählen' }, cascader: { noMatch: 'Nichts gefunden.', loading: 'Lädt.', placeholder: 'Daten wählen', noData: 'Keine Daten' }, pagination: { goto: 'Gehe zu', pagesize: ' pro Seite', total: 'Gesamt {total}', pageClassifier: '' }, messagebox: { confirm: 'OK', cancel: 'Abbrechen', error: 'Fehler' }, upload: { deleteTip: 'Klicke löschen zum entfernen', delete: 'Löschen', preview: 'Vorschau', continue: 'Fortsetzen' }, table: { emptyText: 'Keine Daten', confirmFilter: 'Anwenden', resetFilter: 'Zurücksetzen', clearFilter: 'Alles ', sumText: 'Summe' }, tree: { emptyText: 'Keine Einträge' }, transfer: { noMatch: 'Nichts gefunden.', noData: 'Keine Einträge', titles: ['Liste 1', 'Liste 2'], filterPlaceholder: 'Einträge filtern', noCheckedFormat: '{total} Einträge', hasCheckedFormat: '{checked}/{total} ausgewählt' }, image: { error: 'FAILED' // to be translated }, pageHeader: { title: 'Back' // to be translated }, popconfirm: { confirmButtonText: 'Yes', // to be translated cancelButtonText: 'No' // to be translated } } };
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: b6944b8ec29ad124c9ebbe7b111fdfd5 TextureImporter: fileIDToRecycleName: {} serializedVersion: 2 mipmaps: mipMapMode: 0 enableMipMap: 1 linearTexture: 0 correctGamma: 0 fadeOut: 0 borderMipMap: 0 mipMapFadeDistanceStart: 1 mipMapFadeDistanceEnd: 3 bumpmap: convertToNormalMap: 0 externalNormalMap: 0 heightScale: .25 normalMapFilter: 0 isReadable: 0 grayScaleToAlpha: 1 generateCubemap: 0 cubemapConvolution: 0 cubemapConvolutionSteps: 8 cubemapConvolutionExponent: 1.5 seamlessCubemap: 0 textureFormat: 1 maxTextureSize: 1024 textureSettings: filterMode: -1 aniso: -1 mipBias: -1 wrapMode: 1 nPOTScale: 1 lightmap: 0 rGBM: 0 compressionQuality: 50 spriteMode: 0 spriteExtrude: 1 spriteMeshType: 1 alignment: 0 spritePivot: {x: .5, y: .5} spriteBorder: {x: 0, y: 0, z: 0, w: 0} spritePixelsToUnits: 100 alphaIsTransparency: 1 textureType: 5 buildTargetSettings: [] spriteSheet: sprites: [] spritePackingTag: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
--- title: TaskRequestItem.CustomAction Event (Outlook) ms.prod: outlook api_name: - Outlook.TaskRequestItem.CustomAction ms.assetid: 1b4fbc87-6494-b85e-f5a6-c2a538a21078 ms.date: 06/08/2017 --- # TaskRequestItem.CustomAction Event (Outlook) Occurs when a custom action of an item (which is an instance of the parent object) executes. ## Syntax _expression_ . **CustomAction**( **_Action_** , **_Response_** , **_Cancel_** ) _expression_ A variable that represents a **TaskRequestItem** object. ### Parameters |**Name**|**Required/Optional**|**Data Type**|**Description**| |:-----|:-----|:-----|:-----| | _Action_|Required| **Object**|The **[Action](action-object-outlook.md)** object.| | _Response_|Required| **Object**|The newly created item resulting from the custom action.| | _Cancel_|Required| **Boolean**|(Not used in VBScript). **False** when the event occurs. If the event procedure sets this argument to **True** , the custom action is not completed.| ## Remarks The **Action** object and the newly created item resulting from the custom action are passed to the event. In Microsoft Visual Basic Scripting Edition (VBScript), if you set the return value of this function to **False** , the custom action operation is not completed. ## See also #### Concepts [TaskRequestItem Object](taskrequestitem-object-outlook.md)
{ "pile_set_name": "Github" }
""" Python wrapper for libui. """ from pylibui import libui from .control import Control class BaseMultilineEntry(Control): def getText(self): """ Returns the text of the multiline entry. :return: string """ return libui.uiMultilineEntryText(self.control) def setText(self, text): """ Sets the text of the multiline entry. :param text: string :return: None """ libui.uiMultilineEntrySetText(self.control, text) def append(self, text): """ Appends some text to the multiline entry. :param text: string :return: None """ libui.uiMultilineEntryAppend(self.control, text) def onChanged(self, data): """ Executes when the multiline entry is changed. :param data: data :return: None """ pass def getReadOnly(self): """ Returns whether the multiline entry is read only or not. :return: bool """ return bool(libui.uiMultilineEntryReadOnly(self.control)) def setReadOnly(self, read_only): """ Sets whether the multiline entry is read only or not. :param read_only: bool :return: None """ libui.uiMultilineEntrySetReadOnly(self.control, int(read_only)) class MultilineEntry(BaseMultilineEntry): def __init__(self): """ Creates a new multiline entry. """ super().__init__() self.control = libui.uiNewMultilineEntry() def handler(window, data): self.onChanged(data) return 0 self.changedHandler = libui.uiMultilineEntryOnChanged( self.control, handler, None) class NonWrappingMultilineEntry(BaseMultilineEntry): def __init__(self): """ Creates a new non wrapping multiline entry. """ super().__init__() self.control = libui.uiNewNonWrappingMultilineEntry() def handler(window, data): self.onChanged(data) return 0 self.changedHandler = libui.uiMultilineEntryOnChanged( self.control, handler, None)
{ "pile_set_name": "Github" }
print('hi')
{ "pile_set_name": "Github" }
package com.github.anastr.speedviewapp; import android.os.Bundle; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.SeekBar; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.github.anastr.speedviewlib.Speedometer; import java.util.Locale; import kotlin.jvm.functions.Function2; public class TickActivity extends AppCompatActivity { Speedometer speedometer; CheckBox withRotation; SeekBar seekBarTickNumbers, seekBarTickPadding; TextView textTicks, textTickPadding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tick); setTitle("Work With Ticks"); speedometer = findViewById(R.id.speedometer); withRotation = findViewById(R.id.cb_withRotation); seekBarTickNumbers = findViewById(R.id.seekBarStartDegree); seekBarTickPadding = findViewById(R.id.seekBarTickPadding); textTicks = findViewById(R.id.textTickNumber); textTickPadding = findViewById(R.id.textTickPadding); speedometer.speedPercentTo(53); speedometer.setOnPrintTickLabel(new Function2<Integer, Float, CharSequence>() { @Override public CharSequence invoke(Integer tickPosition, Float tick) { if (tick == 0) { SpannableString s = new SpannableString(String.format(Locale.getDefault(), "%.1f", tick)); s.setSpan(new ForegroundColorSpan(0xffff1117), 0, 1, 0); return s; } return null; } }); withRotation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { speedometer.setTickRotation(b); } }); seekBarTickNumbers.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int value, boolean b) { speedometer.setTickNumber(value); textTicks.setText(String.format(Locale.getDefault(), "%d", value)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); seekBarTickPadding.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int value, boolean b) { speedometer.setTickPadding((int) speedometer.dpTOpx(value)); textTickPadding.setText(String.format(Locale.getDefault(), "%d dp", value)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } }
{ "pile_set_name": "Github" }
############# suite/perfschema/t/transaction.test #################### # # # Test processing of transaction events by the Performance Schema, # # including explicit/implicit transactions, access modes, isolation # # levels, statement counts and state transitions. # # # # # ###################################################################### --source include/have_perfschema.inc --source include/not_embedded.inc --source include/have_innodb.inc --source include/no_protocol.inc --disable_query_log --source ../include/transaction_setup.inc --enable_query_log set global binlog_format=ROW; --echo # --echo # ======================================================================== --echo # STEP 1 - SETUP --echo # ======================================================================== --echo # --echo # Control thread --echo # --connection default SET SESSION AUTOCOMMIT= 1; eval $get_thread_id; let $default_thread_id= `SELECT @my_thread_id`; --echo # --echo # Connection 1 --echo # connect(con1, localhost, root,,); --disable_query_log eval $get_thread_id; let $con1_thread_id= `SELECT @my_thread_id`; --enable_query_log SET SESSION AUTOCOMMIT= 0; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ WRITE; --disable_parsing --echo # --echo # Connection 2 --echo # connect(con2, localhost, root,,); --disable_query_log eval $get_thread_id; let $con2_thread_id= `SELECT @my_thread_id`; --enable_query_log SET SESSION AUTOCOMMIT= 0; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ WRITE; --enable_parsing --connection default --disable_query_log eval SET @con1_thread_id= $con1_thread_id; #eval SET @con2_thread_id= $con2_thread_id; --enable_query_log --echo # --echo # Create test tables, one transactional and one non-transactional --echo # --connection default --disable_warnings DROP TABLE IF EXISTS t1; DROP TABLE IF EXISTS nt1; --enable_warnings CREATE TABLE t1 (s1 int, s2 varchar(64)) ENGINE=INNODB; CREATE TABLE nt1 (s1 int, s2 varchar(64)) ENGINE=MYISAM; --echo # --echo # Disable all events from the control thread --echo # --disable_query_log UPDATE performance_schema.threads SET instrumented='NO' WHERE processlist_id = CONNECTION_ID(); --enable_query_log --echo # --echo # Clear transaction tables --echo # CALL clear_transaction_tables(); --echo # --echo # ======================================================================== --echo # STEP 2 - BASIC TRANSACTION --echo # ======================================================================== --echo # --connection con1 SELECT @@global.tx_isolation; SELECT @@global.autocommit; SELECT @@global.binlog_format; SELECT @@tx_isolation; SELECT @@autocommit; SELECT @@binlog_format; --echo # --echo # STEP 2.1 - START/COMMIT --echo # START TRANSACTION; INSERT INTO t1 VALUES (101, 'COMMITTED'); COMMIT; --echo # --echo # STEP 2.2 - ROLLBACK --echo # START TRANSACTION; INSERT INTO t1 VALUES (102, 'ROLLED BACK'); ROLLBACK; --echo # --echo ## Expect 1 committed and 1 rolled back transaction --connection default CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', 'REPEATABLE READ', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'ROLLED BACK', 0, '', '', '', '', 'READ WRITE', 'REPEATABLE READ', 'NO', 0, 0, 0, 1); CALL clear_transaction_tables(); --echo # --echo # STEP 2.3 - COMMIT AND CHAIN --echo # --connection con1 START TRANSACTION; INSERT INTO t1 VALUES (103, 'COMMIT AND CHAIN'); COMMIT AND CHAIN; INSERT INTO t1 VALUES (104, 'COMMIT AND CHAIN'); COMMIT; --echo # --echo ## Expect 2 committed transactions --connection default CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', 'REPEATABLE READ', 'NO', 0, 0, 0, 2); CALL clear_transaction_tables(); --echo # --echo # ======================================================================== --echo # STEP 3 - ISOLATION LEVEL --echo # ======================================================================== --echo # --echo # connection con1 --connection con1 SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE; START TRANSACTION; INSERT INTO t1 VALUES (301, 'SERIALIZABLE'); COMMIT; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; START TRANSACTION; INSERT INTO t1 VALUES (302, 'REPEATABLE READ'); COMMIT; ## NOTE - InnoDB requires binlog_format = ROW for READ COMMITTED/UNCOMMITTED SELECT @@binlog_format INTO @binlog_save; SET SESSION BINLOG_FORMAT=ROW; SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; START TRANSACTION; INSERT INTO t1 VALUES (303, 'READ COMMITTED'); COMMIT; SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; START TRANSACTION; INSERT INTO t1 VALUES (304, 'READ UNCOMMITTED'); COMMIT; SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ; SET binlog_format= @binlog_save; --echo # --connection default CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', 'SERIALIZABLE', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', 'REPEATABLE READ', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', 'READ COMMITTED', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', 'READ UNCOMMITTED', 'NO', 0, 0, 0, 1); CALL clear_transaction_tables(); --echo # --echo # ======================================================================== --echo # STEP 4 - ACCESS MODE --echo # ======================================================================== --echo # --echo # STEP 4.1 - READ ONLY, TIMING ENABLED --echo # --echo # --echo # connection con1 --connection con1 SET SESSION TRANSACTION READ WRITE; START TRANSACTION; INSERT INTO t1 VALUES (410, 'READ ONLY'); INSERT INTO t1 VALUES (411, 'READ ONLY'); INSERT INTO t1 VALUES (412, 'READ ONLY'); INSERT INTO t1 VALUES (413, 'READ ONLY'); COMMIT; SET SESSION TRANSACTION READ ONLY; START TRANSACTION; SELECT * FROM t1 ORDER BY s1; COMMIT; --echo # --echo ## Expect 1 read only, committed transaction in events_transactions_history --connection default CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ ONLY', 'REPEATABLE READ', 'NO', 0, 0, 0, 1); CALL clear_transaction_tables(); --echo # --echo # --echo # STEP 4.2 - READ ONLY, TIMING DISABLED --echo # --echo # --echo ## Disable timing stats for 'transaction' UPDATE performance_schema.setup_instruments SET timed = 'NO' WHERE name = 'transaction'; --echo # TRUNCATE performance_schema.events_transactions_summary_global_by_event_name; --echo # connection con1 --connection con1 START TRANSACTION; SELECT * FROM t1 ORDER BY s1; COMMIT; --echo # SET SESSION TRANSACTION READ WRITE; --connection default --echo # --echo ## Expect 1 event, 0 stats SELECT * FROM performance_schema.events_transactions_summary_global_by_event_name; --echo # --echo ## Restore setup_instruments UPDATE performance_schema.setup_instruments SET enabled = 'YES' WHERE name = 'transaction'; --echo # --echo # ======================================================================== --echo # STEP 5 - IMPLICIT START --echo # ======================================================================== --echo # When AUTOCOMMIT is disabled, the first statement following a committed --echo # transaction marks the start of a new transaction. Subsequent statements will --echo # be part of the transaction until it is committed. --echo # --connection con1 SET SESSION AUTOCOMMIT = 0; INSERT INTO t1 VALUES (501, 'IMPLICIT START'); --echo # --echo ## Expect 1 active transaction in events_transactions_current --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ACTIVE', 0, '', '', '', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); --connection con1 INSERT INTO t1 VALUES (502, 'IMPLICIT START'); COMMIT; --echo # --echo ## Expect one committed transaction in events_transactions_current and history --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL clear_transaction_tables(); --echo # --echo # ======================================================================== --echo # STEP 6 - IMPLICIT COMMIT (DDL, ETC) --echo # ======================================================================== --echo # Transactions are implicitly ended by DDL statements, locking statements --echo # and server administration commands. --echo # --connection con1 SET SESSION AUTOCOMMIT = 0; INSERT INTO t1 VALUES (601, 'IMPLICIT COMMIT'); --echo # --echo ## Expect one active transaction in events_transactions_current, zero events in history --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ACTIVE', 0, '', '', '', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', '', 0, '', '', '', '', '', '', 'NO', 0, 0, 0, 0); --connection con1 INSERT INTO t1 VALUES (602, 'IMPLICIT COMMIT'); --echo ## Issue a DDL statement to force a commmit CREATE TABLE t2 (s1 INT, s2 VARCHAR(64)) ENGINE=INNODB; --echo # --echo ## Expect 0 active transactions, 1 committed transaction --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ACTIVE', 0, '', '', '', '', 'READ WRITE', '', 'NO', 0, 0, 0, 0); CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL clear_transaction_tables(); DROP TABLE test.t2; --echo # --echo # ======================================================================== --echo # STEP 7 - XA TRANSACTIONS --echo # ======================================================================== --echo # --echo # STEP 7.1 - XA START --echo # --connection con1 XA START 'XA_CON1_GTRID_001', 'XA_CON1_BQUAL_001', 1234567890; --echo # --echo ## Expect 1 active XA transaction, state ACTIVE --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ACTIVE', 1234567890, 'XA_CON1_GTRID_001', 'XA_CON1_BQUAL_001', 'ACTIVE', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); --echo # --echo # STEP 7.2 - XA END --echo # --connection con1 INSERT INTO t1 VALUES (701, 'XA'); XA END 'XA_CON1_GTRID_001', 'XA_CON1_BQUAL_001', 1234567890; --echo # --echo ## Expect 1 active XA transaction, state IDLE --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ACTIVE', 1234567890, 'XA_CON1_GTRID_001', 'XA_CON1_BQUAL_001', 'IDLE', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); --echo # --echo # --echo # STEP 7.3 - XA PREPARE --echo # --connection con1 XA PREPARE 'XA_CON1_GTRID_001', 'XA_CON1_BQUAL_001', 1234567890; --echo # --echo ## Expect 1 active XA transaction, state PREPARED --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ACTIVE', 1234567890, 'XA_CON1_GTRID_001', 'XA_CON1_BQUAL_001', 'PREPARED', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); --echo # --echo # --echo # STEP 7.4 - XA COMMIT --echo # --connection con1 XA COMMIT 'XA_CON1_GTRID_001', 'XA_CON1_BQUAL_001', 1234567890; --echo # --echo ## Expect 1 committed XA transaction, state COMMITTED in current and history --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'COMMITTED', 1234567890, 'XA_CON1_GTRID_001', 'XA_CON1_BQUAL_001', 'COMMITTED', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 1234567890, 'XA_CON1_GTRID_001', 'XA_CON1_BQUAL_001', 'COMMITTED', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL clear_transaction_tables(); --echo # --echo # --echo # STEP 7.5 - XA ROLLBACK --echo # --connection con1 XA START 'XA_CON1_002'; INSERT INTO t1 VALUES (702, 'XA'); XA END 'XA_CON1_002'; XA PREPARE 'XA_CON1_002'; --echo # --echo ## Expect 1 active XA transaction, state PREPARED --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ACTIVE', 0, 'XA_CON1_002', '', 'PREPARED', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); --connection con1 XA ROLLBACK 'XA_CON1_002'; --echo # --echo ## Expect 1 XA transaction, state ROLLBACK ONLY in current and history --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ROLLED BACK', 0, 'XA_CON1_002', '', 'ROLLBACK ONLY', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'ROLLED BACK', 0, 'XA_CON1_002', '', 'ROLLBACK ONLY', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL clear_transaction_tables(); SELECT * FROM performance_schema.events_transactions_current ORDER BY event_id; --echo # --echo # STEP 7.6 - XA TRANSACTION - LONG GTRID AND BQUAL --echo # --connection con1 XA START 'GTRID_6789012345678901234567890123456789012345678901234567890123','BQUAL_6789012345678901234567890123456789012345678901234567890123',1234567890; INSERT INTO t1 VALUES (703, 'XA LONG'); XA END 'GTRID_6789012345678901234567890123456789012345678901234567890123','BQUAL_6789012345678901234567890123456789012345678901234567890123',1234567890; XA PREPARE 'GTRID_6789012345678901234567890123456789012345678901234567890123','BQUAL_6789012345678901234567890123456789012345678901234567890123',1234567890; XA COMMIT 'GTRID_6789012345678901234567890123456789012345678901234567890123','BQUAL_6789012345678901234567890123456789012345678901234567890123',1234567890; --echo # --echo ## Expect 1 committed XA transaction, state COMMITTED in current and history --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'COMMITTED', 1234567890, 'GTRID_6789012345678901234567890123456789012345678901234567890123', 'BQUAL_6789012345678901234567890123456789012345678901234567890123', 'COMMITTED', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 1234567890, 'GTRID_6789012345678901234567890123456789012345678901234567890123', 'BQUAL_6789012345678901234567890123456789012345678901234567890123', 'COMMITTED', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL clear_transaction_tables(); --echo # --echo # STEP 7.7 - XA TRANSACTION - LONG GTRID AND BINARY BQUAL --echo # --connection con1 XA START 'GTRID_6789012345678901234567890123456789012345678901234567890123',0x425155414C5FA5A53839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233,1234567890; INSERT INTO t1 VALUES (704, 'XA LONG/BINARY'); XA END 'GTRID_6789012345678901234567890123456789012345678901234567890123',0x425155414C5FA5A53839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233,1234567890; XA PREPARE 'GTRID_6789012345678901234567890123456789012345678901234567890123',0x425155414C5FA5A53839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233,1234567890; XA COMMIT 'GTRID_6789012345678901234567890123456789012345678901234567890123',0x425155414C5FA5A53839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233,1234567890; --echo # --echo ## Expect 1 committed XA transaction, state COMMITTED in current and history --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'COMMITTED', 1234567890, 'GTRID_6789012345678901234567890123456789012345678901234567890123', '0x425155414C5FA5A53839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233', 'COMMITTED', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 1234567890, 'GTRID_6789012345678901234567890123456789012345678901234567890123', '0x425155414C5FA5A53839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233', 'COMMITTED', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL clear_transaction_tables(); --echo # --echo # ======================================================================== --echo # STEP 8 - TRANSACTIONAL AND NON-TRANSACTIONAL TABLES --echo # ======================================================================== --echo # --echo ## MariaDB bug: MDEV-6012? MDEV-14436? set @mariadb_bug=1; ## Statements that work with non-transactional engines have no effect on the ## transaction state of the connection. For implicit transactions, ## the transaction event begins with the first statement that uses a ## transactional engine. This means that statements operating exclusively on ## non-transactional tables will be ignored, even following START TRANSACTION. --connection con1 SET SESSION AUTOCOMMIT = 0; SELECT * FROM performance_schema.events_transactions_current ORDER BY event_id; --echo # --echo # --echo # STEP 8.1 - UPDATE NON-TRANSACTIONAL TABLE --echo # INSERT INTO nt1 VALUES (801, 'NON-TRANSACTIONAL'); --echo # --echo ## Expect 0 transactions in events_transactions_current --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', '', 0, '', '', '', '', '', '', '', 0, 0, 0, @mariadb_bug); --connection con1 COMMIT; --echo # --echo ## Expect 0 transactions in events_transactions_history --connection default CALL transaction_verifier(1, @con1_thread_id, 'transaction', '', 0, '', '', '', '', '', '', '', 0, 0, 0, @mariadb_bug); --echo # --echo # --echo # STEP 8.2 - UPDATE TRANSACTIONAL AND NON-TRANSACTIONAL TABLES --echo # --echo # --echo ## First non-transactional... --echo # --connection con1 INSERT INTO nt1 VALUES (802, 'NON-TRANSACTIONAL'); --echo # --echo ## Expect 0 transactions in events_transactions_current --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', '', 0, '', '', '', '', '', '', '', 0, 0, 0, @mariadb_bug); --echo # --echo ## Now transactional. Transaction should be started. --connection con1 INSERT INTO t1 VALUES (802, 'TRANSACTIONAL'); --echo # --echo ## Expect 1 transaction in events_transactions_current --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ACTIVE', 0, '', '', '', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); ## Commit --echo # --connection con1 COMMIT; --echo # --echo ## Expect 1 committed transaction in events_transactions_current and history --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1+@mariadb_bug); CALL clear_transaction_tables(); --echo # --echo # ======================================================================== --echo # STEP 9 - SAVEPOINTS --echo # ======================================================================== --echo # --echo # STEP 9.1 - SAVEPOINT 1 --echo # --connection con1 START TRANSACTION; INSERT INTO t1 VALUES (901, 'SAVEPOINT'); SAVEPOINT SVP001; --echo # --echo ## Expect 1 active transaction with 1 savepoint --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ACTIVE', 0, '', '', '', '', 'READ WRITE', '', 'NO', 1, 0, 0, 1); --echo # --echo # --echo # STEP 9.2 - SAVEPOINTS 2 and 3 --echo # --connection con1 INSERT INTO t1 VALUES (902, 'SAVEPOINT'); SAVEPOINT SVP002; INSERT INTO t1 VALUES (903, 'SAVEPOINT'); SAVEPOINT SVP003; INSERT INTO t1 VALUES (904, 'SAVEPOINT'); SELECT COUNT(*) FROM t1 WHERE s1 > 900; --echo # --echo # --echo # STEP 9.3 - ROLLBACK TO SAVEPOINT 2 --echo # --connection con1 ROLLBACK TO SVP002; --echo # --echo ## Expect 1 active transaction with 3 savepoints, 1 rollback to savepoint --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ACTIVE', 0, '', '', '', '', 'READ WRITE', '', 'NO', 3, 1, 0, 1); --echo # --echo # --echo # STEP 9.4 - RELEASE SAVEPOINT 1 --echo # --connection con1 RELEASE SAVEPOINT SVP001; --echo # --echo ## Expect 1 active transaction with 3 savepoints, 1 rollback to savepoint, 1 release savepoint --connection default CALL transaction_verifier(0, @con1_thread_id, 'transaction', 'ACTIVE', 0, '', '', '', '', 'READ WRITE', '', 'NO', 3, 1, 1, 1); --echo # --echo # STEP 9.5 - COMMIT --echo # --connection con1 COMMIT; --echo # --echo ## Expect 1 committed transaction with 3 savepoints, 1 rollback to savepoint, 1 release savepoint --connection default CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', 'READ WRITE', '', 'NO', 3, 1, 1, 1); CALL clear_transaction_tables(); --echo # --echo # ======================================================================== --echo # STEP 10 - GTIDs --echo # ======================================================================== --echo # GTIDs are tested in transaction_gtid.test. --echo # --echo # ======================================================================== --echo # STEP 11 - MISCELLANY --echo # ======================================================================== --echo # --echo # STEP 11.1 - TRUNCATE DURING ACTIVE TRANSACTION --echo # --echo # --echo # Verify that truncating events_transactions_current during an active transaction --echo # does not leave an orphaned transaction event, and that the row index to --echo # events_transactions_history is reset to 0. --echo # --connection con1 START TRANSACTION; INSERT INTO t1 VALUES (1110, 'INSERT 1110'); --connection default TRUNCATE performance_schema.events_transactions_current; --connection con1 --echo # COMMIT; --echo # START TRANSACTION; INSERT INTO t1 VALUES (1111, 'INSERT 1111'); COMMIT; --echo # --echo ## Expect 1 transaction for connection 1 --connection default CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', '', '', '', 0, 0, 0, 1); CALL clear_transaction_tables(); --echo # --echo # --echo # STEP 11.2 - DISABLE THREAD INSTRUMENTATION --echo # --connection default UPDATE performance_schema.setup_consumers SET enabled = 'NO' WHERE name = 'thread_instrumentation'; --echo # TRUNCATE performance_schema.events_transactions_summary_global_by_event_name; --connection con1 --echo # START TRANSACTION; INSERT INTO t1 VALUES (1120, 'INSERT 1120'); COMMIT; --connection default --echo # --echo ## Expect 1 event with non-zero summary stats --replace_column 3 sum_timer_wait 4 min_timer_wait 5 avg_timer_wait SELECT EVENT_NAME, COUNT_STAR, SUM_TIMER_WAIT, MIN_TIMER_WAIT, AVG_TIMER_WAIT, COUNT_READ_WRITE FROM performance_schema.events_transactions_summary_global_by_event_name WHERE count_star = 1 and sum_timer_wait != 0; --echo # --echo ## Disable timing stats for 'transaction' UPDATE performance_schema.setup_instruments SET timed = 'NO' WHERE name = 'transaction'; --echo # TRUNCATE performance_schema.events_transactions_summary_global_by_event_name; --connection default --echo # START TRANSACTION; INSERT INTO t1 VALUES (1121, 'INSERT 1121'); COMMIT; --connection default --echo # --echo ## Expect 1 event, 0 stats SELECT * FROM performance_schema.events_transactions_summary_global_by_event_name; --echo # --echo ## Restore setup_consumers and setup_instruments UPDATE performance_schema.setup_consumers SET enabled = 'YES' WHERE name = 'thread_instrumentation'; UPDATE performance_schema.setup_instruments SET enabled = 'YES' WHERE name = 'transaction'; --echo # DELETE FROM t1; CALL clear_history(); --echo # --echo # --echo # STEP 11.3 - STATEMENT ROLLBACK - AUTOCOMMIT OFF - BINLOG FORMAT 'STATEMENT' --echo # --connection con1 SET SESSION binlog_format = STATEMENT; SET SESSION AUTOCOMMIT = 0; # A transaction with a rolled back statement should not show as rolled back. # # Force a statement rollback by attempting to update a transactional table # and a non-replicatable table with binlog_format = STATEMENT. --echo # START TRANSACTION; INSERT INTO t1 VALUES (1130, 'INSERT 1130'); --echo # --echo ## Expect binlog statement mode error --error 0, ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES UPDATE t1, performance_schema.setup_instruments pfs SET t1.s1 = 1, pfs.timed = 'NO'; --echo # COMMIT; --echo # SET SESSION AUTOCOMMIT = 1; --echo # --echo ## Expect 1 committed transaction --connection default CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'COMMITTED', 0, '', '', '', '', '', '', 'NO', 0, 0, 0, 1); --echo # DELETE FROM t1; CALL clear_history(); --echo # --echo # --echo # STEP 11.4 - STATEMENT ROLLBACK - AUTOCOMMIT ON - BINLOG FORMAT 'STATEMENT' --echo # --connection con1 SET SESSION binlog_format = STATEMENT; SET SESSION AUTOCOMMIT = 1; # A rolled back autocommit statement should be recorded as a rolled back transaction # # Force a statement rollback by attempting to update a transactional table # and a non-replicatable table with binlog_format = STATEMENT. --echo # --echo ## Expect binlog statement mode error --error 0, ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES UPDATE t1, performance_schema.setup_instruments pfs SET t1.s1 = 1, pfs.timed = 'NO'; --echo # --echo ## Expect 1 rolled back transaction --connection default CALL transaction_verifier(1, @con1_thread_id, 'transaction', 'ROLLED BACK', 0, '', '', '', '', '', '', 'YES', 0, 0, 0, 1); CALL clear_history(); --disable_parsing # TODO: Add wait timer --echo # --echo # --echo # STEP 11.5 - DROPPED CONNECTION DURING TRANSACTION --echo # --connection con2 START TRANSACTION; INSERT INTO t1 VALUES (1150, 'DROP CONNECTION'); --echo # --echo ## Expect 1 active transaction for connection 2 --connection default CALL transaction_verifier(0, @con2_thread_id, 'transaction', 'ACTIVE', 0, '', '', '', '', 'READ WRITE', '', 'NO', 0, 0, 0, 1); --echo # --echo ## Drop connection --connection con2 --disconnect con2 --source include/wait_until_disconnected.inc --connection default --echo # --echo ## Expect 0 transactions for connection 2 CALL transaction_verifier(0, @con2_thread_id, '', '', 0, '', '', '', '', '', '', '', 0, 0, 0, 0); CALL transaction_verifier(1, @con2_thread_id, '', '', 0, '', '', '', '', '', '', '', 0, 0, 0, 0); CALL clear_transaction_tables(); --enable_parsing --echo # --echo # ======================================================================== --echo # CLEAN UP --echo # ======================================================================== --echo # --disconnect con1 ##--disconnect con2 --connection default DROP TABLE t1; DROP TABLE nt1; --source ../include/transaction_cleanup.inc set global binlog_format=default;
{ "pile_set_name": "Github" }