text
stringlengths
2
100k
meta
dict
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\mail; /** * MessageInterface is the interface that should be implemented by mail message classes. * * A message represents the settings and content of an email, such as the sender, recipient, * subject, body, etc. * * Messages are sent by a [[\yii\mail\MailerInterface|mailer]], like the following, * * ```php * Yii::$app->mailer->compose() * ->setFrom('[email protected]') * ->setTo($form->email) * ->setSubject($form->subject) * ->setTextBody('Plain text content') * ->setHtmlBody('<b>HTML content</b>') * ->send(); * ``` * * @see MailerInterface * * @author Paul Klimov <[email protected]> * @since 2.0 */ interface MessageInterface { /** * Returns the character set of this message. * @return string the character set of this message. */ public function getCharset(); /** * Sets the character set of this message. * @param string $charset character set name. * @return $this self reference. */ public function setCharset($charset); /** * Returns the message sender. * @return string|array the sender */ public function getFrom(); /** * Sets the message sender. * @param string|array $from sender email address. * You may pass an array of addresses if this message is from multiple people. * You may also specify sender name in addition to email address using format: * `[email => name]`. * @return $this self reference. */ public function setFrom($from); /** * Returns the message recipient(s). * @return string|array the message recipients */ public function getTo(); /** * Sets the message recipient(s). * @param string|array $to receiver email address. * You may pass an array of addresses if multiple recipients should receive this message. * You may also specify receiver name in addition to email address using format: * `[email => name]`. * @return $this self reference. */ public function setTo($to); /** * Returns the reply-to address of this message. * @return string|array the reply-to address of this message. */ public function getReplyTo(); /** * Sets the reply-to address of this message. * @param string|array $replyTo the reply-to address. * You may pass an array of addresses if this message should be replied to multiple people. * You may also specify reply-to name in addition to email address using format: * `[email => name]`. * @return $this self reference. */ public function setReplyTo($replyTo); /** * Returns the Cc (additional copy receiver) addresses of this message. * @return string|array the Cc (additional copy receiver) addresses of this message. */ public function getCc(); /** * Sets the Cc (additional copy receiver) addresses of this message. * @param string|array $cc copy receiver email address. * You may pass an array of addresses if multiple recipients should receive this message. * You may also specify receiver name in addition to email address using format: * `[email => name]`. * @return $this self reference. */ public function setCc($cc); /** * Returns the Bcc (hidden copy receiver) addresses of this message. * @return string|array the Bcc (hidden copy receiver) addresses of this message. */ public function getBcc(); /** * Sets the Bcc (hidden copy receiver) addresses of this message. * @param string|array $bcc hidden copy receiver email address. * You may pass an array of addresses if multiple recipients should receive this message. * You may also specify receiver name in addition to email address using format: * `[email => name]`. * @return $this self reference. */ public function setBcc($bcc); /** * Returns the message subject. * @return string the message subject */ public function getSubject(); /** * Sets the message subject. * @param string $subject message subject * @return $this self reference. */ public function setSubject($subject); /** * Sets message plain text content. * @param string $text message plain text content. * @return $this self reference. */ public function setTextBody($text); /** * Sets message HTML content. * @param string $html message HTML content. * @return $this self reference. */ public function setHtmlBody($html); /** * Attaches existing file to the email message. * @param string $fileName full file name * @param array $options options for embed file. Valid options are: * * - fileName: name, which should be used to attach file. * - contentType: attached file MIME type. * * @return $this self reference. */ public function attach($fileName, array $options = []); /** * Attach specified content as file for the email message. * @param string $content attachment file content. * @param array $options options for embed file. Valid options are: * * - fileName: name, which should be used to attach file. * - contentType: attached file MIME type. * * @return $this self reference. */ public function attachContent($content, array $options = []); /** * Attach a file and return it's CID source. * This method should be used when embedding images or other data in a message. * @param string $fileName file name. * @param array $options options for embed file. Valid options are: * * - fileName: name, which should be used to attach file. * - contentType: attached file MIME type. * * @return string attachment CID. */ public function embed($fileName, array $options = []); /** * Attach a content as file and return it's CID source. * This method should be used when embedding images or other data in a message. * @param string $content attachment file content. * @param array $options options for embed file. Valid options are: * * - fileName: name, which should be used to attach file. * - contentType: attached file MIME type. * * @return string attachment CID. */ public function embedContent($content, array $options = []); /** * Sends this email message. * @param MailerInterface $mailer the mailer that should be used to send this message. * If null, the "mail" application component will be used instead. * @return bool whether this message is sent successfully. */ public function send(MailerInterface $mailer = null); /** * Returns string representation of this message. * @return string the string representation of this message. */ public function toString(); }
{ "pile_set_name": "Github" }
<?php namespace Opencart\Application\Controller\Affiliate; class Login extends \Opencart\System\Engine\Controller { private $error = []; public function index() { if (!$this->config->get('config_affiliate_status') || $this->customer->isLogged()) { $this->response->redirect($this->url->link('account/account', 'language=' . $this->config->get('config_language'))); } $this->load->language('affiliate/login'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('account/customer'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { // Unset guest unset($this->session->data['guest']); // Default Shipping Address $this->load->model('account/address'); if ($this->config->get('config_tax_customer') == 'payment') { $this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId()); } if ($this->config->get('config_tax_customer') == 'shipping') { $this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId()); } // Wishlist if (isset($this->session->data['wishlist']) && is_array($this->session->data['wishlist'])) { $this->load->model('account/wishlist'); foreach ($this->session->data['wishlist'] as $key => $product_id) { $this->model_account_wishlist->addWishlist($product_id); unset($this->session->data['wishlist'][$key]); } } // Log the IP info $this->model_account_customer->addLogin($this->customer->getId(), $this->request->server['REMOTE_ADDR']); // Added strpos check to pass McAfee PCI compliance test (http://forum.opencart.com/viewtopic.php?f=10&t=12043&p=151494#p151295) if (isset($this->request->post['redirect']) && (strpos($this->request->post['redirect'], $this->config->get('config_url')) !== false)) { $this->response->redirect(str_replace('&amp;', '&', $this->request->post['redirect'])); } else { $this->response->redirect($this->url->link('account/account', 'language=' . $this->config->get('config_language'))); } } $data['breadcrumbs'] = []; $data['breadcrumbs'][] = [ 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/home', 'language=' . $this->config->get('config_language')) ]; $data['breadcrumbs'][] = [ 'text' => $this->language->get('text_account'), 'href' => $this->url->link('account/account', 'language=' . $this->config->get('config_language')) ]; $data['breadcrumbs'][] = [ 'text' => $this->language->get('text_login'), 'href' => $this->url->link('affiliate/login', 'language=' . $this->config->get('config_language')) ]; $data['text_description'] = sprintf($this->language->get('text_description'), $this->config->get('config_name'), $this->config->get('config_name'), $this->config->get('config_affiliate_commission') . '%'); if (isset($this->error['warning'])) { $data['error_warning'] = $this->error['warning']; } else { $data['error_warning'] = ''; } $data['action'] = $this->url->link('affiliate/login', 'language=' . $this->config->get('config_language')); $data['register'] = $this->url->link('affiliate/register', 'language=' . $this->config->get('config_language')); $data['forgotten'] = $this->url->link('account/forgotten', 'language=' . $this->config->get('config_language')); if (isset($this->request->post['redirect'])) { $data['redirect'] = $this->request->post['redirect']; } elseif (isset($this->session->data['redirect'])) { $data['redirect'] = $this->session->data['redirect']; unset($this->session->data['redirect']); } else { $data['redirect'] = ''; } if (isset($this->session->data['success'])) { $data['success'] = $this->session->data['success']; unset($this->session->data['success']); } else { $data['success'] = ''; } if (isset($this->request->post['email'])) { $data['email'] = $this->request->post['email']; } else { $data['email'] = ''; } if (isset($this->request->post['password'])) { $data['password'] = $this->request->post['password']; } else { $data['password'] = ''; } $data['column_left'] = $this->load->controller('common/column_left'); $data['column_right'] = $this->load->controller('common/column_right'); $data['content_top'] = $this->load->controller('common/content_top'); $data['content_bottom'] = $this->load->controller('common/content_bottom'); $data['footer'] = $this->load->controller('common/footer'); $data['header'] = $this->load->controller('common/header'); $this->response->setOutput($this->load->view('affiliate/login', $data)); } protected function validate() { // Check how many login attempts have been made. $login_info = $this->model_account_customer->getLoginAttempts($this->request->post['email']); if ($login_info && ($login_info['total'] >= $this->config->get('config_login_attempts')) && strtotime('-1 hour') < strtotime($login_info['date_modified'])) { $this->error['warning'] = $this->language->get('error_attempts'); } // Check if customer has been approved. $customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email']); if ($customer_info && !$customer_info['status']) { $this->error['warning'] = $this->language->get('error_approved'); } if (!$this->error) { if (!$this->customer->login($this->request->post['email'], html_entity_decode($this->request->post['password'], ENT_QUOTES, 'UTF-8'))) { $this->error['warning'] = $this->language->get('error_login'); $this->model_account_customer->addLoginAttempt($this->request->post['email']); } else { $this->model_account_customer->deleteLoginAttempts($this->request->post['email']); } } return !$this->error; } }
{ "pile_set_name": "Github" }
/* * (c) Copyright 2018 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.jdbc; import java.io.File; import java.util.Properties; import com.palantir.atlasdb.jdbc.config.ImmutableHikariDataSourceConfiguration; import com.palantir.atlasdb.keyvalue.jdbc.ImmutableJdbcKeyValueConfiguration; import com.palantir.atlasdb.keyvalue.jdbc.JdbcKeyValueConfiguration; import com.palantir.atlasdb.keyvalue.jdbc.JdbcKeyValueService; public class JdbcTests { private JdbcTests() { // cannot instantiate } public static JdbcKeyValueService createEmptyKvs() { for (File file : new File("var/data").listFiles()) { if (file.getName().endsWith(".db")) { file.delete(); } } Properties properties = new Properties(); properties.put("jdbcUrl", "jdbc:h2:./var/data/h2testDb"); properties.put("username", "sa"); JdbcKeyValueConfiguration config = ImmutableJdbcKeyValueConfiguration.builder() .dataSourceConfig(ImmutableHikariDataSourceConfiguration.builder() .sqlDialect("H2") .properties(properties) .build()) .build(); return JdbcKeyValueService.create(config); } }
{ "pile_set_name": "Github" }
import Form from './Form'; const PASSWORD_FIELD = 'password'; const CONFIRM_PASSWORD_FIELD = 'confirmPassword'; export default Form.extend({ passwordField: function () { return this.input(PASSWORD_FIELD); }, confirmPasswordField: function () { return this.input(CONFIRM_PASSWORD_FIELD); }, setPassword: function (val) { const field = this.passwordField(); field.val(val); field.trigger('change'); }, setConfirmPassword: function (val) { const field = this.confirmPasswordField(); field.val(val); field.trigger('change'); }, getPasswordAutocomplete: function () { return this.autocomplete(PASSWORD_FIELD); }, getConfirmPasswordAutocomplete: function () { return this.autocomplete(CONFIRM_PASSWORD_FIELD); }, backLink: function () { return this.el('back-link'); }, hasPasswordFieldErrors: function () { return this.hasFieldErrors(PASSWORD_FIELD); }, passwordFieldErrorMessage: function () { return this.fieldErrorMessage(PASSWORD_FIELD); }, hasConfirmPasswordFieldErrors: function () { return this.hasFieldErrors(CONFIRM_PASSWORD_FIELD); }, confirmPasswordFieldErrorMessage: function () { return this.fieldErrorMessage(CONFIRM_PASSWORD_FIELD); }, });
{ "pile_set_name": "Github" }
JASC-PAL 0100 16 0 0 0 255 0 255 255 0 255 255 0 255 255 0 255 255 0 255 255 0 255 255 0 255 255 0 255 255 0 255 255 0 255 255 0 255 255 0 255 255 0 255 255 0 255 255 0 255
{ "pile_set_name": "Github" }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.zhy.blogcodes.jni.Jni01Activity"> <TextView android:id="@+id/id_textview" android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <definitions id="definitions" xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" targetNamespace="Examples"> <process id="orderProcess" name="Order process with call activity"> <startEvent id="theStart" /> <sequenceFlow id="flow1" sourceRef="theStart" targetRef="receiveOrder" /> <manualTask id="receiveOrder" name="Receive Order" /> <sequenceFlow id="flow2" sourceRef="receiveOrder" targetRef="callCheckCreditProcess" /> <callActivity id="callCheckCreditProcess" name="Check credit" calledElement="checkCreditProcess" /> <sequenceFlow id="flow3" sourceRef="callCheckCreditProcess" targetRef="prepareAndShipTask" /> <userTask id="prepareAndShipTask" name="Prepare and Ship" /> <sequenceFlow id="flow4" sourceRef="prepareAndShipTask" targetRef="theEnd" /> <endEvent id="theEnd" /> </process> <bpmndi:BPMNDiagram id="diagram"> <bpmndi:BPMNPlane bpmnElement="orderProcess" id="plane"> <bpmndi:BPMNShape bpmnElement="theStart" id="theStart_gui"> <omgdc:Bounds height="30.0" width="30.0" x="75.0" y="270.0" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape bpmnElement="receiveOrder" id="receiveOrder_gui"> <omgdc:Bounds height="80.0" width="100.0" x="155.0" y="245.0" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape bpmnElement="callCheckCreditProcess" id="callCheckCreditProcess_gui" isExpanded="false"> <omgdc:Bounds height="80.0" width="100.0" x="315.0" y="245.0" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape bpmnElement="prepareAndShipTask" id="prepareAndShipTask_gui"> <omgdc:Bounds height="80.0" width="100.0" x="480.0" y="245.0" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape bpmnElement="theEnd" id="theEnd_gui"> <omgdc:Bounds height="28.0" width="28.0" x="630.0" y="271.0" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge bpmnElement="flow1" id="flow1_gui"> <omgdi:waypoint x="105.0" y="285.0" /> <omgdi:waypoint x="155.0" y="285.0" /> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge bpmnElement="flow2" id="flow2_gui"> <omgdi:waypoint x="255.0" y="285.0" /> <omgdi:waypoint x="315.0" y="285.0" /> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge bpmnElement="flow3" id="flow3_gui"> <omgdi:waypoint x="415.0" y="285.0" /> <omgdi:waypoint x="480.0" y="285.0" /> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge bpmnElement="flow4" id="flow4_gui"> <omgdi:waypoint x="580.0" y="285.0" /> <omgdi:waypoint x="630.0" y="285.0" /> </bpmndi:BPMNEdge> </bpmndi:BPMNPlane> </bpmndi:BPMNDiagram> </definitions>
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CSS Flexible Box Test: Minimum height of flex items</title> <link rel="author" title="Manuel Rego Casasnovas" href="mailto:[email protected]" /> <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto" title="4.5. Implied Minimum Size of Flex Items" /> <link rel="match" href="../reference/ref-filled-green-100px-square.xht" /> <meta name="assert" content="Checks that minimum height for flex items is the min-content size (which corresponds to the image size)." /> <style type="text/css"><![CDATA[ #reference-overlapped-red { position: absolute; background-color: red; width: 100px; height: 100px; z-index: -1; } #constrained-flex { display: flex; flex-direction: column; width: 100px; height: 10px; } ]]></style> </head> <body> <p>Test passes if there is a filled green square and <strong>no red</strong>.</p> <div id="reference-overlapped-red"></div> <div id="constrained-flex"> <img src="support/100x100-green.png" /> </div> </body> </html>
{ "pile_set_name": "Github" }
/** * Created by mgobbi on 12/12/2016. */ define(function () { return function (node, dispatcher) { var map = new google.maps.Map(node, { zoom: 8, center: {lat: -34.397, lng: 150.644} }); dispatcher.addEventListener("place-changed",function(e){ var center=e.detail; map.setCenter(center); }) }; });
{ "pile_set_name": "Github" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_64a.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193.label.xml Template File: sources-sink-64a.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate memory for a string, but do not allocate space for NULL terminator * GoodSource: Allocate enough memory for a string and the NULL terminator * Sinks: memmove * BadSink : Copy string to data using memmove() * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif /* MAINTENANCE NOTE: The length of this string should equal the 10 */ #define SRC_STRING "AAAAAAAAAA" namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_64 { #ifndef OMITBAD /* bad function declaration */ void badSink(void * dataVoidPtr); void bad() { char * data; data = NULL; /* FLAW: Did not leave space for a null terminator */ data = new char[10]; badSink(&data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(void * dataVoidPtr); static void goodG2B() { char * data; data = NULL; /* FIX: Allocate space for a null terminator */ data = new char[10+1]; goodG2BSink(&data); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_64; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright (c) 2009-2013 CWI * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * Arnold Lankamp - [email protected] *******************************************************************************/ package org.rascalmpl.parser.gtd.stack; import org.rascalmpl.parser.gtd.stack.filter.ICompletionFilter; import org.rascalmpl.parser.gtd.stack.filter.IEnterFilter; @SuppressWarnings("cast") public class SequenceStackNode<P> extends AbstractExpandableStackNode<P>{ private final P production; private final String name; private final AbstractStackNode<P>[] children; public SequenceStackNode(int id, int dot, P production, AbstractStackNode<P>[] children){ super(id, dot); this.production = production; this.name = String.valueOf(id); this.children = generateChildren(children); } public SequenceStackNode(int id, int dot, P production, AbstractStackNode<P>[] children, IEnterFilter[] enterFilters, ICompletionFilter[] completionFilters){ super(id, dot, enterFilters, completionFilters); this.production = production; this.name = String.valueOf(id); this.children = generateChildren(children); } private SequenceStackNode(SequenceStackNode<P> original, int startLocation){ super(original, startLocation); production = original.production; name = original.name; children = original.children; } /** * Generates and initializes the alternatives for this sequence. */ @SuppressWarnings("unchecked") private AbstractStackNode<P>[] generateChildren(AbstractStackNode<P>[] children){ AbstractStackNode<P>[] prod = (AbstractStackNode<P>[]) new AbstractStackNode[children.length]; for(int i = children.length - 1; i >= 0; --i){ AbstractStackNode<P> child = children[i].getCleanCopy(DEFAULT_START_LOCATION); child.setProduction(prod); prod[i] = child; } prod[prod.length - 1].setAlternativeProduction(production); return (AbstractStackNode<P>[]) new AbstractStackNode[]{prod[0]}; } public String getName(){ return name; } public AbstractStackNode<P> getCleanCopy(int startLocation){ return new SequenceStackNode<P>(this, startLocation); } public AbstractStackNode<P>[] getChildren(){ return children; } public boolean canBeEmpty(){ return false; } public AbstractStackNode<P> getEmptyChild(){ throw new UnsupportedOperationException(); } public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("seq"); sb.append(name); sb.append('('); sb.append(startLocation); sb.append(')'); return sb.toString(); } public int hashCode(){ return production.hashCode(); } public boolean isEqual(AbstractStackNode<P> stackNode){ if(!(stackNode instanceof SequenceStackNode)) return false; SequenceStackNode<P> otherNode = (SequenceStackNode<P>) stackNode; if(!production.equals(otherNode.production)) return false; return hasEqualFilters(stackNode); } }
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright 2012-present Pixate, Inc. * * 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.pixate.freestyle.viewdemo.viewsamples; import android.content.Context; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import com.pixate.freestyle.PixateFreestyle; import com.pixate.freestyle.viewdemo.R; /** * Creates {@link ImageView} views and adds them into a layout. * * @author shalom */ public class ImageViewSample extends ViewSampleBase { @Override public void createViews(Context context, ViewGroup layout) { ImageView imageView = new ImageView(context); PixateFreestyle.setStyleId(imageView, "myImageView"); imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); imageView.setImageResource(R.drawable.ic_launcher); // placeholder layout.addView(imageView); addView(imageView); } }
{ "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 exact import ( "go/token" "strings" "testing" ) // TODO(gri) expand this test framework var opTests = []string{ // unary operations `+ 0 = 0`, `+ ? = ?`, `- 1 = -1`, `- ? = ?`, `^ 0 = -1`, `^ ? = ?`, `! true = false`, `! false = true`, `! ? = ?`, // etc. // binary operations `"" + "" = ""`, `"foo" + "" = "foo"`, `"" + "bar" = "bar"`, `"foo" + "bar" = "foobar"`, `0 + 0 = 0`, `0 + 0.1 = 0.1`, `0 + 0.1i = 0.1i`, `0.1 + 0.9 = 1`, `1e100 + 1e100 = 2e100`, `? + 0 = ?`, `0 + ? = ?`, `0 - 0 = 0`, `0 - 0.1 = -0.1`, `0 - 0.1i = -0.1i`, `1e100 - 1e100 = 0`, `? - 0 = ?`, `0 - ? = ?`, `0 * 0 = 0`, `1 * 0.1 = 0.1`, `1 * 0.1i = 0.1i`, `1i * 1i = -1`, `? * 0 = ?`, `0 * ? = ?`, `0 / 0 = "division_by_zero"`, `10 / 2 = 5`, `5 / 3 = 5/3`, `5i / 3i = 5/3`, `? / 0 = ?`, `0 / ? = ?`, `0 % 0 = "runtime_error:_integer_divide_by_zero"`, // TODO(gri) should be the same as for / `10 % 3 = 1`, `? % 0 = ?`, `0 % ? = ?`, `0 & 0 = 0`, `12345 & 0 = 0`, `0xff & 0xf = 0xf`, `? & 0 = ?`, `0 & ? = ?`, `0 | 0 = 0`, `12345 | 0 = 12345`, `0xb | 0xa0 = 0xab`, `? | 0 = ?`, `0 | ? = ?`, `0 ^ 0 = 0`, `1 ^ -1 = -2`, `? ^ 0 = ?`, `0 ^ ? = ?`, `0 &^ 0 = 0`, `0xf &^ 1 = 0xe`, `1 &^ 0xf = 0`, // etc. // shifts `0 << 0 = 0`, `1 << 10 = 1024`, `0 >> 0 = 0`, `1024 >> 10 == 1`, `? << 0 == ?`, `? >> 10 == ?`, // etc. // comparisons `false == false = true`, `false == true = false`, `true == false = false`, `true == true = true`, `false != false = false`, `false != true = true`, `true != false = true`, `true != true = false`, `"foo" == "bar" = false`, `"foo" != "bar" = true`, `"foo" < "bar" = false`, `"foo" <= "bar" = false`, `"foo" > "bar" = true`, `"foo" >= "bar" = true`, `0 == 0 = true`, `0 != 0 = false`, `0 < 10 = true`, `10 <= 10 = true`, `0 > 10 = false`, `10 >= 10 = true`, `1/123456789 == 1/123456789 == true`, `1/123456789 != 1/123456789 == false`, `1/123456789 < 1/123456788 == true`, `1/123456788 <= 1/123456789 == false`, `0.11 > 0.11 = false`, `0.11 >= 0.11 = true`, `? == 0 = false`, `? != 0 = false`, `? < 10 = false`, `? <= 10 = false`, `? > 10 = false`, `? >= 10 = false`, `0 == ? = false`, `0 != ? = false`, `0 < ? = false`, `10 <= ? = false`, `0 > ? = false`, `10 >= ? = false`, // etc. } func TestOps(t *testing.T) { for _, test := range opTests { a := strings.Split(test, " ") i := 0 // operator index var x, x0 Value switch len(a) { case 4: // unary operation case 5: // binary operation x, x0 = val(a[0]), val(a[0]) i = 1 default: t.Errorf("invalid test case: %s", test) continue } op, ok := optab[a[i]] if !ok { panic("missing optab entry for " + a[i]) } y, y0 := val(a[i+1]), val(a[i+1]) got := doOp(x, op, y) want := val(a[i+3]) if !eql(got, want) { t.Errorf("%s: got %s; want %s", test, got, want) } if x0 != nil && !eql(x, x0) { t.Errorf("%s: x changed to %s", test, x) } if !eql(y, y0) { t.Errorf("%s: y changed to %s", test, y) } } } func eql(x, y Value) bool { _, ux := x.(unknownVal) _, uy := y.(unknownVal) if ux || uy { return ux == uy } return Compare(x, token.EQL, y) } // ---------------------------------------------------------------------------- // Support functions func val(lit string) Value { if len(lit) == 0 { return MakeUnknown() } switch lit { case "?": return MakeUnknown() case "true": return MakeBool(true) case "false": return MakeBool(false) } tok := token.INT switch first, last := lit[0], lit[len(lit)-1]; { case first == '"' || first == '`': tok = token.STRING lit = strings.Replace(lit, "_", " ", -1) case first == '\'': tok = token.CHAR case last == 'i': tok = token.IMAG default: if !strings.HasPrefix(lit, "0x") && strings.ContainsAny(lit, "./Ee") { tok = token.FLOAT } } return MakeFromLiteral(lit, tok) } var optab = map[string]token.Token{ "!": token.NOT, "+": token.ADD, "-": token.SUB, "*": token.MUL, "/": token.QUO, "%": token.REM, "<<": token.SHL, ">>": token.SHR, "&": token.AND, "|": token.OR, "^": token.XOR, "&^": token.AND_NOT, "==": token.EQL, "!=": token.NEQ, "<": token.LSS, "<=": token.LEQ, ">": token.GTR, ">=": token.GEQ, } func panicHandler(v *Value) { switch p := recover().(type) { case nil: // nothing to do case string: *v = MakeString(p) case error: *v = MakeString(p.Error()) default: panic(p) } } func doOp(x Value, op token.Token, y Value) (z Value) { defer panicHandler(&z) if x == nil { return UnaryOp(op, y, -1) } switch op { case token.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ: return MakeBool(Compare(x, op, y)) case token.SHL, token.SHR: s, _ := Int64Val(y) return Shift(x, op, uint(s)) default: return BinaryOp(x, op, y) } } // ---------------------------------------------------------------------------- // Other tests var fracTests = []string{ "0 0 1", "1 1 1", "-1 -1 1", "1.2 6 5", "-0.991 -991 1000", "1e100 1e100 1", } func TestFractions(t *testing.T) { for _, test := range fracTests { a := strings.Split(test, " ") if len(a) != 3 { t.Errorf("invalid test case: %s", test) continue } x := val(a[0]) n := val(a[1]) d := val(a[2]) if got := Num(x); !eql(got, n) { t.Errorf("%s: got num = %s; want %s", test, got, n) } if got := Denom(x); !eql(got, d) { t.Errorf("%s: got denom = %s; want %s", test, got, d) } } } var bytesTests = []string{ "0", "1", "123456789", "123456789012345678901234567890123456789012345678901234567890", } func TestBytes(t *testing.T) { for _, test := range bytesTests { x := val(test) bytes := Bytes(x) // special case 0 if Sign(x) == 0 && len(bytes) != 0 { t.Errorf("%s: got %v; want empty byte slice", test, bytes) } if n := len(bytes); n > 0 && bytes[n-1] == 0 { t.Errorf("%s: got %v; want no leading 0 byte", test, bytes) } if got := MakeFromBytes(bytes); !eql(got, x) { t.Errorf("%s: got %s; want %s (bytes = %v)", test, got, x, bytes) } } } func TestUnknown(t *testing.T) { u := MakeUnknown() var values = []Value{ u, MakeBool(false), // token.ADD ok below, operation is never considered MakeString(""), MakeInt64(1), MakeFromLiteral("-1234567890123456789012345678901234567890", token.INT), MakeFloat64(1.2), MakeImag(MakeFloat64(1.2)), } for _, val := range values { x, y := val, u for i := range [2]int{} { if i == 1 { x, y = y, x } if got := BinaryOp(x, token.ADD, y); got.Kind() != Unknown { t.Errorf("%s + %s: got %s; want %s", x, y, got, u) } if got := Compare(x, token.EQL, y); got { t.Errorf("%s == %s: got true; want false", x, y) } } } }
{ "pile_set_name": "Github" }
using Microsoft.Diagnostics.Runtime; namespace MemoScope.Core.Data { public class ClrDumpObject : ClrDumpType { public ulong Address { get; } public object Value => ClrDump.Eval(GetValue); public bool IsInterior { get; private set; } public int ArrayLength => ClrDump.Eval( () => ClrType.GetArrayLength(Address)); public ClrObject ClrObject => new ClrObject(Address, ClrType, IsInterior); private object GetValue() { var clrObject = new ClrObject(Address, ClrType, IsInterior); if (clrObject.HasSimpleValue && ! clrObject.IsNull) { return clrObject.SimpleValue; } else { return null; } } public ClrDumpObject(ClrDump dump, ClrType type, ulong address, bool isInterior=false) : base(dump, type) { Address = address; IsInterior = isInterior; } public ClrDumpObject(ClrDumpType clrDumpType, ulong address) : this(clrDumpType.ClrDump, clrDumpType.ClrType, address) { } } }
{ "pile_set_name": "Github" }
var composeArgs = require('./_composeArgs'), composeArgsRight = require('./_composeArgsRight'), replaceHolders = require('./_replaceHolders'); /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } module.exports = mergeData;
{ "pile_set_name": "Github" }
# Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx10248m -XX:MaxPermSize=256m # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true android.useAndroidX=true android.enableJetifier=true
{ "pile_set_name": "Github" }
/*! ****************************************************************************** * * \file * * \brief Header file containing RAJA headers for OpenMP execution. * * These methods work only on platforms that support OpenMP. * ****************************************************************************** */ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2016-20, Lawrence Livermore National Security, LLC // and RAJA project contributors. See the RAJA/COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// #ifndef RAJA_openmp_HPP #define RAJA_openmp_HPP #include "RAJA/config.hpp" #if defined(RAJA_ENABLE_OPENMP) #include <omp.h> #include <iostream> #include <thread> #include "RAJA/policy/openmp/atomic.hpp" #include "RAJA/policy/openmp/forall.hpp" #include "RAJA/policy/openmp/kernel.hpp" #include "RAJA/policy/openmp/policy.hpp" #include "RAJA/policy/openmp/reduce.hpp" #include "RAJA/policy/openmp/region.hpp" #include "RAJA/policy/openmp/scan.hpp" #include "RAJA/policy/openmp/sort.hpp" #include "RAJA/policy/openmp/synchronize.hpp" #include "RAJA/policy/openmp/WorkGroup.hpp" #endif // closing endif for if defined(RAJA_ENABLE_OPENMP) #endif // closing endif for header file include guard
{ "pile_set_name": "Github" }
#FIG 3.2 Produced by xfig version 3.2.5b Landscape Center Metric A4 100.00 Single -2 1200 2 0 32 #d9d9d9 0 33 #6e6e6e 0 34 #c9c9c9 0 35 #dfd8df 0 36 #f7f3f7 0 37 #9c0000 0 38 #8c8c8c 0 39 #424242 0 40 #8c8c8c 0 41 #424242 0 42 #8c8c8c 0 43 #424242 0 44 #414541 0 45 #c0c0c0 0 46 #e7e7e7 0 47 #717571 6 2295 1755 10305 5969 6 8311 2109 10112 3396 6 9372 2302 9855 3106 2 1 0 1 -1 7 81 0 20 0.000 0 0 7 0 0 5 9386 3095 9386 2309 9840 2506 9840 2898 9386 3095 -6 2 1 0 1 8 11 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 1.00 64.34 85.78 9832 2686 10112 2689 2 1 0 4 4 7 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 2.00 53.61 21.45 8407 3363 8407 3203 2 1 0 4 4 7 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 2.00 53.61 21.45 8407 2688 8407 2527 2 2 0 1 7 8 50 -1 20 0.000 0 0 -1 0 0 5 8311 2495 9050 2495 9050 2527 8311 2527 8311 2495 2 1 0 1 11 11 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 1.00 64.34 85.78 8986 3042 9469 2817 2 1 0 1 8 11 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 1.00 64.34 85.78 8950 2368 9501 2591 2 2 0 1 7 34 50 -1 20 0.000 0 0 -1 0 0 5 8311 3170 9050 3170 9050 3203 8311 3203 8311 3170 2 2 0 1 32 33 50 -1 -1 0.000 0 0 -1 0 0 5 8311 2109 9050 2109 9050 2688 8311 2688 8311 2109 2 2 0 1 32 33 50 -1 -1 0.000 0 0 -1 0 0 5 8311 2784 9050 2784 9050 3363 8311 3363 8311 2784 4 0 0 50 -1 16 7 4.7124 4 86 257 9662 2559 MUX\001 4 0 33 50 -1 16 9 0.0000 4 139 397 8471 2431 Way 1\001 4 0 33 50 -1 16 9 0.0000 4 139 397 8471 3106 Way 2\001 -6 6 7989 4071 10144 5840 6 9436 4457 9919 5261 2 1 0 1 -1 7 81 0 20 0.000 0 0 7 0 0 5 9450 5250 9450 4464 9904 4661 9904 5053 9450 5250 -6 2 1 0 1 8 11 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 1.00 64.34 85.78 9887 4843 10144 4843 2 1 0 1 11 11 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 1.00 64.34 85.78 9004 4281 9597 4714 2 1 0 1 11 11 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 1.00 64.34 85.78 8983 4685 9565 4811 2 1 0 1 11 11 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 1.00 64.34 85.78 9015 5618 9629 5036 2 1 0 1 8 11 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 1.00 64.34 85.78 9015 5200 9597 4907 2 1 0 4 4 7 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 2.00 53.61 21.45 8375 5808 8375 5551 2 2 0 1 7 34 50 -1 20 0.000 0 0 -1 0 0 5 8278 5519 9050 5519 9050 5551 8278 5551 8278 5519 2 1 0 4 4 7 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 2.00 53.61 21.45 8375 5326 8375 5068 2 1 0 4 4 7 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 2.00 53.61 21.45 8375 4875 8375 4618 2 1 0 4 4 7 50 -1 -1 0.000 0 0 -1 1 0 2 1 1 2.00 53.61 21.45 8375 4425 8375 4168 2 2 0 1 7 34 50 -1 20 0.000 0 0 -1 0 0 5 8278 4586 9050 4586 9050 4618 8278 4618 8278 4586 2 2 0 1 7 34 50 -1 20 0.000 0 0 -1 0 0 5 8278 4135 9050 4135 9050 4168 8278 4168 8278 4135 2 2 0 1 7 8 50 -1 20 0.000 0 0 -1 0 0 5 8278 5036 9050 5036 9050 5068 8278 5068 8278 5036 2 1 0 3 34 44 50 -1 -1 0.000 0 0 -1 0 0 2 8021 4135 8021 5808 2 2 0 1 32 33 50 -1 -1 0.000 0 0 -1 0 0 5 8278 4071 9050 4071 9050 4425 8278 4425 8278 4071 2 2 0 1 32 33 50 -1 -1 0.000 0 0 -1 0 0 5 8278 4521 9050 4521 9050 4875 8278 4875 8278 4521 2 2 0 1 32 33 50 -1 -1 0.000 0 0 -1 0 0 5 8278 4972 9050 4972 9050 5326 8278 5326 8278 4972 2 2 0 1 32 33 50 -1 -1 0.000 0 0 -1 0 0 5 8278 5454 9050 5454 9050 5808 8278 5808 8278 5454 4 0 0 50 -1 16 7 4.7124 4 86 257 9726 4714 MUX\001 4 0 33 50 -1 16 9 0.0000 4 139 397 8504 4296 Way 1\001 4 0 33 50 -1 16 9 0.0000 4 139 397 8504 4747 Way 2\001 4 0 33 50 -1 16 9 0.0000 4 139 397 8504 5197 Way 3\001 4 0 33 50 -1 16 9 0.0000 4 139 397 8504 5679 Way 4\001 -6 2 4 0 1 0 7 50 -1 -1 0.000 0 0 5 0 0 5 10305 3814 10305 1755 2295 1755 2295 3814 10305 3814 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 1 2 1 1 2.00 64.34 85.78 1 1 2.00 64.34 85.78 4129 2977 7056 2977 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 7056 2238 7796 2238 7796 2881 7056 2881 7056 2238 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 2488 2559 4129 2559 4129 2881 2488 2881 2488 2559 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 4129 2559 7056 2559 7056 2881 4129 2881 4129 2559 2 1 0 3 34 34 50 -1 -1 0.000 0 0 -1 0 0 2 8021 1916 8021 3589 2 1 0 1 12 7 50 -1 -1 0.000 0 0 -1 0 0 4 8246 2495 8150 2495 8150 3203 8246 3203 2 4 0 1 0 7 50 -1 -1 0.000 0 0 5 0 0 5 10305 5969 10305 3910 2295 3910 2295 5969 10305 5969 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 2520 4618 7088 4618 7088 4940 2520 4940 2520 4618 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 1 2 1 1 2.00 64.34 85.78 1 1 2.00 64.34 85.78 2520 5358 6509 5358 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 7088 4618 7828 4618 7828 5261 7088 5261 7088 4618 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 2520 4940 6509 4940 6509 5261 2520 5261 2520 4940 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 6509 4940 7088 4940 7088 5261 6509 5261 6509 4940 2 1 0 1 12 7 50 -1 -1 0.000 0 0 -1 0 0 4 8246 4135 8118 4135 8118 5551 8246 5551 2 1 0 1 12 7 50 -1 -1 0.000 0 0 -1 0 0 2 8118 4586 8246 4586 2 1 0 1 12 7 50 -1 -1 0.000 0 0 -1 0 0 2 8118 5036 8246 5036 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 2488 2238 7056 2238 7056 2559 2488 2559 2488 2238 4 0 32 50 -1 18 9 0.0000 4 107 386 7217 2591 Offset\001 4 0 8 50 -1 18 9 0.0000 4 107 290 3164 2784 TAG\001 4 0 4 50 -1 18 9 0.0000 4 107 429 5415 2784 INDEX\001 4 0 12 50 -1 18 10 0.0000 4 129 1394 2456 3685 Less Associative\001 4 0 33 50 -1 16 9 0.0000 4 139 2820 4129 3203 Less set-associativity means more index bits\001 4 0 32 50 -1 18 9 0.0000 4 107 386 7249 4972 Offset\001 4 0 8 50 -1 18 9 0.0000 4 107 290 4515 5165 TAG\001 4 0 4 50 -1 18 9 0.0000 4 107 429 6573 5165 INDEX\001 4 0 12 50 -1 18 10 0.0000 4 129 1405 2488 5840 More Associative\001 4 0 33 50 -1 16 9 0.0000 4 139 2691 3196 5519 More set-associativity means more tag bits\001 4 0 0 50 -1 18 9 0.0000 4 107 547 4547 2463 Address\001 4 0 0 50 -1 18 9 0.0000 4 107 547 4579 4843 Address\001 -6
{ "pile_set_name": "Github" }
// <auto-generated /> using System; using NorthwindMvc.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace NorthwindMvc.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.0-preview1"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasMaxLength(128); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
{ "pile_set_name": "Github" }
{ "actions": [], "creation": "2017-08-28 16:46:41.732676", "doctype": "DocType", "editable_grid": 1, "engine": "InnoDB", "field_order": [ "invoice_fields" ], "fields": [ { "fieldname": "invoice_fields", "fieldtype": "Table", "label": "POS Field", "options": "POS Field" } ], "issingle": 1, "links": [], "modified": "2020-06-01 15:46:41.478928", "modified_by": "Administrator", "module": "Accounts", "name": "POS Settings", "owner": "Administrator", "permissions": [ { "email": 1, "print": 1, "read": 1, "role": "System Manager", "share": 1, "write": 1 }, { "email": 1, "print": 1, "read": 1, "role": "Accounts User", "share": 1, "write": 1 }, { "email": 1, "print": 1, "read": 1, "role": "Sales User", "share": 1, "write": 1 } ], "quick_entry": 1, "sort_field": "modified", "sort_order": "DESC", "track_changes": 1 }
{ "pile_set_name": "Github" }
// Copyright 2011 Mark Cavage <[email protected]> All rights reserved. var test = require('tap').test; ///--- Globals var BerReader; ///--- Tests test('load library', function(t) { BerReader = require('../../lib/index').BerReader; t.ok(BerReader); try { new BerReader(); t.fail('Should have thrown'); } catch (e) { t.ok(e instanceof TypeError, 'Should have been a type error'); } t.end(); }); test('read byte', function(t) { var reader = new BerReader(new Buffer([0xde])); t.ok(reader); t.equal(reader.readByte(), 0xde, 'wrong value'); t.end(); }); test('read 1 byte int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x01, 0x03])); t.ok(reader); t.equal(reader.readInt(), 0x03, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('read 2 byte int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x02, 0x7e, 0xde])); t.ok(reader); t.equal(reader.readInt(), 0x7ede, 'wrong value'); t.equal(reader.length, 0x02, 'wrong length'); t.end(); }); test('read 3 byte int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x03, 0x7e, 0xde, 0x03])); t.ok(reader); t.equal(reader.readInt(), 0x7ede03, 'wrong value'); t.equal(reader.length, 0x03, 'wrong length'); t.end(); }); test('read 4 byte int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x04, 0x7e, 0xde, 0x03, 0x01])); t.ok(reader); t.equal(reader.readInt(), 0x7ede0301, 'wrong value'); t.equal(reader.length, 0x04, 'wrong length'); t.end(); }); test('read 1 byte negative int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x01, 0xdc])); t.ok(reader); t.equal(reader.readInt(), -36, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('read 2 byte negative int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x02, 0xc0, 0x4e])); t.ok(reader); t.equal(reader.readInt(), -16306, 'wrong value'); t.equal(reader.length, 0x02, 'wrong length'); t.end(); }); test('read 3 byte negative int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x03, 0xff, 0x00, 0x19])); t.ok(reader); t.equal(reader.readInt(), -65511, 'wrong value'); t.equal(reader.length, 0x03, 'wrong length'); t.end(); }); test('read 4 byte negative int', function(t) { var reader = new BerReader(new Buffer([0x02, 0x04, 0x91, 0x7c, 0x22, 0x1f])); t.ok(reader); t.equal(reader.readInt(), -1854135777, 'wrong value'); t.equal(reader.length, 0x04, 'wrong length'); t.end(); }); test('read boolean true', function(t) { var reader = new BerReader(new Buffer([0x01, 0x01, 0xff])); t.ok(reader); t.equal(reader.readBoolean(), true, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('read boolean false', function(t) { var reader = new BerReader(new Buffer([0x01, 0x01, 0x00])); t.ok(reader); t.equal(reader.readBoolean(), false, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('read enumeration', function(t) { var reader = new BerReader(new Buffer([0x0a, 0x01, 0x20])); t.ok(reader); t.equal(reader.readEnumeration(), 0x20, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('read string', function(t) { var dn = 'cn=foo,ou=unit,o=test'; var buf = new Buffer(dn.length + 2); buf[0] = 0x04; buf[1] = Buffer.byteLength(dn); buf.write(dn, 2); var reader = new BerReader(buf); t.ok(reader); t.equal(reader.readString(), dn, 'wrong value'); t.equal(reader.length, dn.length, 'wrong length'); t.end(); }); test('read sequence', function(t) { var reader = new BerReader(new Buffer([0x30, 0x03, 0x01, 0x01, 0xff])); t.ok(reader); t.equal(reader.readSequence(), 0x30, 'wrong value'); t.equal(reader.length, 0x03, 'wrong length'); t.equal(reader.readBoolean(), true, 'wrong value'); t.equal(reader.length, 0x01, 'wrong length'); t.end(); }); test('anonymous LDAPv3 bind', function(t) { var BIND = new Buffer(14); BIND[0] = 0x30; // Sequence BIND[1] = 12; // len BIND[2] = 0x02; // ASN.1 Integer BIND[3] = 1; // len BIND[4] = 0x04; // msgid (make up 4) BIND[5] = 0x60; // Bind Request BIND[6] = 7; // len BIND[7] = 0x02; // ASN.1 Integer BIND[8] = 1; // len BIND[9] = 0x03; // v3 BIND[10] = 0x04; // String (bind dn) BIND[11] = 0; // len BIND[12] = 0x80; // ContextSpecific (choice) BIND[13] = 0; // simple bind // Start testing ^^ var ber = new BerReader(BIND); t.equal(ber.readSequence(), 48, 'Not an ASN.1 Sequence'); t.equal(ber.length, 12, 'Message length should be 12'); t.equal(ber.readInt(), 4, 'Message id should have been 4'); t.equal(ber.readSequence(), 96, 'Bind Request should have been 96'); t.equal(ber.length, 7, 'Bind length should have been 7'); t.equal(ber.readInt(), 3, 'LDAP version should have been 3'); t.equal(ber.readString(), '', 'Bind DN should have been empty'); t.equal(ber.length, 0, 'string length should have been 0'); t.equal(ber.readByte(), 0x80, 'Should have been ContextSpecific (choice)'); t.equal(ber.readByte(), 0, 'Should have been simple bind'); t.equal(null, ber.readByte(), 'Should be out of data'); t.end(); }); test('long string', function(t) { var buf = new Buffer(256); var o; var s = '2;649;CN=Red Hat CS 71GA Demo,O=Red Hat CS 71GA Demo,C=US;' + 'CN=RHCS Agent - admin01,UID=admin01,O=redhat,C=US [1] This is ' + 'Teena Vradmin\'s description.'; buf[0] = 0x04; buf[1] = 0x81; buf[2] = 0x94; buf.write(s, 3); var ber = new BerReader(buf.slice(0, 3 + s.length)); t.equal(ber.readString(), s); t.end(); });
{ "pile_set_name": "Github" }
Microsoft Developer Studio Workspace File, Format Version 6.00 # WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! ############################################################################### Project: "libspeex"=..\libspeex\libspeex.dsp - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "libspeexdsp"=..\libspeex\libspeexdsp.dsp - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "ogg_static"=..\..\..\libogg\win32\ogg_static.dsp - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "speexenc"=.\speexenc.dsp - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ Begin Project Dependency Project_Dep_Name libspeex End Project Dependency Begin Project Dependency Project_Dep_Name ogg_static End Project Dependency Begin Project Dependency Project_Dep_Name libspeexdsp End Project Dependency }}} ############################################################################### Global: Package=<5> {{{ }}} Package=<3> {{{ }}} ###############################################################################
{ "pile_set_name": "Github" }
# Practical Business Python This repository contains, code, notebooks and examples from https://pbpython.com
{ "pile_set_name": "Github" }
import Cocoa /* A container view for the 2 types of player views - Default / Expanded Art view. Switches between the 2 views, shows/hides individual UI components, and handles functions such as auto-hide. */ class PlayingTrackView: MouseTrackingView, ColorSchemeable, TextSizeable { @IBOutlet weak var defaultView: PlayingTrackSubview! @IBOutlet weak var expandedArtView: PlayingTrackSubview! // The player view that is currently displayed private var activeView: PlayingTrackSubview { return PlayerViewState.viewType == .defaultView ? defaultView : expandedArtView } // The player view that is NOT currently displayed private var inactiveView: PlayingTrackSubview { return PlayerViewState.viewType == .defaultView ? expandedArtView : defaultView } // Info about the currently playing track var trackInfo: PlayingTrackInfo? { didSet { defaultView.trackInfo = trackInfo expandedArtView.trackInfo = trackInfo } } override func awakeFromNib() { self.addSubviews(defaultView, expandedArtView) inactiveView.hideView() setUpMouseTracking() } // This is required when the player view was hidden and is now shown (eg. after waiting or transcoding). func showView() { setUpMouseTracking() activeView.showView() self.show() } // This is required when the player view is hidden (eg. when waiting or transcoding). func hideView() { self.hide() if isTracking { stopTracking() } } func update() { defaultView.update() expandedArtView.update() } // Switches between the 2 sub-views (Default and Expanded Art) func switchView(_ viewType: PlayerViewType) { inactiveView.hideView() activeView.showView() setUpMouseTracking() } func showOrHidePlayingTrackInfo() { defaultView.showOrHidePlayingTrackInfo() expandedArtView.showOrHidePlayingTrackInfo() } func showOrHidePlayingTrackFunctions() { defaultView.showOrHidePlayingTrackFunctions() expandedArtView.showOrHidePlayingTrackFunctions() } func showOrHideAlbumArt() { defaultView.showOrHideAlbumArt() expandedArtView.showOrHideAlbumArt() } func showOrHideArtist() { defaultView.showOrHideArtist() expandedArtView.showOrHideArtist() } func showOrHideAlbum() { defaultView.showOrHideAlbum() expandedArtView.showOrHideAlbum() } func showOrHideCurrentChapter() { defaultView.showOrHideCurrentChapter() expandedArtView.showOrHideCurrentChapter() } func showOrHideMainControls() { defaultView.showOrHideMainControls() expandedArtView.showOrHideMainControls() setUpMouseTracking() } override func mouseEntered(with event: NSEvent) { activeView.mouseEntered() } override func mouseExited(with event: NSEvent) { // If this check is not performed, the track-peeking buttons (previous/next track) // will cause a false positive mouse exit event. if !self.frame.contains(event.locationInWindow) { activeView.mouseExited() } } // Set up mouse tracking if necessary (for auto-hide). private func setUpMouseTracking() { if activeView.needsMouseTracking { if !isTracking { startTracking() } } else if isTracking { stopTracking() } } func changeTextSize(_ size: TextSize) { defaultView.changeTextSize(size) expandedArtView.changeTextSize(size) } func applyColorScheme(_ scheme: ColorScheme) { defaultView.applyColorScheme(scheme) expandedArtView.applyColorScheme(scheme) } func changeBackgroundColor(_ color: NSColor) { defaultView.changeBackgroundColor(color) expandedArtView.changeBackgroundColor(color) } func changePrimaryTextColor(_ color: NSColor) { defaultView.changePrimaryTextColor(color) expandedArtView.changePrimaryTextColor(color) } func changeSecondaryTextColor(_ color: NSColor) { defaultView.changeSecondaryTextColor(color) expandedArtView.changeSecondaryTextColor(color) } func changeTertiaryTextColor(_ color: NSColor) { defaultView.changeTertiaryTextColor(color) expandedArtView.changeTertiaryTextColor(color) } }
{ "pile_set_name": "Github" }
use strict; use warnings; use utf8; use Test::More; use Test::Fatal; use Test::FailWarnings -allow_deps => 1; binmode(Test::More->builder->$_, ":utf8") for qw/output failure_output todo_output/; use Encode; use Path::Tiny; use Test::DZil; use List::Util 'first'; use Dist::Zilla::File::InMemory; use Dist::Zilla::File::OnDisk; use Dist::Zilla::File::FromCode; my %sample = ( dolmen => "Olivier Mengué", keedi =>"김도형 - Keedi Kim", ); my $sample = join("\n", values %sample); my $encoded_sample = encode("UTF-8", $sample); my $db_sample = $sample x 2; my $db_encoded_sample = $encoded_sample x 2; my $latin1_dolmen = encode("latin1", $sample{dolmen}); my $tzil = Builder->from_config( { dist_root => 't/does_not_exist' }, { add_files => { path(qw(source dist.ini)) => simple_ini( 'GatherDir', ), path(qw(source lib DZT Sample.pm)) => "package DZT::Sample;\n\n1", }, }, ); { # this trickery is so the caller appears to be whatever called new_file() my $gatherdir = first { $_->isa('Dist::Zilla::Plugin::GatherDir') } @{ $tzil->plugins }; my $add_file = $gatherdir->can('add_file'); my $i = 0; sub new_file { my ($objref, $class, @args) = @_; my $obj = $class->new( name => 'foo_' . $i++ . '.txt', @args, ); ok($obj, "created a $class"); $$objref = $obj; # equivalent to: $gatherdir->add_file($obj); @_ = ($gatherdir, $obj); goto &$add_file; } } sub test_mutable_roundtrip { my ($obj) = @_; ok( $obj->DOES("Dist::Zilla::Role::MutableFile"), "does MutableFile role" ); # assumes object content starts as $sample is( $obj->content, $sample, "get content" ); is( $obj->encoded_content, $encoded_sample, "get encoded_content" ); # set content, check content & encoded_content ok( $obj->content($db_sample), "set content"); is( $obj->content, $db_sample, "get content"); is( $obj->encoded_content, $db_encoded_sample, "get encoded_content"); # set encoded_content, check encoded_content & content ok( $obj->encoded_content($encoded_sample), "set encoded_content"); is( $obj->encoded_content, $encoded_sample, "get encoded_content"); is( $obj->content, $sample, "get content"); } sub test_content_from_bytes { my ($obj, $source_re) = @_; # assumes object encoded_content is encoded sample is( $obj->encoded_content, $encoded_sample, "get encoded_content" ); my $err = exception { $obj->content }; like( $err, qr/can't decode text from 'bytes'/i, "get content from bytes should throw error" ); # Match only the first line of the stack trace like( $err, qr/^[^\n]+$source_re/s, "error shows encoded_content source" ); } sub test_latin1 { my ($obj) = @_; # assumes encoded_content is $latin1_dolmen and encoding # is already set to 'latin1" is( $obj->encoded_content, $latin1_dolmen, "get encoded_content" ); is( $obj->content, $sample{dolmen}, "get content" ); } subtest "OnDisk" => sub { my $class = "Dist::Zilla::File::OnDisk"; subtest "UTF-8 file" => sub { my $tempfile = Path::Tiny->tempfile; ok( $tempfile->spew_utf8($sample), "create UTF-8 encoded tempfile" ); my $obj; new_file(\$obj, $class, name => "$tempfile"); test_mutable_roundtrip($obj); }; subtest "binary file" => sub { my $tempfile = Path::Tiny->tempfile; ok( $tempfile->spew_raw($encoded_sample), "create binary tempfile" ); my $obj; new_file(\$obj, $class, name => "$tempfile"); ok( $obj->encoding("bytes"), "set encoding to 'bytes'"); test_content_from_bytes($obj, qr/encoded_content added by \S+ \(\S+ line \d+\)/); }; subtest "latin1 file" => sub { my $tempfile = Path::Tiny->tempfile; ok( $tempfile->spew( { binmode => ":encoding(latin1)"}, $sample{dolmen} ), "create latin1 tempfile" ); my $obj; new_file(\$obj, $class, name => "$tempfile", encoding => 'latin1'); test_latin1($obj); }; }; subtest "InMemory" => sub { my $class = "Dist::Zilla::File::InMemory"; subtest "UTF-8 string" => sub { my $obj; new_file(\$obj, $class, content => $sample); test_mutable_roundtrip($obj); }; subtest "binary string" => sub { my ($obj, $line); new_file(\$obj, $class, encoded_content => $encoded_sample); $line = __LINE__; ok( $obj->encoding("bytes"), "set encoding to 'bytes'"); test_content_from_bytes($obj, qr/encoded_content added by \S+ \(\S+ line $line\)/); }; subtest "latin1 string" => sub { my $obj; new_file(\$obj, $class, encoded_content => $latin1_dolmen, encoding => "latin1"); test_latin1($obj); }; }; subtest "FromCode" => sub { my $class = "Dist::Zilla::File::FromCode"; subtest "UTF-8 string" => sub { my $obj; new_file(\$obj, $class, code => sub { $sample }); is( $obj->content, $sample, "content" ); is( $obj->encoded_content, $encoded_sample, "encoded_content" ); }; subtest "content immutable" => sub { my $obj; new_file(\$obj, $class, code => sub { $sample }); like( exception { $obj->content($sample) }, qr/cannot set content/, "changing content should throw error" ); like( exception { $obj->encoded_content($encoded_sample) }, qr/cannot set encoded_content/, "changing encoded_content should throw error" ); }; subtest "binary string" => sub { my ($obj, $line); new_file(\$obj, $class, code_return_type => 'bytes', code => sub { $encoded_sample }); $line = __LINE__; test_content_from_bytes($obj, qr/bytes from coderef added by \S+ \(main line $line\)/); }; subtest "latin1 string" => sub { my $obj; new_file(\$obj, $class, ( code_return_type => 'bytes', code => sub { $latin1_dolmen }, encoding => 'latin1', ) ); test_latin1($obj); }; }; done_testing;
{ "pile_set_name": "Github" }
/* * DNS Resolver upcall management for CIFS DFS and AFS * Handles host name to IP address resolution and DNS query for AFSDB RR. * * Copyright (c) International Business Machines Corp., 2008 * Author(s): Steve French ([email protected]) * Wang Lei ([email protected]) * * This library 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 2.1 of the License, or * (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _LINUX_DNS_RESOLVER_H #define _LINUX_DNS_RESOLVER_H #ifdef __KERNEL__ extern int dns_query(const char *type, const char *name, size_t namelen, const char *options, char **_result, time64_t *_expiry); #endif /* KERNEL */ #endif /* _LINUX_DNS_RESOLVER_H */
{ "pile_set_name": "Github" }
// Copyright Aleksey Gurtovoy 2000-2004 // // 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) // // Preprocessed version of "boost/mpl/modulus.hpp" header // -- DO NOT modify by hand! namespace boost { namespace mpl { template< typename Tag1 , typename Tag2 > struct modulus_impl : if_c< ( BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag1) > BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag2) ) , aux::cast2nd_impl< modulus_impl< Tag1,Tag1 >,Tag1, Tag2 > , aux::cast1st_impl< modulus_impl< Tag2,Tag2 >,Tag1, Tag2 > >::type { }; /// for Digital Mars C++/compilers with no CTPS/TTP support template<> struct modulus_impl< na,na > { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template< typename Tag > struct modulus_impl< na,Tag > { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template< typename Tag > struct modulus_impl< Tag,na > { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template< typename T > struct modulus_tag { typedef typename T::tag type; }; template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) > struct modulus : modulus_impl< typename modulus_tag<N1>::type , typename modulus_tag<N2>::type >::template apply< N1,N2 >::type { BOOST_MPL_AUX_LAMBDA_SUPPORT(2, modulus, (N1, N2)) }; BOOST_MPL_AUX_NA_SPEC2(2, 2, modulus) }} namespace boost { namespace mpl { template<> struct modulus_impl< integral_c_tag,integral_c_tag > { template< typename N1, typename N2 > struct apply : integral_c< typename aux::largest_int< typename N1::value_type , typename N2::value_type >::type , ( BOOST_MPL_AUX_VALUE_WKND(N1)::value % BOOST_MPL_AUX_VALUE_WKND(N2)::value ) > { }; }; }}
{ "pile_set_name": "Github" }
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright notice shall be // included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #import <Foundation/Foundation.h> NS_SWIFT_NAME(CodelessParameterComponent) @interface FBSDKCodelessParameterComponent : NSObject @property (nonatomic, copy, readonly) NSString *name; @property (nonatomic, copy, readonly) NSString *value; @property (nonatomic, readonly) NSArray *path; @property (nonatomic, copy, readonly) NSString *pathType; - (instancetype)initWithJSON:(NSDictionary *)dict; @end
{ "pile_set_name": "Github" }
// { dg-require-namedlocale "de_DE.ISO8859-15" } // 2005-04-08 Paolo Carlini <[email protected]> // Copyright (C) 2005-2020 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library 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 library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 22.2.2.2.1 num_put members #include <locale> #include <sstream> #include <testsuite_hooks.h> // libstdc++/20909 void test01() { using namespace std; // A locale that expects grouping. locale loc_de = locale(ISO_8859(15,de_DE)); const string empty; string result; ostringstream oss; oss.imbue(loc_de); const num_put<char>& np = use_facet<num_put<char> >(oss.getloc()); double d0 = 2e20; double d1 = -2e20; oss.str(empty); oss.clear(); np.put(oss.rdbuf(), oss, '*', d0); result = oss.str(); VERIFY( result == "2e+20" ); oss.str(empty); oss.clear(); np.put(oss.rdbuf(), oss, '*', d1); result = oss.str(); VERIFY( result == "-2e+20" ); oss.str(empty); oss.clear(); oss.setf(ios::uppercase); np.put(oss.rdbuf(), oss, '*', d0); result = oss.str(); VERIFY( result == "2E+20" ); oss.str(empty); oss.clear(); oss.setf(ios::showpos); np.put(oss.rdbuf(), oss, '*', d0); result = oss.str(); VERIFY( result == "+2E+20" ); } int main() { test01(); return 0; }
{ "pile_set_name": "Github" }
# gogol-fonts * [Version](#version) * [Description](#description) * [Contribute](#contribute) * [Licence](#licence) ## Version `0.5.0` ## Description A client library for the Google Fonts Developer. ## Contribute For any problems, comments, or feedback please create an issue [here on GitHub](https://github.com/brendanhay/gogol/issues). > _Note:_ this library is an auto-generated Haskell package. Please see `gogol-gen` for more information. ## Licence `gogol-fonts` is released under the [Mozilla Public License Version 2.0](http://www.mozilla.org/MPL/).
{ "pile_set_name": "Github" }
/* ** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) ** Copyright (C) 2011 Silicon Graphics, Inc. ** All Rights Reserved. ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ** of the Software, and to permit persons to whom the Software is furnished to do so, ** subject to the following conditions: ** ** The above copyright notice including the dates of first publication and either this ** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ shall be ** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, ** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A ** PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL SILICON GRAPHICS, INC. ** BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE ** OR OTHER DEALINGS IN THE SOFTWARE. ** ** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not ** be used in advertising or otherwise to promote the sale, use or other dealings in ** this Software without prior written authorization from Silicon Graphics, Inc. */ /* ** Original Author: Eric Veach, July 1994. ** libtess2: Mikko Mononen, http://code.google.com/p/libtess2/. ** LibTessDotNet: Remi Gillig, https://github.com/speps/LibTessDotNet */ using System; using System.Collections.Generic; using System.Diagnostics; #if DOUBLE namespace LibTessDotNet.Double #else namespace LibTessDotNet #endif { internal class PriorityQueue<TValue> where TValue : class { private PriorityHeap<TValue>.LessOrEqual _leq; private PriorityHeap<TValue> _heap; private TValue[] _keys; private int[] _order; private int _size, _max; private bool _initialized; public bool Empty { get { return _size == 0 && _heap.Empty; } } public PriorityQueue(int initialSize, PriorityHeap<TValue>.LessOrEqual leq) { _leq = leq; _heap = new PriorityHeap<TValue>(initialSize, leq); _keys = new TValue[initialSize]; _size = 0; _max = initialSize; _initialized = false; } class StackItem { internal int p, r; }; static void Swap(ref int a, ref int b) { int tmp = a; a = b; b = tmp; } public void Init() { var stack = new Stack<StackItem>(); int p, r, i, j, piv; uint seed = 2016473283; p = 0; r = _size - 1; _order = new int[_size + 1]; for (piv = 0, i = p; i <= r; ++piv, ++i) { _order[i] = piv; } stack.Push(new StackItem { p = p, r = r }); while (stack.Count > 0) { var top = stack.Pop(); p = top.p; r = top.r; while (r > p + 10) { seed = seed * 1539415821 + 1; i = p + (int)(seed % (r - p + 1)); piv = _order[i]; _order[i] = _order[p]; _order[p] = piv; i = p - 1; j = r + 1; do { do { ++i; } while (!_leq(_keys[_order[i]], _keys[piv])); do { --j; } while (!_leq(_keys[piv], _keys[_order[j]])); Swap(ref _order[i], ref _order[j]); } while (i < j); Swap(ref _order[i], ref _order[j]); if (i - p < r - j) { stack.Push(new StackItem { p = j + 1, r = r }); r = i - 1; } else { stack.Push(new StackItem { p = p, r = i - 1 }); p = j + 1; } } for (i = p + 1; i <= r; ++i) { piv = _order[i]; for (j = i; j > p && !_leq(_keys[piv], _keys[_order[j - 1]]); --j) { _order[j] = _order[j - 1]; } _order[j] = piv; } } #if DEBUG p = 0; r = _size - 1; for (i = p; i < r; ++i) { Debug.Assert(_leq(_keys[_order[i + 1]], _keys[_order[i]]), "Wrong sort"); } #endif _max = _size; _initialized = true; _heap.Init(); } public PQHandle Insert(TValue value) { if (_initialized) { return _heap.Insert(value); } int curr = _size; if (++_size >= _max) { _max <<= 1; Array.Resize(ref _keys, _max); } _keys[curr] = value; return new PQHandle { _handle = -(curr + 1) }; } public TValue ExtractMin() { Debug.Assert(_initialized); if (_size == 0) { return _heap.ExtractMin(); } TValue sortMin = _keys[_order[_size - 1]]; if (!_heap.Empty) { TValue heapMin = _heap.Minimum(); if (_leq(heapMin, sortMin)) return _heap.ExtractMin(); } do { --_size; } while (_size > 0 && _keys[_order[_size - 1]] == null); return sortMin; } public TValue Minimum() { Debug.Assert(_initialized); if (_size == 0) { return _heap.Minimum(); } TValue sortMin = _keys[_order[_size - 1]]; if (!_heap.Empty) { TValue heapMin = _heap.Minimum(); if (_leq(heapMin, sortMin)) return heapMin; } return sortMin; } public void Remove(PQHandle handle) { Debug.Assert(_initialized); int curr = handle._handle; if (curr >= 0) { _heap.Remove(handle); return; } curr = -(curr + 1); Debug.Assert(curr < _max && _keys[curr] != null); _keys[curr] = null; while (_size > 0 && _keys[_order[_size - 1]] == null) { --_size; } } } }
{ "pile_set_name": "Github" }
#include "mimefile.h" #include <QFileInfo> MimeFile::MimeFile(QFile *file) { this->file = file; this->cType = "application/octet-stream"; this->cName = QFileInfo(*file).fileName(); this->cEncoding = Base64; } MimeFile::~MimeFile() { delete file; } void MimeFile::prepare() { file->open(QIODevice::ReadOnly); this->content = file->readAll(); file->close(); MimePart::prepare(); }
{ "pile_set_name": "Github" }
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.fave.dto import com.google.gson.annotations.SerializedName import kotlin.Int import kotlin.collections.List /** * @param count Total number * @param items no description */ data class FaveGetResponseDto( @SerializedName(value="count") val count: Int? = null, @SerializedName(value="items") val items: List<FaveBookmark>? = null )
{ "pile_set_name": "Github" }
// $Id$ // Author: Yves Lafon <[email protected]> // // (c) COPYRIGHT MIT, ERCIM and Keio University, 2012. // Please first read the full copyright statement in file COPYRIGHT.html package org.w3c.css.atrules.css; import org.w3c.css.parser.AtRule; import org.w3c.css.util.ApplContext; import org.w3c.css.util.InvalidParamException; import org.w3c.css.values.CssIdent; import org.w3c.css.values.CssPercentage; import org.w3c.css.values.CssTypes; import org.w3c.css.values.CssValue; public class AtRuleKeyframes extends AtRule { static final CssIdent to, from; static { to = CssIdent.getIdent("to"); from = CssIdent.getIdent("from"); } public static void checkSelectorValue(CssValue selector, ApplContext ac) throws InvalidParamException { switch (selector.getType()) { case CssTypes.CSS_PERCENTAGE: CssPercentage percentage = selector.getPercentage(); if (!percentage.isPositive() || percentage.floatValue() > 100.f) { throw new InvalidParamException("range", ac); } break; case CssTypes.CSS_IDENT: CssIdent id = (CssIdent) selector; if (to.equals(id) || from.equals(id)) { break; } default: throw new InvalidParamException("selectorname", selector.toString(), ac); } } String name = null; public String keyword() { return "keyframes"; } public boolean isEmpty() { return false; } /** * The second must be exactly the same of this one */ public boolean canApply(AtRule atRule) { return false; } /** * The second must only match this one */ public boolean canMatch(AtRule atRule) { return false; } public void setName(String name) { this.name = name; } public String lookupPrefix() { return ""; } /** * Returns a string representation of the object. */ public String toString() { StringBuilder ret = new StringBuilder(); ret.append('@'); ret.append(keyword()); ret.append(' '); ret.append(name); return ret.toString(); } public AtRuleKeyframes(String name) { this.name = name; } }
{ "pile_set_name": "Github" }
rule n3f0_224b6854b84946f6 { meta: copyright="Copyright (c) 2014-2018 Support Intelligence Inc, All Rights Reserved." engine="saphire/1.3.1 divinorum/0.998 icewater/0.4" viz_url="http://icewater.io/en/cluster/query?h64=n3f0.224b6854b84946f6" cluster="n3f0.224b6854b84946f6" cluster_size="3" filetype = "application/x-dosexec" tlp = "amber" version = "icewater snowflake" author = "Rick Wesson (@wessorh) [email protected]" date = "20171111" license = "RIL-1.0 [Rick's Internet License] " family="mira ccpk malicious" md5_hashes="['bb7e2f9d3b4e742993eaf0af268b835c','efc3f29c046150bb6b12bf4aed7f7bbb','fb2af8ebffac72af36018bc13b31789f']" strings: $hex_string = { 3dc55d3b8b9e925a0d65170c7581867576c9484d65ccc6910ea6aea019e3a346bcdd8ddef99dfbeb7eaa51436fc6df8ce980c947ba93a841bf3cd5a6cfff491f } condition: filesize > 262144 and filesize < 1048576 and $hex_string }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd"> <ldml> <identity> <version number="$Revision: 5798 $"/> <generation date="$Date: 2011-05-02 15:05:34 +0900 (Mon, 02 May 2011) $"/> <language type="yav"/> <territory type="CM"/> </identity> </ldml>
{ "pile_set_name": "Github" }
FIRST_GOPATH := $(firstword $(subst :, ,$(GOPATH))) PKGS := $(shell go list ./... | grep -v /tests | grep -v /xcpb | grep -v /gpb) GOFILES_NOVENDOR := $(shell find . -name vendor -prune -o -type f -name '*.go' -not -name '*.pb.go' -print) GOFILES_BUILD := $(shell find . -type f -name '*.go' -not -name '*_test.go') PROTOFILES := $(shell find . -name vendor -prune -o -type f -name '*.proto' -print) GOPASS_VERSION ?= $(shell cat VERSION) GOPASS_OUTPUT ?= gopass GOPASS_REVISION := $(shell cat COMMIT 2>/dev/null || git rev-parse --short=8 HEAD) BASH_COMPLETION_OUTPUT := bash.completion FISH_COMPLETION_OUTPUT := fish.completion ZSH_COMPLETION_OUTPUT := zsh.completion # Support reproducible builds by embedding date according to SOURCE_DATE_EPOCH if present DATE := $(shell date -u -d "@$(SOURCE_DATE_EPOCH)" '+%FT%T%z' 2>/dev/null || date -u '+%FT%T%z') BUILDFLAGS_NOPIE := -trimpath -ldflags="-s -w -X main.version=$(GOPASS_VERSION) -X main.commit=$(GOPASS_REVISION) -X main.date=$(DATE)" -gcflags="-trimpath=$(GOPATH)" -asmflags="-trimpath=$(GOPATH)" BUILDFLAGS ?= $(BUILDFLAGS_NOPIE) -buildmode=pie TESTFLAGS ?= PWD := $(shell pwd) PREFIX ?= $(GOPATH) BINDIR ?= $(PREFIX)/bin GO := GO111MODULE=on go GOOS ?= $(shell go version | cut -d' ' -f4 | cut -d'/' -f1) GOARCH ?= $(shell go version | cut -d' ' -f4 | cut -d'/' -f2) TAGS ?= netgo export GO111MODULE=on OK := $(shell tput setaf 6; echo ' [OK]'; tput sgr0;) all: build completion build: $(GOPASS_OUTPUT) gopass-git-credentials gopass-hibp gopass-jsonapi gopass-summon-provider completion: $(BASH_COMPLETION_OUTPUT) $(FISH_COMPLETION_OUTPUT) $(ZSH_COMPLETION_OUTPUT) travis: sysinfo crosscompile build install fulltest codequality completion full travis-osx: sysinfo build install test completion full travis-windows: sysinfo build install test completion sysinfo: @echo ">> SYSTEM INFORMATION" @echo -n " PLATFORM: $(shell uname -a)" @printf '%s\n' '$(OK)' @echo -n " PWD: : $(shell pwd)" @printf '%s\n' '$(OK)' @echo -n " GO : $(shell go version)" @printf '%s\n' '$(OK)' @echo -n " BUILDFLAGS: $(BUILDFLAGS)" @printf '%s\n' '$(OK)' @echo -n " GIT : $(shell git version)" @printf '%s\n' '$(OK)' @echo -n " GPG1 : $(shell which gpg) $(shell gpg --version | head -1)" @printf '%s\n' '$(OK)' @echo -n " GPG2 : $(shell which gpg2) $(shell gpg2 --version | head -1)" @printf '%s\n' '$(OK)' @echo -n " GPG-Agent : $(shell which gpg-agent) $(shell gpg-agent --version | head -1)" @printf '%s\n' '$(OK)' clean: @echo -n ">> CLEAN" @$(GO) clean -i ./... @rm -f ./coverage-all.html @rm -f ./coverage-all.out @rm -f ./coverage.out @find . -type f -name "coverage.out" -delete @rm -f gopass_*.deb @rm -f gopass-*.pkg.tar.xz @rm -f gopass-*.rpm @rm -f gopass-*.tar.bz2 @rm -f gopass-*.tar.gz @rm -f gopass-*-* @rm -f tests/tests @rm -f *.test @rm -rf dist/* @rm -f *.completion @printf '%s\n' '$(OK)' $(GOPASS_OUTPUT): $(GOFILES_BUILD) @echo -n ">> BUILD, version = $(GOPASS_VERSION)/$(GOPASS_REVISION), output = $@" @$(GO) build -o $@ $(BUILDFLAGS) @printf '%s\n' '$(OK)' gopass-git-credentials: $(GOFILES_BUILD) @echo -n ">> BUILD, version = $(GOPASS_VERSION)/$(GOPASS_REVISION), output = $@" @cd cmd/gopass-git-credentials && $(GO) build -o gopass-git-credentials $(BUILDFLAGS) @printf '%s\n' '$(OK)' gopass-hibp: $(GOFILES_BUILD) @echo -n ">> BUILD, version = $(GOPASS_VERSION)/$(GOPASS_REVISION), output = $@" @cd cmd/gopass-hibp && $(GO) build -o gopass-hibp $(BUILDFLAGS) @printf '%s\n' '$(OK)' gopass-jsonapi: $(GOFILES_BUILD) @echo -n ">> BUILD, version = $(GOPASS_VERSION)/$(GOPASS_REVISION), output = $@" @cd cmd/gopass-jsonapi && $(GO) build -o gopass-jsonapi $(BUILDFLAGS) @printf '%s\n' '$(OK)' gopass-summon-provider: $(GOFILES_BUILD) @echo -n ">> BUILD, version = $(GOPASS_VERSION)/$(GOPASS_REVISION), output = $@" @cd cmd/gopass-summon-provider && $(GO) build -o gopass-summon-provider $(BUILDFLAGS) @printf '%s\n' '$(OK)' install: all install-completion @echo -n ">> INSTALL, version = $(GOPASS_VERSION)" @install -m 0755 -d $(DESTDIR)$(BINDIR) @install -m 0755 $(GOPASS_OUTPUT) $(DESTDIR)$(BINDIR)/gopass @install -m 0755 cmd/gopass-git-credentials/gopass-git-credentials $(DESTDIR)$(BINDIR)/gopass-git-credentials @install -m 0755 cmd/gopass-hibp/gopass-hibp $(DESTDIR)$(BINDIR)/gopass-hibp @install -m 0755 cmd/gopass-jsonapi/gopass-jsonapi $(DESTDIR)$(BINDIR)/gopass-jsonapi @install -m 0755 cmd/gopass-summon-provider/gopass-summon-provider $(DESTDIR)$(BINDIR)/gopass-summon-provider @printf '%s\n' '$(OK)' fulltest: $(GOPASS_OUTPUT) @echo ">> TEST, \"full-mode\": race detector off, build tags: xc" @echo "mode: atomic" > coverage-all.out @$(foreach pkg, $(PKGS),\ echo -n " ";\ go test -run '(Test|Example)' $(BUILDFLAGS) $(TESTFLAGS) -coverprofile=coverage.out -covermode=atomic $(pkg) || exit 1;\ tail -n +2 coverage.out >> coverage-all.out;) @$(GO) tool cover -html=coverage-all.out -o coverage-all.html fulltest-nocover: $(GOPASS_OUTPUT) @echo ">> TEST, \"full-mode-no-coverage\": race detector off, build tags: xc" @echo "mode: atomic" > coverage-all.out @$(foreach pkg, $(PKGS),\ echo -n " ";\ go test -run '(Test|Example)' $(BUILDFLAGS) $(TESTFLAGS) $(pkg) || exit 1;) racetest: $(GOPASS_OUTPUT) @echo ">> TEST, \"full-mode\": race detector on" @echo "mode: atomic" > coverage-all.out @$(foreach pkg, $(PKGS),\ echo -n " ";\ go test -run '(Test|Example)' $(BUILDFLAGS) $(TESTFLAGS) -race -coverprofile=coverage.out -covermode=atomic $(pkg) || exit 1;\ tail -n +2 coverage.out >> coverage-all.out;) @$(GO) tool cover -html=coverage-all.out -o coverage-all.html test: $(GOPASS_OUTPUT) @echo ">> TEST, \"fast-mode\": race detector off" @$(foreach pkg, $(PKGS),\ echo -n " ";\ $(GO) test -test.short -run '(Test|Example)' $(BUILDFLAGS) $(TESTFLAGS) $(pkg) || exit 1) test-integration: $(GOPASS_OUTPUT) cd tests && GOPASS_BINARY=$(PWD)/$(GOPASS_OUTPUT) GOPASS_TEST_DIR=$(PWD)/tests go test -v crosscompile: @echo -n ">> CROSSCOMPILE linux/amd64" @GOOS=linux GOARCH=amd64 $(GO) build -o $(GOPASS_OUTPUT)-linux-amd64 @printf '%s\n' '$(OK)' @echo -n ">> CROSSCOMPILE darwin/amd64" @GOOS=darwin GOARCH=amd64 $(GO) build -o $(GOPASS_OUTPUT)-darwin-amd64 @printf '%s\n' '$(OK)' @echo -n ">> CROSSCOMPILE windows/amd64" @GOOS=windows GOARCH=amd64 $(GO) build -o $(GOPASS_OUTPUT)-windows-amd64 @printf '%s\n' '$(OK)' full: @echo -n ">> COMPILE linux/amd64 xc" $(GO) build -o $(GOPASS_OUTPUT)-full %.completion: $(GOPASS_OUTPUT) @printf ">> $* completion, output = $@" @./gopass completion $* > $@ @printf "%s\n" "$(OK)" install-completion: completion @install -d $(DESTDIR)$(PREFIX)/share/zsh/site-functions $(DESTDIR)$(PREFIX)/share/bash-completion/completions $(DESTDIR)$(PREFIX)/share/fish/vendor_completions.d @install -m 0755 $(ZSH_COMPLETION_OUTPUT) $(DESTDIR)$(PREFIX)/share/zsh/site-functions/_gopass @install -m 0755 $(BASH_COMPLETION_OUTPUT) $(DESTDIR)$(PREFIX)/share/bash-completion/completions/gopass @install -m 0755 $(FISH_COMPLETION_OUTPUT) $(DESTDIR)$(PREFIX)/share/fish/vendor_completions.d/gopass.fish @printf '%s\n' '$(OK)' codequality: @echo ">> CODE QUALITY" @echo -n " REVIVE " @which revive > /dev/null; if [ $$? -ne 0 ]; then \ $(GO) get -u github.com/mgechev/revive; \ fi @revive -formatter friendly -exclude vendor/... ./... @printf '%s\n' '$(OK)' @echo -n " FMT " @$(foreach gofile, $(GOFILES_NOVENDOR),\ out=$$(gofmt -s -l -d -e $(gofile) | tee /dev/stderr); if [ -n "$$out" ]; then exit 1; fi;) @printf '%s\n' '$(OK)' @echo -n " CLANGFMT " @$(foreach pbfile, $(PROTOFILES),\ if [ $$(clang-format -output-replacements-xml $(pbfile) | wc -l) -gt 3 ]; then exit 1; fi;) @printf '%s\n' '$(OK)' @echo -n " VET " @$(GO) vet ./... @printf '%s\n' '$(OK)' @echo -n " CYCLO " @which gocyclo > /dev/null; if [ $$? -ne 0 ]; then \ $(GO) get -u github.com/fzipp/gocyclo; \ fi @$(foreach gofile, $(GOFILES_NOVENDOR),\ gocyclo -over 22 $(gofile) || exit 1;) @printf '%s\n' '$(OK)' @echo -n " LINT " @which golint > /dev/null; if [ $$? -ne 0 ]; then \ $(GO) get -u golang.org/x/lint/golint; \ fi @$(foreach pkg, $(PKGS),\ golint -set_exit_status $(pkg) || exit 1;) @printf '%s\n' '$(OK)' @echo -n " INEFF " @which ineffassign > /dev/null; if [ $$? -ne 0 ]; then \ $(GO) get -u github.com/gordonklaus/ineffassign; \ fi @ineffassign . || exit 1 @printf '%s\n' '$(OK)' @echo -n " SPELL " @which misspell > /dev/null; if [ $$? -ne 0 ]; then \ $(GO) get -u github.com/client9/misspell/cmd/misspell; \ fi @$(foreach gofile, $(GOFILES_NOVENDOR),\ misspell --error $(gofile) || exit 1;) @printf '%s\n' '$(OK)' @echo -n " STATICCHECK " @which staticcheck > /dev/null; if [ $$? -ne 0 ]; then \ $(GO) get -u honnef.co/go/tools/cmd/staticcheck; \ fi @staticcheck $(PKGS) || exit 1 @printf '%s\n' '$(OK)' @echo -n " UNPARAM " @which unparam > /dev/null; if [ $$? -ne 0 ]; then \ $(GO) get -u mvdan.cc/unparam; \ fi @unparam -exported=false $(PKGS) @printf '%s\n' '$(OK)' gen: @go generate ./... fmt: @gofmt -s -l -w $(GOFILES_NOVENDOR) @goimports -l -w $(GOFILES_NOVENDOR) @which clang-format > /dev/null; if [ $$? -eq 0 ]; then \ clang-format -i $(PROTOFILES); \ fi @go mod tidy fuzz-gpg: mkdir -p workdir/gpg-cli/corpus go-fuzz-build github.com/gopasspw/gopass/backend/gpg/cli go-fuzz -bin=cli-fuzz.zip -workdir=workdir/gpg-cli check-release-env: ifndef GITHUB_TOKEN $(error GITHUB_TOKEN is undefined) endif release: goreleaser goreleaser: check-release-env travis clean @echo ">> RELEASE, goreleaser" @goreleaser deps: @go build -v ./... upgrade: gen fmt @go get -u .PHONY: clean build completion install sysinfo crosscompile test codequality release goreleaser debsign
{ "pile_set_name": "Github" }
module Handler.Add where import Import import Handler.Archive import Data.List (nub) import qualified Data.Text as T (replace) -- View getAddViewR :: Handler Html getAddViewR = do userId <- requireAuthId murl <- lookupGetParam "url" mformdb <- runDB (pure . fmap _toBookmarkForm =<< fetchBookmarkByUrl userId murl) formurl <- bookmarkFormUrl let renderEl = "addForm" :: Text popupLayout do toWidget [whamlet| <div id="#{ renderEl }"> |] toWidgetBody [julius| app.dat.bmark = #{ toJSON (fromMaybe formurl mformdb) }; |] toWidget [julius| PS['Main'].renderAddForm('##{rawJS renderEl}')(app.dat.bmark)(); |] bookmarkFormUrl :: Handler BookmarkForm bookmarkFormUrl = do Entity _ user <- requireAuth url <- lookupGetParam "url" >>= pure . fromMaybe "" title <- lookupGetParam "title" description <- lookupGetParam "description" >>= pure . fmap Textarea tags <- lookupGetParam "tags" private <- lookupGetParam "private" >>= pure . fmap parseChk <&> (<|> Just (userPrivateDefault user)) toread <- lookupGetParam "toread" >>= pure . fmap parseChk pure $ BookmarkForm { _url = url , _title = title , _description = description , _tags = tags , _private = private , _toread = toread , _bid = Nothing , _slug = Nothing , _selected = Nothing , _time = Nothing , _archiveUrl = Nothing } where parseChk s = s == "yes" || s == "on" -- API postAddR :: Handler () postAddR = do bookmarkForm <- requireCheckJsonBody _handleFormSuccess bookmarkForm >>= \case (Created, bid) -> sendStatusJSON created201 bid (Updated, _) -> sendResponseStatus noContent204 () _handleFormSuccess :: BookmarkForm -> Handler (UpsertResult, Key Bookmark) _handleFormSuccess bookmarkForm = do (userId, user) <- requireAuthPair bm <- liftIO $ _toBookmark userId bookmarkForm (res, kbid) <- runDB (upsertBookmark userId mkbid bm tags) whenM (shouldArchiveBookmark user kbid) $ void $ async (archiveBookmarkUrl kbid (unpack (bookmarkHref bm))) pure (res, kbid) where mkbid = BookmarkKey <$> _bid bookmarkForm tags = maybe [] (nub . words . T.replace "," " ") (_tags bookmarkForm) postLookupTitleR :: Handler () postLookupTitleR = do void requireAuthId bookmarkForm <- (requireCheckJsonBody :: Handler BookmarkForm) fetchPageTitle (unpack (_url bookmarkForm)) >>= \case Left _ -> sendResponseStatus noContent204 () Right title -> sendResponseStatus ok200 title
{ "pile_set_name": "Github" }
NAME=PE: corkami appsectableW7.exe - open FILE=bins/pe/appsectableW7.exe ARGS=-A CMDS=q! EXPECT=<<EOF EOF RUN NAME=PE: corkami appsectableW7.exe - entrypoint FILE=bins/pe/appsectableW7.exe CMDS=s EXPECT=<<EOF 0x401000 EOF RUN NAME=PE: corkami appsectableW7.exe - pi 1 FILE=bins/pe/appsectableW7.exe CMDS=pi 1 EXPECT=<<EOF push 0x401018 EOF RUN
{ "pile_set_name": "Github" }
<!-- markdownlint-disable --> <!-- markdownlint-disable --> <!DOCTYPE html> <html lang="en" data-init-theme="default" data-applied-theme="default" data-theme-path-pattern="/luda/0.3.x/.dist/css/luda-$theme$.min.css"> <head> <title>Form Icon | Luda is a library helps to build cross-framework UI components.</title> <!-- markdownlint-disable --> <meta charset="UTF-8"> <!-- viewport --> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"> <!-- render --> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"> <!-- apple app mode --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="apple-mobile-web-app-title" content="Luda"> <!-- chrome --> <meta name="mobile-web-app-capable" content="yes"> <!-- Chrome, Firefox OS and Opera --> <!-- <meta name="theme-color" content="#8c447c"> --> <!-- Windows Phone --> <!-- <meta name="msapplication-navbutton-color" content="#8c447c"> --> <meta name="application-name" content="Luda"> <!-- apple no tel --> <meta content="telephone=no" name="format-detection"> <!-- windows phone no tap color --> <meta name="msapplication-tap-highlight" content="no"> <meta name="author" content="Oatw"> <meta name="keywords" content="luda, cross-framework, component-based, ui-library"> <meta name="description" content="Luda is a library helps to build cross-framework UI components."> <link rel="shortcut icon" href="/luda/0.3.x/favicon.ico"> <link href='https://fonts.googleapis.com/css?family=Playfair+Display:700,900|Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css"> <script type="text/javascript" src="/luda/0.3.x/assets/js/turbolinks.js"></script> <link rel="stylesheet" type="text/css" data-theme-style="default" href="/luda/0.3.x/.dist/css/luda-default.min.css"> <link rel="stylesheet" type="text/css" href="/luda/0.3.x/.dist/css/site.min.css"> <script type="text/javascript" src="/luda/0.3.x/.dist/js/luda-degradation.min.js"></script> <script type="text/javascript" src="/luda/0.3.x/.dist/js/luda.min.js"></script> <script type="text/javascript" src="/luda/0.3.x/assets/js/clipboard.js"></script> <script type="text/javascript" src="/luda/0.3.x/.dist/js/site.min.js"></script> <script type="text/javascript" src="/luda/version.js"></script> <!-- markdownlint-disable --> <script type="text/javascript"> window.site = window.site || {} window.site.version = "0.3.x" luda.ready(function(){ if(window.site.version != window.site.latestVersion){ luda.toggle('#site-version-alert').activate() } }) </script> </head> <body> <!-- markdownlint-disable --> <div id="site-version-alert" class="alert fix-t fix-l w-100 bc-danger jc-center" style="z-index:100" data-toggle-target="site-version-alert"> <div class="alert-content"> <p> There is a newer version of <a class="link-light" data-turbolinks="false" href="/luda">Luda</a>. </p> </div> <div class="alert-action"> <a data-turbolinks="false" href="/luda" class="btn btn-light btn-small mr-small">Let's go!</a> <button data-toggleable class="btn btn-hollow-light btn-small">I don't care.</button> </div> </div> <!-- markdownlint-disable --> <div id="doc" class="grid-edge"> <!-- markdownlint-disable --> <aside id="doc-aside" class="nav-aside col-12 col-3-m pb-medium-m"> <a href="/luda/0.3.x/" data-turbolinks="false" class="nav-logo"> <img src="/luda/0.3.x/assets/img/logo-text-light.svg" alt="logo"> </a> <!-- markdownlint-disable --> <!-- markdownlint-disable --> <div id="theme-dropdown" data-turbolinks-permanent class="dropdown-fixed ml-auto d-none-m"> <button class="btn btn-ico btn-text-primary"> <i class="change-theme-trigger ico material-icons">brush</i> </button> <div class="dropdown-menu"> <div class="dropdown-items"> <div class="btns-y"> <div class="btn-radio btn-hollow-primary"> <input class="change-theme" checked type="radio" name="theme_dropdown_apply_theme" value="default"> <label class="bd-none tt-cap">Theme default</label> </div> </div> </div> </div> </div> <button class="nav-open btn btn-text-light btn-ico ml-none" data-toggle-for="nav-aside-menu"> <i class="ico ico-menu"></i> </button> <div class="nav-menu" data-toggle-target="nav-aside-menu" data-toggleable> <button class="nav-close btn btn-text-light btn-ico"> <i class="ico ico-cross"></i> </button> <div class="nav-items"> <p class="display px-small fw-semibold c-light">Get Started</p> <!-- markdownlint-disable --> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/general/introduction">Introduction</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/general/installation">Installation</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/general/browser-support">Browser Support</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/general/modular-import">Modular Import</a> </div> <div class="nav-items"> <p class="display px-small fw-semibold c-light">Advanced</p> <!-- markdownlint-disable --> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/advanced/theming">Theming</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/advanced/breakpoints">Breakpoints</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/advanced/component">Build A Component</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/advanced/api">Kernel Engine API</a> </div> <div class="nav-items"> <p class="display px-small fw-semibold c-light">Behaviors</p> <!-- markdownlint-disable --> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/behaviors/disabled">Disabled</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/behaviors/enter">Enter</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/behaviors/focus">Focus</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/behaviors/readonly">Readonly</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/behaviors/tabulate">Tabulate</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/behaviors/toggle">Toggle</a> </div> <div class="nav-items"> <p class="display px-small fw-semibold c-light">Elements</p> <!-- markdownlint-disable --> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/badge">Badge</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/baseline">Baseline</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/button">Button</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/container">Container</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/form">Form</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/grid">Grid</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/icon">Icon</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/media">Media</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/overlay">Overlay</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/progress">Progress</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/scrollbar">Scrollbar</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/table">Table</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/elements/typography">Typography</a> </div> <div class="nav-items"> <p class="display px-small fw-semibold c-light">Patterns</p> <!-- markdownlint-disable --> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/alert">Alert</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/article">Article</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/avatar">Avatar</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/breadcrumb">Breadcrumb</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/button-group">Button Group</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/button-icon">Button Icon</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/carousel">Carousel</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/dropdown">Dropdown</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/form-dropdown">Form Dropdown</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/form-group">Form Group</a> <a class="btn btn-small btn-text-light mt-tiny btn-active" href="/luda/0.3.x/patterns/form-icon">Form Icon</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/modal">Modal</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/navigation">Navigation</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/search-bar">Search Bar</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/patterns/tab">Tab</a> </div> <div class="nav-items"> <p class="display px-small fw-semibold c-light">Utilities</p> <!-- markdownlint-disable --> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/alignment">Alignment</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/background">Background</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/border">Border</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/color">Color</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/display">Display</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/flex">Flex</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/float">Float</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/opacity">Opacity</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/overflow">Overflow</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/position">Position</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/shadow">Shadow</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/shape">Shape</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/size">Size</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/spacing">Spacing</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/text">Text</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/visibility">Visibility</a> <a class="btn btn-small btn-text-light mt-tiny" href="/luda/0.3.x/utilities/z-index">Z-index</a> </div> </div> </aside> <button class="btn btn-dark btn-ico fix-r fix-t zi-highest circle sd-high m-small d-none-m" data-toggle-for="nav-aside-menu"> <i class="ico ico-menu"></i> </button> <main id="doc-container" class="col-auto p-medium pt-small-m px-large-m pb-large-m"> <article class="article max-w-100 p-none"> <h1 class="page-title display fw-semibold mt-large-m">Form Icon</h1> <p class="h3 page-sub-title fw-light">An icon can be wrapped in the left or right of a form element.</p> <h2 id="icon-in-the-left">Icon in the Left</h2> <p>To wrap an icon in the left of a form element, add the <code class="highlighter-rouge">.fm-ico-left</code> class to the <code class="highlighter-rouge">.fm</code> container, then wrap an icon element inside.</p> <div class="form-example"> <div class="fm fm-text fm-ico-left fm-small"> <input name="example1" placeholder="Search anything..." /> <i class="ico ico-search"></i> </div> <div class="fm fm-text fm-ico-left"> <input name="example2" placeholder="Search anything..." /> <i class="ico ico-search"></i> </div> <div class="fm fm-text fm-ico-left fm-large"> <input name="example3" placeholder="Search anything..." /> <i class="ico ico-search"></i> </div> </div> <div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"fm fm-text fm-ico-left fm-small"</span><span class="nt">&gt;</span> <span class="nt">&lt;input</span> <span class="na">name=</span><span class="s">"example1"</span> <span class="na">placeholder=</span><span class="s">"Search anything..."</span><span class="nt">&gt;</span> <span class="nt">&lt;i</span> <span class="na">class=</span><span class="s">"ico ico-search"</span><span class="nt">&gt;&lt;/i&gt;</span> <span class="nt">&lt;/div&gt;</span> <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"fm fm-text fm-ico-left"</span><span class="nt">&gt;</span> <span class="nt">&lt;input</span> <span class="na">name=</span><span class="s">"example2"</span> <span class="na">placeholder=</span><span class="s">"Search anything..."</span><span class="nt">&gt;</span> <span class="nt">&lt;i</span> <span class="na">class=</span><span class="s">"ico ico-search"</span><span class="nt">&gt;&lt;/i&gt;</span> <span class="nt">&lt;/div&gt;</span> <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"fm fm-text fm-ico-left fm-large"</span><span class="nt">&gt;</span> <span class="nt">&lt;input</span> <span class="na">name=</span><span class="s">"example3"</span> <span class="na">placeholder=</span><span class="s">"Search anything..."</span><span class="nt">&gt;</span> <span class="nt">&lt;i</span> <span class="na">class=</span><span class="s">"ico ico-search"</span><span class="nt">&gt;&lt;/i&gt;</span> <span class="nt">&lt;/div&gt;</span> </code></pre></div></div> <h2 id="icon-in-the-right">Icon in the Right</h2> <p>To wrap an icon in the right of a form element, add the <code class="highlighter-rouge">.fm-ico-right</code> class to the <code class="highlighter-rouge">.fm</code> container, then wrap an icon element inside.</p> <div class="form-example"> <div class="fm fm-select fm-ico-right fm-small"> <select name="example4" placeholder="E.g., Gamil"> <option value="gmail">Gmail</option> <option value="hotmail">Hotmail</option> </select> <i class="ico material-icons">mail</i> </div> <div class="fm fm-select fm-ico-right"> <select name="example5" placeholder="E.g., Gamil"> <option value="gmail">Gmail</option> <option value="hotmail">Hotmail</option> </select> <i class="ico material-icons">mail</i> </div> <div class="fm fm-select fm-ico-right fm-large"> <select name="example6" placeholder="E.g., Gamil"> <option value="gmail">Gmail</option> <option value="hotmail">Hotmail</option> </select> <i class="ico material-icons">mail</i> </div> </div> <div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"fm fm-select fm-ico-right fm-small"</span><span class="nt">&gt;</span> <span class="nt">&lt;select</span> <span class="na">name=</span><span class="s">"example4"</span> <span class="na">placeholder=</span><span class="s">"E.g., Gamil"</span><span class="nt">&gt;</span> <span class="nt">&lt;option</span> <span class="na">value=</span><span class="s">"gmail"</span><span class="nt">&gt;</span>Gmail<span class="nt">&lt;/option&gt;</span> <span class="nt">&lt;option</span> <span class="na">value=</span><span class="s">"hotmail"</span><span class="nt">&gt;</span>Hotmail<span class="nt">&lt;/option&gt;</span> <span class="nt">&lt;/select&gt;</span> <span class="nt">&lt;i</span> <span class="na">class=</span><span class="s">"ico material-icons"</span><span class="nt">&gt;</span>mail<span class="nt">&lt;/i&gt;</span> <span class="nt">&lt;/div&gt;</span> <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"fm fm-select fm-ico-right"</span><span class="nt">&gt;</span> <span class="nt">&lt;select</span> <span class="na">name=</span><span class="s">"example5"</span> <span class="na">placeholder=</span><span class="s">"E.g., Gamil"</span><span class="nt">&gt;</span> <span class="nt">&lt;option</span> <span class="na">value=</span><span class="s">"gmail"</span><span class="nt">&gt;</span>Gmail<span class="nt">&lt;/option&gt;</span> <span class="nt">&lt;option</span> <span class="na">value=</span><span class="s">"hotmail"</span><span class="nt">&gt;</span>Hotmail<span class="nt">&lt;/option&gt;</span> <span class="nt">&lt;/select&gt;</span> <span class="nt">&lt;i</span> <span class="na">class=</span><span class="s">"ico material-icons"</span><span class="nt">&gt;</span>mail<span class="nt">&lt;/i&gt;</span> <span class="nt">&lt;/div&gt;</span> <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"fm fm-select fm-ico-right fm-large"</span><span class="nt">&gt;</span> <span class="nt">&lt;select</span> <span class="na">name=</span><span class="s">"example6"</span> <span class="na">placeholder=</span><span class="s">"E.g., Gamil"</span><span class="nt">&gt;</span> <span class="nt">&lt;option</span> <span class="na">value=</span><span class="s">"gmail"</span><span class="nt">&gt;</span>Gmail<span class="nt">&lt;/option&gt;</span> <span class="nt">&lt;option</span> <span class="na">value=</span><span class="s">"hotmail"</span><span class="nt">&gt;</span>Hotmail<span class="nt">&lt;/option&gt;</span> <span class="nt">&lt;/select&gt;</span> <span class="nt">&lt;i</span> <span class="na">class=</span><span class="s">"ico material-icons"</span><span class="nt">&gt;</span>mail<span class="nt">&lt;/i&gt;</span> <span class="nt">&lt;/div&gt;</span> </code></pre></div></div> <h2 id="sass-variables">Sass Variables</h2> <div class="language-sass highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$form-element-icon-size-em</span><span class="p">:</span> <span class="n">null</span> <span class="o">!</span><span class="nb">default</span> </code></pre></div></div> <div class="language-sass highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$form-element-icon-color</span><span class="p">:</span> <span class="nf">lighten</span><span class="p">(</span><span class="nv">$color-muted</span><span class="o">,</span> <span class="m">10%</span><span class="p">)</span> <span class="o">!</span><span class="nb">default</span> </code></pre></div></div> <div class="language-sass highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$form-element-icon-color-on-error</span><span class="p">:</span> <span class="nv">$form-element-border-color-on-error</span> <span class="o">!</span><span class="nb">default</span> </code></pre></div></div> <div class="language-sass highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$form-element-icon-color-on-focus</span><span class="p">:</span> <span class="nv">$form-element-border-color-on-focus</span> <span class="o">!</span><span class="nb">default</span> </code></pre></div></div> </article> </main> <nav id="doc-sub-nav" class="nav-aside col-auto zi-normal d-none d-block-l pr-large pl-medium pb-medium bc-none bi-none"> <div class="nav-items m-none"> </div> </nav> <!-- markdownlint-disable --> <!-- markdownlint-disable --> <div id="theme-pannel" data-turbolinks-permanent class="d-none d-block-m fix-r fix-b zi-high mr-large mb-large"> <div class="btns-x btns-margin jc-end" data-toggle-target="change_theme"> <div class="theme-pannel-option btn-radio btn-hollow-dark bc-main circle"> <input class="change-theme" checked type="radio" name="theme_pannel_apply_theme" value="default"> <label class="bd-none circle sd-high tt-cap">Theme default</label> </div> <div class="btn btn-light btn-ico circle sd-high" data-toggleable data-toggle-for="change_theme_trigger"> <i class="ico ico-cross"></i> </div> </div> <button class="theme-pannel-trigger btn btn-ico-left btn-dark toggle-active mb-small mr-small circle sd-high" data-toggle-for="change_theme" data-toggle-target="change_theme_trigger" data-toggleable> <i class="ico material-icons">brush</i> Change Theme </button> </div> </div> </body> </html>
{ "pile_set_name": "Github" }
all: credentials: see_diagrams
{ "pile_set_name": "Github" }
/* Prompts a person to go to the URL listed to enter the confirmation code that is presented to them above the given string. */ "DeviceLogin.LogInPrompt" = "%@를 방문하여 위에 표시된 코드를 입력하세요."; /* Prompts a person that the next thing they need to do to finish connecting their Smart TV and Facebook application is to navigate to their Facebook application on their mobile device and look through their notifications for a message about the connection being formed */ "DeviceLogin.SmartLogInPrompt" = "계정을 연결하려면 모바일 기기에서 Facebook 앱을 열고 알림을 확인하세요."; /* Displayed as a separator between two options. First option is on a line above this, and second option is below */ "DeviceLogin.SmartLogInOrLabel" = "- 또는 -"; /* The title of the label to dismiss the alert when presenting user facing error messages */ "ErrorRecovery.Alert.OK" = "확인"; /* The title of the label to decline attempting error recovery */ "ErrorRecovery.Cancel" = "취소"; /* The fallback message to display to recover invalidated tokens */ "ErrorRecovery.Login.Suggestion" = "Facebook 계정을 다시 연결하려면 이 앱에 다시 로그인하세요."; /* The title of the label to start attempting error recovery */ "ErrorRecovery.OK" = "확인"; /* The fallback message to display to retry transient errors */ "ErrorRecovery.Transient.Suggestion" = "일시적으로 서버 사용량이 많아졌습니다. 다시 시도하세요."; /* The label for the FBSDKLikeButton when the object is not currently liked. */ "LikeButton.Like" = "좋아요"; /* The label for the FBSDKLikeButton when the object is currently liked. */ "LikeButton.Liked" = "좋아요"; /* The label for the FBSDKLoginButton action sheet to cancel logging out */ "LoginButton.CancelLogout" = "취소"; /* The label for the FBSDKLoginButton action sheet to confirm logging out */ "LoginButton.ConfirmLogOut" = "로그아웃"; /* The fallback string for the FBSDKLoginButton label when the user name is not available yet */ "LoginButton.LoggedIn" = "Facebook 계정으로 로그인함"; /* The format string for the FBSDKLoginButton label when the user is logged in */ "LoginButton.LoggedInAs" = "%@(으)로 로그인함"; /* The short label for the FBSDKLoginButton when the user is currently logged out */ "LoginButton.LogIn" = "로그인"; /* The long label for the FBSDKLoginButton when the user is currently logged out */ "LoginButton.LogInContinue" = "Facebook으로 계속"; /* The long label for the FBSDKLoginButton when the user is currently logged out */ "LoginButton.LogInLong" = "Facebook으로 로그인"; /* The label for the FBSDKLoginButton when the user is currently logged in */ "LoginButton.LogOut" = "로그아웃"; /* The user facing error message when the app slider has been disabled and login fails. */ "LoginError.SystemAccount.Disabled" = "Facebook 계정에 대한 액세스가 승인되지 않았습니다. 기기 설정을 확인하세요."; /* The user facing error message when the Accounts framework encounters a network error. */ "LoginError.SystemAccount.Network" = "Facebook에 연결할 수 없습니다. 네트워크 연결을 확인하고 다시 시도하세요."; /* The user facing error message when the device Facebook account password is incorrect and login fails. */ "LoginError.SystemAccount.PasswordChange" = "Facebook 비밀번호가 변경되었습니다. 비밀번호를 확인하려면 설정 &gt; Facebook으로 이동하여 이름을 누르세요."; /* The user facing error message when the device Facebook account is unavailable and login fails. */ "LoginError.SystemAccount.Unavailable" = "Facebook 계정이 기기에 구성되어 있지 않습니다."; /* The user facing error message when the Facebook account signed in to the Accounts framework becomes unconfirmed. */ "LoginError.SystemAccount.UnconfirmedUser" = "계정이 확인되지 않았습니다. www.facebook.com에 로그인한 뒤 안내를 따라주세요."; /* The user facing error message when the Facebook account signed in to the Accounts framework has been checkpointed. */ "LoginError.SystemAccount.UserCheckpointed" = "현재 앱에 로그인할 수 없습니다. www.facebook.com에 로그인한 뒤 안내를 따라주세요."; /* The message of the FBSDKLoginTooltipView */ "LoginTooltip.Message" = "원하는 정보를 선택하여 앱에 공유할 수 있습니다."; /* Title of the web dialog that prompts the user to log in to Facebook. */ "LoginWeb.LogInTitle" = "로그인"; /* The label for FBSDKSendButton */ "SendButton.Send" = "보내기"; /* The label for FBSDKShareButton */ "ShareButton.Share" = "공유하기"; /* Prompts a person if this is their current account */ "SmartLogin.NotYou" = "회원님이 아닌가요?"; /* Text on a button that a person presses to confirm that they are finished with the login experience */ "SmartLogin.ConfirmationTitle" = "로그인 확인"; /* Text on a button that lets a person continue with their name linked to a Facebook account (Name = %@) */ "SmartLogin.Continue" = "%@님으로 계속";
{ "pile_set_name": "Github" }
$SEMISYNC_PLUGIN_OPT
{ "pile_set_name": "Github" }
// <copyright file="FileNotFoundExceptionHandler.cs" company="Automate The Planet Ltd."> // Copyright 2018 Automate The Planet Ltd. // 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. // </copyright> // <author>Anton Angelov</author> // <site>http://automatetheplanet.com/</site> namespace HybridTestFramework.UITests.Core.Utilities.ExceptionsAnalysis.ChainOfResponsibility { public class FileNotFoundExceptionHandler : HtmlSourceExceptionHandler { protected override string DetailedIssueExplanation { get { return "IT IS NOT A TEST PROBLEM. THE PAGE DOES NOT EXIST."; } } protected override string TextToSearchInSource { get { return "404 - File or directory not found."; } } } }
{ "pile_set_name": "Github" }
import { pieData } from "./pie"; export const donutData = pieData; export const donutOptions = { title: "Donut", resizable: true, donut: { center: { label: "Browsers" } } }; export const donutCenteredData = pieData; export const donutCenteredOptions = { title: "Donut (centered)", resizable: true, legend: { alignment: "center" }, donut: { center: { label: "Browsers" }, alignment: "center" } }; // donut - empty state export const donutEmptyStateData = []; export const donutEmptyStateOptions = { title: "Donut (empty state)", resizable: true, donut: { center: { label: "Browsers" } } }; // donut - skeleton export const donutSkeletonData = []; export const donutSkeletonOptions = { title: "Donut (skeleton)", resizable: true, donut: { center: { label: "Browsers" } }, data: { loading: true } };
{ "pile_set_name": "Github" }
{"audio": "rnn/data/test/ah/56a.wav", "text": ["5", "6"], "duration": 24576} {"audio": "rnn/data/test/ah/3oa.wav", "text": ["3", "0"], "duration": 19200} {"audio": "rnn/data/test/ah/63a.wav", "text": ["6", "3"], "duration": 21760} {"audio": "rnn/data/test/ah/o9a.wav", "text": ["0", "9"], "duration": 20736} {"audio": "rnn/data/test/ah/65a.wav", "text": ["6", "5"], "duration": 22784} {"audio": "rnn/data/test/ah/73a.wav", "text": ["7", "3"], "duration": 27904} {"audio": "rnn/data/test/ah/69a.wav", "text": ["6", "9"], "duration": 22272} {"audio": "rnn/data/test/ar/16a.wav", "text": ["1", "6"], "duration": 27136} {"audio": "rnn/data/test/ar/35a.wav", "text": ["3", "5"], "duration": 24320} {"audio": "rnn/data/test/ar/19a.wav", "text": ["1", "9"], "duration": 21760} {"audio": "rnn/data/test/ar/o3a.wav", "text": ["0", "3"], "duration": 22016} {"audio": "rnn/data/test/ar/5oa.wav", "text": ["5", "0"], "duration": 30464} {"audio": "rnn/data/test/ar/91a.wav", "text": ["9", "1"], "duration": 24832} {"audio": "rnn/data/test/ar/o4a.wav", "text": ["0", "4"], "duration": 25600} {"audio": "rnn/data/test/ar/28a.wav", "text": ["2", "8"], "duration": 27392} {"audio": "rnn/data/test/bn/67a.wav", "text": ["6", "7"], "duration": 27392} {"audio": "rnn/data/test/bn/62a.wav", "text": ["6", "2"], "duration": 22784} {"audio": "rnn/data/test/bn/15a.wav", "text": ["1", "5"], "duration": 24832} {"audio": "rnn/data/test/bn/5oa.wav", "text": ["5", "0"], "duration": 24320} {"audio": "rnn/data/test/bn/43a.wav", "text": ["4", "3"], "duration": 24064} {"audio": "rnn/data/test/bn/34a.wav", "text": ["3", "4"], "duration": 23040} {"audio": "rnn/data/test/bn/3oa.wav", "text": ["3", "0"], "duration": 21248} {"audio": "rnn/data/test/bn/52a.wav", "text": ["5", "2"], "duration": 23040} {"audio": "rnn/data/test/bn/53a.wav", "text": ["5", "3"], "duration": 25600} {"audio": "rnn/data/test/cc/66a.wav", "text": ["6", "6"], "duration": 25600} {"audio": "rnn/data/test/cc/26a.wav", "text": ["2", "6"], "duration": 25344} {"audio": "rnn/data/test/cc/71a.wav", "text": ["7", "1"], "duration": 30208} {"audio": "rnn/data/test/cc/17a.wav", "text": ["1", "7"], "duration": 21504} {"audio": "rnn/data/test/cc/41a.wav", "text": ["4", "1"], "duration": 22528} {"audio": "rnn/data/test/cc/59a.wav", "text": ["5", "9"], "duration": 21760} {"audio": "rnn/data/test/cc/3oa.wav", "text": ["3", "0"], "duration": 28160} {"audio": "rnn/data/test/cc/25a.wav", "text": ["2", "5"], "duration": 23808} {"audio": "rnn/data/test/cc/73a.wav", "text": ["7", "3"], "duration": 27136} {"audio": "rnn/data/test/ef/o7a.wav", "text": ["0", "7"], "duration": 26368} {"audio": "rnn/data/test/ef/85a.wav", "text": ["8", "5"], "duration": 26112} {"audio": "rnn/data/test/ef/97a.wav", "text": ["9", "7"], "duration": 23808} {"audio": "rnn/data/test/ef/o3a.wav", "text": ["0", "3"], "duration": 25600} {"audio": "rnn/data/test/ef/5oa.wav", "text": ["5", "0"], "duration": 26368} {"audio": "rnn/data/test/ef/1oa.wav", "text": ["1", "0"], "duration": 26112} {"audio": "rnn/data/test/ef/22a.wav", "text": ["2", "2"], "duration": 27904} {"audio": "rnn/data/test/ef/72a.wav", "text": ["7", "2"], "duration": 29184} {"audio": "rnn/data/test/ef/24a.wav", "text": ["2", "4"], "duration": 23296} {"audio": "rnn/data/test/ef/ooa.wav", "text": ["0", "0"], "duration": 25856} {"audio": "rnn/data/test/et/o7a.wav", "text": ["0", "7"], "duration": 30464} {"audio": "rnn/data/test/et/67a.wav", "text": ["6", "7"], "duration": 26112} {"audio": "rnn/data/test/et/37a.wav", "text": ["3", "7"], "duration": 28160} {"audio": "rnn/data/test/et/62a.wav", "text": ["6", "2"], "duration": 26880} {"audio": "rnn/data/test/et/43a.wav", "text": ["4", "3"], "duration": 27136} {"audio": "rnn/data/test/et/52a.wav", "text": ["5", "2"], "duration": 25088} {"audio": "rnn/data/test/et/64a.wav", "text": ["6", "4"], "duration": 28672} {"audio": "rnn/data/test/et/48a.wav", "text": ["4", "8"], "duration": 24832} {"audio": "rnn/data/test/et/32a.wav", "text": ["3", "2"], "duration": 27648} {"audio": "rnn/data/test/et/73a.wav", "text": ["7", "3"], "duration": 32512} {"audio": "rnn/data/test/et/2oa.wav", "text": ["2", "0"], "duration": 28672} {"audio": "rnn/data/test/fp/94a.wav", "text": ["9", "4"], "duration": 22784} {"audio": "rnn/data/test/fp/41a.wav", "text": ["4", "1"], "duration": 20480} {"audio": "rnn/data/test/fp/35a.wav", "text": ["3", "5"], "duration": 20480} {"audio": "rnn/data/test/fp/1oa.wav", "text": ["1", "0"], "duration": 20224} {"audio": "rnn/data/test/fp/34a.wav", "text": ["3", "4"], "duration": 19968} {"audio": "rnn/data/test/fp/29a.wav", "text": ["2", "9"], "duration": 19456} {"audio": "rnn/data/test/fp/12a.wav", "text": ["1", "2"], "duration": 17664} {"audio": "rnn/data/test/fp/45a.wav", "text": ["4", "5"], "duration": 20992} {"audio": "rnn/data/test/fp/69a.wav", "text": ["6", "9"], "duration": 18944} {"audio": "rnn/data/test/fr/o7a.wav", "text": ["0", "7"], "duration": 22528} {"audio": "rnn/data/test/fr/95a.wav", "text": ["9", "5"], "duration": 22784} {"audio": "rnn/data/test/fr/16a.wav", "text": ["1", "6"], "duration": 28928} {"audio": "rnn/data/test/fr/43a.wav", "text": ["4", "3"], "duration": 22016} {"audio": "rnn/data/test/fr/63a.wav", "text": ["6", "3"], "duration": 27392} {"audio": "rnn/data/test/fr/22a.wav", "text": ["2", "2"], "duration": 18432} {"audio": "rnn/data/test/fr/25a.wav", "text": ["2", "5"], "duration": 20736} {"audio": "rnn/data/test/ft/11a.wav", "text": ["1", "1"], "duration": 23296} {"audio": "rnn/data/test/ft/26a.wav", "text": ["2", "6"], "duration": 27136} {"audio": "rnn/data/test/ft/51a.wav", "text": ["5", "1"], "duration": 29440} {"audio": "rnn/data/test/ft/41a.wav", "text": ["4", "1"], "duration": 28416} {"audio": "rnn/data/test/ft/77a.wav", "text": ["7", "7"], "duration": 32000} {"audio": "rnn/data/test/ft/81a.wav", "text": ["8", "1"], "duration": 32768} {"audio": "rnn/data/test/ft/75a.wav", "text": ["7", "5"], "duration": 30464} {"audio": "rnn/data/test/ft/22a.wav", "text": ["2", "2"], "duration": 25088} {"audio": "rnn/data/test/ft/68a.wav", "text": ["6", "8"], "duration": 35840} {"audio": "rnn/data/test/ga/46a.wav", "text": ["4", "6"], "duration": 27136} {"audio": "rnn/data/test/ga/17a.wav", "text": ["1", "7"], "duration": 26112} {"audio": "rnn/data/test/ga/98a.wav", "text": ["9", "8"], "duration": 27392} {"audio": "rnn/data/test/ga/3oa.wav", "text": ["3", "0"], "duration": 26112} {"audio": "rnn/data/test/ga/75a.wav", "text": ["7", "5"], "duration": 43264} {"audio": "rnn/data/test/ga/29a.wav", "text": ["2", "9"], "duration": 26880} {"audio": "rnn/data/test/ga/33a.wav", "text": ["3", "3"], "duration": 22272} {"audio": "rnn/data/test/ga/o9a.wav", "text": ["0", "9"], "duration": 22528} {"audio": "rnn/data/test/ga/45a.wav", "text": ["4", "5"], "duration": 29184} {"audio": "rnn/data/test/jh/8oa.wav", "text": ["8", "0"], "duration": 21504} {"audio": "rnn/data/test/jh/99a.wav", "text": ["9", "9"], "duration": 29696} {"audio": "rnn/data/test/jh/62a.wav", "text": ["6", "2"], "duration": 29440} {"audio": "rnn/data/test/jh/19a.wav", "text": ["1", "9"], "duration": 23296} {"audio": "rnn/data/test/jh/58a.wav", "text": ["5", "8"], "duration": 26368} {"audio": "rnn/data/test/jh/14a.wav", "text": ["1", "4"], "duration": 23808} {"audio": "rnn/data/test/jh/79a.wav", "text": ["7", "9"], "duration": 28672} {"audio": "rnn/data/test/jh/22a.wav", "text": ["2", "2"], "duration": 21760} {"audio": "rnn/data/test/jh/72a.wav", "text": ["7", "2"], "duration": 32768} {"audio": "rnn/data/test/jh/48a.wav", "text": ["4", "8"], "duration": 30208} {"audio": "rnn/data/test/ka/47a.wav", "text": ["4", "7"], "duration": 28160} {"audio": "rnn/data/test/ka/51a.wav", "text": ["5", "1"], "duration": 35328} {"audio": "rnn/data/test/ka/99a.wav", "text": ["9", "9"], "duration": 33536} {"audio": "rnn/data/test/ka/19a.wav", "text": ["1", "9"], "duration": 30720} {"audio": "rnn/data/test/ka/43a.wav", "text": ["4", "3"], "duration": 28928} {"audio": "rnn/data/test/ka/38a.wav", "text": ["3", "8"], "duration": 33280} {"audio": "rnn/data/test/ka/32a.wav", "text": ["3", "2"], "duration": 29440} {"audio": "rnn/data/test/ka/65a.wav", "text": ["6", "5"], "duration": 39936} {"audio": "rnn/data/test/ka/ooa.wav", "text": ["0", "0"], "duration": 31744} {"audio": "rnn/data/test/ke/89a.wav", "text": ["8", "9"], "duration": 25856} {"audio": "rnn/data/test/ke/94a.wav", "text": ["9", "4"], "duration": 30464} {"audio": "rnn/data/test/ke/41a.wav", "text": ["4", "1"], "duration": 25600} {"audio": "rnn/data/test/ke/62a.wav", "text": ["6", "2"], "duration": 24576} {"audio": "rnn/data/test/ke/19a.wav", "text": ["1", "9"], "duration": 32768} {"audio": "rnn/data/test/ke/54a.wav", "text": ["5", "4"], "duration": 27904} {"audio": "rnn/data/test/ke/o5a.wav", "text": ["0", "5"], "duration": 34816} {"audio": "rnn/data/test/kg/93a.wav", "text": ["9", "3"], "duration": 28672} {"audio": "rnn/data/test/kg/99a.wav", "text": ["9", "9"], "duration": 26624} {"audio": "rnn/data/test/kg/21a.wav", "text": ["2", "1"], "duration": 23552} {"audio": "rnn/data/test/kg/o1a.wav", "text": ["0", "1"], "duration": 25856} {"audio": "rnn/data/test/kg/16a.wav", "text": ["1", "6"], "duration": 29952} {"audio": "rnn/data/test/kg/3oa.wav", "text": ["3", "0"], "duration": 25088} {"audio": "rnn/data/test/kg/4oa.wav", "text": ["4", "0"], "duration": 22784} {"audio": "rnn/data/test/kg/72a.wav", "text": ["7", "2"], "duration": 27392} {"audio": "rnn/data/test/kg/24a.wav", "text": ["2", "4"], "duration": 26624} {"audio": "rnn/data/test/kg/ooa.wav", "text": ["0", "0"], "duration": 23808} {"audio": "rnn/data/test/nl/46a.wav", "text": ["4", "6"], "duration": 31744} {"audio": "rnn/data/test/nl/17a.wav", "text": ["1", "7"], "duration": 24832} {"audio": "rnn/data/test/nl/95a.wav", "text": ["9", "5"], "duration": 23040} {"audio": "rnn/data/test/nl/16a.wav", "text": ["1", "6"], "duration": 28672} {"audio": "rnn/data/test/nl/54a.wav", "text": ["5", "4"], "duration": 24320} {"audio": "rnn/data/test/nl/34a.wav", "text": ["3", "4"], "duration": 21504} {"audio": "rnn/data/test/nl/o5a.wav", "text": ["0", "5"], "duration": 21504} {"audio": "rnn/data/test/nl/72a.wav", "text": ["7", "2"], "duration": 24320} {"audio": "rnn/data/test/nl/33a.wav", "text": ["3", "3"], "duration": 23552} {"audio": "rnn/data/test/nl/49a.wav", "text": ["4", "9"], "duration": 25088} {"audio": "rnn/data/test/np/85a.wav", "text": ["8", "5"], "duration": 23040} {"audio": "rnn/data/test/np/37a.wav", "text": ["3", "7"], "duration": 24832} {"audio": "rnn/data/test/np/o1a.wav", "text": ["0", "1"], "duration": 19968} {"audio": "rnn/data/test/np/81a.wav", "text": ["8", "1"], "duration": 23552} {"audio": "rnn/data/test/np/34a.wav", "text": ["3", "4"], "duration": 21760} {"audio": "rnn/data/test/np/4oa.wav", "text": ["4", "0"], "duration": 24320} {"audio": "rnn/data/test/np/13a.wav", "text": ["1", "3"], "duration": 29440} {"audio": "rnn/data/test/np/64a.wav", "text": ["6", "4"], "duration": 24064} {"audio": "rnn/data/test/pc/31a.wav", "text": ["3", "1"], "duration": 23552} {"audio": "rnn/data/test/pc/37a.wav", "text": ["3", "7"], "duration": 25344} {"audio": "rnn/data/test/pc/95a.wav", "text": ["9", "5"], "duration": 28416} {"audio": "rnn/data/test/pc/9oa.wav", "text": ["9", "0"], "duration": 28928} {"audio": "rnn/data/test/pc/41a.wav", "text": ["4", "1"], "duration": 35584} {"audio": "rnn/data/test/pc/23a.wav", "text": ["2", "3"], "duration": 26368} {"audio": "rnn/data/test/pc/ooa.wav", "text": ["0", "0"], "duration": 33024} {"audio": "rnn/data/test/ph/89a.wav", "text": ["8", "9"], "duration": 22272} {"audio": "rnn/data/test/ph/27a.wav", "text": ["2", "7"], "duration": 23808} {"audio": "rnn/data/test/ph/92a.wav", "text": ["9", "2"], "duration": 22528} {"audio": "rnn/data/test/ph/41a.wav", "text": ["4", "1"], "duration": 21504} {"audio": "rnn/data/test/ph/19a.wav", "text": ["1", "9"], "duration": 20992} {"audio": "rnn/data/test/ph/43a.wav", "text": ["4", "3"], "duration": 22784} {"audio": "rnn/data/test/ph/3oa.wav", "text": ["3", "0"], "duration": 23040} {"audio": "rnn/data/test/ph/29a.wav", "text": ["2", "9"], "duration": 23808} {"audio": "rnn/data/test/ph/o8a.wav", "text": ["0", "8"], "duration": 20480} {"audio": "rnn/data/test/ph/24a.wav", "text": ["2", "4"], "duration": 21504} {"audio": "rnn/data/test/pr/66a.wav", "text": ["6", "6"], "duration": 29952} {"audio": "rnn/data/test/pr/8oa.wav", "text": ["8", "0"], "duration": 23552} {"audio": "rnn/data/test/pr/37a.wav", "text": ["3", "7"], "duration": 23296} {"audio": "rnn/data/test/pr/95a.wav", "text": ["9", "5"], "duration": 29440} {"audio": "rnn/data/test/pr/7oa.wav", "text": ["7", "0"], "duration": 28416} {"audio": "rnn/data/test/pr/1oa.wav", "text": ["1", "0"], "duration": 24320} {"audio": "rnn/data/test/pr/43a.wav", "text": ["4", "3"], "duration": 27648} {"audio": "rnn/data/test/pr/44a.wav", "text": ["4", "4"], "duration": 30720} {"audio": "rnn/data/test/pr/12a.wav", "text": ["1", "2"], "duration": 25344} {"audio": "rnn/data/test/rk/85a.wav", "text": ["8", "5"], "duration": 25344} {"audio": "rnn/data/test/rk/8oa.wav", "text": ["8", "0"], "duration": 25088} {"audio": "rnn/data/test/rk/21a.wav", "text": ["2", "1"], "duration": 22016} {"audio": "rnn/data/test/rk/74a.wav", "text": ["7", "4"], "duration": 28928} {"audio": "rnn/data/test/rk/35a.wav", "text": ["3", "5"], "duration": 27136} {"audio": "rnn/data/test/rk/75a.wav", "text": ["7", "5"], "duration": 27648} {"audio": "rnn/data/test/rk/22a.wav", "text": ["2", "2"], "duration": 21504} {"audio": "rnn/data/test/rk/44a.wav", "text": ["4", "4"], "duration": 25600} {"audio": "rnn/data/test/rk/o9a.wav", "text": ["0", "9"], "duration": 23808} {"audio": "rnn/data/test/rk/32a.wav", "text": ["3", "2"], "duration": 25600} {"audio": "rnn/data/test/sa/85a.wav", "text": ["8", "5"], "duration": 27648} {"audio": "rnn/data/test/sa/71a.wav", "text": ["7", "1"], "duration": 27904} {"audio": "rnn/data/test/sa/67a.wav", "text": ["6", "7"], "duration": 22272} {"audio": "rnn/data/test/sa/47a.wav", "text": ["4", "7"], "duration": 23552} {"audio": "rnn/data/test/sa/51a.wav", "text": ["5", "1"], "duration": 21760} {"audio": "rnn/data/test/sa/98a.wav", "text": ["9", "8"], "duration": 21248} {"audio": "rnn/data/test/sa/74a.wav", "text": ["7", "4"], "duration": 28416} {"audio": "rnn/data/test/sa/18a.wav", "text": ["1", "8"], "duration": 24064} {"audio": "rnn/data/test/sa/64a.wav", "text": ["6", "4"], "duration": 24320} {"audio": "rnn/data/test/sa/69a.wav", "text": ["6", "9"], "duration": 30720} {"audio": "rnn/data/test/sl/31a.wav", "text": ["3", "1"], "duration": 27136} {"audio": "rnn/data/test/sl/89a.wav", "text": ["8", "9"], "duration": 24064} {"audio": "rnn/data/test/sl/92a.wav", "text": ["9", "2"], "duration": 24320} {"audio": "rnn/data/test/sl/8oa.wav", "text": ["8", "0"], "duration": 25088} {"audio": "rnn/data/test/sl/77a.wav", "text": ["7", "7"], "duration": 27904} {"audio": "rnn/data/test/sl/97a.wav", "text": ["9", "7"], "duration": 26112} {"audio": "rnn/data/test/sl/38a.wav", "text": ["3", "8"], "duration": 33280} {"audio": "rnn/data/test/sl/29a.wav", "text": ["2", "9"], "duration": 21248} {"audio": "rnn/data/test/sl/49a.wav", "text": ["4", "9"], "duration": 27392} {"audio": "rnn/data/test/sl/28a.wav", "text": ["2", "8"], "duration": 25088} {"audio": "rnn/data/test/sr/95a.wav", "text": ["9", "5"], "duration": 24064} {"audio": "rnn/data/test/sr/94a.wav", "text": ["9", "4"], "duration": 24064} {"audio": "rnn/data/test/sr/42a.wav", "text": ["4", "2"], "duration": 25600} {"audio": "rnn/data/test/sr/14a.wav", "text": ["1", "4"], "duration": 25856} {"audio": "rnn/data/test/sr/59a.wav", "text": ["5", "9"], "duration": 28928} {"audio": "rnn/data/test/sr/18a.wav", "text": ["1", "8"], "duration": 23296} {"audio": "rnn/data/test/sr/2oa.wav", "text": ["2", "0"], "duration": 32768} {"audio": "rnn/data/test/sw/93a.wav", "text": ["9", "3"], "duration": 23552} {"audio": "rnn/data/test/sw/47a.wav", "text": ["4", "7"], "duration": 21248} {"audio": "rnn/data/test/sw/37a.wav", "text": ["3", "7"], "duration": 23552} {"audio": "rnn/data/test/sw/76a.wav", "text": ["7", "6"], "duration": 26112} {"audio": "rnn/data/test/sw/82a.wav", "text": ["8", "2"], "duration": 21248} {"audio": "rnn/data/test/sw/62a.wav", "text": ["6", "2"], "duration": 24832} {"audio": "rnn/data/test/sw/o3a.wav", "text": ["0", "3"], "duration": 23552} {"audio": "rnn/data/test/sw/5oa.wav", "text": ["5", "0"], "duration": 25344} {"audio": "rnn/data/test/sw/25a.wav", "text": ["2", "5"], "duration": 21760}
{ "pile_set_name": "Github" }
// // UISlider+Rx.swift // RxCocoa // // Created by Alexander van der Werff on 28/05/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) #if !RX_NO_MODULE import RxSwift #endif import UIKit extension Reactive where Base: UISlider { /// Reactive wrapper for `value` property. public var value: ControlProperty<Float> { return UIControl.rx.value( self.base, getter: { slider in slider.value }, setter: { slider, value in slider.value = value } ) } } #endif
{ "pile_set_name": "Github" }
#!/usr/bin/python3 # # Copyright 2019 Google LLC # # 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.
{ "pile_set_name": "Github" }
"use strict"; function parseHost(urlObj, options) { // TWEAK :: condition only for speed optimization if (options.ignore_www) { var host = urlObj.host.full; if (host) { var stripped = host; if (host.indexOf("www.") === 0) { stripped = host.substr(4); } urlObj.host.stripped = stripped; } } } module.exports = parseHost;
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: k8s.io/kubernetes/vendor/k8s.io/api/rbac/v1/generated.proto /* Package v1 is a generated protocol buffer package. It is generated from these files: k8s.io/kubernetes/vendor/k8s.io/api/rbac/v1/generated.proto It has these top-level messages: AggregationRule ClusterRole ClusterRoleBinding ClusterRoleBindingList ClusterRoleList PolicyRule Role RoleBinding RoleBindingList RoleList RoleRef Subject */ package v1 import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import k8s_io_apimachinery_pkg_apis_meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" import strings "strings" import reflect "reflect" import io "io" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package func (m *AggregationRule) Reset() { *m = AggregationRule{} } func (*AggregationRule) ProtoMessage() {} func (*AggregationRule) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{0} } func (m *ClusterRole) Reset() { *m = ClusterRole{} } func (*ClusterRole) ProtoMessage() {} func (*ClusterRole) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{1} } func (m *ClusterRoleBinding) Reset() { *m = ClusterRoleBinding{} } func (*ClusterRoleBinding) ProtoMessage() {} func (*ClusterRoleBinding) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{2} } func (m *ClusterRoleBindingList) Reset() { *m = ClusterRoleBindingList{} } func (*ClusterRoleBindingList) ProtoMessage() {} func (*ClusterRoleBindingList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{3} } func (m *ClusterRoleList) Reset() { *m = ClusterRoleList{} } func (*ClusterRoleList) ProtoMessage() {} func (*ClusterRoleList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{4} } func (m *PolicyRule) Reset() { *m = PolicyRule{} } func (*PolicyRule) ProtoMessage() {} func (*PolicyRule) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{5} } func (m *Role) Reset() { *m = Role{} } func (*Role) ProtoMessage() {} func (*Role) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{6} } func (m *RoleBinding) Reset() { *m = RoleBinding{} } func (*RoleBinding) ProtoMessage() {} func (*RoleBinding) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{7} } func (m *RoleBindingList) Reset() { *m = RoleBindingList{} } func (*RoleBindingList) ProtoMessage() {} func (*RoleBindingList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{8} } func (m *RoleList) Reset() { *m = RoleList{} } func (*RoleList) ProtoMessage() {} func (*RoleList) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{9} } func (m *RoleRef) Reset() { *m = RoleRef{} } func (*RoleRef) ProtoMessage() {} func (*RoleRef) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{10} } func (m *Subject) Reset() { *m = Subject{} } func (*Subject) ProtoMessage() {} func (*Subject) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{11} } func init() { proto.RegisterType((*AggregationRule)(nil), "k8s.io.api.rbac.v1.AggregationRule") proto.RegisterType((*ClusterRole)(nil), "k8s.io.api.rbac.v1.ClusterRole") proto.RegisterType((*ClusterRoleBinding)(nil), "k8s.io.api.rbac.v1.ClusterRoleBinding") proto.RegisterType((*ClusterRoleBindingList)(nil), "k8s.io.api.rbac.v1.ClusterRoleBindingList") proto.RegisterType((*ClusterRoleList)(nil), "k8s.io.api.rbac.v1.ClusterRoleList") proto.RegisterType((*PolicyRule)(nil), "k8s.io.api.rbac.v1.PolicyRule") proto.RegisterType((*Role)(nil), "k8s.io.api.rbac.v1.Role") proto.RegisterType((*RoleBinding)(nil), "k8s.io.api.rbac.v1.RoleBinding") proto.RegisterType((*RoleBindingList)(nil), "k8s.io.api.rbac.v1.RoleBindingList") proto.RegisterType((*RoleList)(nil), "k8s.io.api.rbac.v1.RoleList") proto.RegisterType((*RoleRef)(nil), "k8s.io.api.rbac.v1.RoleRef") proto.RegisterType((*Subject)(nil), "k8s.io.api.rbac.v1.Subject") } func (m *AggregationRule) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *AggregationRule) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if len(m.ClusterRoleSelectors) > 0 { for _, msg := range m.ClusterRoleSelectors { dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(msg.Size())) n, err := msg.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n } } return i, nil } func (m *ClusterRole) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ClusterRole) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(m.ObjectMeta.Size())) n1, err := m.ObjectMeta.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n1 if len(m.Rules) > 0 { for _, msg := range m.Rules { dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(msg.Size())) n, err := msg.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n } } if m.AggregationRule != nil { dAtA[i] = 0x1a i++ i = encodeVarintGenerated(dAtA, i, uint64(m.AggregationRule.Size())) n2, err := m.AggregationRule.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n2 } return i, nil } func (m *ClusterRoleBinding) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ClusterRoleBinding) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(m.ObjectMeta.Size())) n3, err := m.ObjectMeta.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n3 if len(m.Subjects) > 0 { for _, msg := range m.Subjects { dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(msg.Size())) n, err := msg.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n } } dAtA[i] = 0x1a i++ i = encodeVarintGenerated(dAtA, i, uint64(m.RoleRef.Size())) n4, err := m.RoleRef.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n4 return i, nil } func (m *ClusterRoleBindingList) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ClusterRoleBindingList) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(m.ListMeta.Size())) n5, err := m.ListMeta.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n5 if len(m.Items) > 0 { for _, msg := range m.Items { dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(msg.Size())) n, err := msg.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n } } return i, nil } func (m *ClusterRoleList) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *ClusterRoleList) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(m.ListMeta.Size())) n6, err := m.ListMeta.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n6 if len(m.Items) > 0 { for _, msg := range m.Items { dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(msg.Size())) n, err := msg.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n } } return i, nil } func (m *PolicyRule) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *PolicyRule) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if len(m.Verbs) > 0 { for _, s := range m.Verbs { dAtA[i] = 0xa i++ l = len(s) for l >= 1<<7 { dAtA[i] = uint8(uint64(l)&0x7f | 0x80) l >>= 7 i++ } dAtA[i] = uint8(l) i++ i += copy(dAtA[i:], s) } } if len(m.APIGroups) > 0 { for _, s := range m.APIGroups { dAtA[i] = 0x12 i++ l = len(s) for l >= 1<<7 { dAtA[i] = uint8(uint64(l)&0x7f | 0x80) l >>= 7 i++ } dAtA[i] = uint8(l) i++ i += copy(dAtA[i:], s) } } if len(m.Resources) > 0 { for _, s := range m.Resources { dAtA[i] = 0x1a i++ l = len(s) for l >= 1<<7 { dAtA[i] = uint8(uint64(l)&0x7f | 0x80) l >>= 7 i++ } dAtA[i] = uint8(l) i++ i += copy(dAtA[i:], s) } } if len(m.ResourceNames) > 0 { for _, s := range m.ResourceNames { dAtA[i] = 0x22 i++ l = len(s) for l >= 1<<7 { dAtA[i] = uint8(uint64(l)&0x7f | 0x80) l >>= 7 i++ } dAtA[i] = uint8(l) i++ i += copy(dAtA[i:], s) } } if len(m.NonResourceURLs) > 0 { for _, s := range m.NonResourceURLs { dAtA[i] = 0x2a i++ l = len(s) for l >= 1<<7 { dAtA[i] = uint8(uint64(l)&0x7f | 0x80) l >>= 7 i++ } dAtA[i] = uint8(l) i++ i += copy(dAtA[i:], s) } } return i, nil } func (m *Role) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Role) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(m.ObjectMeta.Size())) n7, err := m.ObjectMeta.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n7 if len(m.Rules) > 0 { for _, msg := range m.Rules { dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(msg.Size())) n, err := msg.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n } } return i, nil } func (m *RoleBinding) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *RoleBinding) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(m.ObjectMeta.Size())) n8, err := m.ObjectMeta.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n8 if len(m.Subjects) > 0 { for _, msg := range m.Subjects { dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(msg.Size())) n, err := msg.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n } } dAtA[i] = 0x1a i++ i = encodeVarintGenerated(dAtA, i, uint64(m.RoleRef.Size())) n9, err := m.RoleRef.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n9 return i, nil } func (m *RoleBindingList) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *RoleBindingList) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(m.ListMeta.Size())) n10, err := m.ListMeta.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n10 if len(m.Items) > 0 { for _, msg := range m.Items { dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(msg.Size())) n, err := msg.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n } } return i, nil } func (m *RoleList) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *RoleList) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(m.ListMeta.Size())) n11, err := m.ListMeta.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n11 if len(m.Items) > 0 { for _, msg := range m.Items { dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(msg.Size())) n, err := msg.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n } } return i, nil } func (m *RoleRef) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *RoleRef) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(len(m.APIGroup))) i += copy(dAtA[i:], m.APIGroup) dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(len(m.Kind))) i += copy(dAtA[i:], m.Kind) dAtA[i] = 0x1a i++ i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) i += copy(dAtA[i:], m.Name) return i, nil } func (m *Subject) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Subject) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintGenerated(dAtA, i, uint64(len(m.Kind))) i += copy(dAtA[i:], m.Kind) dAtA[i] = 0x12 i++ i = encodeVarintGenerated(dAtA, i, uint64(len(m.APIGroup))) i += copy(dAtA[i:], m.APIGroup) dAtA[i] = 0x1a i++ i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) i += copy(dAtA[i:], m.Name) dAtA[i] = 0x22 i++ i = encodeVarintGenerated(dAtA, i, uint64(len(m.Namespace))) i += copy(dAtA[i:], m.Namespace) return i, nil } func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return offset + 1 } func (m *AggregationRule) Size() (n int) { var l int _ = l if len(m.ClusterRoleSelectors) > 0 { for _, e := range m.ClusterRoleSelectors { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *ClusterRole) Size() (n int) { var l int _ = l l = m.ObjectMeta.Size() n += 1 + l + sovGenerated(uint64(l)) if len(m.Rules) > 0 { for _, e := range m.Rules { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } if m.AggregationRule != nil { l = m.AggregationRule.Size() n += 1 + l + sovGenerated(uint64(l)) } return n } func (m *ClusterRoleBinding) Size() (n int) { var l int _ = l l = m.ObjectMeta.Size() n += 1 + l + sovGenerated(uint64(l)) if len(m.Subjects) > 0 { for _, e := range m.Subjects { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } l = m.RoleRef.Size() n += 1 + l + sovGenerated(uint64(l)) return n } func (m *ClusterRoleBindingList) Size() (n int) { var l int _ = l l = m.ListMeta.Size() n += 1 + l + sovGenerated(uint64(l)) if len(m.Items) > 0 { for _, e := range m.Items { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *ClusterRoleList) Size() (n int) { var l int _ = l l = m.ListMeta.Size() n += 1 + l + sovGenerated(uint64(l)) if len(m.Items) > 0 { for _, e := range m.Items { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *PolicyRule) Size() (n int) { var l int _ = l if len(m.Verbs) > 0 { for _, s := range m.Verbs { l = len(s) n += 1 + l + sovGenerated(uint64(l)) } } if len(m.APIGroups) > 0 { for _, s := range m.APIGroups { l = len(s) n += 1 + l + sovGenerated(uint64(l)) } } if len(m.Resources) > 0 { for _, s := range m.Resources { l = len(s) n += 1 + l + sovGenerated(uint64(l)) } } if len(m.ResourceNames) > 0 { for _, s := range m.ResourceNames { l = len(s) n += 1 + l + sovGenerated(uint64(l)) } } if len(m.NonResourceURLs) > 0 { for _, s := range m.NonResourceURLs { l = len(s) n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *Role) Size() (n int) { var l int _ = l l = m.ObjectMeta.Size() n += 1 + l + sovGenerated(uint64(l)) if len(m.Rules) > 0 { for _, e := range m.Rules { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *RoleBinding) Size() (n int) { var l int _ = l l = m.ObjectMeta.Size() n += 1 + l + sovGenerated(uint64(l)) if len(m.Subjects) > 0 { for _, e := range m.Subjects { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } l = m.RoleRef.Size() n += 1 + l + sovGenerated(uint64(l)) return n } func (m *RoleBindingList) Size() (n int) { var l int _ = l l = m.ListMeta.Size() n += 1 + l + sovGenerated(uint64(l)) if len(m.Items) > 0 { for _, e := range m.Items { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *RoleList) Size() (n int) { var l int _ = l l = m.ListMeta.Size() n += 1 + l + sovGenerated(uint64(l)) if len(m.Items) > 0 { for _, e := range m.Items { l = e.Size() n += 1 + l + sovGenerated(uint64(l)) } } return n } func (m *RoleRef) Size() (n int) { var l int _ = l l = len(m.APIGroup) n += 1 + l + sovGenerated(uint64(l)) l = len(m.Kind) n += 1 + l + sovGenerated(uint64(l)) l = len(m.Name) n += 1 + l + sovGenerated(uint64(l)) return n } func (m *Subject) Size() (n int) { var l int _ = l l = len(m.Kind) n += 1 + l + sovGenerated(uint64(l)) l = len(m.APIGroup) n += 1 + l + sovGenerated(uint64(l)) l = len(m.Name) n += 1 + l + sovGenerated(uint64(l)) l = len(m.Namespace) n += 1 + l + sovGenerated(uint64(l)) return n } func sovGenerated(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (this *AggregationRule) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&AggregationRule{`, `ClusterRoleSelectors:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ClusterRoleSelectors), "LabelSelector", "k8s_io_apimachinery_pkg_apis_meta_v1.LabelSelector", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } func (this *ClusterRole) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&ClusterRole{`, `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_apimachinery_pkg_apis_meta_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, `Rules:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Rules), "PolicyRule", "PolicyRule", 1), `&`, ``, 1) + `,`, `AggregationRule:` + strings.Replace(fmt.Sprintf("%v", this.AggregationRule), "AggregationRule", "AggregationRule", 1) + `,`, `}`, }, "") return s } func (this *ClusterRoleBinding) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&ClusterRoleBinding{`, `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_apimachinery_pkg_apis_meta_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, `Subjects:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Subjects), "Subject", "Subject", 1), `&`, ``, 1) + `,`, `RoleRef:` + strings.Replace(strings.Replace(this.RoleRef.String(), "RoleRef", "RoleRef", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } func (this *ClusterRoleBindingList) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&ClusterRoleBindingList{`, `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_apimachinery_pkg_apis_meta_v1.ListMeta", 1), `&`, ``, 1) + `,`, `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ClusterRoleBinding", "ClusterRoleBinding", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } func (this *ClusterRoleList) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&ClusterRoleList{`, `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_apimachinery_pkg_apis_meta_v1.ListMeta", 1), `&`, ``, 1) + `,`, `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ClusterRole", "ClusterRole", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } func (this *PolicyRule) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&PolicyRule{`, `Verbs:` + fmt.Sprintf("%v", this.Verbs) + `,`, `APIGroups:` + fmt.Sprintf("%v", this.APIGroups) + `,`, `Resources:` + fmt.Sprintf("%v", this.Resources) + `,`, `ResourceNames:` + fmt.Sprintf("%v", this.ResourceNames) + `,`, `NonResourceURLs:` + fmt.Sprintf("%v", this.NonResourceURLs) + `,`, `}`, }, "") return s } func (this *Role) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&Role{`, `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_apimachinery_pkg_apis_meta_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, `Rules:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Rules), "PolicyRule", "PolicyRule", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } func (this *RoleBinding) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&RoleBinding{`, `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_apimachinery_pkg_apis_meta_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, `Subjects:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Subjects), "Subject", "Subject", 1), `&`, ``, 1) + `,`, `RoleRef:` + strings.Replace(strings.Replace(this.RoleRef.String(), "RoleRef", "RoleRef", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } func (this *RoleBindingList) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&RoleBindingList{`, `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_apimachinery_pkg_apis_meta_v1.ListMeta", 1), `&`, ``, 1) + `,`, `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "RoleBinding", "RoleBinding", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } func (this *RoleList) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&RoleList{`, `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_apimachinery_pkg_apis_meta_v1.ListMeta", 1), `&`, ``, 1) + `,`, `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Role", "Role", 1), `&`, ``, 1) + `,`, `}`, }, "") return s } func (this *RoleRef) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&RoleRef{`, `APIGroup:` + fmt.Sprintf("%v", this.APIGroup) + `,`, `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, `Name:` + fmt.Sprintf("%v", this.Name) + `,`, `}`, }, "") return s } func (this *Subject) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&Subject{`, `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, `APIGroup:` + fmt.Sprintf("%v", this.APIGroup) + `,`, `Name:` + fmt.Sprintf("%v", this.Name) + `,`, `Namespace:` + fmt.Sprintf("%v", this.Namespace) + `,`, `}`, }, "") return s } func valueToStringGenerated(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } func (m *AggregationRule) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: AggregationRule: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: AggregationRule: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ClusterRoleSelectors", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } m.ClusterRoleSelectors = append(m.ClusterRoleSelectors, k8s_io_apimachinery_pkg_apis_meta_v1.LabelSelector{}) if err := m.ClusterRoleSelectors[len(m.ClusterRoleSelectors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *ClusterRole) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ClusterRole: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ClusterRole: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Rules", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } m.Rules = append(m.Rules, PolicyRule{}) if err := m.Rules[len(m.Rules)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field AggregationRule", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if m.AggregationRule == nil { m.AggregationRule = &AggregationRule{} } if err := m.AggregationRule.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *ClusterRoleBinding) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ClusterRoleBinding: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ClusterRoleBinding: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Subjects", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } m.Subjects = append(m.Subjects, Subject{}) if err := m.Subjects[len(m.Subjects)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field RoleRef", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.RoleRef.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *ClusterRoleBindingList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ClusterRoleBindingList: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ClusterRoleBindingList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } m.Items = append(m.Items, ClusterRoleBinding{}) if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *ClusterRoleList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: ClusterRoleList: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: ClusterRoleList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } m.Items = append(m.Items, ClusterRole{}) if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *PolicyRule) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: PolicyRule: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: PolicyRule: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Verbs", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Verbs = append(m.Verbs, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field APIGroups", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.APIGroups = append(m.APIGroups, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Resources", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Resources = append(m.Resources, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ResourceNames", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.ResourceNames = append(m.ResourceNames, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field NonResourceURLs", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.NonResourceURLs = append(m.NonResourceURLs, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *Role) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Role: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Role: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Rules", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } m.Rules = append(m.Rules, PolicyRule{}) if err := m.Rules[len(m.Rules)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *RoleBinding) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: RoleBinding: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: RoleBinding: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ObjectMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Subjects", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } m.Subjects = append(m.Subjects, Subject{}) if err := m.Subjects[len(m.Subjects)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field RoleRef", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.RoleRef.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *RoleBindingList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: RoleBindingList: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: RoleBindingList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } m.Items = append(m.Items, RoleBinding{}) if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *RoleList) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: RoleList: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: RoleList: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.ListMeta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } m.Items = append(m.Items, Role{}) if err := m.Items[len(m.Items)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *RoleRef) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: RoleRef: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: RoleRef: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field APIGroup", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.APIGroup = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Kind = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *Subject) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Subject: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Subject: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Kind = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field APIGroup", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.APIGroup = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Namespace", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Namespace = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipGenerated(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } iNdEx += length if length < 0 { return 0, ErrInvalidLengthGenerated } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipGenerated(dAtA[start:]) if err != nil { return 0, err } iNdEx = start + next } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") } var ( ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") ) func init() { proto.RegisterFile("k8s.io/kubernetes/vendor/k8s.io/api/rbac/v1/generated.proto", fileDescriptorGenerated) } var fileDescriptorGenerated = []byte{ // 807 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x55, 0xcf, 0x6f, 0xe3, 0x44, 0x14, 0xce, 0xa4, 0x89, 0x1a, 0x4f, 0x88, 0x42, 0x87, 0x0a, 0x59, 0x05, 0x39, 0x95, 0x91, 0x50, 0x25, 0xc0, 0x26, 0x05, 0x01, 0x12, 0xea, 0xa1, 0x2e, 0x02, 0x55, 0x2d, 0xa5, 0x9a, 0x0a, 0x0e, 0x88, 0x03, 0x63, 0x67, 0xea, 0x0e, 0xf1, 0x2f, 0xcd, 0xd8, 0x91, 0x2a, 0x2e, 0x08, 0x89, 0x03, 0xb7, 0x3d, 0xee, 0xfe, 0x05, 0x7b, 0xd9, 0x3d, 0xee, 0x5f, 0xb0, 0x97, 0x1e, 0x7b, 0xec, 0x29, 0xda, 0x7a, 0xff, 0x90, 0x5d, 0xf9, 0x57, 0x9c, 0x1f, 0xee, 0x36, 0xa7, 0x48, 0xab, 0x3d, 0xb5, 0xf3, 0xde, 0xf7, 0xbe, 0xf7, 0xcd, 0xe7, 0x79, 0x2f, 0xf0, 0xfb, 0xe1, 0x77, 0x42, 0x63, 0xbe, 0x3e, 0x8c, 0x4c, 0xca, 0x3d, 0x1a, 0x52, 0xa1, 0x8f, 0xa8, 0x37, 0xf0, 0xb9, 0x9e, 0x27, 0x48, 0xc0, 0x74, 0x6e, 0x12, 0x4b, 0x1f, 0xf5, 0x75, 0x9b, 0x7a, 0x94, 0x93, 0x90, 0x0e, 0xb4, 0x80, 0xfb, 0xa1, 0x8f, 0x50, 0x86, 0xd1, 0x48, 0xc0, 0xb4, 0x04, 0xa3, 0x8d, 0xfa, 0x5b, 0x5f, 0xd8, 0x2c, 0xbc, 0x88, 0x4c, 0xcd, 0xf2, 0x5d, 0xdd, 0xf6, 0x6d, 0x5f, 0x4f, 0xa1, 0x66, 0x74, 0x9e, 0x9e, 0xd2, 0x43, 0xfa, 0x5f, 0x46, 0xb1, 0xf5, 0x75, 0xd9, 0xc6, 0x25, 0xd6, 0x05, 0xf3, 0x28, 0xbf, 0xd4, 0x83, 0xa1, 0x9d, 0x04, 0x84, 0xee, 0xd2, 0x90, 0x54, 0x34, 0xde, 0xd2, 0xef, 0xaa, 0xe2, 0x91, 0x17, 0x32, 0x97, 0x2e, 0x14, 0x7c, 0x73, 0x5f, 0x81, 0xb0, 0x2e, 0xa8, 0x4b, 0xe6, 0xeb, 0xd4, 0x47, 0x00, 0x76, 0xf7, 0x6d, 0x9b, 0x53, 0x9b, 0x84, 0xcc, 0xf7, 0x70, 0xe4, 0x50, 0xf4, 0x1f, 0x80, 0x9b, 0x96, 0x13, 0x89, 0x90, 0x72, 0xec, 0x3b, 0xf4, 0x8c, 0x3a, 0xd4, 0x0a, 0x7d, 0x2e, 0x64, 0xb0, 0xbd, 0xb6, 0xd3, 0xde, 0xfd, 0x4a, 0x2b, 0x5d, 0x99, 0xf4, 0xd2, 0x82, 0xa1, 0x9d, 0x04, 0x84, 0x96, 0x5c, 0x49, 0x1b, 0xf5, 0xb5, 0x63, 0x62, 0x52, 0xa7, 0xa8, 0x35, 0x3e, 0xbe, 0x1a, 0xf7, 0x6a, 0xf1, 0xb8, 0xb7, 0x79, 0x50, 0x41, 0x8c, 0x2b, 0xdb, 0xa9, 0x0f, 0xeb, 0xb0, 0x3d, 0x05, 0x47, 0x7f, 0xc2, 0x56, 0x42, 0x3e, 0x20, 0x21, 0x91, 0xc1, 0x36, 0xd8, 0x69, 0xef, 0x7e, 0xb9, 0x9c, 0x94, 0x5f, 0xcc, 0xbf, 0xa8, 0x15, 0xfe, 0x4c, 0x43, 0x62, 0xa0, 0x5c, 0x07, 0x2c, 0x63, 0x78, 0xc2, 0x8a, 0x0e, 0x60, 0x93, 0x47, 0x0e, 0x15, 0x72, 0x3d, 0xbd, 0xa9, 0xa2, 0x2d, 0x7e, 0x7f, 0xed, 0xd4, 0x77, 0x98, 0x75, 0x99, 0x18, 0x65, 0x74, 0x72, 0xb2, 0x66, 0x72, 0x12, 0x38, 0xab, 0x45, 0x26, 0xec, 0x92, 0x59, 0x47, 0xe5, 0xb5, 0x54, 0xed, 0x27, 0x55, 0x74, 0x73, 0xe6, 0x1b, 0x1f, 0xc4, 0xe3, 0xde, 0xfc, 0x17, 0xc1, 0xf3, 0x84, 0xea, 0xff, 0x75, 0x88, 0xa6, 0xac, 0x31, 0x98, 0x37, 0x60, 0x9e, 0xbd, 0x02, 0x87, 0x0e, 0x61, 0x4b, 0x44, 0x69, 0xa2, 0x30, 0xe9, 0xa3, 0xaa, 0x5b, 0x9d, 0x65, 0x18, 0xe3, 0xfd, 0x9c, 0xac, 0x95, 0x07, 0x04, 0x9e, 0x94, 0xa3, 0x1f, 0xe1, 0x3a, 0xf7, 0x1d, 0x8a, 0xe9, 0x79, 0xee, 0x4f, 0x25, 0x13, 0xce, 0x20, 0x46, 0x37, 0x67, 0x5a, 0xcf, 0x03, 0xb8, 0x28, 0x56, 0x9f, 0x03, 0xf8, 0xe1, 0xa2, 0x17, 0xc7, 0x4c, 0x84, 0xe8, 0x8f, 0x05, 0x3f, 0xb4, 0x25, 0x1f, 0x2f, 0x13, 0x99, 0x1b, 0x93, 0x0b, 0x14, 0x91, 0x29, 0x2f, 0x8e, 0x60, 0x93, 0x85, 0xd4, 0x2d, 0x8c, 0xf8, 0xb4, 0x4a, 0xfe, 0xa2, 0xb0, 0xf2, 0xd5, 0x1c, 0x26, 0xc5, 0x38, 0xe3, 0x50, 0x9f, 0x01, 0xd8, 0x9d, 0x02, 0xaf, 0x40, 0xfe, 0x0f, 0xb3, 0xf2, 0x7b, 0xf7, 0xc9, 0xaf, 0xd6, 0xfd, 0x0a, 0x40, 0x58, 0x8e, 0x04, 0xea, 0xc1, 0xe6, 0x88, 0x72, 0x33, 0xdb, 0x15, 0x92, 0x21, 0x25, 0xf8, 0xdf, 0x92, 0x00, 0xce, 0xe2, 0xe8, 0x33, 0x28, 0x91, 0x80, 0xfd, 0xc4, 0xfd, 0x28, 0xc8, 0x3a, 0x4b, 0x46, 0x27, 0x1e, 0xf7, 0xa4, 0xfd, 0xd3, 0xc3, 0x2c, 0x88, 0xcb, 0x7c, 0x02, 0xe6, 0x54, 0xf8, 0x11, 0xb7, 0xa8, 0x90, 0xd7, 0x4a, 0x30, 0x2e, 0x82, 0xb8, 0xcc, 0xa3, 0x6f, 0x61, 0xa7, 0x38, 0x9c, 0x10, 0x97, 0x0a, 0xb9, 0x91, 0x16, 0x6c, 0xc4, 0xe3, 0x5e, 0x07, 0x4f, 0x27, 0xf0, 0x2c, 0x0e, 0xed, 0xc1, 0xae, 0xe7, 0x7b, 0x05, 0xe4, 0x57, 0x7c, 0x2c, 0xe4, 0x66, 0x5a, 0x9a, 0xce, 0xe2, 0xc9, 0x6c, 0x0a, 0xcf, 0x63, 0xd5, 0xa7, 0x00, 0x36, 0xde, 0xa2, 0xfd, 0xa4, 0xfe, 0x5b, 0x87, 0xed, 0x77, 0x7e, 0x69, 0x24, 0xe3, 0xb6, 0xda, 0x6d, 0xb1, 0xcc, 0xb8, 0xdd, 0xbf, 0x26, 0x1e, 0x03, 0xd8, 0x5a, 0xd1, 0x7e, 0xd8, 0x9b, 0x15, 0x2c, 0xdf, 0x29, 0xb8, 0x5a, 0xe9, 0xdf, 0xb0, 0x70, 0x1d, 0x7d, 0x0e, 0x5b, 0xc5, 0x4c, 0xa7, 0x3a, 0xa5, 0xb2, 0x6f, 0x31, 0xf6, 0x78, 0x82, 0x40, 0xdb, 0xb0, 0x31, 0x64, 0xde, 0x40, 0xae, 0xa7, 0xc8, 0xf7, 0x72, 0x64, 0xe3, 0x88, 0x79, 0x03, 0x9c, 0x66, 0x12, 0x84, 0x47, 0xdc, 0xec, 0x67, 0x75, 0x0a, 0x91, 0x4c, 0x33, 0x4e, 0x33, 0xea, 0x13, 0x00, 0xd7, 0xf3, 0xd7, 0x33, 0xe1, 0x03, 0x77, 0xf2, 0x4d, 0xeb, 0xab, 0x2f, 0xa3, 0xef, 0xcd, 0xdd, 0x91, 0x0e, 0xa5, 0xe4, 0xaf, 0x08, 0x88, 0x45, 0xe5, 0x46, 0x0a, 0xdb, 0xc8, 0x61, 0xd2, 0x49, 0x91, 0xc0, 0x25, 0xc6, 0xd8, 0xb9, 0xba, 0x55, 0x6a, 0xd7, 0xb7, 0x4a, 0xed, 0xe6, 0x56, 0xa9, 0xfd, 0x13, 0x2b, 0xe0, 0x2a, 0x56, 0xc0, 0x75, 0xac, 0x80, 0x9b, 0x58, 0x01, 0x2f, 0x62, 0x05, 0x3c, 0x78, 0xa9, 0xd4, 0x7e, 0xaf, 0x8f, 0xfa, 0xaf, 0x03, 0x00, 0x00, 0xff, 0xff, 0x24, 0xa1, 0x47, 0x98, 0xcf, 0x0a, 0x00, 0x00, }
{ "pile_set_name": "Github" }
# frozen_string_literal: true require 'spec_helper' require 'cancan/matchers' describe 'User' do describe 'Abilities' do let!(:admin) { create(:admin) } # see https://github.com/CanCanCommunity/cancancan/wiki/Testing-Abilities subject(:ability){ Ability.new(user) } let(:user){ nil } let!(:organization) { create(:organization) } let!(:my_conference) { create(:full_conference, organization: organization) } let(:my_room) { create(:room, venue: my_conference.venue) } let(:conference_not_public) { create(:conference, splashpage: create(:splashpage, public: false)) } let(:conference_public) { create(:full_conference, splashpage: create(:splashpage, public: true)) } let(:event_confirmed) { create(:event, state: 'confirmed') } let(:event_unconfirmed) { create(:event) } let(:commercial_event_confirmed) { create(:commercial, commercialable: event_confirmed) } let(:commercial_event_unconfirmed) { create(:commercial, commercialable: event_unconfirmed) } let(:registration) { create(:registration) } let(:program_with_cfp) { create(:program, :with_cfp) } let(:program_without_cfp) { create(:program) } let(:program_with_call_for_tracks) { create(:cfp, cfp_type: 'tracks').program } let(:conference_with_open_registration) { create(:conference) } let!(:open_registration_period) { create(:registration_period, conference: conference_with_open_registration, start_date: Date.current - 6.days) } let(:conference_with_closed_registration) { create(:conference) } let!(:closed_registration_period) { create(:registration_period, conference: conference_with_closed_registration, start_date: Date.current - 6.days, end_date: Date.current - 6.days) } # Test abilities for not signed in users context 'when user is not signed in' do it{ should be_able_to(:index, Organization)} it{ should be_able_to(:index, Conference)} it{ should be_able_to(:show, conference_public)} it{ should_not be_able_to(:show, conference_not_public)} it do conference_public.program.schedule_public = true conference_public.program.save should be_able_to(:schedule, conference_public) end it{ should_not be_able_to(:schedule, conference_not_public)} it{ should be_able_to(:show, event_confirmed)} it{ should_not be_able_to(:show, event_unconfirmed)} it{ should be_able_to(:show, commercial_event_confirmed)} it{ should_not be_able_to(:show, commercial_event_unconfirmed)} it{ should be_able_to(:show, User)} it{ should be_able_to(:create, User)} it{ should be_able_to(:show, Registration.new)} it{ should be_able_to(:create, Registration.new(conference_id: conference_with_open_registration.id))} it{ should be_able_to(:new, Registration.new(conference_id: conference_with_open_registration.id))} it{ should_not be_able_to(:new, Registration.new(conference_id: conference_with_closed_registration.id))} it{ should_not be_able_to(:create, Registration.new(conference_id: conference_with_closed_registration.id))} it{ should_not be_able_to(:manage, registration)} it{ should be_able_to(:new, Event.new(program: program_with_cfp)) } it{ should_not be_able_to(:new, Event.new(program: program_without_cfp)) } it{ should_not be_able_to(:create, Event.new(program: program_without_cfp))} it{ should be_able_to(:show, Event.new)} it{ should_not be_able_to(:manage, :any)} end # Test abilities for signed in users (without any role) context 'when user is signed in' do let(:user) { create(:user) } let(:user2) { create(:user) } let(:event_user2) { create(:submitter, user: user2) } let(:subscription) { create(:subscription, user: user) } let(:registration_public) { create(:registration, conference: conference_public, user: user) } let(:registration_not_public) { create(:registration, conference: conference_not_public, user: user) } let(:user_event_with_cfp) { create(:event, users: [user], program: program_with_cfp) } let(:user_commercial) { create(:commercial, commercialable: user_event_with_cfp) } let(:user_self_organized_track) { create(:track, :self_organized, submitter: user) } let(:accepted_user_self_organized_track) { create(:track, :self_organized, submitter: user, state: 'accepted') } let(:confirmed_user_self_organized_track) { create(:track, :self_organized, submitter: user, state: 'confirmed') } let(:other_self_organized_track) { create(:track, :self_organized) } it{ should be_able_to(:manage, user) } it{ should be_able_to(:manage, registration_public) } it{ should be_able_to(:manage, registration_not_public) } # Test for user can register or not context 'when user is not a speaker with event confirmed' do let(:conference) { create(:conference) } context 'when the registration is closed' do before :each do create(:registration_period, conference: conference, start_date: Date.current - 6.days, end_date: Date.current - 6.days) end it{ should_not be_able_to(:new, Registration.new(conference: conference)) } it{ should_not be_able_to(:create, Registration.new(conference: conference)) } end context 'when the registration period is not set' do it{ should_not be_able_to(:new, Registration.new(conference: conference)) } it{ should_not be_able_to(:create, Registration.new(conference: conference)) } end context 'when user has already registered' do before :each do create(:registration, conference: conference, user: user) end it{ should_not be_able_to(:new, Registration.new(conference: conference)) } it{ should_not be_able_to(:create, Registration.new(conference: conference)) } end context 'when registrations are open' do before :each do create(:registration_period, conference: conference) end it{ should be_able_to(:new, Registration.new(conference: conference)) } it{ should be_able_to(:create, Registration.new(conference: conference)) } context 'when user has not registered with no registration_limit_exceeded' do before :each do conference.registration_limit = 1 end it{ should be_able_to(:new, Registration.new(conference: conference)) } it{ should be_able_to(:create, Registration.new(conference: conference)) } end context 'when user has not registered with registration_limit_exceeded' do before :each do conference.registration_limit = 1 create(:registration, conference: conference, user: user2) end it{ should_not be_able_to(:new, Registration.new(conference: conference)) } it{ should_not be_able_to(:create, Registration.new(conference: conference)) } end end end context 'when user is a speaker with event confirmed' do let(:conference_with_speaker_confirmed) { create(:conference) } let(:event_with_speaker_confirmed) { create(:event, state: 'confirmed', program: conference_with_speaker_confirmed.program) } before :each do event_with_speaker_confirmed.speakers << user end context 'when registration period is not set' do it{ should_not be_able_to(:new, Registration.new(conference: conference_with_speaker_confirmed)) } it{ should_not be_able_to(:create, Registration.new(conference: conference_with_speaker_confirmed)) } end context 'when speaker has already registered' do before :each do create(:registration, conference: conference_with_speaker_confirmed, user: user) end it{ should_not be_able_to(:new, Registration.new(conference: conference_with_speaker_confirmed)) } it{ should_not be_able_to(:create, Registration.new(conference: conference_with_speaker_confirmed)) } end context 'when registration period is set' do before :each do create(:registration_period, conference: conference_with_speaker_confirmed) end context 'when registrations are open' do context 'when speaker has not registered' do it{ should be_able_to(:new, Registration.new(conference: conference_with_speaker_confirmed)) } it{ should be_able_to(:create, Registration.new(conference: conference_with_speaker_confirmed)) } end context 'when registration_limit_exceeded' do before :each do conference_with_speaker_confirmed.registration_limit = 1 create(:registration, conference: conference_with_speaker_confirmed, user: user2) end it{ should be_able_to(:new, Registration.new(conference: conference_with_speaker_confirmed)) } it{ should be_able_to(:create, Registration.new(conference: conference_with_speaker_confirmed)) } end end context 'when registrations are closed' do before :each do create(:registration_period, conference: conference_with_speaker_confirmed, start_date: Date.current - 6.days, end_date: Date.current - 6.days) end context 'when speaker has not registered' do it{ should be_able_to(:new, Registration.new(conference: conference_with_speaker_confirmed)) } it{ should be_able_to(:create, Registration.new(conference: conference_with_speaker_confirmed)) } end context 'with registration_limit_exceeded' do before :each do conference_with_speaker_confirmed.registration_limit = 1 create(:registration, conference: conference_with_speaker_confirmed, user: user2) end it{ should be_able_to(:new, Registration.new(conference: conference_with_speaker_confirmed)) } it{ should be_able_to(:create, Registration.new(conference: conference_with_speaker_confirmed)) } end end end end it{ should be_able_to(:index, Ticket) } it{ should be_able_to(:manage, TicketPurchase.new(user_id: user.id)) } it{ should be_able_to(:new, Payment.new(user_id: user.id)) } it{ should be_able_to(:create, Payment.new(user_id: user.id)) } it{ should be_able_to(:create, Subscription.new(user_id: user.id)) } it{ should be_able_to(:destroy, subscription) } it{ should be_able_to(:update, user_event_with_cfp) } it{ should be_able_to(:show, user_event_with_cfp) } it{ should_not be_able_to(:new, Event.new(program: program_without_cfp)) } it{ should_not be_able_to(:create, Event.new(program: program_without_cfp)) } # TODO: At moment it's not possible to manually add someone else as event_user # This needs some more work once we allow user to add event_user it 'should_not be_able to :new, Event.new(program: program_with_cfp, event_users: [event_user2])' it 'should_not be_able to :create, Event.new(program: program_with_cfp, event_users: [event_user2])' it{ should_not be_able_to(:manage, event_unconfirmed) } it{ should be_able_to(:create, user_event_with_cfp.commercials.new) } it{ should be_able_to(:manage, user_commercial) } it{ should_not be_able_to(:manage, commercial_event_unconfirmed) } it{ should be_able_to(:new, Track.new(program: program_with_call_for_tracks)) } it{ should be_able_to(:create, Track.new(program: program_with_call_for_tracks)) } it{ should_not be_able_to(:new, Track.new(program: program_without_cfp)) } it{ should_not be_able_to(:create, Track.new(program: program_without_cfp)) } it{ should be_able_to(:index, user_self_organized_track) } it{ should be_able_to(:show, user_self_organized_track) } it{ should be_able_to(:restart, user_self_organized_track) } it{ should be_able_to(:confirm, user_self_organized_track) } it{ should be_able_to(:withdraw, user_self_organized_track) } it{ should_not be_able_to(:index, other_self_organized_track) } it{ should_not be_able_to(:show, other_self_organized_track) } it{ should_not be_able_to(:restart, other_self_organized_track) } it{ should_not be_able_to(:confirm, other_self_organized_track) } it{ should_not be_able_to(:withdraw, other_self_organized_track) } it{ should be_able_to(:edit, user_self_organized_track) } it{ should be_able_to(:update, user_self_organized_track) } it{ should_not be_able_to(:edit, accepted_user_self_organized_track) } it{ should_not be_able_to(:update, accepted_user_self_organized_track) } it{ should_not be_able_to(:edit, confirmed_user_self_organized_track) } it{ should_not be_able_to(:update, confirmed_user_self_organized_track) } it{ should_not be_able_to(:edit, other_self_organized_track) } it{ should_not be_able_to(:update, other_self_organized_track) } end end end
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by lister-gen. DO NOT EDIT. package v1 import ( v1 "k8s.io/api/apps/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" ) // DaemonSetLister helps list DaemonSets. type DaemonSetLister interface { // List lists all DaemonSets in the indexer. List(selector labels.Selector) (ret []*v1.DaemonSet, err error) // DaemonSets returns an object that can list and get DaemonSets. DaemonSets(namespace string) DaemonSetNamespaceLister DaemonSetListerExpansion } // daemonSetLister implements the DaemonSetLister interface. type daemonSetLister struct { indexer cache.Indexer } // NewDaemonSetLister returns a new DaemonSetLister. func NewDaemonSetLister(indexer cache.Indexer) DaemonSetLister { return &daemonSetLister{indexer: indexer} } // List lists all DaemonSets in the indexer. func (s *daemonSetLister) List(selector labels.Selector) (ret []*v1.DaemonSet, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1.DaemonSet)) }) return ret, err } // DaemonSets returns an object that can list and get DaemonSets. func (s *daemonSetLister) DaemonSets(namespace string) DaemonSetNamespaceLister { return daemonSetNamespaceLister{indexer: s.indexer, namespace: namespace} } // DaemonSetNamespaceLister helps list and get DaemonSets. type DaemonSetNamespaceLister interface { // List lists all DaemonSets in the indexer for a given namespace. List(selector labels.Selector) (ret []*v1.DaemonSet, err error) // Get retrieves the DaemonSet from the indexer for a given namespace and name. Get(name string) (*v1.DaemonSet, error) DaemonSetNamespaceListerExpansion } // daemonSetNamespaceLister implements the DaemonSetNamespaceLister // interface. type daemonSetNamespaceLister struct { indexer cache.Indexer namespace string } // List lists all DaemonSets in the indexer for a given namespace. func (s daemonSetNamespaceLister) List(selector labels.Selector) (ret []*v1.DaemonSet, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1.DaemonSet)) }) return ret, err } // Get retrieves the DaemonSet from the indexer for a given namespace and name. func (s daemonSetNamespaceLister) Get(name string) (*v1.DaemonSet, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1.Resource("daemonset"), name) } return obj.(*v1.DaemonSet), nil }
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "scale" : "1x" }, { "idiom" : "universal", "scale" : "2x" }, { "idiom" : "universal", "filename" : "[email protected]", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } }
{ "pile_set_name": "Github" }
module BubbleWrap module Reactor # A GCD scheduled, linear queue. # # This class provides a simple “Queue” like abstraction on top of the # GCD scheduler. # # Useful as an API sugar for stateful protocols # # q = BubbleWrap::Reactor::Queue.new # q.push('one', 'two', 'three') # 3.times do # q.pop{ |msg| puts(msg) } # end class Queue # Create a new queue def initialize @items = [] end # Is the queue empty? def empty? @items.empty? end # The size of the queue def size @items.size end # Push items onto the work queue. The items will not appear in the queue # immediately, but will be scheduled for addition. def push(*items) ::BubbleWrap::Reactor.schedule do @items.push(*items) @popq.shift.call @items.shift until @items.empty? || @popq.empty? end end # Pop items off the queue, running the block on the work queue. The pop # will not happen immediately, but at some point in the future, either # in the next tick, if the queue has data, or when the queue is populated. def pop(*args, &blk) cb = proc do blk.call(*args) end ::BubbleWrap::Reactor.schedule do if @items.empty? @popq << cb else cb.call @items.shift end end nil # Always returns nil end end end end
{ "pile_set_name": "Github" }
--- electron/lib/browser/api/app.js.orig 2019-06-04 19:13:27 UTC +++ electron/lib/browser/api/app.js @@ -84,7 +84,7 @@ if (process.platform === 'darwin') { } } -if (process.platform === 'linux') { +if (process.platform === 'linux' || process.platform === 'freebsd') { app.launcher = { setBadgeCount: bindings.unityLauncherSetBadgeCount, getBadgeCount: bindings.unityLauncherGetBadgeCount,
{ "pile_set_name": "Github" }
/* * Filename: rsxx_priv.h * * * Authors: Joshua Morris <[email protected]> * Philip Kelleher <[email protected]> * * (C) Copyright 2013 IBM Corporation * * 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 2 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __RSXX_PRIV_H__ #define __RSXX_PRIV_H__ #include <linux/version.h> #include <linux/semaphore.h> #include <linux/fs.h> #include <linux/interrupt.h> #include <linux/mutex.h> #include <linux/pci.h> #include <linux/spinlock.h> #include <linux/sysfs.h> #include <linux/workqueue.h> #include <linux/bio.h> #include <linux/vmalloc.h> #include <linux/timer.h> #include <linux/ioctl.h> #include <linux/delay.h> #include "rsxx.h" #include "rsxx_cfg.h" struct proc_cmd; #define PCI_DEVICE_ID_FS70_FLASH 0x04A9 #define PCI_DEVICE_ID_FS80_FLASH 0x04AA #define RS70_PCI_REV_SUPPORTED 4 #define DRIVER_NAME "rsxx" #define DRIVER_VERSION "4.0.3.2516" /* Block size is 4096 */ #define RSXX_HW_BLK_SHIFT 12 #define RSXX_HW_BLK_SIZE (1 << RSXX_HW_BLK_SHIFT) #define RSXX_HW_BLK_MASK (RSXX_HW_BLK_SIZE - 1) #define MAX_CREG_DATA8 32 #define LOG_BUF_SIZE8 128 #define RSXX_MAX_OUTSTANDING_CMDS 255 #define RSXX_CS_IDX_MASK 0xff #define STATUS_BUFFER_SIZE8 4096 #define COMMAND_BUFFER_SIZE8 4096 #define RSXX_MAX_TARGETS 8 struct dma_tracker_list; /* DMA Command/Status Buffer structure */ struct rsxx_cs_buffer { dma_addr_t dma_addr; void *buf; u32 idx; }; struct rsxx_dma_stats { u32 crc_errors; u32 hard_errors; u32 soft_errors; u32 writes_issued; u32 writes_failed; u32 reads_issued; u32 reads_failed; u32 reads_retried; u32 discards_issued; u32 discards_failed; u32 done_rescheduled; u32 issue_rescheduled; u32 dma_sw_err; u32 dma_hw_fault; u32 dma_cancelled; u32 sw_q_depth; /* Number of DMAs on the SW queue. */ atomic_t hw_q_depth; /* Number of DMAs queued to HW. */ }; struct rsxx_dma_ctrl { struct rsxx_cardinfo *card; int id; void __iomem *regmap; struct rsxx_cs_buffer status; struct rsxx_cs_buffer cmd; u16 e_cnt; spinlock_t queue_lock; struct list_head queue; struct workqueue_struct *issue_wq; struct work_struct issue_dma_work; struct workqueue_struct *done_wq; struct work_struct dma_done_work; struct timer_list activity_timer; struct dma_tracker_list *trackers; struct rsxx_dma_stats stats; struct mutex work_lock; }; struct rsxx_cardinfo { struct pci_dev *dev; unsigned int halt; unsigned int eeh_state; void __iomem *regmap; spinlock_t irq_lock; unsigned int isr_mask; unsigned int ier_mask; struct rsxx_card_cfg config; int config_valid; /* Embedded CPU Communication */ struct { spinlock_t lock; bool active; struct creg_cmd *active_cmd; struct workqueue_struct *creg_wq; struct work_struct done_work; struct list_head queue; unsigned int q_depth; /* Cache the creg status to prevent ioreads */ struct { u32 stat; u32 failed_cancel_timer; u32 creg_timeout; } creg_stats; struct timer_list cmd_timer; struct mutex reset_lock; int reset; } creg_ctrl; struct { char tmp[MAX_CREG_DATA8]; char buf[LOG_BUF_SIZE8]; /* terminated */ int buf_len; } log; struct workqueue_struct *event_wq; struct work_struct event_work; unsigned int state; u64 size8; /* Lock the device attach/detach function */ struct mutex dev_lock; /* Block Device Variables */ bool bdev_attached; int disk_id; int major; struct request_queue *queue; struct gendisk *gendisk; struct { /* Used to convert a byte address to a device address. */ u64 lower_mask; u64 upper_shift; u64 upper_mask; u64 target_mask; u64 target_shift; } _stripe; unsigned int dma_fault; int scrub_hard; int n_targets; struct rsxx_dma_ctrl *ctrl; struct dentry *debugfs_dir; }; enum rsxx_pci_regmap { HWID = 0x00, /* Hardware Identification Register */ SCRATCH = 0x04, /* Scratch/Debug Register */ RESET = 0x08, /* Reset Register */ ISR = 0x10, /* Interrupt Status Register */ IER = 0x14, /* Interrupt Enable Register */ IPR = 0x18, /* Interrupt Poll Register */ CB_ADD_LO = 0x20, /* Command Host Buffer Address [31:0] */ CB_ADD_HI = 0x24, /* Command Host Buffer Address [63:32]*/ HW_CMD_IDX = 0x28, /* Hardware Processed Command Index */ SW_CMD_IDX = 0x2C, /* Software Processed Command Index */ SB_ADD_LO = 0x30, /* Status Host Buffer Address [31:0] */ SB_ADD_HI = 0x34, /* Status Host Buffer Address [63:32] */ HW_STATUS_CNT = 0x38, /* Hardware Status Counter */ SW_STATUS_CNT = 0x3C, /* Deprecated */ CREG_CMD = 0x40, /* CPU Command Register */ CREG_ADD = 0x44, /* CPU Address Register */ CREG_CNT = 0x48, /* CPU Count Register */ CREG_STAT = 0x4C, /* CPU Status Register */ CREG_DATA0 = 0x50, /* CPU Data Registers */ CREG_DATA1 = 0x54, CREG_DATA2 = 0x58, CREG_DATA3 = 0x5C, CREG_DATA4 = 0x60, CREG_DATA5 = 0x64, CREG_DATA6 = 0x68, CREG_DATA7 = 0x6c, INTR_COAL = 0x70, /* Interrupt Coalescing Register */ HW_ERROR = 0x74, /* Card Error Register */ PCI_DEBUG0 = 0x78, /* PCI Debug Registers */ PCI_DEBUG1 = 0x7C, PCI_DEBUG2 = 0x80, PCI_DEBUG3 = 0x84, PCI_DEBUG4 = 0x88, PCI_DEBUG5 = 0x8C, PCI_DEBUG6 = 0x90, PCI_DEBUG7 = 0x94, PCI_POWER_THROTTLE = 0x98, PERF_CTRL = 0x9c, PERF_TIMER_LO = 0xa0, PERF_TIMER_HI = 0xa4, PERF_RD512_LO = 0xa8, PERF_RD512_HI = 0xac, PERF_WR512_LO = 0xb0, PERF_WR512_HI = 0xb4, PCI_RECONFIG = 0xb8, }; enum rsxx_intr { CR_INTR_DMA0 = 0x00000001, CR_INTR_CREG = 0x00000002, CR_INTR_DMA1 = 0x00000004, CR_INTR_EVENT = 0x00000008, CR_INTR_DMA2 = 0x00000010, CR_INTR_DMA3 = 0x00000020, CR_INTR_DMA4 = 0x00000040, CR_INTR_DMA5 = 0x00000080, CR_INTR_DMA6 = 0x00000100, CR_INTR_DMA7 = 0x00000200, CR_INTR_ALL_C = 0x0000003f, CR_INTR_ALL_G = 0x000003ff, CR_INTR_DMA_ALL = 0x000003f5, CR_INTR_ALL = 0xffffffff, }; static inline int CR_INTR_DMA(int N) { static const unsigned int _CR_INTR_DMA[] = { CR_INTR_DMA0, CR_INTR_DMA1, CR_INTR_DMA2, CR_INTR_DMA3, CR_INTR_DMA4, CR_INTR_DMA5, CR_INTR_DMA6, CR_INTR_DMA7 }; return _CR_INTR_DMA[N]; } enum rsxx_pci_reset { DMA_QUEUE_RESET = 0x00000001, }; enum rsxx_hw_fifo_flush { RSXX_FLUSH_BUSY = 0x00000002, RSXX_FLUSH_TIMEOUT = 0x00000004, }; enum rsxx_pci_revision { RSXX_DISCARD_SUPPORT = 2, RSXX_EEH_SUPPORT = 3, }; enum rsxx_creg_cmd { CREG_CMD_TAG_MASK = 0x0000FF00, CREG_OP_WRITE = 0x000000C0, CREG_OP_READ = 0x000000E0, }; enum rsxx_creg_addr { CREG_ADD_CARD_CMD = 0x80001000, CREG_ADD_CARD_STATE = 0x80001004, CREG_ADD_CARD_SIZE = 0x8000100c, CREG_ADD_CAPABILITIES = 0x80001050, CREG_ADD_LOG = 0x80002000, CREG_ADD_NUM_TARGETS = 0x80003000, CREG_ADD_CRAM = 0xA0000000, CREG_ADD_CONFIG = 0xB0000000, }; enum rsxx_creg_card_cmd { CARD_CMD_STARTUP = 1, CARD_CMD_SHUTDOWN = 2, CARD_CMD_LOW_LEVEL_FORMAT = 3, CARD_CMD_FPGA_RECONFIG_BR = 4, CARD_CMD_FPGA_RECONFIG_MAIN = 5, CARD_CMD_BACKUP = 6, CARD_CMD_RESET = 7, CARD_CMD_deprecated = 8, CARD_CMD_UNINITIALIZE = 9, CARD_CMD_DSTROY_EMERGENCY = 10, CARD_CMD_DSTROY_NORMAL = 11, CARD_CMD_DSTROY_EXTENDED = 12, CARD_CMD_DSTROY_ABORT = 13, }; enum rsxx_card_state { CARD_STATE_SHUTDOWN = 0x00000001, CARD_STATE_STARTING = 0x00000002, CARD_STATE_FORMATTING = 0x00000004, CARD_STATE_UNINITIALIZED = 0x00000008, CARD_STATE_GOOD = 0x00000010, CARD_STATE_SHUTTING_DOWN = 0x00000020, CARD_STATE_FAULT = 0x00000040, CARD_STATE_RD_ONLY_FAULT = 0x00000080, CARD_STATE_DSTROYING = 0x00000100, }; enum rsxx_led { LED_DEFAULT = 0x0, LED_IDENTIFY = 0x1, LED_SOAK = 0x2, }; enum rsxx_creg_flash_lock { CREG_FLASH_LOCK = 1, CREG_FLASH_UNLOCK = 2, }; enum rsxx_card_capabilities { CARD_CAP_SUBPAGE_WRITES = 0x00000080, }; enum rsxx_creg_stat { CREG_STAT_STATUS_MASK = 0x00000003, CREG_STAT_SUCCESS = 0x1, CREG_STAT_ERROR = 0x2, CREG_STAT_CHAR_PENDING = 0x00000004, /* Character I/O pending bit */ CREG_STAT_LOG_PENDING = 0x00000008, /* HW log message pending bit */ CREG_STAT_TAG_MASK = 0x0000ff00, }; enum rsxx_dma_finish { FREE_DMA = 0x0, COMPLETE_DMA = 0x1, }; static inline unsigned int CREG_DATA(int N) { return CREG_DATA0 + (N << 2); } /*----------------- Convenient Log Wrappers -------------------*/ #define CARD_TO_DEV(__CARD) (&(__CARD)->dev->dev) /***** config.c *****/ int rsxx_load_config(struct rsxx_cardinfo *card); /***** core.c *****/ void rsxx_enable_ier(struct rsxx_cardinfo *card, unsigned int intr); void rsxx_disable_ier(struct rsxx_cardinfo *card, unsigned int intr); void rsxx_enable_ier_and_isr(struct rsxx_cardinfo *card, unsigned int intr); void rsxx_disable_ier_and_isr(struct rsxx_cardinfo *card, unsigned int intr); /***** dev.c *****/ int rsxx_attach_dev(struct rsxx_cardinfo *card); void rsxx_detach_dev(struct rsxx_cardinfo *card); int rsxx_setup_dev(struct rsxx_cardinfo *card); void rsxx_destroy_dev(struct rsxx_cardinfo *card); int rsxx_dev_init(void); void rsxx_dev_cleanup(void); /***** dma.c ****/ typedef void (*rsxx_dma_cb)(struct rsxx_cardinfo *card, void *cb_data, unsigned int status); int rsxx_dma_setup(struct rsxx_cardinfo *card); void rsxx_dma_destroy(struct rsxx_cardinfo *card); int rsxx_dma_init(void); int rsxx_cleanup_dma_queue(struct rsxx_dma_ctrl *ctrl, struct list_head *q, unsigned int done); int rsxx_dma_cancel(struct rsxx_dma_ctrl *ctrl); void rsxx_dma_cleanup(void); void rsxx_dma_queue_reset(struct rsxx_cardinfo *card); int rsxx_dma_configure(struct rsxx_cardinfo *card); blk_status_t rsxx_dma_queue_bio(struct rsxx_cardinfo *card, struct bio *bio, atomic_t *n_dmas, rsxx_dma_cb cb, void *cb_data); int rsxx_hw_buffers_init(struct pci_dev *dev, struct rsxx_dma_ctrl *ctrl); int rsxx_eeh_save_issued_dmas(struct rsxx_cardinfo *card); int rsxx_eeh_remap_dmas(struct rsxx_cardinfo *card); /***** cregs.c *****/ int rsxx_creg_write(struct rsxx_cardinfo *card, u32 addr, unsigned int size8, void *data, int byte_stream); int rsxx_creg_read(struct rsxx_cardinfo *card, u32 addr, unsigned int size8, void *data, int byte_stream); int rsxx_read_hw_log(struct rsxx_cardinfo *card); int rsxx_get_card_state(struct rsxx_cardinfo *card, unsigned int *state); int rsxx_get_card_size8(struct rsxx_cardinfo *card, u64 *size8); int rsxx_get_num_targets(struct rsxx_cardinfo *card, unsigned int *n_targets); int rsxx_get_card_capabilities(struct rsxx_cardinfo *card, u32 *capabilities); int rsxx_issue_card_cmd(struct rsxx_cardinfo *card, u32 cmd); int rsxx_creg_setup(struct rsxx_cardinfo *card); void rsxx_creg_destroy(struct rsxx_cardinfo *card); int rsxx_creg_init(void); void rsxx_creg_cleanup(void); int rsxx_reg_access(struct rsxx_cardinfo *card, struct rsxx_reg_access __user *ucmd, int read); void rsxx_eeh_save_issued_creg(struct rsxx_cardinfo *card); void rsxx_kick_creg_queue(struct rsxx_cardinfo *card); #endif /* __DRIVERS_BLOCK_RSXX_H__ */
{ "pile_set_name": "Github" }
/************************************************************************* * * File Name (AccessibleAction.idl) * * IAccessible2 IDL Specification * * Copyright (c) 2007, 2013 Linux Foundation * Copyright (c) 2006 IBM Corporation * Copyright (c) 2000, 2006 Sun Microsystems, Inc. * All rights reserved. * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the Linux Foundation nor the names of its * contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This BSD License conforms to the Open Source Initiative "Simplified * BSD License" as published at: * http://www.opensource.org/licenses/bsd-license.php * * IAccessible2 is a trademark of the Linux Foundation. The IAccessible2 * mark may be used in accordance with the Linux Foundation Trademark * Policy to indicate compliance with the IAccessible2 specification. * ************************************************************************/ import "objidl.idl"; import "oaidl.idl"; import "oleacc.idl"; /** This enum defines values which are predefined actions for use when implementing support for media. This enum is used when specifying an action for IAccessibleAction::doAction. */ enum IA2Actions { IA2_ACTION_OPEN = -1, /**< Used to inform the server that the client will signal via IA2_ACTION_COMPLETE when it has consumed the content provided by the object. This action allows the object's server to wait for all clients to signal their readiness for additional content. Any form of content generation that requires synchronization with an AT would require use of this action. One example is the generation of text describing visual content not obvious from a video's sound track. In this scenario the Text to Speech or Braille output may take more time than the related length of silence in the video's sound track. */ IA2_ACTION_COMPLETE = -2, /**< Used by the client to inform the server that it has consumed the most recent content provided by this object. */ IA2_ACTION_CLOSE = -3 /**< Used to inform the server that the client no longer requires synchronization. */ }; /** @brief This interface gives access to actions that can be executed for accessible objects. Every accessible object that can be manipulated via the native GUI beyond the methods available either in the MSAA IAccessible interface or in the set of IAccessible2 interfaces (other than this IAccessibleAction interface) should support the IAccessibleAction interface in order to provide Assistive Technology access to all the actions that can be performed by the object. Each action can be performed or queried for a name, description or associated key bindings. Actions are needed more for ATs that assist the mobility impaired, such as on-screen keyboards and voice command software. By providing actions directly, the AT can present them to the user without the user having to perform the extra steps to navigate a context menu. The first action should be equivalent to the MSAA default action. If there is only one action, %IAccessibleAction should also be implemented. */ [object, uuid(B70D9F59-3B5A-4dba-AB9E-22012F607DF5)] interface IAccessibleAction : IUnknown { /** @brief Returns the number of accessible actions available in this object. If there are more than one, the first one is considered the "default" action of the object. @param [out] nActions The returned value of the number of actions is zero if there are no actions. @retval S_OK @note This method is missing a [propget] prefix in the IDL. The result is the method is named nActions in generated C++ code instead of get_nActions. */ HRESULT nActions ( [out,retval] long* nActions ); /** @brief Performs the specified Action on the object. @param [in] actionIndex 0 based index specifying the action to perform. If it lies outside the valid range no action is performed. @retval S_OK @retval S_FALSE if action could not be performed @retval E_INVALIDARG if bad [in] passed @note If implementing support for media, refer to the predefined constants in the ::IA2Actions enum. */ HRESULT doAction ( [in] long actionIndex ); /** @brief Returns a description of the specified action of the object. @param [in] actionIndex 0 based index specifying which action's description to return. If it lies outside the valid range an empty string is returned. @param [out] description The returned value is a localized string of the specified action. @retval S_OK @retval S_FALSE if there is nothing to return, [out] value is NULL @retval E_INVALIDARG if bad [in] passed */ [propget] HRESULT description ( [in] long actionIndex, [out, retval] BSTR *description ); /** @brief Returns an array of BSTRs describing one or more key bindings, if there are any, associated with the specified action. The returned strings are the localized human readable key sequences to be used to activate each action, e.g. "Ctrl+Shift+D". Since these key sequences are to be used when the object has focus, they are like mnemonics (access keys), and not like shortcut (accelerator) keys. There is no need to implement this method for single action controls since that would be redundant with the standard MSAA programming practice of getting the mnemonic from get_accKeyboardShortcut. An AT such as an On Screen Keyboard might not expose these bindings but provide alternative means of activation. Note: the client allocates and passes in an array of pointers. The server allocates the BSTRs and passes back one or more pointers to these BSTRs into the array of pointers allocated by the client. The client is responsible for deallocating the BSTRs. @param [in] actionIndex 0 based index specifying which action's key bindings should be returned. @param [in] nMaxBindings This parameter is ignored. Refer to @ref _arrayConsideration "Special Consideration when using Arrays" for more details. @param [out] keyBindings An array of BSTRs, allocated by the server, one for each key binding. The client must free it with CoTaskMemFree. @param [out] nBindings The number of key bindings returned; the size of the returned array. @retval S_OK @retval S_FALSE if there are no key bindings, [out] values are NULL and 0 respectively @retval E_INVALIDARG if bad [in] passed */ [propget] HRESULT keyBinding ( [in] long actionIndex, [in] long nMaxBindings, [out, size_is(,nMaxBindings), length_is(,*nBindings)] BSTR **keyBindings, [out, retval] long *nBindings ); /** @brief Returns the non-localized name of specified action. @param [in] actionIndex 0 based index specifying which action's non-localized name should be returned. @param [out] name @retval S_OK @retval S_FALSE if there is nothing to return, [out] value is NULL @retval E_INVALIDARG if bad [in] passed */ [propget] HRESULT name ( [in] long actionIndex, [out, retval] BSTR *name ); /** @brief Returns the localized name of specified action. @param [in] actionIndex 0 based index specifying which action's localized name should be returned. @param [out] localizedName @retval S_OK @retval S_FALSE if there is nothing to return, [out] value is NULL @retval E_INVALIDARG if bad [in] passed */ [propget] HRESULT localizedName ( [in] long actionIndex, [out, retval] BSTR *localizedName ); }
{ "pile_set_name": "Github" }
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package wafregional import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/client/metadata" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/signer/v4" "github.com/aws/aws-sdk-go/private/protocol" "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) // WAFRegional provides the API operation methods for making requests to // AWS WAF Regional. See this package's package overview docs // for details on the service. // // WAFRegional methods are safe to use concurrently. It is not safe to // modify mutate any of the struct's properties though. type WAFRegional struct { *client.Client } // Used for custom client initialization logic var initClient func(*client.Client) // Used for custom request initialization logic var initRequest func(*request.Request) // Service information constants const ( ServiceName = "waf-regional" // Name of service. EndpointsID = ServiceName // ID to lookup a service endpoint with. ServiceID = "WAF Regional" // ServiceID is a unique identifier of a specific service. ) // New creates a new instance of the WAFRegional client with a session. // If additional configuration is needed for the client instance use the optional // aws.Config parameter to add your extra config. // // Example: // mySession := session.Must(session.NewSession()) // // // Create a WAFRegional client from just a session. // svc := wafregional.New(mySession) // // // Create a WAFRegional client with additional configuration // svc := wafregional.New(mySession, aws.NewConfig().WithRegion("us-west-2")) func New(p client.ConfigProvider, cfgs ...*aws.Config) *WAFRegional { c := p.ClientConfig(EndpointsID, cfgs...) return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) } // newClient creates, initializes and returns a new service client instance. func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *WAFRegional { svc := &WAFRegional{ Client: client.New( cfg, metadata.ClientInfo{ ServiceName: ServiceName, ServiceID: ServiceID, SigningName: signingName, SigningRegion: signingRegion, PartitionID: partitionID, Endpoint: endpoint, APIVersion: "2016-11-28", JSONVersion: "1.1", TargetPrefix: "AWSWAF_Regional_20161128", }, handlers, ), } // Handlers svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) svc.Handlers.UnmarshalError.PushBackNamed( protocol.NewUnmarshalErrorHandler(jsonrpc.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(), ) // Run custom client initialization if present if initClient != nil { initClient(svc.Client) } return svc } // newRequest creates a new request for a WAFRegional operation and runs any // custom request initialization. func (c *WAFRegional) newRequest(op *request.Operation, params, data interface{}) *request.Request { req := c.NewRequest(op, params, data) // Run custom request initialization if present if initRequest != nil { initRequest(req) } return req }
{ "pile_set_name": "Github" }
/* * Modifications and adaptations - Copyright (C) 2015 Stratio (http://stratio.com) * 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.apache.spark.sql.crossdata.catalyst.parser import scala.language.implicitConversions import org.apache.spark.sql.AnalysisException import org.apache.spark.sql.catalyst.{AbstractSparkSQLParser, ParserDialect, TableIdentifier} import org.apache.spark.sql.catalyst.analysis._ import org.apache.spark.sql.catalyst.expressions._ import org.apache.spark.sql.catalyst.expressions.aggregate._ import org.apache.spark.sql.catalyst.plans._ import org.apache.spark.sql.catalyst.plans.logical._ import org.apache.spark.sql.catalyst.util.DataTypeParser import org.apache.spark.sql.types._ import org.apache.spark.unsafe.types.CalendarInterval private[spark] class CrossdataParserDialect extends ParserDialect { @transient protected val sqlParser = CrossdataSqlParser override def parse(sqlText: String): LogicalPlan = { sqlParser.parse(sqlText) } } /** * A very simple SQL parser. Based loosely on: * https://github.com/stephentu/scala-sql-parser/blob/master/src/main/scala/parser.scala * * Limitations: * - Only supports a very limited subset of SQL. * * This is currently included mostly for illustrative purposes. Users wanting more complete support * for a SQL like language should checkout the HiveQL support in the sql/hive sub-project. */ object CrossdataSqlParser extends AbstractSparkSQLParser with DataTypeParser { def parseExpression(input: String): Expression = synchronized { // Initialize the Keywords. initLexical phrase(projection)(new lexical.Scanner(input)) match { case Success(plan, _) => plan case failureOrError => sys.error(failureOrError.toString) } } def parseTableIdentifier(input: String): TableIdentifier = synchronized { // Initialize the Keywords. initLexical phrase(tableIdentifier)(new lexical.Scanner(input)) match { case Success(ident, _) => ident case failureOrError => sys.error(failureOrError.toString) } } // Keyword is a convention with AbstractSparkSQLParser, which will scan all of the `Keyword` // properties via reflection the class in runtime for constructing the SqlLexical object protected val ALL = Keyword("ALL") protected val AND = Keyword("AND") protected val APPROXIMATE = Keyword("APPROXIMATE") protected val AS = Keyword("AS") protected val ASC = Keyword("ASC") protected val BETWEEN = Keyword("BETWEEN") protected val BY = Keyword("BY") protected val CASE = Keyword("CASE") protected val CAST = Keyword("CAST") protected val CROSS = Keyword("CROSS") protected val DESC = Keyword("DESC") protected val DISTINCT = Keyword("DISTINCT") protected val ELSE = Keyword("ELSE") protected val END = Keyword("END") protected val EXCEPT = Keyword("EXCEPT") protected val FALSE = Keyword("FALSE") protected val FROM = Keyword("FROM") protected val FULL = Keyword("FULL") protected val GROUP = Keyword("GROUP") protected val HAVING = Keyword("HAVING") protected val IN = Keyword("IN") protected val INNER = Keyword("INNER") protected val INSERT = Keyword("INSERT") protected val INTERSECT = Keyword("INTERSECT") protected val INTERVAL = Keyword("INTERVAL") protected val INTO = Keyword("INTO") protected val IS = Keyword("IS") protected val JOIN = Keyword("JOIN") protected val LEFT = Keyword("LEFT") protected val LIKE = Keyword("LIKE") protected val LIMIT = Keyword("LIMIT") protected val NOT = Keyword("NOT") protected val NULL = Keyword("NULL") protected val ON = Keyword("ON") protected val OR = Keyword("OR") protected val ORDER = Keyword("ORDER") protected val SORT = Keyword("SORT") protected val OUTER = Keyword("OUTER") protected val OVERWRITE = Keyword("OVERWRITE") protected val REGEXP = Keyword("REGEXP") protected val RIGHT = Keyword("RIGHT") protected val RLIKE = Keyword("RLIKE") protected val SELECT = Keyword("SELECT") protected val SEMI = Keyword("SEMI") protected val TABLE = Keyword("TABLE") protected val THEN = Keyword("THEN") protected val TRUE = Keyword("TRUE") protected val UNION = Keyword("UNION") protected val WHEN = Keyword("WHEN") protected val WHERE = Keyword("WHERE") protected val WITH = Keyword("WITH") protected lazy val start: Parser[LogicalPlan] = start1 | insert | cte protected lazy val start1: Parser[LogicalPlan] = (select | ("(" ~> select <~ ")")) * ( UNION ~ ALL ^^^ { (q1: LogicalPlan, q2: LogicalPlan) => Union(q1, q2) } | INTERSECT ^^^ { (q1: LogicalPlan, q2: LogicalPlan) => Intersect(q1, q2) } | EXCEPT ^^^ { (q1: LogicalPlan, q2: LogicalPlan) => Except(q1, q2)} | UNION ~ DISTINCT.? ^^^ { (q1: LogicalPlan, q2: LogicalPlan) => Distinct(Union(q1, q2)) } ) protected lazy val select: Parser[LogicalPlan] = SELECT ~> DISTINCT.? ~ repsep(projection, ",") ~ (FROM ~> relations).? ~ (WHERE ~> expression).? ~ (GROUP ~ BY ~> rep1sep(expression, ",")).? ~ (HAVING ~> expression).? ~ sortType.? ~ (LIMIT ~> expression).? ^^ { case d ~ p ~ r ~ f ~ g ~ h ~ o ~ l => val base = r.getOrElse(OneRowRelation) val withFilter = f.map(Filter(_, base)).getOrElse(base) val withProjection = g .map(Aggregate(_, p.map(UnresolvedAlias(_)), withFilter)) .getOrElse(Project(p.map(UnresolvedAlias(_)), withFilter)) val withDistinct = d.map(_ => Distinct(withProjection)).getOrElse(withProjection) val withHaving = h.map(Filter(_, withDistinct)).getOrElse(withDistinct) val withOrder = o.map(_(withHaving)).getOrElse(withHaving) val withLimit = l.map(Limit(_, withOrder)).getOrElse(withOrder) withLimit } protected lazy val insert: Parser[LogicalPlan] = INSERT ~> (OVERWRITE ^^^ true | INTO ^^^ false) ~ (TABLE ~> relation) ~ select ^^ { case o ~ r ~ s => InsertIntoTable(r, Map.empty[String, Option[String]], s, o, false) } protected lazy val cte: Parser[LogicalPlan] = WITH ~> rep1sep(ident ~ ( AS ~ "(" ~> start1 <~ ")"), ",") ~ (start1 | insert) ^^ { case r ~ s => With(s, r.map({case n ~ s => (n, Subquery(n, s))}).toMap) } protected lazy val projection: Parser[Expression] = expression ~ (AS.? ~> ident.?) ^^ { case e ~ a => a.fold(e)(Alias(e, _)()) } // Based very loosely on the MySQL Grammar. // http://dev.mysql.com/doc/refman/5.0/en/join.html protected lazy val relations: Parser[LogicalPlan] = ( relation ~ rep1("," ~> relation) ^^ { case r1 ~ joins => joins.foldLeft(r1) { case(lhs, r) => Join(lhs, r, Inner, None) } } | relation ) protected lazy val relation: Parser[LogicalPlan] = joinedRelation | relationFactor protected lazy val relationFactor: Parser[LogicalPlan] = ( tableIdentifier ~ (opt(AS) ~> opt(ident)) ^^ { case tableIdent ~ alias => UnresolvedRelation(tableIdent, alias) } | ("(" ~> start <~ ")") ~ (AS.? ~> ident) ^^ { case s ~ a => Subquery(a, s) } ) protected lazy val joinedRelation: Parser[LogicalPlan] = relationFactor ~ rep1(joinType.? ~ (JOIN ~> relationFactor) ~ joinConditions.?) ^^ { case r1 ~ joins => joins.foldLeft(r1) { case (lhs, jt ~ rhs ~ cond) => Join(lhs, rhs, joinType = jt.getOrElse(Inner), cond) } } protected lazy val joinConditions: Parser[Expression] = ON ~> expression protected lazy val joinType: Parser[JoinType] = ( INNER ^^^ Inner | CROSS ^^^ Inner | LEFT ~ SEMI ^^^ LeftSemi | LEFT ~ OUTER.? ^^^ LeftOuter | RIGHT ~ OUTER.? ^^^ RightOuter | FULL ~ OUTER.? ^^^ FullOuter ) protected lazy val sortType: Parser[LogicalPlan => LogicalPlan] = ( ORDER ~ BY ~> ordering ^^ { case o => l: LogicalPlan => Sort(o, true, l) } | SORT ~ BY ~> ordering ^^ { case o => l: LogicalPlan => Sort(o, false, l) } ) protected lazy val ordering: Parser[Seq[SortOrder]] = ( rep1sep(expression ~ direction.? , ",") ^^ { case exps => exps.map(pair => SortOrder(pair._1, pair._2.getOrElse(Ascending))) } ) protected lazy val direction: Parser[SortDirection] = ( ASC ^^^ Ascending | DESC ^^^ Descending ) protected lazy val expression: Parser[Expression] = orExpression protected lazy val orExpression: Parser[Expression] = andExpression * (OR ^^^ { (e1: Expression, e2: Expression) => Or(e1, e2) }) protected lazy val andExpression: Parser[Expression] = notExpression * (AND ^^^ { (e1: Expression, e2: Expression) => And(e1, e2) }) protected lazy val notExpression: Parser[Expression] = NOT.? ~ comparisonExpression ^^ { case maybeNot ~ e => maybeNot.map(_ => Not(e)).getOrElse(e) } protected lazy val comparisonExpression: Parser[Expression] = ( termExpression ~ ("=" ~> termExpression) ^^ { case e1 ~ e2 => EqualTo(e1, e2) } | termExpression ~ ("<" ~> termExpression) ^^ { case e1 ~ e2 => LessThan(e1, e2) } | termExpression ~ ("<=" ~> termExpression) ^^ { case e1 ~ e2 => LessThanOrEqual(e1, e2) } | termExpression ~ (">" ~> termExpression) ^^ { case e1 ~ e2 => GreaterThan(e1, e2) } | termExpression ~ (">=" ~> termExpression) ^^ { case e1 ~ e2 => GreaterThanOrEqual(e1, e2) } | termExpression ~ ("!=" ~> termExpression) ^^ { case e1 ~ e2 => Not(EqualTo(e1, e2)) } | termExpression ~ ("<>" ~> termExpression) ^^ { case e1 ~ e2 => Not(EqualTo(e1, e2)) } | termExpression ~ ("<=>" ~> termExpression) ^^ { case e1 ~ e2 => EqualNullSafe(e1, e2) } | termExpression ~ NOT.? ~ (BETWEEN ~> termExpression) ~ (AND ~> termExpression) ^^ { case e ~ not ~ el ~ eu => val betweenExpr: Expression = And(GreaterThanOrEqual(e, el), LessThanOrEqual(e, eu)) not.fold(betweenExpr)(f => Not(betweenExpr)) } | termExpression ~ (RLIKE ~> termExpression) ^^ { case e1 ~ e2 => RLike(e1, e2) } | termExpression ~ (REGEXP ~> termExpression) ^^ { case e1 ~ e2 => RLike(e1, e2) } | termExpression ~ (LIKE ~> termExpression) ^^ { case e1 ~ e2 => Like(e1, e2) } | termExpression ~ (NOT ~ LIKE ~> termExpression) ^^ { case e1 ~ e2 => Not(Like(e1, e2)) } | termExpression ~ (IN ~ "(" ~> rep1sep(termExpression, ",")) <~ ")" ^^ { case e1 ~ e2 => In(e1, e2) } | termExpression ~ (NOT ~ IN ~ "(" ~> rep1sep(termExpression, ",")) <~ ")" ^^ { case e1 ~ e2 => Not(In(e1, e2)) } | termExpression <~ IS ~ NULL ^^ { case e => IsNull(e) } | termExpression <~ IS ~ NOT ~ NULL ^^ { case e => IsNotNull(e) } | termExpression ) protected lazy val termExpression: Parser[Expression] = productExpression * ( "+" ^^^ { (e1: Expression, e2: Expression) => Add(e1, e2) } | "-" ^^^ { (e1: Expression, e2: Expression) => Subtract(e1, e2) } ) protected lazy val productExpression: Parser[Expression] = baseExpression * ( "*" ^^^ { (e1: Expression, e2: Expression) => Multiply(e1, e2) } | "/" ^^^ { (e1: Expression, e2: Expression) => Divide(e1, e2) } | "%" ^^^ { (e1: Expression, e2: Expression) => Remainder(e1, e2) } | "&" ^^^ { (e1: Expression, e2: Expression) => BitwiseAnd(e1, e2) } | "|" ^^^ { (e1: Expression, e2: Expression) => BitwiseOr(e1, e2) } | "^" ^^^ { (e1: Expression, e2: Expression) => BitwiseXor(e1, e2) } ) protected lazy val function: Parser[Expression] = ( ident <~ ("(" ~ "*" ~ ")") ^^ { case udfName => if (lexical.normalizeKeyword(udfName) == "count") { AggregateExpression(Count(Literal(1)), mode = Complete, isDistinct = false) } else { throw new AnalysisException(s"invalid expression $udfName(*)") } } | ident ~ ("(" ~> repsep(expression, ",")) <~ ")" ^^ { case udfName ~ exprs => UnresolvedFunction(udfName, exprs, isDistinct = false) } | ident ~ ("(" ~ DISTINCT ~> repsep(expression, ",")) <~ ")" ^^ { case udfName ~ exprs => lexical.normalizeKeyword(udfName) match { case "count" => aggregate.Count(exprs).toAggregateExpression(isDistinct = true) case _ => UnresolvedFunction(udfName, exprs, isDistinct = true) } } | APPROXIMATE ~> ident ~ ("(" ~ DISTINCT ~> expression <~ ")") ^^ { case udfName ~ exp => if (lexical.normalizeKeyword(udfName) == "count") { AggregateExpression(new HyperLogLogPlusPlus(exp), mode = Complete, isDistinct = false) } else { throw new AnalysisException(s"invalid function approximate $udfName") } } | APPROXIMATE ~> "(" ~> unsignedFloat ~ ")" ~ ident ~ "(" ~ DISTINCT ~ expression <~ ")" ^^ { case s ~ _ ~ udfName ~ _ ~ _ ~ exp => if (lexical.normalizeKeyword(udfName) == "count") { AggregateExpression( HyperLogLogPlusPlus(exp, s.toDouble, 0, 0), mode = Complete, isDistinct = false) } else { throw new AnalysisException(s"invalid function approximate($s) $udfName") } } | CASE ~> whenThenElse ^^ CaseWhen | CASE ~> expression ~ whenThenElse ^^ { case keyPart ~ branches => CaseKeyWhen(keyPart, branches) } ) protected lazy val whenThenElse: Parser[List[Expression]] = rep1(WHEN ~> expression ~ (THEN ~> expression)) ~ (ELSE ~> expression).? <~ END ^^ { case altPart ~ elsePart => altPart.flatMap { case whenExpr ~ thenExpr => Seq(whenExpr, thenExpr) } ++ elsePart } protected lazy val cast: Parser[Expression] = CAST ~ "(" ~> expression ~ (AS ~> dataType) <~ ")" ^^ { case exp ~ t => Cast(exp, t) } protected lazy val literal: Parser[Literal] = ( numericLiteral | booleanLiteral | stringLit ^^ { case s => Literal.create(s, StringType) } | intervalLiteral | NULL ^^^ Literal.create(null, NullType) ) protected lazy val booleanLiteral: Parser[Literal] = ( TRUE ^^^ Literal.create(true, BooleanType) | FALSE ^^^ Literal.create(false, BooleanType) ) protected lazy val numericLiteral: Parser[Literal] = ( integral ^^ { case i => Literal(toNarrowestIntegerType(i)) } | sign.? ~ unsignedFloat ^^ { case s ~ f => Literal(toDecimalOrDouble(s.getOrElse("") + f)) } ) protected lazy val unsignedFloat: Parser[String] = ( "." ~> numericLit ^^ { u => "0." + u } | elem("decimal", _.isInstanceOf[lexical.DecimalLit]) ^^ (_.chars) ) protected lazy val sign: Parser[String] = ("+" | "-") protected lazy val integral: Parser[String] = sign.? ~ numericLit ^^ { case s ~ n => s.getOrElse("") + n } private def intervalUnit(unitName: String) = acceptIf { case lexical.Identifier(str) => val normalized = lexical.normalizeKeyword(str) normalized == unitName || normalized == unitName + "s" case _ => false } {_ => "wrong interval unit"} protected lazy val month: Parser[Int] = integral <~ intervalUnit("month") ^^ { case num => num.toInt } protected lazy val year: Parser[Int] = integral <~ intervalUnit("year") ^^ { case num => num.toInt * 12 } protected lazy val microsecond: Parser[Long] = integral <~ intervalUnit("microsecond") ^^ { case num => num.toLong } protected lazy val millisecond: Parser[Long] = integral <~ intervalUnit("millisecond") ^^ { case num => num.toLong * CalendarInterval.MICROS_PER_MILLI } protected lazy val second: Parser[Long] = integral <~ intervalUnit("second") ^^ { case num => num.toLong * CalendarInterval.MICROS_PER_SECOND } protected lazy val minute: Parser[Long] = integral <~ intervalUnit("minute") ^^ { case num => num.toLong * CalendarInterval.MICROS_PER_MINUTE } protected lazy val hour: Parser[Long] = integral <~ intervalUnit("hour") ^^ { case num => num.toLong * CalendarInterval.MICROS_PER_HOUR } protected lazy val day: Parser[Long] = integral <~ intervalUnit("day") ^^ { case num => num.toLong * CalendarInterval.MICROS_PER_DAY } protected lazy val week: Parser[Long] = integral <~ intervalUnit("week") ^^ { case num => num.toLong * CalendarInterval.MICROS_PER_WEEK } private def intervalKeyword(keyword: String) = acceptIf { case lexical.Identifier(str) => lexical.normalizeKeyword(str) == keyword case _ => false } {_ => "wrong interval keyword"} protected lazy val intervalLiteral: Parser[Literal] = ( INTERVAL ~> stringLit <~ intervalKeyword("year") ~ intervalKeyword("to") ~ intervalKeyword("month") ^^ { case s => Literal(CalendarInterval.fromYearMonthString(s)) } | INTERVAL ~> stringLit <~ intervalKeyword("day") ~ intervalKeyword("to") ~ intervalKeyword("second") ^^ { case s => Literal(CalendarInterval.fromDayTimeString(s)) } | INTERVAL ~> stringLit <~ intervalKeyword("year") ^^ { case s => Literal(CalendarInterval.fromSingleUnitString("year", s)) } | INTERVAL ~> stringLit <~ intervalKeyword("month") ^^ { case s => Literal(CalendarInterval.fromSingleUnitString("month", s)) } | INTERVAL ~> stringLit <~ intervalKeyword("day") ^^ { case s => Literal(CalendarInterval.fromSingleUnitString("day", s)) } | INTERVAL ~> stringLit <~ intervalKeyword("hour") ^^ { case s => Literal(CalendarInterval.fromSingleUnitString("hour", s)) } | INTERVAL ~> stringLit <~ intervalKeyword("minute") ^^ { case s => Literal(CalendarInterval.fromSingleUnitString("minute", s)) } | INTERVAL ~> stringLit <~ intervalKeyword("second") ^^ { case s => Literal(CalendarInterval.fromSingleUnitString("second", s)) } | INTERVAL ~> year.? ~ month.? ~ week.? ~ day.? ~ hour.? ~ minute.? ~ second.? ~ millisecond.? ~ microsecond.? ^^ { case year ~ month ~ week ~ day ~ hour ~ minute ~ second ~ millisecond ~ microsecond => if (!Seq(year, month, week, day, hour, minute, second, millisecond, microsecond).exists(_.isDefined)) { throw new AnalysisException( "at least one time unit should be given for interval literal") } val months = Seq(year, month).map(_.getOrElse(0)).sum val microseconds = Seq(week, day, hour, minute, second, millisecond, microsecond) .map(_.getOrElse(0L)).sum Literal(new CalendarInterval(months, microseconds)) } ) private def toNarrowestIntegerType(value: String): Any = { val bigIntValue = BigDecimal(value) bigIntValue match { case v if bigIntValue.isValidInt => v.toIntExact case v if bigIntValue.isValidLong => v.toLongExact case v => v.underlying() } } private def toDecimalOrDouble(value: String): Any = { val decimal = BigDecimal(value) // follow the behavior in MS SQL Server // https://msdn.microsoft.com/en-us/library/ms179899.aspx if (value.contains('E') || value.contains('e')) { decimal.doubleValue() } else { decimal.underlying() } } protected lazy val baseExpression: Parser[Expression] = ( "*" ^^^ UnresolvedStar(None) | rep1(ident <~ ".") <~ "*" ^^ { case target => UnresolvedStar(Option(target))} | primary ) protected lazy val signedPrimary: Parser[Expression] = sign ~ primary ^^ { case s ~ e => if (s == "-") UnaryMinus(e) else e } protected lazy val attributeName: Parser[String] = acceptMatch("attribute name", { case lexical.Identifier(str) => str case lexical.Keyword(str) if !lexical.delimiters.contains(str) => str }) protected lazy val primary: PackratParser[Expression] = ( literal | expression ~ ("[" ~> expression <~ "]") ^^ { case base ~ ordinal => UnresolvedExtractValue(base, ordinal) } | (expression <~ ".") ~ ident ^^ { case base ~ fieldName => UnresolvedExtractValue(base, Literal(fieldName)) } | cast | "(" ~> expression <~ ")" | function | dotExpressionHeader | signedPrimary | "~" ~> expression ^^ BitwiseNot | attributeName ^^ UnresolvedAttribute.quoted ) protected lazy val dotExpressionHeader: Parser[Expression] = (ident <~ ".") ~ ident ~ rep("." ~> ident) ^^ { case i1 ~ i2 ~ rest => UnresolvedAttribute(Seq(i1, i2) ++ rest) } protected lazy val tableIdentifier: Parser[TableIdentifier] = (ident <~ ".").? ~ ident ^^ { case maybeDbName ~ tableName => TableIdentifier(tableName, maybeDbName) } }
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.IO; using Baseline; using Oakton; namespace StorytellerDocGen { public class DocInput { public DocInput() { DirectoryFlag = "documentation"; CodeFlag = new List<string>() {"src"}; } [Description("The documentation directory. The default is 'documentation'")] public string DirectoryFlag { get; set; } [Description("Override the application version. Default is 'Unknown'")] public string VersionFlag { get; set; } [Description("GitHub project name when exporting to project pages of a GitHub repo")] public string ProjectFlag { get; set; } [Description("Override the directories where sample scanning should be enabled. Default is [src]")] public List<string> CodeFlag { get; set; } public DocSettings ToSettings() { if (!Directory.Exists(DirectoryFlag)) { throw new Exception("Could not find requested documentation folder " + DirectoryFlag); } return new DocSettings { Root = DirectoryFlag.ToFullPath(), Version = VersionFlag, UrlStyle = UrlStyle.Live, SampleDirectories = CodeFlag, ProjectName = ProjectFlag }; } } }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html class="vrl"> <head> <title>Bug 1114329 testcase</title> <style> .vrl { writing-mode: vertical-rl; -webkit-writing-mode: vertical-rl; writing-mode: tb-rl; direction: ltr; } </style> </head> <body> <div dir="rtl" style="inline-size:-moz-fit-content"> <div style="height:300px"> <div style="height:100px;width:120px;background:rgba(0,255,0,0.8);float:left;"></div> </div> <div style="height:200px"> <div style="height:100px;width:150px;background:rgba(255,0,0,0.8);float:left;"></div> </div> </div> <div style="background:silver"> This text should appear BELOW the green and red blocks. </div> </body> </html>
{ "pile_set_name": "Github" }
{ "version": 1, "size": { "x": 32, "y": 32 }, "license": "CC-BY-SA-3.0", "copyright": "https://github.com/discordia-space/CEV-Eris/raw/aed9cbddbf9039dae1e4f02bab592248b0539431/icons/obj/ammo_mags.dmi", "states": [ { "name": "icon", "directions": 1 }, { "name": "base", "directions": 1 }, { "name": "mag-1", "directions": 1 } ] }
{ "pile_set_name": "Github" }
<?php namespace Drupal\services\Plugin\ServiceDefinition; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Entity\Query\QueryFactory; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Drupal\services\ServiceDefinitionBase; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\HttpFoundation\Request; use Drupal\Core\Routing\RouteMatchInterface; /** * @ServiceDefinition( * id = "entity_index", * methods = { * "GET" * }, * translatable = true, * deriver = "\Drupal\services\Plugin\Deriver\EntityIndex" * ) */ class EntityIndex extends ServiceDefinitionBase implements ContainerFactoryPluginInterface { /** * The entity query factory. * * @var \Drupal\Core\Entity\Query\QueryFactoryInterface */ protected $queryFactory; /** * The entity type manager. * * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityTypeManager; /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('entity.query'), $container->get('entity_type.manager') ); } /** * @param array $configuration * @param string $plugin_id * @param mixed $plugin_definition * @param \Drupal\Core\Entity\Query\QueryFactory $query_factory * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */ public function __construct(array $configuration, $plugin_id, $plugin_definition, QueryFactory $query_factory, EntityTypeManagerInterface $entity_type_manager) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->queryFactory = $query_factory; $this->entityTypeManager = $entity_type_manager; } /** * {@inheritdoc} */ public function processRequest(Request $request, RouteMatchInterface $route_match, SerializerInterface $serializer) { $entity_type_id = $this->getDerivativeId(); $start = 0; $limit = 30; if ($request->query->has('start') && is_numeric($request->query->get('start'))) { $start = $request->query->get('start'); } if ($request->query->has('limit') && is_numeric($request->query->get('limit'))) { $limit = $request->query->get('limit'); } $result = $this->queryFactory->get($entity_type_id, 'AND') ->range($start, $limit) ->execute(); $map_function = function ($id) use ($entity_type_id) { return $this->entityTypeManager->getStorage($entity_type_id) ->load($id) ->label(); }; return array_map($map_function, $result); } }
{ "pile_set_name": "Github" }
# Schema to Yup schema Build a Yup schema from a JSON Schema, GraphQL schema (type definition) or any other similar type/class and field/properties model or schema :) ## Schemas - [AJV: JSON Schema keywords](https://ajv.js.org/keywords.html) - [Learn JsonSchema](https://cswr.github.io/JsonSchema/) The builder currently supports the most commonly used [JSON Schema layout](https://json-schema.org/) and GraphQL type definition exports using [graphSchemaToJson](https://github.com/kristianmandrup/graphSchemaToJson) (see [GraphQL schema](#graphql-schema)). It also supports some extra convenience schema properties that make it more "smooth" to define validation requirements declaratively (see below). According to the JSON schema specs, you are free to add extra metadata to the field schema definitions beyond those supported "natively". ## Customisation hooks This library is built to be easy to customise or extend to suit individual developer needs. |Use any of the following customisation hooks to add custom features, circumvent missing functionality or bugs or extend any way you see fit. You can even use these hooks to support a different validator library, leveraging the generic schema validator builder infrastructure. - [entry builders](#Custom-entry-builders) - [type handlers](#Custom-type-handlers) - [constraint handler functions](#Custom-constraint-handler-functions) - [constraint builder](#Custom-constraint-builder) ## Stability The most recent versions have more functionality but are still a bit unstable in some areas. For a solid/stable version, try `1.9.16`. ## Quick start Install `npm install schema-to-yup -S` or `yarn add schema-to-yup` Use ```js const schema = { $schema: "http://json-schema.org/draft-07/schema#", $id: "http://example.com/person.schema.json", title: "Person", description: "A person", type: "object", properties: { name: { description: "Name of the person", type: "string" }, email: { type: "string", format: "email" }, fooorbar: { type: "string", matches: "(foo|bar)" }, age: { description: "Age of person", type: "number", exclusiveMinimum: 0, required: true }, characterType: { enum: ["good", "bad"], enum_titles: ["Good", "Bad"], type: "string", title: "Type of people", propertyOrder: 3 } }, required: ["name", "email"] }; const config = { // for error messages... errMessages: { age: { required: "A person must have an age" }, email: { required: "You must enter an email address", format: "Not a valid email address" } } }; const { buildYup } = require("schema-to-yup"); const yupSchema = buildYup(schema, config); // console.dir(schema) const valid = await yupSchema.isValid({ name: "jimmy", age: 24 }); console.log({ valid }); // => {valid: true} ``` This would generate the following Yup validation schema: ```js const schema = yup.object().shape({ name: yup.string().required(), age: yup .number() .required() .positive() }); ``` Note the `"required": true` for the `age` property (not natively supported by JSON schema). ### Refs Please note that this library does not currently resolve `$ref` (JSON Pointers) out of the box. You can use another library for that. You could f.ex use [json-schema-ref-parser](https://www.npmjs.com/package/json-schema-ref-parser) to preprocess your schema. Also see: - [schema-deref](https://www.npmjs.com/package/schema-deref) - [jsonref](https://www.npmjs.com/package/jsonref) ### Mode By default, any property will be explicitly `notRequired` unless set to be required, either via `required: true` in the property constraint object or via the `required` list of properties of the `object` schema definition (of the property). You can override the `notRequired` behavior by setting it on the new `mode` object of the configuration which can be used to control and fine-tune runtime behaviour. ```js const jsonSchema = { title: "users", type: "object", properties: { username: { type: "string" } } }; ``` ```js const yupSchema = buildYup(jsonSchema, { mode: { notRequired: true // default setting } }); // will be valid since username is not required by default const valid = yupSchema.validateSync({ foo: "dfds" }); ``` ```js const yupSchema = buildYup(jsonSchema, { mode: { notRequired: true // default setting } }); // will be invalid since username is required by default when notRequired mode is disabled const valid = yupSchema.validateSync({ foo: "dfds" }); ``` The new run time mode settings are demonstrated under `sample-runs/mode` No validation error (prop not required unless explicitly specified): `$ npx babel-node sample-runs/modes/not-required-on.js` Validation error if not valid type: `$ npx babel-node sample-runs/modes/not-required-on.js` ### Shape You can access the internal Yup shape, via `shapeConfig` on the yup schema returned by the `buildYup` schema builder function. This allows you to easily mix and match to suit more advanced requirements. ```js const { buildYup } = require("json-schema-to-yup"); const { shapeConfig } = buildYup(json, config); const schema = yup.object().shape({ ...shapeConfig, ...customShapeConfig }); ``` ## Types Currently the following schema types are supported: - `array` - `boolean` - `date` - `number` - `object` - `string` ### Mixed (any type) - `strict` - `default` - `nullable` - `required` - `notRequired` - `oneOf` (`enum`, `anyOf`) - `notOneOf` - `when` _NEW_ - `isType` _NEW_ - `nullable` (`isNullable`) _NEW_ ### Array - `ensure` - `compact` - `items` (`of`) - `maxItems` (`max`) - `minItems` (`min`) - `itemsOf` (`of`) _NEW_ ### Boolean No keys ### Date - `maxDate` (`max`) - `minDate` (`min`) ### Number - `integer` - `moreThan` (`exclusiveMinimum`) - `lessThan` (`exclusiveMaximum`) - `positive` - `negative` - `min` (`minimum`) - `max` (`maximum`) - `truncate` - `round` ### Object - `camelCase` - `constantCase` - `noUnknown` (`propertyNames`) ### String - `minLength` (`min`) - `maxLength` (`max`) - `pattern` (`matches` or `regex`) - `email` (`format: 'email'`) - `url` (`format: 'url'`) - `lowercase` - `uppercase` - `trim` For pattern (RegExp) you can additionally provide a flags property, such as `flags: 'i'`. Will be converted to a regexp using `new RegExp(pattern, flags)` ## Multi-type constraints This library currently does not come with built-in support for multi valued (list/array) type constraints such as `['string', 'null']` See [Issue 52](https://github.com/kristianmandrup/schema-to-yup/issues/52#issuecomment-561720235) for a discussion and current state. To support this, you can either add your own logic for the `toMultiType` function/method of `YupSchemaEntry` or pass a custom factory method `createMultiTypeValueResolver` on the `config` object. Sample code for multi type support (untested): ```js export const createPropertyValueHandler = (opts, config) => { return new PropertyValueResolver(opts, config); }; export class MyMultiTypeValueResolver extends MultiTypeValueResolver { constructor(opts, config) { this.propertyHandler = createPropertyValueHandler(opts, config); } resolve() { const { value, name } = this; let constraintListValue = this.normalizeValue(value); // ['string', 'null'] const multiTypePropSchema = constraintListValue.reduce( (accSchema, constraintValue) => { return this.resolvePropertyValue(constraintValue, accSchema); }, null ); return yup.mixed().test({ name, exclusive: true, params: {}, message: "${path} does not conform to all constraints defined", test: val => { return multiTypePropSchema.validateSync(val); } }); } resolvePropertyValue(constraintValue, accSchema) { const opts = { ...this.opts, constraintValue }; return this.propertyHandler.resolve(opts, this.config); } // expand/normalize to list of objects each with a valid type entry normalizeList(multiTypeList) { return multiTypeList.reduce((acc, entry) => { acc.push(normalizedEntry); return acc; }, []); } normalizeTypeEntry(entry) { if (!this.isStringType(entry)) return entry; return { type: entry }; } } ``` ## Custom entry builders You can pass in custom functions for the following kinds of type entry values - object value, such as `{type: 'string'}` - list value, such as `["string", "integer"]` The custom functions are: - `toSingleType(yupSchemaEntryBuilder)` - `toMultiType(yupSchemaEntryBuilder)` Each takes an instance `yupSchemaEntryBuilder` of `YupSchemaEntry`, which primarily holds the following properties of interest, that you can leverage in your custom handler logic ```js { schema, key, name, value, type, obj, config; } ``` ### Custom type handlers You can pass any custom typehandlers in a `typeHandlers` object as part of the `config` object passes. See `setTypeHandlers()` in `entry.js` for how this works internally. ```js function myCustomStringHandler = (obj, config) => { // ... custom handler // return yup type schema such as yup.string() // with one or more constraints added } const yupSchema = buildYup(jsonSchema, { typeHandlers: { string: myCustomStringHandler }, }); ``` This can be used to support special cases, to circumvent a bug or unexpected/unwarranted behaviour for one or more of the built-in type handlers etc. You can then use the built in classes as building blocks. To control which constraints are enabled (executed), simply edit the `typeEnabled` getter on your type handler class. Here is the default `typeEnabled` getter for the `YupDate` (Date) type handler, which is configured to execute constraint handler functions: `minDate` and `maxDate`. ```js get typeEnabled() { return ["minDate", "maxDate"]; } ``` This can also be used to add custom handlers as described in the next section. ### Custom constraint handler functions You can also add custom custraint handler functions directly via the `config` object as follows: This can be used to override built in constraints or extend with your own. A custom handler to validate a string formatted as a valid `ip` address might look something like this (presuming such a method is available on `yup` string). You can also use this with [yup schema type extensions](https://github.com/jquense/yup#extending-schema-types). ```js // takes the typehandler (such as YupString) instance as argument const ipHandler = th => { const constraintName = th.constraintNameFor("ip", "format"); const method = "ip"; th.addConstraint("ip", { constraintValue: true, constraintName, method, errName: method }); }; const config = { string: { convert: { ip: ipHandler }, enabled: [ "ip", // custom // built in "normalize", "minLength", "maxLength", "pattern", "lowercase", "uppercase", "email", "url", "genericFormat" ] } // ... more configuration }; buildYup(jsonSchema, config); ``` Instead of using enabled with the full list, you can also use `extends` ```js extends: [ // custom additions "ip", // built in handlers all included automatically ] ``` Note that if `convert` has entries and `extends` for the type configuration is not set (and no `enabled` list of constraints defined either) it will use all the entries in `convert` by default (ie. `extends` set to all keys). We welcome feedback on how to better structure the `config` object to make it easy and intuitive to add run-time configuration to suit your needs. ### Custom constraint builder This library supports using a custom constraint builder to add and build constraints. All factories are initialised in `initHelpers` and executed as the first step of `convert` (see `mixed.js`) ```js import { ConstraintBuilder } from "schema-to-yup"; class MyConstraintBuilder extends ConstraintBuilder { constructor(typeHandler, opts = {}) { super(typeHandler, opts); // custom instance configuration } build(propName, opts) { /// custom build logic // returns new type validation handler (base) with built constraint added return newBase; } addConstraint(propName, opts) { // custom add constraint logic return this.typeHandler; } // custom event handler onConstraintAdded({ name, value }) { // ... return this.typeHandler; } } ``` To use a custom constraint builder we recommend subclassing the `ConstraintBuilder` class that comes with the library. Then create a factory method thart can instanciate it. ```js const createConstraintBuilder = (typeHandler, config) => { return new MyConstraintBuilder(typeHandler, config); }; const config = { createConstraintBuilder // ... more configuration }; buildYup(jsonSchema, config); ``` ## Conditional logic Basic support for [when conditions](https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema) as requested and outlined in [this issue](https://github.com/kristianmandrup/schema-to-yup/issues/14) is now included. Work will continue in the [when-condition](https://github.com/kristianmandrup/schema-to-yup/tree/when-condition) branch. Sample schema using simple `when` constraint: ```js const biggyJson = { title: "biggy", type: "object", properties: { isBig: { type: "boolean" }, count: { type: "number", when: { isBig: { is: true, then: { min: 5 } } } } } }; ``` Sample valid and invalid values with respect to `biggyJson` schema ```js const bigJson = { valid: { isBig: true, count: 5 // since isBig is set, must be >= 5 }, invalid: { isBig: true, count: 4 // since isBig is set, must be >= 5 } }; ``` Currently basic support is included in `[email protected]` on [npmjs](https://www.npmjs.com) More advanced conditionals support will likely be included the next major release: `2.0`. You are welcome to continue the effort to support more conditional schema logic by continuing on this branch and making PRs. Support for `if` `then` and `else` [conditional JSON schema constraints](https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.6) can likely be added using an approach like the `when` condition (perhaps by transalating to equivalent: `when`, `then` and `otherwise`). - `if` - This keyword's value MUST be a valid JSON Schema - `then` - This keyword's value MUST be a valid JSON Schema - `else` - This keyword's value MUST be a valid JSON Schema See also [json-schema-spec](https://github.com/json-schema-org/json-schema-spec/issues/180) ### Customizing conditional logic You can now also override, extend or customize the `when` condition logic by passing in your own factory method for the config object entry `createWhenCondition` ```js const myWhenConditionFactoryFn = (opts = {}) => { const { type, key, value, when, schema, properties, config } = opts; // ... }; const config = { createWhenCondition: myWhenConditionFactoryFn }; const schema = buildYup(nameJsonSchema, config); ``` The best and easiest way to do this is to extend the `WhenCondition` class which contains most of the necessary infrastructure you can further build on. See the `src/conditions/legacy` folder for the legacy `1.9.0` logic that works but has limited functionality. ## Additional properties Currently this library does not have built-in support for the `additionalProperties` feature of JSON schema as described [here](https://json-schema.org/understanding-json-schema/reference/object.html) ```js { "type": "object", "properties": { "number": { "type": "number" }, "street_name": { "type": "string" }, "street_type": { "type": "string", "enum": ["Street", "Avenue", "Boulevard"] } }, "additionalProperties": { "type": "string" } } ``` See [issue 55](https://github.com/kristianmandrup/schema-to-yup/issues/55#issuecomment-561127144) Yup does not directly support this, so it would require some "hacking" to make it work. You can extend `YupBuilder` to include custom logic to support `additionalProperties` ```js class YupBuilderWithSupportForAdditionalProperties extends YupBuilder { additionalPropsToShape(opts, shape) { // do your magic here using this.additionalProps // make new yup constraint function calls on the incoming yup shape object return shape; } } ``` See the issue for ideas and hints on how to achieve support for this. ## Complex example Here a more complete example of the variations currently possible ```json { "title": "Person", "description": "A person", "type": "object", "properties": { "name": { "description": "Name of the person", "type": "string", "required": true, "matches": "[a-zA-Z- ]+", "min": 3, "maxLength": 40, }, "age": { "description": "Age of person", "type": "integer", "moreThan": 0, "max": 130, "default": 32, "required": false, "nullable": true }, "birthday": { "type": "date", "min": "1-1-1900", "maxDate": "1-1-2015" }, "married": { "type": "boolean" }, "boss": { "type": "object", "noUnknown": [ "name" ], "properties": { "name": { "type": "string", "notOneOf": ["Dr. evil", "bad ass"] } } }, "colleagues": { "type": "array", "items": { "type": "object", "propertyNames": [ "name" ], "properties": { "name": { "type": "string" } } } }, "programming": { "type": "object", "properties": { "languages": { "type": "array", "of": { "type": "string", "enum": ["javascript", "java", "C#"] }, "min": 1, "max": 3 } } } } } } ``` ### Complex/Nested schemas Nested object schema properties are supported. See `test/types/object/complex-schema.test.js` ## Custom models This library now also supports non JSON schema models. See the `types/defaults` mappings. `types/defaults/json-schema.js` ```js module.exports { getProps: obj => obj.properties, getType: obj => obj.type, getName: obj => obj.name || obj.title, getConstraints: obj => obj, isString: obj => obj.type === "string", isArray: obj => obj.type === "array", isInteger: obj => obj.type === "integer", isBoolean: obj => obj.type === "boolean", hasDateFormat: obj => ["date", "date-time"].find(t => t === obj.format), isDate: obj => obj.type === "string" && defaults.hasDateFormat(obj.format), isNumber: obj => obj.type === "number" || defaults.isInteger(obj.type), isObject: obj => obj.type === "object", isRequired: obj => obj.required }; ``` This can be used to support any kind of schema, including JSN schema and GraphQL type definition schemas etc. ### GraphQL schema To support another model, such as GraphQL schema (type definitions) via [graphSchemaToJson](https://github.com/kristianmandrup/graphSchemaToJson) Person: ```js { Person: { name: 'Person', fields: { name: { type: 'String', directives: { constraints: { minLength: 2 } }, isNullable: false, isList: false } } directives: {}, type: 'Object', implements: [] } } ``` Create a map of methods to match your model layout: ```js const typeDefConf = { getProps: obj => obj.fields, getType: obj => obj.type, getName: obj => obj.name, getConstraints: obj => (obj.directives || {}).constraints || {}, isString: obj => obj.type === "String", isArray: obj => obj.isList, isInteger: obj => obj.type === "Int", isBoolean: obj => obj.type === "Boolean", isDate: obj => obj.type === "Date" || obj.directives.date, isNumber: obj => obj.type === "Int" || obj.type === "Float", isObject: obj => obj.type === "Object", isRequired: obj => !obj.isNullable }; ``` Please note that `getConstraints` can be used to control where the constraints of the field will be taken from (depending on the type of model/schema or your preference). Pass overrides to match your model in `config` as follows: ```js const schema = buildYup(nameJsonSchema, { ...typeDefConf, log: true }); ``` The type definition mappings above are already built-in and available. To switch the schema type, pass `schemaType` in config as follows. ```js const schema = buildYup(nameJsonSchema, { schemaType: "type-def", log: true }); ``` Feel free to make PRs to make more common schema models conveniently available! ### Custom logs and error handling You can enable logging py passing a `log` option in the `config` argument. If set to true, it will by default assign the internal log function to `console.log` ```js const schema = buildYup(nameJsonSchema, { log: true }); ``` You can also pass a log function in the `log` option to handle log messages and an `err` option with a custom error handler function. See [Custom errors in Node](https://rclayton.silvrback.com/custom-errors-in-node-js) for how to design custom errors ```js class ValidationError extends Error {} const schema = buildYup(nameJsonSchema, { log: (name, msg) => console.log(`[${name}] ${msg}`) err: (msg) => { console.error(`[${name}] ERROR: ${msg}` throw new ValidationError(msg) }) }); ``` ## Customization You can supply a `createYupSchemaEntry` function as an entry in the `config` object. This function will then be used to build each Yup Schema entry in the Yup Schema being built. Use the Yup Type classes such as `types.YupArray` to act as building blocks or create your own custom logic as you see fit. ### Customization example ```js const { YupSchemaEntry, buildYup, types } = require("schema-to-yup"); class CustomYupArray extends types.YupArray { // ... } class CustomYupSchemaEntry extends YupSchemaEntry { // ... } function createYupSchemaEntry(key, value, config) { const builder = new CustomYupSchemaEntryBuilder(key, value, config); builder.types.array = config => createYupArray(config); return builder.toEntry(); } // use some localized error messages const messages = i18n.locale(LOCALE); const yupSchema = buildYup(json, { createYupSchemaEntry, messages }); ``` ### Extend Yup API to bridge other validators You can use `extendYupApi` to extend the Yup API with extra validation methods: ```js const validator = require("validator"); const { extendYupApi } = require("schema-to-yup/validator-bridge"); // by default extends with string format validation methods of validator // See https://www.npmjs.com/package/validator extendYupApi({ validator }); ``` You can optionally pass in a custom `validator` and a constraints map of your choice. You can either extend the default constraints or override them with your own map. PS: Check out `src/validator-bridge` for more many options for fine control ```js const myValidator = new MyValidator(); const constraints = ["creditCard", "currency", { name: "hash", opts: "algo" }]; extendYupApi({ validator: myValidator, override: true, constraints }); const { buildYup } = require("schema-to-yup"); // type def sample schema, using credit-card format validator const schema = { name: "BankAccount", fields: { accountNumber: { type: "String", format: "credit-card" } } }; // opt in to use generic string format validation, via format: true config option const yupSchema = buildYup(schema, { format: true, schemaType: "type-def" }); // ...do your validation const valid = await yupSchema.isValid({ accountNumber: "123-4567-1828-2929" }); ``` Now the bridge includes tests and seems to work ;) ### Subclassing You can sublass `YupBuilder` or any of the internal classes to create your own custom infrastructure to suit your particular needs, extend with extra features etc. ```js const { YupBuilder } = require("schema-to-yup"); class MyYupBuilder extends YupBuilder { // ... custom overrides etc } const builder = new MyYupBuilder(schema, config); const { yupSchema } = builder; // ... ``` ### Error messages You can pass an `errMessages` object in the optional `config` object argument with key mappings for your custom validation error messages. Internally the validator error messages are resolved via an instance of the `ErrorMessageHandler` calling the `valErrMessage` method. ```js notOneOf() { const {not, notOneOf} = this.value const $oneOf = notOneOf || (not && (not.enum || not.oneOf)) $oneOf && this .base .notOneOf($oneOf, this.valErrMessage('notOneOf')) return this } ``` #### Use a custom error message handler We recommend you subclass the existing `ErrorMessageHandler` as follow ```js import { ErrorMessageHandler } from "schema-to-yup"; class MyErrorMessageHandler extends ErrorMessageHandler { // ... } const createErrorMessageHandler = (typeHandler, config = {}) => { return new MyErrorMessageHandler(typeHandler, config); }; ``` You could f.ex override `errMessageFor` as follows, using the `type` ```js errMessageFor(name) { return this.propertyErrMessageFor(name) || this.genericErrMessageFor(name) } propertyErrMessageFor(name) { const { errMessages, key } = this; const errMsg = errMessages[key]; if (!errMsg) return return errMsg[name] } genericErrMessageFor(name) { const { errMessages, type } = this; const genricErrMsgMap = errMessages['_generic_']; const fullName = `${type}.${name}` return genricErrMsgMap[fullName] || genricErrMsgMap[name]; } ``` Then pass in your factory function in `config` as follows. ```js const config = { createErrorMessageHandler }; ``` You can pass the `errMessages` as follows. Note that you can define error messages specific to a property such as `emailAdr.format` and generic messages prefixed with `$` such as `$email`. Note: This convention might well change in future releases. ```js let config = { errMessages: { emailAdr: { // note: would also work with email as the key format: "emailAdr must be a valid email" }, // generic fallback message for any email format validation // note: if not present uses yup default validation message $email: "Email format incorrect" } }; ``` The key entries can be either a function, taking a `value` argument or a static string. Here are some of the defaults that you can override as needed. ```js export const errValKeys = [ "oneOf", "enum", "required", "notRequired", "minDate", "min", "maxDate", "max", "trim", "lowercase", "uppercase", "email", "url", "minLength", "maxLength", "pattern", "matches", "regex", "integer", "positive", "minimum", "maximum" ]; export const defaults = { errMessages: (keys = errValKeys) => keys.reduce((acc, key) => { const fn = ({ key, value }) => `${key}: invalid for ${value.name || value.title}`; acc[key] = fn; return acc; }, {}) }; ``` ### Custom validation messages using select defaults ```js const { buildYup, types } = require("schema-to-yup"); const { defaults } = types; const myErrMessages = require("./err-messages"); const valKeys = ["lowercase", "integer"]; // by default Yup built-in validation error messages will be used if not overridden here const errMessages = { ...defaults.errMessages(valKeys), myErrMessages }; const yupSchema = buildYup(json, { errMessages }); ``` ## Adding custom constraints See the `number` type for the current best practice to add type constraints. For simple cases: use `addConstraint` from the superclass `YupMixed` ```js required() { return this.addConstraint("required"); } ``` For types with several of these, we should map through a list or map to add them all. ```js strict() { return this.addValueConstraint("strict"); } required() { return this.addConstraint("required"); } notRequired() { return this.addConstraint("notRequired"); } ``` Can be rewritten to use conventions, iterating a map: ```js addMappedConstraints() { Object.keys(this.constraintsMap).map(key => { const list = constraintsMap[key]; const fnName = key === 'value' ? 'addValueConstraint' : 'addConstraint' list.map(this.[fnName]); }); } get constraintsMap() { return { simple: ["required", "notRequired", "nullable"], value: ["default", "strict"] }; } ``` For more complex contraints that: - have multiple valid constraint names - require validation - optional transformation You can create a separate `Constraint` subclass, to offload and handle it all separately. Here is a sample `RangeConstraint` used by number. ```js class RangeConstraint extends NumericConstraint { constructor(typer) { super(typer); } get $map() { return { moreThan: ["exclusiveMinimum", "moreThan"], lessThan: ["exclusiveMaximum", "lessThan"], max: ["maximum", "max"], min: ["minimum", "min"] }; } } ``` Instead of wrapping a `Constraint` you can call it directly with a `map` ```js // this would be an instance such as YupNumber // map equivalent to $map in the RangeConstraint range() { return createNumericConstraint(this, map); } ``` For the core type constraint class (such as `YupNumber`) you should now be able to simplify it to: ```js get enabled() { return ["range", "posNeg", "integer"]; } convert() { this.enabled.map(name => this.processConstraint(name)); super.convert(); return this; } ``` The following constraint classes are available for use: - `NumericConstraint` - `StringConstraint` - `RegExpConstraint` - `DateConstraint` Currently only `YupNumber` has been (partly) refactored to take advantage of this new infrastructure. Please help refactor the rest! `YupNumber` also has the most unit test coverage, used to test the current infrastructure! ## Similar projects - [JSON schema to Elastic Search mapping](https://github.com/kristianmandrup/json-schema-to-es-mapping) - [JSON Schema to GraphQL types with decorators/directives](https://github.com/kristianmandrup/json-schema-to-graphql-types-decorated) - [JSON Schema to Mongoose schema](https://github.com/kristianmandrup/convert-json-schema-to-mongoose) - [JSON Schema to MobX State Tree types](https://github.com/ralusek/jsonschema-to-mobx-state-tree) - [Convert JSON schema to mongoose 5 schema](https://github.com/kristianmandrup/convert-json-schema-to-mongoose) The library [JSON Schema model builder](https://github.com/kristianmandrup/json-schema-model-builder#readme) is a powerful toolset to build a framework to create any kind of output model from a JSON schema. If you enjoy this declarative/generator approach, try it out! ## Testing Uses [jest](jestjs.io/) for unit testing. - Have unit tests that cover most of the constraints supported. - Could use some refactoring using the latest infrastructure (see `NumericConstraint`) - Please help add more test coverage and help refactor to make this lib even more awesome :) ## Development Current development is taking place on [refactoring](https://github.com/kristianmandrup/schema-to-yup/tree/refactoring) branch. On his branch: - all the code has been converted to TypeScript - constraint classes for String, Numeric, RegExp etc. - Validator building has been extracted so you can add support for any Validator, such as Forg - more... If you would like to further improved this library or add support for more validators than Yup, please help on this branch. Cheers! ## Ideas and suggestions Please feel free to come with ideas and suggestions on how to further improve this library. ## Author 2018 Kristian Mandrup (CTO@Tecla5) ## License MIT
{ "pile_set_name": "Github" }
// // Copyright (C) 2017 The Android Open Source Project // // 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. // #include "property_info_serializer/property_info_serializer.h" #include "property_info_parser/property_info_parser.h" #include <gtest/gtest.h> namespace android { namespace properties { TEST(propertyinfoserializer, TrieNodeCheck) { auto property_info = std::vector<PropertyInfoEntry>{ {"test.", "1st", "1st", false}, {"test.test", "2nd", "2nd", false}, {"test.test1", "3rd", "3rd", true}, {"test.test2", "3rd", "3rd", true}, {"test.test3", "3rd", "3rd", true}, {"this.is.a.long.string", "4th", "4th", true}, }; auto serialized_trie = std::string(); auto build_trie_error = std::string(); ASSERT_TRUE(BuildTrie(property_info, "default", "default", &serialized_trie, &build_trie_error)) << build_trie_error; auto property_info_area = reinterpret_cast<const PropertyInfoArea*>(serialized_trie.data()); // Initial checks for property area. EXPECT_EQ(1U, property_info_area->current_version()); EXPECT_EQ(1U, property_info_area->minimum_supported_version()); // Check the root node auto root_node = property_info_area->root_node(); EXPECT_STREQ("root", root_node.name()); EXPECT_STREQ("default", property_info_area->context(root_node.context_index())); EXPECT_STREQ("default", property_info_area->type(root_node.type_index())); EXPECT_EQ(0U, root_node.num_prefixes()); EXPECT_EQ(0U, root_node.num_exact_matches()); ASSERT_EQ(2U, root_node.num_child_nodes()); // Check the 'test'. node TrieNode test_node; ASSERT_TRUE(root_node.FindChildForString("test", 4, &test_node)); EXPECT_STREQ("test", test_node.name()); EXPECT_STREQ("1st", property_info_area->context(test_node.context_index())); EXPECT_STREQ("1st", property_info_area->type(test_node.type_index())); EXPECT_EQ(0U, test_node.num_child_nodes()); EXPECT_EQ(1U, test_node.num_prefixes()); { auto prefix = test_node.prefix(0); EXPECT_STREQ("test", serialized_trie.data() + prefix->name_offset); EXPECT_EQ(4U, prefix->namelen); EXPECT_STREQ("2nd", property_info_area->context(prefix->context_index)); EXPECT_STREQ("2nd", property_info_area->type(prefix->type_index)); } EXPECT_EQ(3U, test_node.num_exact_matches()); { auto match1 = test_node.exact_match(0); auto match2 = test_node.exact_match(1); auto match3 = test_node.exact_match(2); EXPECT_STREQ("test1", serialized_trie.data() + match1->name_offset); EXPECT_STREQ("test2", serialized_trie.data() + match2->name_offset); EXPECT_STREQ("test3", serialized_trie.data() + match3->name_offset); EXPECT_STREQ("3rd", property_info_area->context(match1->context_index)); EXPECT_STREQ("3rd", property_info_area->context(match2->context_index)); EXPECT_STREQ("3rd", property_info_area->context(match3->context_index)); EXPECT_STREQ("3rd", property_info_area->type(match1->type_index)); EXPECT_STREQ("3rd", property_info_area->type(match2->type_index)); EXPECT_STREQ("3rd", property_info_area->type(match3->type_index)); } // Check the long string node auto expect_empty_one_child = [](auto& node) { EXPECT_EQ(-1U, node.context_index()); EXPECT_EQ(0U, node.num_prefixes()); EXPECT_EQ(0U, node.num_exact_matches()); EXPECT_EQ(1U, node.num_child_nodes()); }; // Start with 'this' TrieNode long_string_node; ASSERT_TRUE(root_node.FindChildForString("this", 4, &long_string_node)); expect_empty_one_child(long_string_node); // Move to 'is' ASSERT_TRUE(long_string_node.FindChildForString("is", 2, &long_string_node)); expect_empty_one_child(long_string_node); // Move to 'a' ASSERT_TRUE(long_string_node.FindChildForString("a", 1, &long_string_node)); expect_empty_one_child(long_string_node); // Move to 'long' ASSERT_TRUE(long_string_node.FindChildForString("long", 4, &long_string_node)); EXPECT_EQ(0U, long_string_node.num_prefixes()); EXPECT_EQ(1U, long_string_node.num_exact_matches()); EXPECT_EQ(0U, long_string_node.num_child_nodes()); auto final_match = long_string_node.exact_match(0); EXPECT_STREQ("string", serialized_trie.data() + final_match->name_offset); EXPECT_STREQ("4th", property_info_area->context(final_match->context_index)); EXPECT_STREQ("4th", property_info_area->type(final_match->type_index)); } TEST(propertyinfoserializer, GetPropertyInfo) { auto property_info = std::vector<PropertyInfoEntry>{ {"test.", "1st", "1st", false}, {"test.test", "2nd", "2nd", false}, {"test.test2.", "6th", "6th", false}, {"test.test", "5th", "5th", true}, {"test.test1", "3rd", "3rd", true}, {"test.test2", "7th", "7th", true}, {"test.test3", "3rd", "3rd", true}, {"this.is.a.long.string", "4th", "4th", true}, {"testoneword", "8th", "8th", true}, {"testwordprefix", "9th", "9th", false}, }; auto serialized_trie = std::string(); auto build_trie_error = std::string(); ASSERT_TRUE(BuildTrie(property_info, "default", "default", &serialized_trie, &build_trie_error)) << build_trie_error; auto property_info_area = reinterpret_cast<const PropertyInfoArea*>(serialized_trie.data()); // Smoke test auto root_node = property_info_area->root_node(); EXPECT_STREQ("root", root_node.name()); EXPECT_STREQ("default", property_info_area->context(root_node.context_index())); EXPECT_STREQ("default", property_info_area->type(root_node.type_index())); const char* context; const char* type; property_info_area->GetPropertyInfo("abc", &context, &type); EXPECT_STREQ("default", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("abc.abc", &context, &type); EXPECT_STREQ("default", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("123.abc", &context, &type); EXPECT_STREQ("default", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("test.a", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("1st", type); property_info_area->GetPropertyInfo("test.b", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("1st", type); property_info_area->GetPropertyInfo("test.c", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("1st", type); property_info_area->GetPropertyInfo("test.test", &context, &type); EXPECT_STREQ("5th", context); EXPECT_STREQ("5th", type); property_info_area->GetPropertyInfo("test.testa", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("test.testb", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("test.testc", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("test.test.a", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("test.test.b", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("test.test.c", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("test.test1", &context, &type); EXPECT_STREQ("3rd", context); EXPECT_STREQ("3rd", type); property_info_area->GetPropertyInfo("test.test2", &context, &type); EXPECT_STREQ("7th", context); EXPECT_STREQ("7th", type); property_info_area->GetPropertyInfo("test.test3", &context, &type); EXPECT_STREQ("3rd", context); EXPECT_STREQ("3rd", type); property_info_area->GetPropertyInfo("test.test11", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("test.test22", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("test.test33", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("this.is.a.long.string", &context, &type); EXPECT_STREQ("4th", context); EXPECT_STREQ("4th", type); property_info_area->GetPropertyInfo("this.is.a.long", &context, &type); EXPECT_STREQ("default", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("this.is.a", &context, &type); EXPECT_STREQ("default", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("this.is", &context, &type); EXPECT_STREQ("default", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("this", &context, &type); EXPECT_STREQ("default", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("test.test2.a", &context, &type); EXPECT_STREQ("6th", context); EXPECT_STREQ("6th", type); property_info_area->GetPropertyInfo("testoneword", &context, &type); EXPECT_STREQ("8th", context); EXPECT_STREQ("8th", type); property_info_area->GetPropertyInfo("testwordprefix", &context, &type); EXPECT_STREQ("9th", context); EXPECT_STREQ("9th", type); property_info_area->GetPropertyInfo("testwordprefixblah", &context, &type); EXPECT_STREQ("9th", context); EXPECT_STREQ("9th", type); property_info_area->GetPropertyInfo("testwordprefix.blah", &context, &type); EXPECT_STREQ("9th", context); EXPECT_STREQ("9th", type); } TEST(propertyinfoserializer, RealProperties) { auto property_info = std::vector<PropertyInfoEntry>{ // Contexts from system/sepolicy/private/property_contexts {"net.rmnet", "u:object_r:net_radio_prop:s0", "string", false}, {"net.gprs", "u:object_r:net_radio_prop:s0", "string", false}, {"net.ppp", "u:object_r:net_radio_prop:s0", "string", false}, {"net.qmi", "u:object_r:net_radio_prop:s0", "string", false}, {"net.lte", "u:object_r:net_radio_prop:s0", "string", false}, {"net.cdma", "u:object_r:net_radio_prop:s0", "string", false}, {"net.dns", "u:object_r:net_dns_prop:s0", "string", false}, {"sys.usb.config", "u:object_r:system_radio_prop:s0", "string", false}, {"ril.", "u:object_r:radio_prop:s0", "string", false}, {"ro.ril.", "u:object_r:radio_prop:s0", "string", false}, {"gsm.", "u:object_r:radio_prop:s0", "string", false}, {"persist.radio", "u:object_r:radio_prop:s0", "string", false}, {"net.", "u:object_r:system_prop:s0", "string", false}, {"dev.", "u:object_r:system_prop:s0", "string", false}, {"ro.runtime.", "u:object_r:system_prop:s0", "string", false}, {"ro.runtime.firstboot", "u:object_r:firstboot_prop:s0", "string", false}, {"hw.", "u:object_r:system_prop:s0", "string", false}, {"ro.hw.", "u:object_r:system_prop:s0", "string", false}, {"sys.", "u:object_r:system_prop:s0", "string", false}, {"sys.cppreopt", "u:object_r:cppreopt_prop:s0", "string", false}, {"sys.powerctl", "u:object_r:powerctl_prop:s0", "string", false}, {"sys.usb.ffs.", "u:object_r:ffs_prop:s0", "string", false}, {"service.", "u:object_r:system_prop:s0", "string", false}, {"dhcp.", "u:object_r:dhcp_prop:s0", "string", false}, {"dhcp.bt-pan.result", "u:object_r:pan_result_prop:s0", "string", false}, {"bluetooth.", "u:object_r:bluetooth_prop:s0", "string", false}, {"debug.", "u:object_r:debug_prop:s0", "string", false}, {"debug.db.", "u:object_r:debuggerd_prop:s0", "string", false}, {"dumpstate.", "u:object_r:dumpstate_prop:s0", "string", false}, {"dumpstate.options", "u:object_r:dumpstate_options_prop:s0", "string", false}, {"log.", "u:object_r:log_prop:s0", "string", false}, {"log.tag", "u:object_r:log_tag_prop:s0", "string", false}, {"log.tag.WifiHAL", "u:object_r:wifi_log_prop:s0", "string", false}, {"security.perf_harden", "u:object_r:shell_prop:s0", "string", false}, {"service.adb.root", "u:object_r:shell_prop:s0", "string", false}, {"service.adb.tcp.port", "u:object_r:shell_prop:s0", "string", false}, {"persist.audio.", "u:object_r:audio_prop:s0", "string", false}, {"persist.bluetooth.", "u:object_r:bluetooth_prop:s0", "string", false}, {"persist.debug.", "u:object_r:persist_debug_prop:s0", "string", false}, {"persist.logd.", "u:object_r:logd_prop:s0", "string", false}, {"persist.logd.security", "u:object_r:device_logging_prop:s0", "string", false}, {"persist.logd.logpersistd", "u:object_r:logpersistd_logging_prop:s0", "string", false}, {"logd.logpersistd", "u:object_r:logpersistd_logging_prop:s0", "string", false}, {"persist.log.tag", "u:object_r:log_tag_prop:s0", "string", false}, {"persist.mmc.", "u:object_r:mmc_prop:s0", "string", false}, {"persist.netd.stable_secret", "u:object_r:netd_stable_secret_prop:s0", "string", false}, {"persist.sys.", "u:object_r:system_prop:s0", "string", false}, {"persist.sys.safemode", "u:object_r:safemode_prop:s0", "string", false}, {"ro.sys.safemode", "u:object_r:safemode_prop:s0", "string", false}, {"persist.sys.audit_safemode", "u:object_r:safemode_prop:s0", "string", false}, {"persist.service.", "u:object_r:system_prop:s0", "string", false}, {"persist.service.bdroid.", "u:object_r:bluetooth_prop:s0", "string", false}, {"persist.security.", "u:object_r:system_prop:s0", "string", false}, {"persist.vendor.overlay.", "u:object_r:overlay_prop:s0", "string", false}, {"ro.boot.vendor.overlay.", "u:object_r:overlay_prop:s0", "string", false}, {"ro.boottime.", "u:object_r:boottime_prop:s0", "string", false}, {"ro.serialno", "u:object_r:serialno_prop:s0", "string", false}, {"ro.boot.btmacaddr", "u:object_r:bluetooth_prop:s0", "string", false}, {"ro.boot.serialno", "u:object_r:serialno_prop:s0", "string", false}, {"ro.bt.", "u:object_r:bluetooth_prop:s0", "string", false}, {"ro.boot.bootreason", "u:object_r:bootloader_boot_reason_prop:s0", "string", false}, {"persist.sys.boot.reason", "u:object_r:last_boot_reason_prop:s0", "string", false}, {"sys.boot.reason", "u:object_r:system_boot_reason_prop:s0", "string", false}, {"ro.organization_owned", "u:object_r:device_logging_prop:s0", "string", false}, {"selinux.restorecon_recursive", "u:object_r:restorecon_prop:s0", "string", false}, {"vold.", "u:object_r:vold_prop:s0", "string", false}, {"ro.crypto.", "u:object_r:vold_prop:s0", "string", false}, {"ro.build.fingerprint", "u:object_r:fingerprint_prop:s0", "string", false}, {"ro.persistent_properties.ready", "u:object_r:persistent_properties_ready_prop:s0", "string", false}, {"ctl.bootanim", "u:object_r:ctl_bootanim_prop:s0", "string", false}, {"ctl.dumpstate", "u:object_r:ctl_dumpstate_prop:s0", "string", false}, {"ctl.fuse_", "u:object_r:ctl_fuse_prop:s0", "string", false}, {"ctl.mdnsd", "u:object_r:ctl_mdnsd_prop:s0", "string", false}, {"ctl.ril-daemon", "u:object_r:ctl_rildaemon_prop:s0", "string", false}, {"ctl.bugreport", "u:object_r:ctl_bugreport_prop:s0", "string", false}, {"ctl.console", "u:object_r:ctl_console_prop:s0", "string", false}, {"ctl.", "u:object_r:ctl_default_prop:s0", "string", false}, {"nfc.", "u:object_r:nfc_prop:s0", "string", false}, {"config.", "u:object_r:config_prop:s0", "string", false}, {"ro.config.", "u:object_r:config_prop:s0", "string", false}, {"dalvik.", "u:object_r:dalvik_prop:s0", "string", false}, {"ro.dalvik.", "u:object_r:dalvik_prop:s0", "string", false}, {"wlan.", "u:object_r:wifi_prop:s0", "string", false}, {"lowpan.", "u:object_r:lowpan_prop:s0", "string", false}, {"ro.lowpan.", "u:object_r:lowpan_prop:s0", "string", false}, {"hwservicemanager.", "u:object_r:hwservicemanager_prop:s0", "string", false}, // Contexts from device/lge/bullhead/sepolicy/property_contexts {"wc_transport.", "u:object_r:wc_transport_prop:s0", "string", false}, {"sys.listeners.", "u:object_r:qseecomtee_prop:s0", "string", false}, {"sys.keymaster.", "u:object_r:qseecomtee_prop:s0", "string", false}, {"radio.atfwd.", "u:object_r:radio_atfwd_prop:s0", "string", false}, {"sys.ims.", "u:object_r:qcom_ims_prop:s0", "string", false}, {"sensors.contexthub.", "u:object_r:contexthub_prop:s0", "string", false}, {"net.r_rmnet", "u:object_r:net_radio_prop:s0", "string", false}, }; auto serialized_trie = std::string(); auto build_trie_error = std::string(); ASSERT_TRUE(BuildTrie(property_info, "u:object_r:default_prop:s0", "string", &serialized_trie, &build_trie_error)) << build_trie_error; auto property_info_area = reinterpret_cast<const PropertyInfoArea*>(serialized_trie.data()); auto properties_and_contexts = std::vector<std::pair<std::string, std::string>>{ // Actual properties on bullhead via `getprop -Z` {"af.fast_track_multiplier", "u:object_r:default_prop:s0"}, {"audio_hal.period_size", "u:object_r:default_prop:s0"}, {"bluetooth.enable_timeout_ms", "u:object_r:bluetooth_prop:s0"}, {"dalvik.vm.appimageformat", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.boot-dex2oat-cpu-set", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.boot-dex2oat-threads", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.dex2oat-Xms", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.dex2oat-Xmx", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.dex2oat-cpu-set", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.dex2oat-threads", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.dexopt.secondary", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.heapgrowthlimit", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.heapmaxfree", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.heapminfree", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.heapsize", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.heapstartsize", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.heaptargetutilization", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.image-dex2oat-Xms", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.image-dex2oat-Xmx", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.image-dex2oat-cpu-set", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.image-dex2oat-threads", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.isa.arm.features", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.isa.arm.variant", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.isa.arm64.features", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.isa.arm64.variant", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.lockprof.threshold", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.stack-trace-file", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.usejit", "u:object_r:dalvik_prop:s0"}, {"dalvik.vm.usejitprofiles", "u:object_r:dalvik_prop:s0"}, {"debug.atrace.tags.enableflags", "u:object_r:debug_prop:s0"}, {"debug.force_rtl", "u:object_r:debug_prop:s0"}, {"dev.bootcomplete", "u:object_r:system_prop:s0"}, {"drm.service.enabled", "u:object_r:default_prop:s0"}, {"gsm.current.phone-type", "u:object_r:radio_prop:s0"}, {"gsm.network.type", "u:object_r:radio_prop:s0"}, {"gsm.operator.alpha", "u:object_r:radio_prop:s0"}, {"gsm.operator.iso-country", "u:object_r:radio_prop:s0"}, {"gsm.operator.isroaming", "u:object_r:radio_prop:s0"}, {"gsm.operator.numeric", "u:object_r:radio_prop:s0"}, {"gsm.sim.operator.alpha", "u:object_r:radio_prop:s0"}, {"gsm.sim.operator.iso-country", "u:object_r:radio_prop:s0"}, {"gsm.sim.operator.numeric", "u:object_r:radio_prop:s0"}, {"gsm.sim.state", "u:object_r:radio_prop:s0"}, {"gsm.version.baseband", "u:object_r:radio_prop:s0"}, {"gsm.version.ril-impl", "u:object_r:radio_prop:s0"}, {"hwservicemanager.ready", "u:object_r:hwservicemanager_prop:s0"}, {"init.svc.adbd", "u:object_r:default_prop:s0"}, {"init.svc.atfwd", "u:object_r:default_prop:s0"}, {"init.svc.audioserver", "u:object_r:default_prop:s0"}, {"init.svc.bootanim", "u:object_r:default_prop:s0"}, {"init.svc.bullhead-sh", "u:object_r:default_prop:s0"}, {"init.svc.cameraserver", "u:object_r:default_prop:s0"}, {"init.svc.cnd", "u:object_r:default_prop:s0"}, {"init.svc.cnss-daemon", "u:object_r:default_prop:s0"}, {"init.svc.cnss_diag", "u:object_r:default_prop:s0"}, {"init.svc.configstore-hal-1-0", "u:object_r:default_prop:s0"}, {"init.svc.console", "u:object_r:default_prop:s0"}, {"init.svc.devstart_sh", "u:object_r:default_prop:s0"}, {"init.svc.drm", "u:object_r:default_prop:s0"}, {"init.svc.dumpstate-1-0", "u:object_r:default_prop:s0"}, {"init.svc.flash-nanohub-fw", "u:object_r:default_prop:s0"}, {"init.svc.fps_hal", "u:object_r:default_prop:s0"}, {"init.svc.gatekeeperd", "u:object_r:default_prop:s0"}, {"init.svc.gralloc-2-0", "u:object_r:default_prop:s0"}, {"init.svc.healthd", "u:object_r:default_prop:s0"}, {"init.svc.hidl_memory", "u:object_r:default_prop:s0"}, {"init.svc.hostapd", "u:object_r:default_prop:s0"}, {"init.svc.hwservicemanager", "u:object_r:default_prop:s0"}, {"init.svc.imsdatadaemon", "u:object_r:default_prop:s0"}, {"init.svc.imsqmidaemon", "u:object_r:default_prop:s0"}, {"init.svc.installd", "u:object_r:default_prop:s0"}, {"init.svc.irsc_util", "u:object_r:default_prop:s0"}, {"init.svc.keystore", "u:object_r:default_prop:s0"}, {"init.svc.lmkd", "u:object_r:default_prop:s0"}, {"init.svc.loc_launcher", "u:object_r:default_prop:s0"}, {"init.svc.logd", "u:object_r:default_prop:s0"}, {"init.svc.logd-reinit", "u:object_r:default_prop:s0"}, {"init.svc.media", "u:object_r:default_prop:s0"}, {"init.svc.mediadrm", "u:object_r:default_prop:s0"}, {"init.svc.mediaextractor", "u:object_r:default_prop:s0"}, {"init.svc.mediametrics", "u:object_r:default_prop:s0"}, {"init.svc.msm_irqbalance", "u:object_r:default_prop:s0"}, {"init.svc.netd", "u:object_r:default_prop:s0"}, {"init.svc.netmgrd", "u:object_r:default_prop:s0"}, {"init.svc.per_mgr", "u:object_r:default_prop:s0"}, {"init.svc.per_proxy", "u:object_r:default_prop:s0"}, {"init.svc.perfd", "u:object_r:default_prop:s0"}, {"init.svc.qcamerasvr", "u:object_r:default_prop:s0"}, {"init.svc.qmuxd", "u:object_r:default_prop:s0"}, {"init.svc.qseecomd", "u:object_r:default_prop:s0"}, {"init.svc.qti", "u:object_r:default_prop:s0"}, {"init.svc.ril-daemon", "u:object_r:default_prop:s0"}, {"init.svc.rmt_storage", "u:object_r:default_prop:s0"}, {"init.svc.servicemanager", "u:object_r:default_prop:s0"}, {"init.svc.ss_ramdump", "u:object_r:default_prop:s0"}, {"init.svc.start_hci_filter", "u:object_r:default_prop:s0"}, {"init.svc.storaged", "u:object_r:default_prop:s0"}, {"init.svc.surfaceflinger", "u:object_r:default_prop:s0"}, {"init.svc.thermal-engine", "u:object_r:default_prop:s0"}, {"init.svc.time_daemon", "u:object_r:default_prop:s0"}, {"init.svc.tombstoned", "u:object_r:default_prop:s0"}, {"init.svc.ueventd", "u:object_r:default_prop:s0"}, {"init.svc.update_engine", "u:object_r:default_prop:s0"}, {"init.svc.usb-hal-1-0", "u:object_r:default_prop:s0"}, {"init.svc.vndservicemanager", "u:object_r:default_prop:s0"}, {"init.svc.vold", "u:object_r:default_prop:s0"}, {"init.svc.webview_zygote32", "u:object_r:default_prop:s0"}, {"init.svc.wifi_hal_legacy", "u:object_r:default_prop:s0"}, {"init.svc.wificond", "u:object_r:default_prop:s0"}, {"init.svc.wpa_supplicant", "u:object_r:default_prop:s0"}, {"init.svc.zygote", "u:object_r:default_prop:s0"}, {"init.svc.zygote_secondary", "u:object_r:default_prop:s0"}, {"keyguard.no_require_sim", "u:object_r:default_prop:s0"}, {"log.tag.WifiHAL", "u:object_r:wifi_log_prop:s0"}, {"logd.logpersistd.enable", "u:object_r:logpersistd_logging_prop:s0"}, {"media.aac_51_output_enabled", "u:object_r:default_prop:s0"}, {"media.recorder.show_manufacturer_and_model", "u:object_r:default_prop:s0"}, {"net.bt.name", "u:object_r:system_prop:s0"}, {"net.lte.ims.data.enabled", "u:object_r:net_radio_prop:s0"}, {"net.qtaguid_enabled", "u:object_r:system_prop:s0"}, {"net.tcp.default_init_rwnd", "u:object_r:system_prop:s0"}, {"nfc.initialized", "u:object_r:nfc_prop:s0"}, {"persist.audio.fluence.speaker", "u:object_r:audio_prop:s0"}, {"persist.audio.fluence.voicecall", "u:object_r:audio_prop:s0"}, {"persist.audio.fluence.voicecomm", "u:object_r:audio_prop:s0"}, {"persist.audio.fluence.voicerec", "u:object_r:audio_prop:s0"}, {"persist.camera.tnr.preview", "u:object_r:default_prop:s0"}, {"persist.camera.tnr.video", "u:object_r:default_prop:s0"}, {"persist.data.iwlan.enable", "u:object_r:default_prop:s0"}, {"persist.hwc.mdpcomp.enable", "u:object_r:default_prop:s0"}, {"persist.logd.logpersistd", "u:object_r:logpersistd_logging_prop:s0"}, {"persist.media.treble_omx", "u:object_r:default_prop:s0"}, {"persist.qcril.disable_retry", "u:object_r:default_prop:s0"}, {"persist.radio.adb_log_on", "u:object_r:radio_prop:s0"}, {"persist.radio.always_send_plmn", "u:object_r:radio_prop:s0"}, {"persist.radio.apm_sim_not_pwdn", "u:object_r:radio_prop:s0"}, {"persist.radio.custom_ecc", "u:object_r:radio_prop:s0"}, {"persist.radio.data_con_rprt", "u:object_r:radio_prop:s0"}, {"persist.radio.data_no_toggle", "u:object_r:radio_prop:s0"}, {"persist.radio.eons.enabled", "u:object_r:radio_prop:s0"}, {"persist.radio.eri64_as_home", "u:object_r:radio_prop:s0"}, {"persist.radio.mode_pref_nv10", "u:object_r:radio_prop:s0"}, {"persist.radio.process_sups_ind", "u:object_r:radio_prop:s0"}, {"persist.radio.redir_party_num", "u:object_r:radio_prop:s0"}, {"persist.radio.ril_payload_on", "u:object_r:radio_prop:s0"}, {"persist.radio.snapshot_enabled", "u:object_r:radio_prop:s0"}, {"persist.radio.snapshot_timer", "u:object_r:radio_prop:s0"}, {"persist.radio.use_cc_names", "u:object_r:radio_prop:s0"}, {"persist.speaker.prot.enable", "u:object_r:default_prop:s0"}, {"persist.sys.boot.reason", "u:object_r:last_boot_reason_prop:s0"}, {"persist.sys.dalvik.vm.lib.2", "u:object_r:system_prop:s0"}, {"persist.sys.debug.color_temp", "u:object_r:system_prop:s0"}, {"persist.sys.preloads.file_cache_expired", "u:object_r:system_prop:s0"}, {"persist.sys.timezone", "u:object_r:system_prop:s0"}, {"persist.sys.usb.config", "u:object_r:system_prop:s0"}, {"persist.sys.webview.vmsize", "u:object_r:system_prop:s0"}, {"persist.tom", "u:object_r:default_prop:s0"}, {"persist.tom2", "u:object_r:default_prop:s0"}, {"pm.dexopt.ab-ota", "u:object_r:default_prop:s0"}, {"pm.dexopt.bg-dexopt", "u:object_r:default_prop:s0"}, {"pm.dexopt.boot", "u:object_r:default_prop:s0"}, {"pm.dexopt.first-boot", "u:object_r:default_prop:s0"}, {"pm.dexopt.install", "u:object_r:default_prop:s0"}, {"qcom.bluetooth.soc", "u:object_r:default_prop:s0"}, {"radio.atfwd.start", "u:object_r:radio_atfwd_prop:s0"}, {"ril.ecclist", "u:object_r:radio_prop:s0"}, {"ril.nosim.ecc_list_1", "u:object_r:radio_prop:s0"}, {"ril.nosim.ecc_list_count", "u:object_r:radio_prop:s0"}, {"ril.qcril_pre_init_lock_held", "u:object_r:radio_prop:s0"}, {"rild.libpath", "u:object_r:default_prop:s0"}, {"ro.allow.mock.location", "u:object_r:default_prop:s0"}, {"ro.audio.flinger_standbytime_ms", "u:object_r:default_prop:s0"}, {"ro.baseband", "u:object_r:default_prop:s0"}, {"ro.bionic.ld.warning", "u:object_r:default_prop:s0"}, {"ro.board.platform", "u:object_r:default_prop:s0"}, {"ro.boot.baseband", "u:object_r:default_prop:s0"}, {"ro.boot.bootloader", "u:object_r:default_prop:s0"}, {"ro.boot.bootreason", "u:object_r:bootloader_boot_reason_prop:s0"}, {"ro.boot.dlcomplete", "u:object_r:default_prop:s0"}, {"ro.boot.emmc", "u:object_r:default_prop:s0"}, {"ro.boot.flash.locked", "u:object_r:default_prop:s0"}, {"ro.boot.hardware", "u:object_r:default_prop:s0"}, {"ro.boot.hardware.sku", "u:object_r:default_prop:s0"}, {"ro.boot.revision", "u:object_r:default_prop:s0"}, {"ro.boot.serialno", "u:object_r:serialno_prop:s0"}, {"ro.boot.verifiedbootstate", "u:object_r:default_prop:s0"}, {"ro.boot.veritymode", "u:object_r:default_prop:s0"}, {"ro.boot.wificountrycode", "u:object_r:default_prop:s0"}, {"ro.bootimage.build.date", "u:object_r:default_prop:s0"}, {"ro.bootimage.build.date.utc", "u:object_r:default_prop:s0"}, {"ro.bootimage.build.fingerprint", "u:object_r:default_prop:s0"}, {"ro.bootloader", "u:object_r:default_prop:s0"}, {"ro.bootmode", "u:object_r:default_prop:s0"}, {"ro.boottime.adbd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.atfwd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.audioserver", "u:object_r:boottime_prop:s0"}, {"ro.boottime.bootanim", "u:object_r:boottime_prop:s0"}, {"ro.boottime.bullhead-sh", "u:object_r:boottime_prop:s0"}, {"ro.boottime.cameraserver", "u:object_r:boottime_prop:s0"}, {"ro.boottime.cnd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.cnss-daemon", "u:object_r:boottime_prop:s0"}, {"ro.boottime.cnss_diag", "u:object_r:boottime_prop:s0"}, {"ro.boottime.configstore-hal-1-0", "u:object_r:boottime_prop:s0"}, {"ro.boottime.console", "u:object_r:boottime_prop:s0"}, {"ro.boottime.devstart_sh", "u:object_r:boottime_prop:s0"}, {"ro.boottime.drm", "u:object_r:boottime_prop:s0"}, {"ro.boottime.dumpstate-1-0", "u:object_r:boottime_prop:s0"}, {"ro.boottime.flash-nanohub-fw", "u:object_r:boottime_prop:s0"}, {"ro.boottime.fps_hal", "u:object_r:boottime_prop:s0"}, {"ro.boottime.gatekeeperd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.gralloc-2-0", "u:object_r:boottime_prop:s0"}, {"ro.boottime.healthd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.hidl_memory", "u:object_r:boottime_prop:s0"}, {"ro.boottime.hwservicemanager", "u:object_r:boottime_prop:s0"}, {"ro.boottime.imsdatadaemon", "u:object_r:boottime_prop:s0"}, {"ro.boottime.imsqmidaemon", "u:object_r:boottime_prop:s0"}, {"ro.boottime.init", "u:object_r:boottime_prop:s0"}, {"ro.boottime.init.first_stage", "u:object_r:boottime_prop:s0"}, {"ro.boottime.init.cold_boot_wait", "u:object_r:boottime_prop:s0"}, {"ro.boottime.init.mount_all.default", "u:object_r:boottime_prop:s0"}, {"ro.boottime.init.selinux", "u:object_r:boottime_prop:s0"}, {"ro.boottime.installd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.irsc_util", "u:object_r:boottime_prop:s0"}, {"ro.boottime.keystore", "u:object_r:boottime_prop:s0"}, {"ro.boottime.lmkd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.loc_launcher", "u:object_r:boottime_prop:s0"}, {"ro.boottime.logd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.logd-reinit", "u:object_r:boottime_prop:s0"}, {"ro.boottime.media", "u:object_r:boottime_prop:s0"}, {"ro.boottime.mediadrm", "u:object_r:boottime_prop:s0"}, {"ro.boottime.mediaextractor", "u:object_r:boottime_prop:s0"}, {"ro.boottime.mediametrics", "u:object_r:boottime_prop:s0"}, {"ro.boottime.msm_irqbalance", "u:object_r:boottime_prop:s0"}, {"ro.boottime.netd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.netmgrd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.per_mgr", "u:object_r:boottime_prop:s0"}, {"ro.boottime.per_proxy", "u:object_r:boottime_prop:s0"}, {"ro.boottime.perfd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.qcamerasvr", "u:object_r:boottime_prop:s0"}, {"ro.boottime.qmuxd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.qseecomd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.qti", "u:object_r:boottime_prop:s0"}, {"ro.boottime.ril-daemon", "u:object_r:boottime_prop:s0"}, {"ro.boottime.rmt_storage", "u:object_r:boottime_prop:s0"}, {"ro.boottime.servicemanager", "u:object_r:boottime_prop:s0"}, {"ro.boottime.ss_ramdump", "u:object_r:boottime_prop:s0"}, {"ro.boottime.start_hci_filter", "u:object_r:boottime_prop:s0"}, {"ro.boottime.storaged", "u:object_r:boottime_prop:s0"}, {"ro.boottime.surfaceflinger", "u:object_r:boottime_prop:s0"}, {"ro.boottime.thermal-engine", "u:object_r:boottime_prop:s0"}, {"ro.boottime.time_daemon", "u:object_r:boottime_prop:s0"}, {"ro.boottime.tombstoned", "u:object_r:boottime_prop:s0"}, {"ro.boottime.ueventd", "u:object_r:boottime_prop:s0"}, {"ro.boottime.update_engine", "u:object_r:boottime_prop:s0"}, {"ro.boottime.usb-hal-1-0", "u:object_r:boottime_prop:s0"}, {"ro.boottime.vndservicemanager", "u:object_r:boottime_prop:s0"}, {"ro.boottime.vold", "u:object_r:boottime_prop:s0"}, {"ro.boottime.webview_zygote32", "u:object_r:boottime_prop:s0"}, {"ro.boottime.wifi_hal_legacy", "u:object_r:boottime_prop:s0"}, {"ro.boottime.wificond", "u:object_r:boottime_prop:s0"}, {"ro.boottime.zygote", "u:object_r:boottime_prop:s0"}, {"ro.boottime.zygote_secondary", "u:object_r:boottime_prop:s0"}, {"ro.bt.bdaddr_path", "u:object_r:bluetooth_prop:s0"}, {"ro.build.characteristics", "u:object_r:default_prop:s0"}, {"ro.build.date", "u:object_r:default_prop:s0"}, {"ro.build.date.utc", "u:object_r:default_prop:s0"}, {"ro.build.description", "u:object_r:default_prop:s0"}, {"ro.build.display.id", "u:object_r:default_prop:s0"}, {"ro.build.expect.baseband", "u:object_r:default_prop:s0"}, {"ro.build.expect.bootloader", "u:object_r:default_prop:s0"}, {"ro.build.fingerprint", "u:object_r:fingerprint_prop:s0"}, {"ro.build.flavor", "u:object_r:default_prop:s0"}, {"ro.build.host", "u:object_r:default_prop:s0"}, {"ro.build.id", "u:object_r:default_prop:s0"}, {"ro.build.product", "u:object_r:default_prop:s0"}, {"ro.build.tags", "u:object_r:default_prop:s0"}, {"ro.build.type", "u:object_r:default_prop:s0"}, {"ro.build.user", "u:object_r:default_prop:s0"}, {"ro.build.version.all_codenames", "u:object_r:default_prop:s0"}, {"ro.build.version.base_os", "u:object_r:default_prop:s0"}, {"ro.build.version.codename", "u:object_r:default_prop:s0"}, {"ro.build.version.incremental", "u:object_r:default_prop:s0"}, {"ro.build.version.preview_sdk", "u:object_r:default_prop:s0"}, {"ro.build.version.release", "u:object_r:default_prop:s0"}, {"ro.build.version.sdk", "u:object_r:default_prop:s0"}, {"ro.build.version.security_patch", "u:object_r:default_prop:s0"}, {"ro.camera.notify_nfc", "u:object_r:default_prop:s0"}, {"ro.carrier", "u:object_r:default_prop:s0"}, {"ro.com.android.dataroaming", "u:object_r:default_prop:s0"}, {"ro.config.alarm_alert", "u:object_r:config_prop:s0"}, {"ro.config.notification_sound", "u:object_r:config_prop:s0"}, {"ro.config.ringtone", "u:object_r:config_prop:s0"}, {"ro.config.vc_call_vol_steps", "u:object_r:config_prop:s0"}, {"ro.crypto.fs_crypto_blkdev", "u:object_r:vold_prop:s0"}, {"ro.crypto.state", "u:object_r:vold_prop:s0"}, {"ro.crypto.type", "u:object_r:vold_prop:s0"}, {"ro.dalvik.vm.native.bridge", "u:object_r:dalvik_prop:s0"}, {"ro.debuggable", "u:object_r:default_prop:s0"}, {"ro.organization_owned", "u:object_r:device_logging_prop:s0"}, {"ro.expect.recovery_id", "u:object_r:default_prop:s0"}, {"ro.frp.pst", "u:object_r:default_prop:s0"}, {"ro.hardware", "u:object_r:default_prop:s0"}, {"ro.hwui.drop_shadow_cache_size", "u:object_r:default_prop:s0"}, {"ro.hwui.gradient_cache_size", "u:object_r:default_prop:s0"}, {"ro.hwui.layer_cache_size", "u:object_r:default_prop:s0"}, {"ro.hwui.path_cache_size", "u:object_r:default_prop:s0"}, {"ro.hwui.r_buffer_cache_size", "u:object_r:default_prop:s0"}, {"ro.hwui.text_large_cache_height", "u:object_r:default_prop:s0"}, {"ro.hwui.text_large_cache_width", "u:object_r:default_prop:s0"}, {"ro.hwui.text_small_cache_height", "u:object_r:default_prop:s0"}, {"ro.hwui.text_small_cache_width", "u:object_r:default_prop:s0"}, {"ro.hwui.texture_cache_flushrate", "u:object_r:default_prop:s0"}, {"ro.hwui.texture_cache_size", "u:object_r:default_prop:s0"}, {"ro.min_freq_0", "u:object_r:default_prop:s0"}, {"ro.min_freq_4", "u:object_r:default_prop:s0"}, {"ro.oem_unlock_supported", "u:object_r:default_prop:s0"}, {"ro.opengles.version", "u:object_r:default_prop:s0"}, {"ro.persistent_properties.ready", "u:object_r:persistent_properties_ready_prop:s0"}, {"ro.product.board", "u:object_r:default_prop:s0"}, {"ro.product.brand", "u:object_r:default_prop:s0"}, {"ro.product.cpu.abi", "u:object_r:default_prop:s0"}, {"ro.product.cpu.abilist", "u:object_r:default_prop:s0"}, {"ro.product.cpu.abilist32", "u:object_r:default_prop:s0"}, {"ro.product.cpu.abilist64", "u:object_r:default_prop:s0"}, {"ro.product.device", "u:object_r:default_prop:s0"}, {"ro.product.first_api_level", "u:object_r:default_prop:s0"}, {"ro.product.locale", "u:object_r:default_prop:s0"}, {"ro.product.manufacturer", "u:object_r:default_prop:s0"}, {"ro.product.model", "u:object_r:default_prop:s0"}, {"ro.product.name", "u:object_r:default_prop:s0"}, {"ro.property_service.version", "u:object_r:default_prop:s0"}, {"ro.qc.sdk.audio.fluencetype", "u:object_r:default_prop:s0"}, {"ro.recovery_id", "u:object_r:default_prop:s0"}, {"ro.revision", "u:object_r:default_prop:s0"}, {"ro.ril.svdo", "u:object_r:radio_prop:s0"}, {"ro.ril.svlte1x", "u:object_r:radio_prop:s0"}, {"ro.runtime.firstboot", "u:object_r:firstboot_prop:s0"}, {"ro.secure", "u:object_r:default_prop:s0"}, {"ro.serialno", "u:object_r:serialno_prop:s0"}, {"ro.sf.lcd_density", "u:object_r:default_prop:s0"}, {"ro.telephony.call_ring.multiple", "u:object_r:default_prop:s0"}, {"ro.telephony.default_cdma_sub", "u:object_r:default_prop:s0"}, {"ro.telephony.default_network", "u:object_r:default_prop:s0"}, {"ro.treble.enabled", "u:object_r:default_prop:s0"}, {"ro.vendor.build.date", "u:object_r:default_prop:s0"}, {"ro.vendor.build.date.utc", "u:object_r:default_prop:s0"}, {"ro.vendor.build.fingerprint", "u:object_r:default_prop:s0"}, {"ro.vendor.extension_library", "u:object_r:default_prop:s0"}, {"ro.wifi.channels", "u:object_r:default_prop:s0"}, {"ro.zygote", "u:object_r:default_prop:s0"}, {"security.perf_harden", "u:object_r:shell_prop:s0"}, {"sensors.contexthub.lid_state", "u:object_r:contexthub_prop:s0"}, {"service.adb.root", "u:object_r:shell_prop:s0"}, {"service.bootanim.exit", "u:object_r:system_prop:s0"}, {"service.sf.present_timestamp", "u:object_r:system_prop:s0"}, {"sys.boot.reason", "u:object_r:system_boot_reason_prop:s0"}, {"sys.boot_completed", "u:object_r:system_prop:s0"}, {"sys.ims.QMI_DAEMON_STATUS", "u:object_r:qcom_ims_prop:s0"}, {"sys.listeners.registered", "u:object_r:qseecomtee_prop:s0"}, {"sys.logbootcomplete", "u:object_r:system_prop:s0"}, {"sys.oem_unlock_allowed", "u:object_r:system_prop:s0"}, {"sys.qcom.devup", "u:object_r:system_prop:s0"}, {"sys.sysctl.extra_free_kbytes", "u:object_r:system_prop:s0"}, {"sys.usb.config", "u:object_r:system_radio_prop:s0"}, {"sys.usb.configfs", "u:object_r:system_radio_prop:s0"}, {"sys.usb.controller", "u:object_r:system_prop:s0"}, {"sys.usb.ffs.aio_compat", "u:object_r:ffs_prop:s0"}, {"sys.usb.ffs.max_read", "u:object_r:ffs_prop:s0"}, {"sys.usb.ffs.max_write", "u:object_r:ffs_prop:s0"}, {"sys.usb.ffs.ready", "u:object_r:ffs_prop:s0"}, {"sys.usb.mtp.device_type", "u:object_r:system_prop:s0"}, {"sys.usb.state", "u:object_r:system_prop:s0"}, {"telephony.lteOnCdmaDevice", "u:object_r:default_prop:s0"}, {"tombstoned.max_tombstone_count", "u:object_r:default_prop:s0"}, {"vidc.debug.perf.mode", "u:object_r:default_prop:s0"}, {"vidc.enc.dcvs.extra-buff-count", "u:object_r:default_prop:s0"}, {"vold.decrypt", "u:object_r:vold_prop:s0"}, {"vold.has_adoptable", "u:object_r:vold_prop:s0"}, {"vold.post_fs_data_done", "u:object_r:vold_prop:s0"}, {"wc_transport.clean_up", "u:object_r:wc_transport_prop:s0"}, {"wc_transport.hci_filter_status", "u:object_r:wc_transport_prop:s0"}, {"wc_transport.ref_count", "u:object_r:wc_transport_prop:s0"}, {"wc_transport.soc_initialized", "u:object_r:wc_transport_prop:s0"}, {"wc_transport.start_hci", "u:object_r:wc_transport_prop:s0"}, {"wc_transport.vnd_power", "u:object_r:wc_transport_prop:s0"}, {"wifi.interface", "u:object_r:default_prop:s0"}, {"wifi.supplicant_scan_interval", "u:object_r:default_prop:s0"}, }; for (const auto& [property, context] : properties_and_contexts) { const char* returned_context; property_info_area->GetPropertyInfo(property.c_str(), &returned_context, nullptr); EXPECT_EQ(context, returned_context) << property; } } TEST(propertyinfoserializer, GetPropertyInfo_prefix_without_dot) { auto property_info = std::vector<PropertyInfoEntry>{ {"persist.radio", "1st", "1st", false}, {"persist.radio.something.else.here", "2nd", "2nd", false}, }; auto serialized_trie = std::string(); auto build_trie_error = std::string(); ASSERT_TRUE(BuildTrie(property_info, "default", "default", &serialized_trie, &build_trie_error)) << build_trie_error; auto property_info_area = reinterpret_cast<const PropertyInfoArea*>(serialized_trie.data()); const char* context; const char* type; property_info_area->GetPropertyInfo("persist.radio", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("1st", type); property_info_area->GetPropertyInfo("persist.radio.subproperty", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("1st", type); property_info_area->GetPropertyInfo("persist.radiowords", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("1st", type); property_info_area->GetPropertyInfo("persist.radio.long.long.long.sub.property", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("1st", type); property_info_area->GetPropertyInfo("persist.radio.something.else.here", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("persist.radio.something.else.here2", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("persist.radio.something.else.here.after", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("persist.radio.something.else.nothere", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("1st", type); property_info_area->GetPropertyInfo("persist.radio.something.else", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("1st", type); } TEST(propertyinfoserializer, GetPropertyInfo_prefix_with_dot_vs_without) { auto property_info = std::vector<PropertyInfoEntry>{ {"persist.", "1st", "1st", false}, {"persist.radio", "2nd", "2nd", false}, {"persist.radio.long.property.exact.match", "3rd", "3rd", true}, }; auto serialized_trie = std::string(); auto build_trie_error = std::string(); ASSERT_TRUE(BuildTrie(property_info, "default", "default", &serialized_trie, &build_trie_error)) << build_trie_error; auto property_info_area = reinterpret_cast<const PropertyInfoArea*>(serialized_trie.data()); const char* context; const char* type; property_info_area->GetPropertyInfo("persist.notradio", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("1st", type); property_info_area->GetPropertyInfo("persist.radio", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("persist.radio.subproperty", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("persist.radiowords", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("persist.radio.long.property.prefix.match", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("2nd", type); property_info_area->GetPropertyInfo("persist.radio.long.property.exact.match", &context, &type); EXPECT_STREQ("3rd", context); EXPECT_STREQ("3rd", type); } TEST(propertyinfoserializer, GetPropertyInfo_empty_context_and_type) { auto property_info = std::vector<PropertyInfoEntry>{ {"persist.", "1st", "", false}, {"persist.dot_prefix.", "2nd", "", false}, {"persist.non_dot_prefix", "3rd", "", false}, {"persist.exact_match", "", "", true}, {"persist.dot_prefix2.", "", "4th", false}, {"persist.non_dot_prefix2", "", "5th", false}, }; auto serialized_trie = std::string(); auto build_trie_error = std::string(); ASSERT_TRUE(BuildTrie(property_info, "default", "default", &serialized_trie, &build_trie_error)) << build_trie_error; auto property_info_area = reinterpret_cast<const PropertyInfoArea*>(serialized_trie.data()); const char* context; const char* type; property_info_area->GetPropertyInfo("notpersist.radio.something", &context, &type); EXPECT_STREQ("default", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("persist.nomatch", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("persist.dot_prefix.something", &context, &type); EXPECT_STREQ("2nd", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("persist.non_dot_prefix.something", &context, &type); EXPECT_STREQ("3rd", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("persist.exact_match", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("default", type); property_info_area->GetPropertyInfo("persist.dot_prefix2.something", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("4th", type); property_info_area->GetPropertyInfo("persist.non_dot_prefix2.something", &context, &type); EXPECT_STREQ("1st", context); EXPECT_STREQ("5th", type); } } // namespace properties } // namespace android
{ "pile_set_name": "Github" }
// This is a generated file. Not intended for manual editing. package com.intellij.lang.jsgraphql.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.intellij.lang.jsgraphql.psi.GraphQLElementTypes.*; import com.intellij.lang.jsgraphql.psi.*; public class GraphQLUnionTypeExtensionDefinitionImpl extends GraphQLTypeExtensionImpl implements GraphQLUnionTypeExtensionDefinition { public GraphQLUnionTypeExtensionDefinitionImpl(ASTNode node) { super(node); } public void accept(@NotNull GraphQLVisitor visitor) { visitor.visitUnionTypeExtensionDefinition(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GraphQLVisitor) accept((GraphQLVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GraphQLTypeName getTypeName() { return findChildByClass(GraphQLTypeName.class); } @Override @Nullable public GraphQLUnionMembership getUnionMembership() { return findChildByClass(GraphQLUnionMembership.class); } @Override @NotNull public List<GraphQLDirective> getDirectives() { return PsiTreeUtil.getChildrenOfTypeAsList(this, GraphQLDirective.class); } }
{ "pile_set_name": "Github" }
//===--- DiagnosticsClangImporter.h - Diagnostic Definitions ----*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // /// \file /// This file defines diagnostics for the Clang importer. // //===----------------------------------------------------------------------===// #ifndef SWIFT_DIAGNOSTICSCLANGIMPORTER_H #define SWIFT_DIAGNOSTICSCLANGIMPORTER_H #include "swift/AST/DiagnosticsCommon.h" namespace swift { namespace diag { // Declare common diagnostics objects with their appropriate types. #define DIAG(KIND,ID,Options,Text,Signature) \ extern detail::DiagWithArguments<void Signature>::type ID; #include "DiagnosticsClangImporter.def" } } #endif
{ "pile_set_name": "Github" }
{ "name": "Mawdoo3 Limited", "displayName": "Mawdoo3", "properties": [ "mawdoo3.com", "modo3.com" ] }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <style> div { width: 500px; height: 500px; box-shadow: 0 0 40px #000; } </style> <div id="d"></div>
{ "pile_set_name": "Github" }
=========== Form wizard =========== .. module:: django.contrib.formtools.wizard :synopsis: Splits forms across multiple Web pages. Django comes with an optional "form wizard" application that splits :doc:`forms </topics/forms/index>` across multiple Web pages. It maintains state in hashed HTML :samp:`<input type="hidden">` fields so that the full server-side processing can be delayed until the submission of the final form. You might want to use this if you have a lengthy form that would be too unwieldy for display on a single page. The first page might ask the user for core information, the second page might ask for less important information, etc. The term "wizard," in this context, is `explained on Wikipedia`_. .. _explained on Wikipedia: http://en.wikipedia.org/wiki/Wizard_%28software%29 .. _forms: ../forms/ How it works ============ Here's the basic workflow for how a user would use a wizard: 1. The user visits the first page of the wizard, fills in the form and submits it. 2. The server validates the data. If it's invalid, the form is displayed again, with error messages. If it's valid, the server calculates a secure hash of the data and presents the user with the next form, saving the validated data and hash in :samp:`<input type="hidden">` fields. 3. Step 1 and 2 repeat, for every subsequent form in the wizard. 4. Once the user has submitted all the forms and all the data has been validated, the wizard processes the data -- saving it to the database, sending an e-mail, or whatever the application needs to do. Usage ===== This application handles as much machinery for you as possible. Generally, you just have to do these things: 1. Define a number of :class:`~django.forms.Form` classes -- one per wizard page. 2. Create a :class:`FormWizard` class that specifies what to do once all of your forms have been submitted and validated. This also lets you override some of the wizard's behavior. 3. Create some templates that render the forms. You can define a single, generic template to handle every one of the forms, or you can define a specific template for each form. 4. Point your URLconf at your :class:`FormWizard` class. Defining ``Form`` classes ========================= The first step in creating a form wizard is to create the :class:`~django.forms.Form` classes. These should be standard :class:`django.forms.Form` classes, covered in the :doc:`forms documentation </topics/forms/index>`. These classes can live anywhere in your codebase, but convention is to put them in a file called :file:`forms.py` in your application. For example, let's write a "contact form" wizard, where the first page's form collects the sender's e-mail address and subject, and the second page collects the message itself. Here's what the :file:`forms.py` might look like:: from django import forms class ContactForm1(forms.Form): subject = forms.CharField(max_length=100) sender = forms.EmailField() class ContactForm2(forms.Form): message = forms.CharField(widget=forms.Textarea) **Important limitation:** Because the wizard uses HTML hidden fields to store data between pages, you may not include a :class:`~django.forms.FileField` in any form except the last one. Creating a ``FormWizard`` class =============================== The next step is to create a :class:`django.contrib.formtools.wizard.FormWizard` subclass. As with your :class:`~django.forms.Form` classes, this :class:`FormWizard` class can live anywhere in your codebase, but convention is to put it in :file:`forms.py`. The only requirement on this subclass is that it implement a :meth:`~FormWizard.done()` method. .. method:: FormWizard.done This method specifies what should happen when the data for *every* form is submitted and validated. This method is passed two arguments: * ``request`` -- an :class:`~django.http.HttpRequest` object * ``form_list`` -- a list of :class:`~django.forms.Form` classes In this simplistic example, rather than perform any database operation, the method simply renders a template of the validated data:: from django.shortcuts import render_to_response from django.contrib.formtools.wizard import FormWizard class ContactWizard(FormWizard): def done(self, request, form_list): return render_to_response('done.html', { 'form_data': [form.cleaned_data for form in form_list], }) Note that this method will be called via ``POST``, so it really ought to be a good Web citizen and redirect after processing the data. Here's another example:: from django.http import HttpResponseRedirect from django.contrib.formtools.wizard import FormWizard class ContactWizard(FormWizard): def done(self, request, form_list): do_something_with_the_form_data(form_list) return HttpResponseRedirect('/page-to-redirect-to-when-done/') See the section `Advanced FormWizard methods`_ below to learn about more :class:`FormWizard` hooks. Creating templates for the forms ================================ Next, you'll need to create a template that renders the wizard's forms. By default, every form uses a template called :file:`forms/wizard.html`. (You can change this template name by overriding :meth:`~FormWizard.get_template()`, which is documented below. This hook also allows you to use a different template for each form.) This template expects the following context: * ``step_field`` -- The name of the hidden field containing the step. * ``step0`` -- The current step (zero-based). * ``step`` -- The current step (one-based). * ``step_count`` -- The total number of steps. * ``form`` -- The :class:`~django.forms.Form` instance for the current step (either empty or with errors). * ``previous_fields`` -- A string representing every previous data field, plus hashes for completed forms, all in the form of hidden fields. Note that you'll need to run this through the :tfilter:`safe` template filter, to prevent auto-escaping, because it's raw HTML. You can supply extra context to this template in two ways: * Set the :attr:`~FormWizard.extra_context` attribute on your :class:`FormWizard` subclass to a dictionary. * Pass a dictionary as a parameter named ``extra_context`` to your wizard's URL pattern in your URLconf. See :ref:`hooking-wizard-into-urlconf`. Here's a full example template: .. code-block:: html+django {% extends "base.html" %} {% block content %} <p>Step {{ step }} of {{ step_count }}</p> <form action="." method="post">{% csrf_token %} <table> {{ form }} </table> <input type="hidden" name="{{ step_field }}" value="{{ step0 }}" /> {{ previous_fields|safe }} <input type="submit"> </form> {% endblock %} Note that ``previous_fields``, ``step_field`` and ``step0`` are all required for the wizard to work properly. .. _hooking-wizard-into-urlconf: Hooking the wizard into a URLconf ================================= Finally, we need to specify which forms to use in the wizard, and then deploy the new :class:`FormWizard` object a URL in ``urls.py``. The wizard takes a list of your :class:`~django.forms.Form` objects as arguments when you instantiate the Wizard:: from django.conf.urls.defaults import * from testapp.forms import ContactForm1, ContactForm2, ContactWizard urlpatterns = patterns('', (r'^contact/$', ContactWizard([ContactForm1, ContactForm2])), ) Advanced ``FormWizard`` methods =============================== .. class:: FormWizard Aside from the :meth:`~done()` method, :class:`FormWizard` offers a few advanced method hooks that let you customize how your wizard works. Some of these methods take an argument ``step``, which is a zero-based counter representing the current step of the wizard. (E.g., the first form is ``0`` and the second form is ``1``.) .. method:: FormWizard.prefix_for_step Given the step, returns a form prefix to use. By default, this simply uses the step itself. For more, see the :ref:`form prefix documentation <form-prefix>`. Default implementation:: def prefix_for_step(self, step): return str(step) .. method:: FormWizard.render_hash_failure Renders a template if the hash check fails. It's rare that you'd need to override this. Default implementation:: def render_hash_failure(self, request, step): return self.render(self.get_form(step), request, step, context={'wizard_error': 'We apologize, but your form has expired. Please' ' continue filling out the form from this page.'}) .. method:: FormWizard.security_hash Calculates the security hash for the given request object and :class:`~django.forms.Form` instance. By default, this generates a SHA1 HMAC using your form data and your :setting:`SECRET_KEY` setting. It's rare that somebody would need to override this. Example:: def security_hash(self, request, form): return my_hash_function(request, form) .. method:: FormWizard.parse_params A hook for saving state from the request object and ``args`` / ``kwargs`` that were captured from the URL by your URLconf. By default, this does nothing. Example:: def parse_params(self, request, *args, **kwargs): self.my_state = args[0] .. method:: FormWizard.get_template Returns the name of the template that should be used for the given step. By default, this returns :file:`'forms/wizard.html'`, regardless of step. Example:: def get_template(self, step): return 'myapp/wizard_%s.html' % step If :meth:`~FormWizard.get_template` returns a list of strings, then the wizard will use the template system's :func:`~django.template.loader.select_template` function. This means the system will use the first template that exists on the filesystem. For example:: def get_template(self, step): return ['myapp/wizard_%s.html' % step, 'myapp/wizard.html'] .. method:: FormWizard.render_template Renders the template for the given step, returning an :class:`~django.http.HttpResponse` object. Override this method if you want to add a custom context, return a different MIME type, etc. If you only need to override the template name, use :meth:`~FormWizard.get_template` instead. The template will be rendered with the context documented in the "Creating templates for the forms" section above. .. method:: FormWizard.process_step Hook for modifying the wizard's internal state, given a fully validated :class:`~django.forms.Form` object. The Form is guaranteed to have clean, valid data. This method should *not* modify any of that data. Rather, it might want to set ``self.extra_context`` or dynamically alter ``self.form_list``, based on previously submitted forms. Note that this method is called every time a page is rendered for *all* submitted steps. The function signature:: def process_step(self, request, form, step): # ...
{ "pile_set_name": "Github" }
#!/bin/sh java -jar -Djava.security.egd=file:/dev/./urandom /home/webgoat/webgoat.jar --server.address=0.0.0.0 --server.port=8080
{ "pile_set_name": "Github" }
/* Minimal Xlib port Stefano Bodrato, 6/3/2007 $Id: DefaultScreen.c,v 1.1 2014-04-16 06:16:16 stefano Exp $ */ #define _BUILDING_X #include <X11/Xlib.h> int DefaultScreen(Display *display) { return 1; }
{ "pile_set_name": "Github" }
/* * Copyright 2013 Goldman Sachs. * * 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.gs.collections.impl.map.mutable.primitive; import com.gs.collections.impl.test.Verify; import org.junit.Test; public class IntShortHashMapSerializationTest { @Test public void serializedForm() { Verify.assertSerializedForm( 1L, "rO0ABXNyAD1jb20uZ3MuY29sbGVjdGlvbnMuaW1wbC5tYXAubXV0YWJsZS5wcmltaXRpdmUuSW50\n" + "U2hvcnRIYXNoTWFwAAAAAAAAAAEMAAB4cHcEAAAAAHg=", new IntShortHashMap()); } }
{ "pile_set_name": "Github" }
Cache-Control: no-cache, no-store, must-revalidate Content-Length: 4145 Content-Type: text/html; charset=utf-8 Date: Thu, 05 Oct 2017 12:39:27 GMT Expires: -1 P3p: CP="NON COR ADMa CURa DEVa OUR IND COM UNI NAV INT PRE LOC ONL PHY STA ONL" Pragma: no-cache Set-Cookie: .ASPXAUTH=; expires=Tue, 12-Oct-1999 00:00:00 GMT; path=/; secure; HttpOnly antixss=-Kt3mkHGKjG56u7YvgrFdRw__; path=/; secure sessdata=L3dVTFVtOXZkRWx1WkdWNE9qRUNGNkpTMmZ0bTExTWRzM09MYTFNeUxpTXZ1OFpLWEhvNDNhdGovTTdpOENra2xGVmlXRHRYdlpmMTlTTjVKd1YrNWdOVzhxYkoyRFVlQ1IyZGQwbWZ2WHdyK0lmZlBlZzNZck1XeXd3OEJwdz0_; path=/; secure; HttpOnly X-Cfy-Tx-Dt: MTAvNS8yMDE3IDEyOjM5OjI3IFBN X-Cfy-Tx-Id: 5341c6d8b861419fa497d23f4f0122c1 X-Cfy-Tx-Pn: pod14 X-Cfy-Tx-Tm: 226 X-Frame-Options: SAMEORIGIN X-Robots-Tag: noindex, nofollow X-Ua-Compatible: IE=8,9,10
{ "pile_set_name": "Github" }
/* * This file is part of libFirm. * Copyright (C) 2012 University of Karlsruhe. */ /** * @file * @brief Intraprozedural analyses to estimate the call graph. * @author Hubert Schmid * @date 09.06.2002 * @brief * Interprocedural analysis to estimate the calling relation. * * This analysis computes all entities representing methods that * can be called at a Call node. Further it computes a set of * methods that are 'free', i.e., their adress is handled by * the program directly, or they are visible external. */ #ifndef FIRM_ANA_CGANA_H #define FIRM_ANA_CGANA_H #include <stddef.h> #include "firm_types.h" #include "begin.h" /** @addtogroup callgraph * @{ */ /** Analyses a rough estimation of the possible call graph. * * Determines for each Call node the set of possibly called methods. * Stores the result in the field 'callees' of the Call node. If the * address can not be analysed, e.g. because it is loaded from a * variable, the array contains the unknown_entity. (See * set_Call_callee()). cgana() returns the set of 'free' methods, i.e., * the methods that can be called from external or via function * pointers. This data structure must be freed with 'xfree()' by the * caller of cgana(). * * cgana() sets the callee_info_state of each graph and the program to * consistent. * * The algorithm implements roughly Static Class Hierarchy Analysis * as described in "Optimization of Object-Oriented Programs Using * Static Class Hierarchy Analysis" by Jeffrey Dean and David Grove * and Craig Chambers. * * Performs some optimizations possible by the analysed information: * - Replace (Sel-method(Alloc)) by Address. * - Replaces Sel-method by Address if the method is never overwritten. */ FIRM_API size_t cgana(ir_entity ***free_methods); /** * Frees callee information. * * Sets callee_info_state of the graph passed to none. Sets callee field * in all call nodes to NULL. Else it happens that the field contains * pointers to other than firm arrays. */ FIRM_API void free_callee_info(ir_graph *irg); /** Frees callee information for all graphs in the current program. */ FIRM_API void free_irp_callee_info(void); /** * Optimizes the address expressions passed to call nodes. * Performs only the optimizations done by cgana. */ FIRM_API void opt_call_addrs(void); /** Sets, get and remove the callee information for a Call node. * * The callee information lists all method entities that can be called * from this node. If the address expression can not be analyzed fully, * e.g., as entities can be called that are not in the compilation unit, * the array contains the unknown_entity. The array contains only entities * with peculiarity_existent, but with all kinds of visibility. The entities * not necessarily contain an irg. * * The array is only accessible if callee information is valid. See flag * in graph. * * The memory allocated for the array is managed automatically, i.e., it must * not be freed if the Call node is removed from the graph. * * @param node A Call node. */ FIRM_API int cg_call_has_callees(const ir_node *node); /** Returns the number of callees of Call node @p node. */ FIRM_API size_t cg_get_call_n_callees(const ir_node *node); /** Returns callee number @p pos of Call node @p node. */ FIRM_API ir_entity *cg_get_call_callee(const ir_node *node, size_t pos); /** Sets the full callee array. * * The passed array is copied. */ FIRM_API void cg_set_call_callee_arr(ir_node *node, size_t n, ir_entity **arr); /** Frees callee array of call node @p node */ FIRM_API void cg_remove_call_callee_arr(ir_node *node); /** @} */ #include "end.h" #endif
{ "pile_set_name": "Github" }
--no-step-log --no-duration-log --net-file=net.net.xml -a input_routes.rou.xml --seed 0
{ "pile_set_name": "Github" }
/** * Copyright (c) 2008 Greg Whalin * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the BSD license * * This library 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. * * You should have received a copy of the BSD License along with this * library. * * @author greg whalin <[email protected]> */ package com.meetup.memcached; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.List; public final class ByteBufArrayInputStream extends InputStream implements LineInputStream { private ByteBuffer[] bufs; private int currentBuf = 0; public ByteBufArrayInputStream( List<ByteBuffer> bufs ) throws Exception { this( bufs.toArray( new ByteBuffer[] {} ) ); } public ByteBufArrayInputStream( ByteBuffer[] bufs ) throws Exception { if ( bufs == null || bufs.length == 0 ) throw new Exception( "buffer is empty" ); this.bufs = bufs; for ( ByteBuffer b : bufs ) b.flip(); } public int read() { do { if ( bufs[currentBuf].hasRemaining() ) return bufs[currentBuf].get(); currentBuf++; } while ( currentBuf < bufs.length ); currentBuf--; return -1; } public int read( byte[] buf ) { int len = buf.length; int bufPos = 0; do { if ( bufs[currentBuf].hasRemaining() ) { int n = Math.min( bufs[currentBuf].remaining(), len-bufPos ); bufs[currentBuf].get( buf, bufPos, n ); bufPos += n; } currentBuf++; } while ( currentBuf < bufs.length && bufPos < len ); currentBuf--; if ( bufPos > 0 || ( bufPos == 0 && len == 0 ) ) return bufPos; else return -1; } public String readLine() throws IOException { byte[] b = new byte[1]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); boolean eol = false; while ( read( b, 0, 1 ) != -1 ) { if ( b[0] == 13 ) { eol = true; } else { if ( eol ) { if ( b[0] == 10 ) break; eol = false; } } // cast byte into char array bos.write( b, 0, 1 ); } if ( bos == null || bos.size() <= 0 ) { throw new IOException( "++++ Stream appears to be dead, so closing it down" ); } // else return the string return bos.toString().trim(); } public void clearEOL() throws IOException { byte[] b = new byte[1]; boolean eol = false; while ( read( b, 0, 1 ) != -1 ) { // only stop when we see // \r (13) followed by \n (10) if ( b[0] == 13 ) { eol = true; continue; } if ( eol ) { if ( b[0] == 10 ) break; eol = false; } } } public String toString() { StringBuilder sb = new StringBuilder( "ByteBufArrayIS: " ); sb.append( bufs.length ).append( " bufs of sizes: \n" ); for ( int i=0; i < bufs.length; i++ ) { sb.append( " " ) .append (i ).append( ": " ).append( bufs[i] ).append( "\n" ); } return sb.toString(); } }
{ "pile_set_name": "Github" }
<div binding="post"> <h1 binding="title">title</h1> default </div> <div binding="post" version="@testable.for-current-user"> <h1 binding="title">title</h1> for current user </div>
{ "pile_set_name": "Github" }
package main import ( "context" "flag" "io" "log" "math/rand" "runtime" "strings" "time" "github.com/golangplus/errors" "github.com/golangplus/sort" "github.com/golangplus/time" "github.com/daviddengcn/gcse" "github.com/daviddengcn/gcse/configs" "github.com/daviddengcn/gcse/spider/github" "github.com/daviddengcn/gcse/spider/godocorg" "github.com/daviddengcn/gcse/store" "github.com/daviddengcn/gcse/utils" "github.com/daviddengcn/gddo/doc" "github.com/daviddengcn/go-easybi" "github.com/daviddengcn/go-villa" "github.com/daviddengcn/sophie" "github.com/daviddengcn/sophie/kv" gpb "github.com/daviddengcn/gcse/shared/proto" ) var ( cDB *gcse.CrawlerDB ) func loadPackageUpdateTimes(fpDocs sophie.FsPath) (map[string]time.Time, error) { dir := kv.DirInput(fpDocs) cnt, err := dir.PartCount() if err != nil { return nil, err } pkgUTs := make(map[string]time.Time) var pkg sophie.RawString var info gcse.DocInfo for i := 0; i < cnt; i++ { it, err := dir.Iterator(i) if err != nil { return nil, err } for { if err := it.Next(&pkg, &info); err != nil { if errorsp.Cause(err) == io.EOF { break } return nil, err } pkgUTs[string(pkg)] = info.LastUpdated } } return pkgUTs, nil } func generateCrawlEntries(db *gcse.MemDB, hostFromID func(id string) string, out kv.DirOutput, pkgUTs map[string]time.Time) error { now := time.Now() type idAndCrawlingEntry struct { id string ent *gcse.CrawlingEntry } groups := make(map[string][]idAndCrawlingEntry) count := 0 type nameAndAges struct { maxName string maxAge time.Duration sumAgeHours float64 cnt int // The number of packages not in pkgUTs newCnt int } skippedVendors := 0 ages := make(map[string]nameAndAges) if err := db.Iterate(func(id string, val interface{}) error { ent, ok := val.(gcse.CrawlingEntry) if !ok { log.Printf("Wrong entry: %+v", ent) return nil } if ent.Version == gcse.CrawlerVersion && ent.ScheduleTime.After(now) { return nil } if strings.Contains(id, "/vendor/") { // Ignoring vendors skippedVendors++ return nil } host := hostFromID(id) if host != "github.com" { return nil } // check host black list if configs.NonCrawlHosts.Contain(host) { return nil } if rand.Intn(10) == 0 { // randomly set Etag to empty to fetch stars ent.Etag = "" } groups[host] = append(groups[host], idAndCrawlingEntry{ id: id, ent: &ent, }) age := now.Sub(ent.ScheduleTime) na := ages[host] if age > na.maxAge { na.maxName, na.maxAge = id, age } na.sumAgeHours += age.Hours() na.cnt++ if _, ok := pkgUTs[id]; !ok { na.newCnt++ } ages[host] = na count++ return nil }); err != nil { return errorsp.WithStacks(err) } if skippedVendors > 0 { log.Printf("skippedVendors: %d", skippedVendors) } gcse.AddBiValueAndProcess(bi.Average, "crawler.skipped_vendor_packages", skippedVendors) index := 0 for _, g := range groups { sortp.SortF(len(g), func(i, j int) bool { if pkgUTs != nil { _, inDocsI := pkgUTs[g[i].id] _, inDocsJ := pkgUTs[g[j].id] if inDocsI != inDocsJ { // The one not in docs should be crawled first. // I.e. if g[i] in doc (inDocsI = true), g[j] not in doc (inDocsJ == false), shoud return false // vice versa. return inDocsJ } } return g[i].ent.ScheduleTime.Before(g[j].ent.ScheduleTime) }, func(i, j int) { g[i], g[j] = g[j], g[i] }) if err := func(index int, ies []idAndCrawlingEntry) error { c, err := out.Collector(index) if err != nil { return err } defer c.Close() for i, ie := range ies { if err := c.Collect(sophie.RawString(ie.id), ie.ent); err != nil { return err } if i < 10 { log.Printf("id: %s, ent: %+v", ie.id, *ie.ent) } } return nil }(index, g); err != nil { log.Printf("Saving ents failed: %v", err) } index++ } for host, na := range ages { aveAge := time.Duration(na.sumAgeHours / float64(na.cnt) * float64(time.Hour)) log.Printf("%s age: max -> %v(%s), ave -> %v, new -> %v", host, na.maxAge, na.maxName, aveAge, na.newCnt) if host == "github.com" && strings.Contains(out.Path, configs.FnPackage) { gcse.AddBiValueAndProcess(bi.Average, "crawler.github_max_age.hours", int(na.maxAge.Hours())) gcse.AddBiValueAndProcess(bi.Average, "crawler.github_max_age.days", int(na.maxAge/timep.Day)) gcse.AddBiValueAndProcess(bi.Average, "crawler.github_ave_age.hours", int(aveAge.Hours())) gcse.AddBiValueAndProcess(bi.Average, "crawler.github_ave_age.days", int(aveAge/timep.Day)) gcse.AddBiValueAndProcess(bi.Average, "crawler.github_new_cnt", na.newCnt) } } log.Printf("%d entries to crawl for folder %v", count, out.Path) return nil } func syncDatabases() { utils.DumpMemStats() log.Printf("Synchronizing databases to disk...") if err := cDB.Sync(); err != nil { log.Fatalf("cdb.Sync() failed: %v", err) } utils.DumpMemStats() runtime.GC() utils.DumpMemStats() } func main() { flag.Set("log_dir", "./logs") flag.Parse() ctx := context.Background() log.Println("Running tocrawl tool, to generate crawling list") log.Println("NonCrawlHosts: ", configs.NonCrawlHosts) log.Println("CrawlGithubUpdate: ", configs.CrawlGithubUpdate) log.Println("CrawlByGodocApi: ", configs.CrawlByGodocApi) log.Printf("Using personal: %v", configs.CrawlerGithubPersonal) gcse.GithubSpider = github.NewSpiderWithToken(configs.CrawlerGithubPersonal) // Load CrawlerDB cDB = gcse.LoadCrawlerDB() // load pkgUTs pkgUTs, err := loadPackageUpdateTimes(sophie.LocalFsPath(configs.DocsDBPath())) if err != nil { log.Fatalf("loadPackageUpdateTimes failed: %v", err) } if configs.CrawlGithubUpdate || configs.CrawlByGodocApi { if configs.CrawlGithubUpdate { touchByGithubUpdates(ctx, pkgUTs) } if configs.CrawlByGodocApi { httpClient := gcse.GenHttpClient("") pkgs, err := godocorg.FetchAllPackagesInGodoc(httpClient) if err != nil { log.Fatalf("FetchAllPackagesInGodoc failed: %v", err) } gcse.AddBiValueAndProcess(bi.Max, "godoc.doc-count", len(pkgs)) log.Printf("FetchAllPackagesInGodoc returns %d entries", len(pkgs)) now := time.Now() for _, pkg := range pkgs { if !doc.IsValidRemotePath(pkg) { continue } cDB.AppendPackage(pkg, func(pkg string) bool { _, ok := pkgUTs[pkg] return ok }) site, path := utils.SplitPackage(pkg) if err := store.AppendPackageEvent(site, path, "godoc", now, gpb.HistoryEvent_Action_None); err != nil { log.Printf("UpdatePackageHistory %s %s failed: %v", site, path, err) } } } syncDatabases() } log.Printf("Package DB: %d entries", cDB.PackageDB.Count()) log.Printf("Person DB: %d entries", cDB.PersonDB.Count()) pathToCrawl := villa.Path(configs.ToCrawlPath()) kvPackage := kv.DirOutput(sophie.LocalFsPath( pathToCrawl.Join(configs.FnPackage).S())) kvPackage.Clean() if err := generateCrawlEntries(cDB.PackageDB, gcse.HostOfPackage, kvPackage, pkgUTs); err != nil { log.Fatalf("generateCrawlEntries %v failed: %v", kvPackage.Path, err) } kvPerson := kv.DirOutput(sophie.LocalFsPath( pathToCrawl.Join(configs.FnPerson).S())) kvPerson.Clean() if err := generateCrawlEntries(cDB.PersonDB, func(id string) string { site, _ := gcse.ParsePersonId(id) return site }, kvPerson, nil); err != nil { log.Fatalf("generateCrawlEntries %v failed: %v", kvPerson.Path, err) } }
{ "pile_set_name": "Github" }
/// Copyright 2016 Pinterest Inc. /// /// 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. // // @author bol ([email protected]) // #include <folly/io/async/EventBase.h> #if __GNUC__ >= 8 #include "folly/system/ThreadName.h" #else #include <folly/ThreadName.h> #endif #include <gflags/gflags.h> #include "rocksdb_replicator/rocksdb_replicator.h" DEFINE_int32(replicator_idle_iter_timeout_ms, 60 * 1000, "Timeout value after which idle cached iters are removed"); namespace replicator { RocksDBReplicator::CachedIterCleaner::CachedIterCleaner() : dbs_(), dbs_mutex_(), thread_(), evb_() { scheduleCleanup(); thread_ = std::thread([this] { if (!folly::setThreadName("IterCleaner")) { LOG(ERROR) << "Failed to setThreadName() for CachedIterCleaner thread"; } LOG(INFO) << "Starting idle iter cleanup thread ..."; this->evb_.loopForever(); LOG(INFO) << "Stopping idle iter cleanup thread ..."; }); } void RocksDBReplicator::CachedIterCleaner::scheduleCleanup() { evb_.runAfterDelay([this] { { std::lock_guard<std::mutex> g(dbs_mutex_); auto itor = dbs_.begin(); while (itor != dbs_.end()) { auto db = itor->lock(); if (db == nullptr) { itor = dbs_.erase(itor); continue; } db->cleanIdleCachedIters(); ++itor; } } this->scheduleCleanup(); }, FLAGS_replicator_idle_iter_timeout_ms); } void RocksDBReplicator::CachedIterCleaner::addDB( std::weak_ptr<ReplicatedDB> db) { std::lock_guard<std::mutex> g(dbs_mutex_); dbs_.emplace_back(std::move(db)); } void RocksDBReplicator::CachedIterCleaner::stopAndWait() { evb_.terminateLoopSoon(); thread_.join(); } } // namespace replicator
{ "pile_set_name": "Github" }
// Copyright (C) 2013 The Android Open Source Project // // 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.google.gerrit.server.restapi.access; import com.google.gerrit.extensions.registration.DynamicMap; import com.google.gerrit.extensions.restapi.IdString; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.RestCollection; import com.google.gerrit.extensions.restapi.RestView; import com.google.gerrit.extensions.restapi.TopLevelResource; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; /** REST collection that serves requests to {@code /access/}. */ @Singleton public class AccessCollection implements RestCollection<TopLevelResource, AccessResource> { private final Provider<ListAccess> list; private final DynamicMap<RestView<AccessResource>> views; @Inject public AccessCollection(Provider<ListAccess> list, DynamicMap<RestView<AccessResource>> views) { this.list = list; this.views = views; } @Override public RestView<TopLevelResource> list() { return list.get(); } @Override public AccessResource parse(TopLevelResource parent, IdString id) throws ResourceNotFoundException { throw new ResourceNotFoundException(id); } @Override public DynamicMap<RestView<AccessResource>> views() { return views; } }
{ "pile_set_name": "Github" }
<system> <name>EPIC 204221263</name> <name>K2-38</name> <rightascension>16 00 08.0583</rightascension> <declination>-23 11 21.3272</declination> <distance errorminus="2.6" errorplus="2.6">193.7</distance> <star> <name>EPIC 204221263</name> <name>TYC 6779-268-1</name> <name>2MASS J16000805-2311213</name> <name>K2-38</name> <name>Gaia DR2 6237129658760381056</name> <magB errorminus="0.246" errorplus="0.246">12.344</magB> <magV errorminus="0.03" errorplus="0.03">11.39</magV> <magJ errorminus="0.024" errorplus="0.024">9.911</magJ> <magH errorminus="0.026" errorplus="0.026">9.600</magH> <magK errorminus="0.021" errorplus="0.021">9.470</magK> <temperature errorminus="60" errorplus="60">5757</temperature> <metallicity errorminus="0.04" errorplus="0.04">0.28</metallicity> <mass errorminus="0.05" errorplus="0.05">1.07</mass> <radius errorminus="0.09" errorplus="0.09">1.10</radius> <planet> <name>EPIC 204221263 b</name> <name>K2-38 b</name> <name>Gaia DR2 6237129658760381056 b</name> <name>TYC 6779-268-1 b</name> <transittime errorminus="0.0054" errorplus="0.0054" unit="BJD">2456896.8786</transittime> <period errorminus="0.00050" errorplus="0.00050">4.01593</period> <inclination errorminus="3.08" errorplus="1.88">87.28</inclination> <radius errorminus="0.014" errorplus="0.014">0.138</radius> <semimajoraxis errorminus="0.0008" errorplus="0.0008">0.0506</semimajoraxis> <mass errorminus="0.0091" errorplus="0.0091">0.0378</mass> <istransiting>1</istransiting> <discoverymethod>transit</discoverymethod> <discoveryyear>2015</discoveryyear> <description>EPIC 204221263 is a multi-transiting system in the K2 mission campaign 2 field. Radial velocity measurements with Keck/HIRES have allowed the determination of the planetary masses. The radial velocities exhibit a linear trend indicating the presence of an additional non-transiting companion in the system.</description> <lastupdate>15/12/06</lastupdate> <list>Confirmed planets</list> </planet> <planet> <name>EPIC 204221263 c</name> <name>K2-38 c</name> <name>Gaia DR2 6237129658760381056 c</name> <name>TYC 6779-268-1 c</name> <transittime errorminus="0.0033" errorplus="0.0033" unit="BJD">2456900.4752</transittime> <period errorminus="0.00090" errorplus="0.00090">10.56103</period> <inclination errorminus="1.67" errorplus="1.00">88.61</inclination> <radius errorminus="0.026" errorplus="0.026">0.216</radius> <semimajoraxis errorminus="0.0016" errorplus="0.0016">0.0964</semimajoraxis> <mass errorminus="0.014" errorplus="0.014">0.031</mass> <istransiting>1</istransiting> <discoverymethod>transit</discoverymethod> <discoveryyear>2015</discoveryyear> <description>EPIC 204221263 is a multi-transiting system in the K2 mission campaign 2 field. Radial velocity measurements with Keck/HIRES have allowed the determination of the planetary masses. The radial velocities exhibit a linear trend indicating the presence of an additional non-transiting companion in the system.</description> <lastupdate>15/12/06</lastupdate> <list>Confirmed planets</list> </planet> </star> </system>
{ "pile_set_name": "Github" }
;; Unit tests for the (cyclone foreign) module. ;; (import (scheme base) (scheme write) (cyclone test) (cyclone foreign) (scheme cyclone util) (scheme cyclone pretty-print) ) (define *my-global* #f) (c-define-type my-string string) (c-define-type my-integer integer) (c-define-type my-integer-as-string integer string->number number->string) (c-define-type string-as-integer string number->string string->number) (test-group "foreign value" (test 3 (c-value "1 + 2" integer)) (test 4 (c-value "2 + 2" my-integer)) (test "4" (c-value "2 + 2" my-integer-as-string)) (test "test" (c-value "\"test\"" string)) ) (test-group "foreign code" (test #f *my-global*) (c-code "printf(\"test %d %d \\n\", 1, 2);" "printf(\"test %d %d %d\\n\", 1, 2, 3);" "__glo__85my_91global_85 = boolean_t;") (test #t *my-global*) (set! *my-global* 1) (test 1 *my-global*) ) ;; Must be top-level ;TODO: support custom types (arg and ret) for c-define. ; Also need to be able to support arg/ret convert optional type arguments ; Would need to generate scheme wrappers to handle these conversions (c-define scm-strlen my-integer "strlen" string) (c-define scm-strlen-str my-integer-as-string "strlen" string) ;(c-define scm-strlen "int" "strlen" string) (c-define scm-strlend double "strlen" string) (c-define scm-strlen2 integer "strlen" my-string) (c-define scm-strlen3 integer "strlen" string-as-integer) (test-group "foreign lambda" (test 15 (scm-strlen "testing 1, 2, 3")) (test 15 (scm-strlen2 "testing 1, 2, 3")) (test 15.0 (scm-strlend "testing 1, 2, 3")) (test "15" (scm-strlen-str "testing 1, 2, 3")) (test 3 (scm-strlen3 255)) ) (test-exit)
{ "pile_set_name": "Github" }
import * as React from 'react'; import { StyleSheet, css } from 'aphrodite'; import classnames from 'classnames'; import withThemeName, { ThemeName } from '../Preferences/withThemeName'; import colors from '../../configs/colors'; type Props = { value: string; onSubmitText: (value: string) => Promise<void>; className?: string; theme: ThemeName; }; type State = { value: string; focused: boolean; }; const RETURN_KEYCODE = 13; const ESCAPE_KEYCODE = 27; class EditableField extends React.Component<Props, State> { static getDerivedStateFromProps(props: Props, state: State) { if (state.value !== props.value && !state.focused) { return { value: props.value || '', }; } return null; } state = { value: this.props.value || '', focused: false, }; _handleChangeText = (e: React.ChangeEvent<HTMLInputElement>) => this.setState({ value: e.target.value }); _handleFocus = (e: React.FocusEvent<HTMLInputElement>) => { e.target.select(); this.setState({ focused: true }); }; _handleBlur = async () => { await this.props.onSubmitText(this.state.value); this.setState({ focused: false }); }; _handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.keyCode === RETURN_KEYCODE || e.keyCode === ESCAPE_KEYCODE) { (e.target as HTMLInputElement).blur(); } }; render() { return ( <div className={css(styles.container)}> <div className={classnames(css(styles.field, styles.phantom), this.props.className)}> {this.state.value.replace(/\n/g, '')} &nbsp; </div> <input onFocus={this._handleFocus} onBlur={this._handleBlur} onKeyDown={this._handleKeyDown} value={this.state.value} onChange={this._handleChangeText} className={classnames( css( styles.field, styles.editable, this.props.theme === 'dark' ? styles.editableDark : styles.editableLight ), this.props.className )} /> </div> ); } } export default withThemeName(EditableField); const styles = StyleSheet.create({ container: { display: 'flex', alignItems: 'center', maxWidth: '100%', position: 'relative', }, field: { display: 'inline-block', margin: 0, padding: '1px 6px', }, editable: { position: 'absolute', appearance: 'none', background: 'none', outline: 0, border: 0, left: 0, width: '100%', borderRadius: 0, ':focus': { boxShadow: `inset 0 0 0 1px ${colors.primary}`, }, ':hover:focus': { boxShadow: `inset 0 0 0 1px ${colors.primary}`, }, }, editableLight: { ':hover': { boxShadow: `inset 0 0 0 1px rgba(0, 0, 0, .16)`, }, }, editableDark: { ':hover': { boxShadow: `inset 0 0 0 1px rgba(255, 255, 255, .16)`, }, }, phantom: { display: 'inline-block', maxWidth: '100%', pointerEvents: 'none', whiteSpace: 'pre', overflow: 'hidden', opacity: 0, }, });
{ "pile_set_name": "Github" }
Pod::Spec.new do |s| s.name = 'CoreAardvark' s.version = '2.2.1' s.license = 'Apache License, Version 2.0' s.summary = 'Aardvark is a library that makes it dead simple to create actionable bug reports. Usable by extensions.' s.homepage = 'https://github.com/square/Aardvark' s.authors = 'Square' s.source = { :git => 'https://github.com/square/Aardvark.git', :tag => "CoreAardvark/#{ s.version.to_s }" } s.swift_version = '4.0' s.ios.deployment_target = '8.0' s.watchos.deployment_target = '3.0' s.source_files = 'CoreAardvark/**/*.{h,m,swift}' s.private_header_files = 'CoreAardvark/*_Testing.h', 'CoreAardvark/Private Categories/*.h' end
{ "pile_set_name": "Github" }
^Matched string properly results from: setting up initial state CMAKE_MATCH_0: -->01<-- CMAKE_MATCH_1: -->0<-- CMAKE_MATCH_2: -->1<-- CMAKE_MATCH_COUNT: -->2<-- Matched string properly results from: making a match inside of find_package CMAKE_MATCH_0: -->01<-- CMAKE_MATCH_1: -->0<-- CMAKE_MATCH_2: -->1<-- CMAKE_MATCH_COUNT: -->2<-- Matched nothing properly results from: making a failure inside of find_package CMAKE_MATCH_0: --><-- CMAKE_MATCH_1: --><-- CMAKE_MATCH_2: --><-- CMAKE_MATCH_COUNT: -->0<-- Matched nothing properly results from: checking after find_package CMAKE_MATCH_0: --><-- CMAKE_MATCH_1: --><-- CMAKE_MATCH_2: --><-- CMAKE_MATCH_COUNT: -->0<-- Matched nothing properly results from: clearing out results with a failing match CMAKE_MATCH_0: --><-- CMAKE_MATCH_1: --><-- CMAKE_MATCH_2: --><-- CMAKE_MATCH_COUNT: -->0<-- Matched string properly results from: making a successful match before add_subdirectory CMAKE_MATCH_0: -->01<-- CMAKE_MATCH_1: -->0<-- CMAKE_MATCH_2: -->1<-- CMAKE_MATCH_COUNT: -->2<-- Matched string properly results from: check for success in add_subdirectory CMAKE_MATCH_0: -->01<-- CMAKE_MATCH_1: -->0<-- CMAKE_MATCH_2: -->1<-- CMAKE_MATCH_COUNT: -->2<-- Matched nothing properly results from: failing inside of add_subdirectory CMAKE_MATCH_0: --><-- CMAKE_MATCH_1: --><-- CMAKE_MATCH_2: --><-- CMAKE_MATCH_COUNT: -->0<-- Matched string properly results from: ensuring the subdirectory did not interfere with the parent CMAKE_MATCH_0: -->01<-- CMAKE_MATCH_1: -->0<-- CMAKE_MATCH_2: -->1<-- CMAKE_MATCH_COUNT: -->2<--$
{ "pile_set_name": "Github" }
/** ****************************************************************************** * @file stm32f4xx_hal_rtc_ex.h * @author MCD Application Team * @version V1.1.0 * @date 19-June-2014 * @brief Header file of RTC HAL Extension module. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_RTC_EX_H #define __STM32F4xx_HAL_RTC_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup RTCEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief RTC Tamper structure definition */ typedef struct { uint32_t Tamper; /*!< Specifies the Tamper Pin. This parameter can be a value of @ref RTCEx_Tamper_Pins_Definitions */ uint32_t PinSelection; /*!< Specifies the Tamper Pin. This parameter can be a value of @ref RTCEx_Tamper_Pins_Selection */ uint32_t Trigger; /*!< Specifies the Tamper Trigger. This parameter can be a value of @ref RTCEx_Tamper_Trigger_Definitions */ uint32_t Filter; /*!< Specifies the RTC Filter Tamper. This parameter can be a value of @ref RTCEx_Tamper_Filter_Definitions */ uint32_t SamplingFrequency; /*!< Specifies the sampling frequency. This parameter can be a value of @ref RTCEx_Tamper_Sampling_Frequencies_Definitions */ uint32_t PrechargeDuration; /*!< Specifies the Precharge Duration . This parameter can be a value of @ref RTCEx_Tamper_Pin_Precharge_Duration_Definitions */ uint32_t TamperPullUp; /*!< Specifies the Tamper PullUp . This parameter can be a value of @ref RTCEx_Tamper_Pull_UP_Definitions */ uint32_t TimeStampOnTamperDetection; /*!< Specifies the TimeStampOnTamperDetection. This parameter can be a value of @ref RTCEx_Tamper_TimeStampOnTamperDetection_Definitions */ }RTC_TamperTypeDef; /* Exported constants --------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Constants * @{ */ /** @defgroup RTCEx_Backup_Registers_Definitions * @{ */ #define RTC_BKP_DR0 ((uint32_t)0x00000000) #define RTC_BKP_DR1 ((uint32_t)0x00000001) #define RTC_BKP_DR2 ((uint32_t)0x00000002) #define RTC_BKP_DR3 ((uint32_t)0x00000003) #define RTC_BKP_DR4 ((uint32_t)0x00000004) #define RTC_BKP_DR5 ((uint32_t)0x00000005) #define RTC_BKP_DR6 ((uint32_t)0x00000006) #define RTC_BKP_DR7 ((uint32_t)0x00000007) #define RTC_BKP_DR8 ((uint32_t)0x00000008) #define RTC_BKP_DR9 ((uint32_t)0x00000009) #define RTC_BKP_DR10 ((uint32_t)0x0000000A) #define RTC_BKP_DR11 ((uint32_t)0x0000000B) #define RTC_BKP_DR12 ((uint32_t)0x0000000C) #define RTC_BKP_DR13 ((uint32_t)0x0000000D) #define RTC_BKP_DR14 ((uint32_t)0x0000000E) #define RTC_BKP_DR15 ((uint32_t)0x0000000F) #define RTC_BKP_DR16 ((uint32_t)0x00000010) #define RTC_BKP_DR17 ((uint32_t)0x00000011) #define RTC_BKP_DR18 ((uint32_t)0x00000012) #define RTC_BKP_DR19 ((uint32_t)0x00000013) #define IS_RTC_BKP(BKP) (((BKP) == RTC_BKP_DR0) || \ ((BKP) == RTC_BKP_DR1) || \ ((BKP) == RTC_BKP_DR2) || \ ((BKP) == RTC_BKP_DR3) || \ ((BKP) == RTC_BKP_DR4) || \ ((BKP) == RTC_BKP_DR5) || \ ((BKP) == RTC_BKP_DR6) || \ ((BKP) == RTC_BKP_DR7) || \ ((BKP) == RTC_BKP_DR8) || \ ((BKP) == RTC_BKP_DR9) || \ ((BKP) == RTC_BKP_DR10) || \ ((BKP) == RTC_BKP_DR11) || \ ((BKP) == RTC_BKP_DR12) || \ ((BKP) == RTC_BKP_DR13) || \ ((BKP) == RTC_BKP_DR14) || \ ((BKP) == RTC_BKP_DR15) || \ ((BKP) == RTC_BKP_DR16) || \ ((BKP) == RTC_BKP_DR17) || \ ((BKP) == RTC_BKP_DR18) || \ ((BKP) == RTC_BKP_DR19)) /** * @} */ /** @defgroup RTCEx_Time_Stamp_Edges_definitions * @{ */ #define RTC_TIMESTAMPEDGE_RISING ((uint32_t)0x00000000) #define RTC_TIMESTAMPEDGE_FALLING ((uint32_t)0x00000008) #define IS_TIMESTAMP_EDGE(EDGE) (((EDGE) == RTC_TIMESTAMPEDGE_RISING) || \ ((EDGE) == RTC_TIMESTAMPEDGE_FALLING)) /** * @} */ /** @defgroup RTCEx_Tamper_Pins_Definitions * @{ */ #define RTC_TAMPER_1 RTC_TAFCR_TAMP1E #define RTC_TAMPER_2 RTC_TAFCR_TAMP2E #define IS_TAMPER(TAMPER) ((((TAMPER) & (uint32_t)0xFFFFFFF6) == 0x00) && ((TAMPER) != (uint32_t)RESET)) /** * @} */ /** @defgroup RTCEx_Tamper_Pins_Selection * @{ */ #define RTC_TAMPERPIN_PC13 ((uint32_t)0x00000000) #define RTC_TAMPERPIN_PI8 ((uint32_t)0x00010000) #define IS_RTC_TAMPER_PIN(PIN) (((PIN) == RTC_TAMPERPIN_PC13) || \ ((PIN) == RTC_TAMPERPIN_PI8)) /** * @} */ /** @defgroup RTCEx_TimeStamp_Pin_Selection * @{ */ #define RTC_TIMESTAMPPIN_PC13 ((uint32_t)0x00000000) #define RTC_TIMESTAMPPIN_PI8 ((uint32_t)0x00020000) #define IS_RTC_TIMESTAMP_PIN(PIN) (((PIN) == RTC_TIMESTAMPPIN_PC13) || \ ((PIN) == RTC_TIMESTAMPPIN_PI8)) /** * @} */ /** @defgroup RTCEx_Tamper_Trigger_Definitions * @{ */ #define RTC_TAMPERTRIGGER_RISINGEDGE ((uint32_t)0x00000000) #define RTC_TAMPERTRIGGER_FALLINGEDGE ((uint32_t)0x00000002) #define RTC_TAMPERTRIGGER_LOWLEVEL RTC_TAMPERTRIGGER_RISINGEDGE #define RTC_TAMPERTRIGGER_HIGHLEVEL RTC_TAMPERTRIGGER_FALLINGEDGE #define IS_TAMPER_TRIGGER(TRIGGER) (((TRIGGER) == RTC_TAMPERTRIGGER_RISINGEDGE) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_FALLINGEDGE) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_LOWLEVEL) || \ ((TRIGGER) == RTC_TAMPERTRIGGER_HIGHLEVEL)) /** * @} */ /** @defgroup RTCEx_Tamper_Filter_Definitions * @{ */ #define RTC_TAMPERFILTER_DISABLE ((uint32_t)0x00000000) /*!< Tamper filter is disabled */ #define RTC_TAMPERFILTER_2SAMPLE ((uint32_t)0x00000800) /*!< Tamper is activated after 2 consecutive samples at the active level */ #define RTC_TAMPERFILTER_4SAMPLE ((uint32_t)0x00001000) /*!< Tamper is activated after 4 consecutive samples at the active level */ #define RTC_TAMPERFILTER_8SAMPLE ((uint32_t)0x00001800) /*!< Tamper is activated after 8 consecutive samples at the active leve. */ #define IS_TAMPER_FILTER(FILTER) (((FILTER) == RTC_TAMPERFILTER_DISABLE) || \ ((FILTER) == RTC_TAMPERFILTER_2SAMPLE) || \ ((FILTER) == RTC_TAMPERFILTER_4SAMPLE) || \ ((FILTER) == RTC_TAMPERFILTER_8SAMPLE)) /** * @} */ /** @defgroup RTCEx_Tamper_Sampling_Frequencies_Definitions * @{ */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768 ((uint32_t)0x00000000) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 32768 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384 ((uint32_t)0x00000100) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 16384 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192 ((uint32_t)0x00000200) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 8192 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096 ((uint32_t)0x00000300) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 4096 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048 ((uint32_t)0x00000400) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 2048 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024 ((uint32_t)0x00000500) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 1024 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512 ((uint32_t)0x00000600) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 512 */ #define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256 ((uint32_t)0x00000700) /*!< Each of the tamper inputs are sampled with a frequency = RTCCLK / 256 */ #define IS_TAMPER_SAMPLING_FREQ(FREQ) (((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768)|| \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384)|| \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512) || \ ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256)) /** * @} */ /** @defgroup RTCEx_Tamper_Pin_Precharge_Duration_Definitions * @{ */ #define RTC_TAMPERPRECHARGEDURATION_1RTCCLK ((uint32_t)0x00000000) /*!< Tamper pins are pre-charged before sampling during 1 RTCCLK cycle */ #define RTC_TAMPERPRECHARGEDURATION_2RTCCLK ((uint32_t)0x00002000) /*!< Tamper pins are pre-charged before sampling during 2 RTCCLK cycles */ #define RTC_TAMPERPRECHARGEDURATION_4RTCCLK ((uint32_t)0x00004000) /*!< Tamper pins are pre-charged before sampling during 4 RTCCLK cycles */ #define RTC_TAMPERPRECHARGEDURATION_8RTCCLK ((uint32_t)0x00006000) /*!< Tamper pins are pre-charged before sampling during 8 RTCCLK cycles */ #define IS_TAMPER_PRECHARGE_DURATION(DURATION) (((DURATION) == RTC_TAMPERPRECHARGEDURATION_1RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_2RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_4RTCCLK) || \ ((DURATION) == RTC_TAMPERPRECHARGEDURATION_8RTCCLK)) /** * @} */ /** @defgroup RTCEx_Tamper_TimeStampOnTamperDetection_Definitions * @{ */ #define RTC_TIMESTAMPONTAMPERDETECTION_ENABLE ((uint32_t)RTC_TAFCR_TAMPTS) /*!< TimeStamp on Tamper Detection event saved */ #define RTC_TIMESTAMPONTAMPERDETECTION_DISABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event is not saved */ #define IS_TAMPER_TIMESTAMPONTAMPER_DETECTION(DETECTION) (((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_ENABLE) || \ ((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_DISABLE)) /** * @} */ /** @defgroup RTCEx_Tamper_Pull_UP_Definitions * @{ */ #define RTC_TAMPER_PULLUP_ENABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event saved */ #define RTC_TAMPER_PULLUP_DISABLE ((uint32_t)RTC_TAFCR_TAMPPUDIS) /*!< TimeStamp on Tamper Detection event is not saved */ #define IS_TAMPER_PULLUP_STATE(STATE) (((STATE) == RTC_TAMPER_PULLUP_ENABLE) || \ ((STATE) == RTC_TAMPER_PULLUP_DISABLE)) /** * @} */ /** @defgroup RTCEx_Wakeup_Timer_Definitions * @{ */ #define RTC_WAKEUPCLOCK_RTCCLK_DIV16 ((uint32_t)0x00000000) #define RTC_WAKEUPCLOCK_RTCCLK_DIV8 ((uint32_t)0x00000001) #define RTC_WAKEUPCLOCK_RTCCLK_DIV4 ((uint32_t)0x00000002) #define RTC_WAKEUPCLOCK_RTCCLK_DIV2 ((uint32_t)0x00000003) #define RTC_WAKEUPCLOCK_CK_SPRE_16BITS ((uint32_t)0x00000004) #define RTC_WAKEUPCLOCK_CK_SPRE_17BITS ((uint32_t)0x00000006) #define IS_WAKEUP_CLOCK(CLOCK) (((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV16) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV8) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV4) || \ ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV2) || \ ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_16BITS) || \ ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_17BITS)) #define IS_WAKEUP_COUNTER(COUNTER) ((COUNTER) <= 0xFFFF) /** * @} */ /** @defgroup RTCEx_Digital_Calibration_Definitions * @{ */ #define RTC_CALIBSIGN_POSITIVE ((uint32_t)0x00000000) #define RTC_CALIBSIGN_NEGATIVE ((uint32_t)0x00000080) #define IS_RTC_CALIB_SIGN(SIGN) (((SIGN) == RTC_CALIBSIGN_POSITIVE) || \ ((SIGN) == RTC_CALIBSIGN_NEGATIVE)) #define IS_RTC_CALIB_VALUE(VALUE) ((VALUE) < 0x20) /** * @} */ /** @defgroup RTCEx_Smooth_calib_period_Definitions * @{ */ #define RTC_SMOOTHCALIB_PERIOD_32SEC ((uint32_t)0x00000000) /*!< If RTCCLK = 32768 Hz, Smooth calibation period is 32s, else 2exp20 RTCCLK seconds */ #define RTC_SMOOTHCALIB_PERIOD_16SEC ((uint32_t)0x00002000) /*!< If RTCCLK = 32768 Hz, Smooth calibation period is 16s, else 2exp19 RTCCLK seconds */ #define RTC_SMOOTHCALIB_PERIOD_8SEC ((uint32_t)0x00004000) /*!< If RTCCLK = 32768 Hz, Smooth calibation period is 8s, else 2exp18 RTCCLK seconds */ #define IS_RTC_SMOOTH_CALIB_PERIOD(PERIOD) (((PERIOD) == RTC_SMOOTHCALIB_PERIOD_32SEC) || \ ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_16SEC) || \ ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_8SEC)) /** * @} */ /** @defgroup RTCEx_Smooth_calib_Plus_pulses_Definitions * @{ */ #define RTC_SMOOTHCALIB_PLUSPULSES_SET ((uint32_t)0x00008000) /*!< The number of RTCCLK pulses added during a X -second window = Y - CALM[8:0] with Y = 512, 256, 128 when X = 32, 16, 8 */ #define RTC_SMOOTHCALIB_PLUSPULSES_RESET ((uint32_t)0x00000000) /*!< The number of RTCCLK pulses subbstited during a 32-second window = CALM[8:0] */ #define IS_RTC_SMOOTH_CALIB_PLUS(PLUS) (((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_SET) || \ ((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_RESET)) /** * @} */ /** @defgroup RTCEx_Smooth_calib_Minus_pulses_Definitions * @{ */ #define IS_RTC_SMOOTH_CALIB_MINUS(VALUE) ((VALUE) <= 0x000001FF) /** * @} */ /** @defgroup RTCEx_Add_1_Second_Parameter_Definitions * @{ */ #define RTC_SHIFTADD1S_RESET ((uint32_t)0x00000000) #define RTC_SHIFTADD1S_SET ((uint32_t)0x80000000) #define IS_RTC_SHIFT_ADD1S(SEL) (((SEL) == RTC_SHIFTADD1S_RESET) || \ ((SEL) == RTC_SHIFTADD1S_SET)) /** * @} */ /** @defgroup RTCEx_Substract_Fraction_Of_Second_Value * @{ */ #define IS_RTC_SHIFT_SUBFS(FS) ((FS) <= 0x00007FFF) /** * @} */ /** @defgroup RTCEx_Calib_Output_selection_Definitions * @{ */ #define RTC_CALIBOUTPUT_512HZ ((uint32_t)0x00000000) #define RTC_CALIBOUTPUT_1HZ ((uint32_t)0x00080000) #define IS_RTC_CALIB_OUTPUT(OUTPUT) (((OUTPUT) == RTC_CALIBOUTPUT_512HZ) || \ ((OUTPUT) == RTC_CALIBOUTPUT_1HZ)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** * @brief Enable the RTC WakeUp Timer peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_WUTE)) /** * @brief Enable the RTC TimeStamp peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TIMESTAMP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_TSE)) /** * @brief Disable the RTC WakeUp Timer peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_WAKEUPTIMER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_WUTE)) /** * @brief Disable the RTC TimeStamp peripheral. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_TIMESTAMP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_TSE)) /** * @brief Enable the Coarse calibration process. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_COARSE_CALIB_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_DCE)) /** * @brief Disable the Coarse calibration process. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_COARSE_CALIB_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_DCE)) /** * @brief Enable the RTC calibration output. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_COE)) /** * @brief Disable the calibration output. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_COE)) /** * @brief Enable the clock reference detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CLOCKREF_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_REFCKON)) /** * @brief Disable the clock reference detection. * @param __HANDLE__: specifies the RTC handle. * @retval None */ #define __HAL_RTC_CLOCKREF_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_REFCKON)) /** * @brief Enable the RTC TimeStamp interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Enable the RTC WakeUpTimer interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disable the RTC TimeStamp interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Disable the RTC WakeUpTimer interrupt. * @param __HANDLE__: specifies the RTC handle. * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Check whether the specified RTC Tamper interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TAMP1 * @retval None */ #define __HAL_RTC_TAMPER_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC WakeUpTimer interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_WUT: WakeUpTimer A interrupt * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) /** * @brief Check whether the specified RTC TimeStamp interrupt has occurred or not. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. * This parameter can be: * @arg RTC_IT_TS: TimeStamp interrupt * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) /** * @brief Get the selected RTC TimeStamp's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC TimeStamp Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TSF * @arg RTC_FLAG_TSOVF * @retval None */ #define __HAL_RTC_TIMESTAMP_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Get the selected RTC WakeUpTimer's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC WakeUpTimer Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_WUTF * @arg RTC_FLAG_WUTWF * @retval None */ #define __HAL_RTC_WAKEUPTIMER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Get the selected RTC Tamper's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @retval None */ #define __HAL_RTC_TAMPER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Get the selected RTC shift operation's flag status. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC shift operation Flag is pending or not. * This parameter can be: * @arg RTC_FLAG_SHPF * @retval None */ #define __HAL_RTC_SHIFT_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) /** * @brief Clear the RTC Time Stamp's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TSF * @retval None */ #define __HAL_RTC_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @brief Clear the RTC Tamper's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_TAMP1F * @retval None */ #define __HAL_RTC_TAMPER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /** * @brief Clear the RTC Wake Up timer's pending flags. * @param __HANDLE__: specifies the RTC handle. * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. * This parameter can be: * @arg RTC_FLAG_WUTF * @retval None */ #define __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) /* Exported functions --------------------------------------------------------*/ /* RTC TimeStamp and Tamper functions *****************************************/ HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format); HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper); void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /* RTC Wake-up functions ******************************************************/ HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc); uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc); void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /* Extension Control functions ************************************************/ void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data); uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister); HAL_StatusTypeDef HAL_RTCEx_SetCoarseCalib(RTC_HandleTypeDef *hrtc, uint32_t CalibSign, uint32_t Value); HAL_StatusTypeDef HAL_RTCEx_DeactivateCoarseCalib(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue); HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef *hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS); HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc, uint32_t CalibOutput); HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc); /* Extension RTC features functions *******************************************/ void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc); HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_RTC_EX_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{ "pile_set_name": "Github" }
using System; using System.Diagnostics.CodeAnalysis; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewValley; namespace Pathoschild.Stardew.Common.Integrations.CustomFarmingRedux { /// <summary>The API provided by the Custom Farming Redux mod.</summary> [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "The naming convention is defined by the Custom Farming Redux mod.")] public interface ICustomFarmingApi { /********* ** Public methods *********/ /// <summary>Get metadata for a custom machine and draw metadata for an object.</summary> /// <param name="dummy">The item that would be replaced by the custom item.</param> Tuple<Item, Texture2D, Rectangle, Color> getRealItemAndTexture(StardewValley.Object dummy); } }
{ "pile_set_name": "Github" }
"PMEM file for NEW PARSER Copyright (C) 1988 Infocom, Inc. All rights reserved." <ZZPACKAGE "PMEM"> <ENTRY PMEM PMEM-ALLOC PMEM-TYPE? PMEM-RESET PM-TYPE MAKE-PM-TYPE PMEM-WORDS-USED PDEFS-INTERNAL-OBLIST PMEM-STORE-WARN PMEM-STORE-LENGTH> <INCLUDE "BASEDEFS" "PBITDEFS"> <USE "NEWSTRUC"> <SET-DEFSTRUCT-FILE-DEFAULTS> <FILE-FLAGS MDL-ZIL? ;ZAP-TO-SOURCE-DIRECTORY?> <BEGIN-SEGMENT 0> "All storage allocated by the parser looks like this; the rest of each block depends on the type field." <DEFSTRUCT PMEM (TABLE 'CONSTRUCTOR ('PRINTTYPE PRINT-PMEM) 'NODECL ('NTH ZGET) ('PUT ZPUT) ('START-OFFSET 0)) (PM-HEADER <OR FIX FALSE>) (PM-LENGTH <OR FIX FALSE> 'OFFSET 0 'NTH GETB 'PUT PUTB) (PM-TYPE-CODE <OR FIX FALSE> 'OFFSET 1 'NTH GETB 'PUT PUTB)> <MSETG PM-HEADER-LEN 1> "Only used in muddle world" <DEFSTRUCT PM-TYPE VECTOR (PMT-NAME ATOM) (PMT-CODE FIX) (PMT-LENGTH <OR FIX FALSE>) (PMT-ARGS <VECTOR [REST PM-ARG]> [])> <DEFSTRUCT PM-ARG VECTOR (PMA-NAME ATOM) (PMA-OFFS FIX) (PMA-TYPE ANY) (PMA-DEFAULT ANY)> <GDECL (PM-TYPE-COUNT) FIX (PM-LIST) LIST> <MSETG PMEM-STORE-LENGTH:FIX 180 ;(160 125 100 300)> <CONSTANT PMEM-STORE:TABLE <ITABLE ,PMEM-STORE-LENGTH>> <GLOBAL PMEM-STORE-POINTER PMEM-STORE> <GLOBAL PMEM-STORE-WORDS:NUMBER PMEM-STORE-LENGTH> ;<DEFINE-GLOBALS PMEM-GLOBALS (PMEM-STORE-POINTER:<OR TABLE FALSE> <>) (PMEM-STORE-WORDS:FIX ,PMEM-STORE-LENGTH)> <IF-P-DEBUGGING-PARSER <GLOBAL PMEM-STORE-WARN:NUMBER 50>> <DEFINE PMEM? (PTR) <AND <G=? .PTR ,PMEM-STORE> <L? .PTR <+ ,PMEM-STORE ,PMEM-STORE-LENGTH>>>> <DEFINE20 PM-TYPE (NAME:ATOM LENGTH:<OR FIX FALSE> "ARGS" STUFF "AUX" ATM CODE TYPE-OBJ (OCT ,PM-HEADER-LEN) ARGS) <SET ATM <PARSE <STRING "PM-TYPE-" <SPNAME .NAME>> 10 ,PDEFS-INTERNAL-OBLIST>> <COND (<NOT <GASSIGNED? PM-TYPE-COUNT>> <SETG PM-TYPE-COUNT 0> <SETG PM-LIST (T)>)> <SET CODE <SETG PM-TYPE-COUNT <+ ,PM-TYPE-COUNT 1>>> <SET TYPE-OBJ <MAKE-PM-TYPE 'PMT-NAME .ATM 'PMT-CODE .CODE 'PMT-LENGTH .LENGTH>> <EVAL <FORM CONSTANT <PARSE <STRING "PMEM-TYPE-" <SPNAME .NAME>> 10 ,PDEFS-INTERNAL-OBLIST> .CODE>> <PUTREST <REST ,PM-LIST <- <LENGTH ,PM-LIST> 1>> (.TYPE-OBJ)> <SETG .ATM .TYPE-OBJ> <SET ARGS <MAPF ,VECTOR <FUNCTION (ARG:<OR LIST ATOM> "AUX" NATM OFFS (TYPE ANY) (DEFAULT <>) NNATM) <COND (<TYPE? .ARG LIST> <SET NATM <1 .ARG>> <SET ARG <REST .ARG>>) (T <SET NATM .ARG> <SET ARG ()>)> <SET NATM <PARSE <STRING <SPNAME .NAME> "-" <SPNAME .NATM>> 10 ,PDEFS-INTERNAL-OBLIST>> <SET NNATM <PARSE <STRING <SPNAME .NAME> "-" <SPNAME .NATM> "-OFFSET"> 10 ,PDEFS-INTERNAL-OBLIST>> <EVAL <FORM DEFMAC .NATM (''OBJ "OPT" ''NEW) <FORM COND (<FORM ASSIGNED? NEW> <FORM FORM ZPUT '.OBJ .OCT '.NEW>) (T <FORM FORM ZGET '.OBJ .OCT>)>>> <SETG .NNATM <SET OFFS .OCT>> <SET OCT <+ .OCT 1>> <COND (<EMPTY? .ARG>) (T <SET TYPE <1 .ARG>> <COND (<NOT <LENGTH? .ARG 1>> <COND (<AND <TYPE? <SET DEFAULT <2 .ARG>> FORM> <EMPTY? .DEFAULT>> <SET DEFAULT <>>)>)> <COND (<AND <NOT <MATCH-KEY .DEFAULT NONE>> <NOT <TYPE? .DEFAULT FORM>>> <COND (<NOT <DECL? .DEFAULT .TYPE>> <COND (<DECL? .DEFAULT <FORM OR FALSE .TYPE>> <SET TYPE <FORM OR FALSE .TYPE>>) (T <ERROR DEFAULT-DOESNT-MATCH-DECL .TYPE .DEFAULT PM-TYPE>)>)>)>)> <MAKE-PM-ARG 'PMA-NAME .NATM 'PMA-OFFS .OFFS 'PMA-TYPE .TYPE 'PMA-DEFAULT .DEFAULT>> .STUFF>> <PMT-ARGS .TYPE-OBJ .ARGS>> <DEFINE20 GET-PM-TYPE (TYPE:ATOM "AUX" TEMP) <COND (<AND <GASSIGNED? .TYPE> <TYPE? ,.TYPE PM-TYPE>> ,.TYPE) (T <SET TEMP <PARSE <STRING "PM-TYPE-" <SPNAME .TYPE>> 10 ,PDEFS-INTERNAL-OBLIST>> <COND (<AND <GASSIGNED? .TEMP> <TYPE? ,.TEMP PM-TYPE>> ,.TEMP) (T <ERROR NOT-A-PMEM-TYPE!-ERRORS .TYPE>)>)>> <DEFMAC PMEM-TYPE? ('PMEM 'TYPE "OPT" 'TYPE2 "AUX" (ATM <>) (ATM2 <>)) <SET TYPE <GET-PM-TYPE .TYPE>> <COND (<ASSIGNED? TYPE2> <SET TYPE2 <GET-PM-TYPE .TYPE2>>) (T <SET TYPE2 <>>)> <COND (<NOT .TYPE2> <FORM ==? <FORM PM-TYPE-CODE .PMEM> <PMT-CODE .TYPE>>) (T <FORM OR <FORM ==? <FORM PM-TYPE .PMEM> <PMT-CODE .TYPE>> <FORM ==? <FORM PM-TYPE .PMEM> <PMT-CODE .TYPE2>>>)>> <DEFINE20 PRINT-PMEM (PMEM:PMEM "OPT" (OUTCHAN:CHANNEL .OUTCHAN) "AUX" (CODE <PM-TYPE-CODE .PMEM>) (OBJ:PM-TYPE <NTH ,PM-LIST <+ .CODE 1>>)) <PRINT-MANY .OUTCHAN PRINC "#" <PMT-NAME .OBJ> " ["> <REPEAT ((CT <PM-LENGTH .PMEM>) (N 1)) <COND (<L? <SET CT <- .CT 1>> 0> <RETURN>)> <PRIN1 <ZGET .PMEM .N>> <PRINC !\ > <SET N <+ .N 1>>> <PRINC !\]> .PMEM> <SETG PMEM-WORDS-USED 0> <GDECL (PMEM-WORDS-USED) FIX> <DEFINE PMEM-RESET ("OPT" (FULL?:<OR ATOM FALSE> T)) <COND (<G? ,PMEM-WORDS-USED 0> <SETG PMEM-WORDS-USED 0> <COPYT ,PMEM-STORE 0 <* 2 <- ,PMEM-STORE-LENGTH ,PMEM-STORE-WORDS>>>)> <SETG PMEM-STORE-WORDS ,PMEM-STORE-LENGTH> <SETG PMEM-STORE-POINTER ,PMEM-STORE> T> <DEFINE20 MATCH-KEY (FOO BAR) <AND <TYPE? .FOO ATOM> <TYPE? .BAR ATOM> <=? <SPNAME .FOO> <SPNAME .BAR>>>> <DEFMAC PMEM-ALLOC PA (TYPNAM:ATOM "ARGS" STUFF "AUX" TEMP NT:PM-TYPE BASE LENARG ATM BL) <SET NT <GET-PM-TYPE .TYPNAM>> <COND (<SET TEMP <MEMQ LENGTH .STUFF>> <SET LENARG <2 .TEMP>>) (<NOT <SET LENARG <PMT-LENGTH .NT>>> <ERROR BAD-PMEM-LENGTH-ARG!-ERRORS .TYPNAM PMEM-ALLOC>)> <SET BASE <FORM BIND ((NEW-OBJECT <FORM DO-PMEM-ALLOC <PMT-CODE .NT> .LENARG>))>> <SET BL <REST .BASE>> <REPEAT ((ARGS <PMT-ARGS .NT>) (INIT <CHTYPE <STACK <IVECTOR <* 2 <+ <LENGTH .ARGS> ,PM-HEADER-LEN>> NONE>> TABLE>) THIS-ARG OFFS:FIX FRM) <COND (<EMPTY? .STUFF> <MAPF <> <FUNCTION (ARG:PM-ARG "AUX" (IVAL <ZGET .INIT <PMA-OFFS .ARG>>)) <COND (<AND <MATCH-KEY .IVAL NONE> <MATCH-KEY <PMA-DEFAULT .ARG> NONE>> <ERROR NO-VALUE-FOR-MANDATORY-SLOT!-ERRORS .TYPNAM PMEM-ALLOC>) (<MATCH-KEY .IVAL NONE> <COND (<AND <PMA-DEFAULT .ARG> <N==? <PMA-DEFAULT .ARG> '<>> <N==? <PMA-DEFAULT .ARG> 0>> ;"PMEM-RESET zeroes memory, so if something is going to be defaulted to 0 or false, don't bother." <SET BL <REST <PUTREST .BL (<FORM <PMA-NAME .ARG> '.NEW-OBJECT <PMA-DEFAULT .ARG>>)>>>)>)>> .ARGS> <RETURN>)> <COND (<OR <NOT <TYPE? <SET ATM <1 .STUFF>> ATOM>> <AND <OR <NOT <GASSIGNED? .ATM>> <NOT <TYPE? ,.ATM FIX MACRO>>> <SET ATM <PARSE <STRING <SPNAME .TYPNAM> "-" <SPNAME .ATM>> 10 ,PDEFS-INTERNAL-OBLIST>> <OR <NOT <GASSIGNED? .ATM>> <NOT <TYPE? ,.ATM FIX MACRO>>>>> <COND (<N==? <1 .STUFF> LENGTH> <ERROR BAD-PMEM-ARG!-ERRORS .STUFF PMEM-ALLOC>)>) (T <SET FRM <EXPAND <FORM .ATM .INIT T>>> <ZPUT .INIT <3 .FRM:FORM> T> <COND (<AND <2 .STUFF> <N==? <2 .STUFF> '<>> <N==? <2 .STUFF> 0>> <SET BL <REST <PUTREST .BL (<FORM .ATM '.NEW-OBJECT <2 .STUFF>>)>>>)>)> <SET STUFF <REST .STUFF 2>>> <PUTREST .BL ('.NEW-OBJECT)> .BASE> <DEFINE DO-PMEM-ALLOC PA (TYPE:FIX LENGTH:FIX "AUX" (STOR ,PMEM-STORE-POINTER) (LEFT:FIX ,PMEM-STORE-WORDS) NEW) ;<COND (<NOT .STOR> <SET STOR ,PMEM-STORE>)> <SET LENGTH <+ .LENGTH 1>> ;"in words" <DEBUG-CHECK <G? .LENGTH .LEFT> <COND (<ERROR OUT-OF-MEMORY!-ERRORS ERRET-T-TO-ALLOCATE-MORE!-ERRORS PMEM-ALLOC> <SETG PMEM-STORE-WORDS 500> <SET LEFT 500> <PMEM-STORE-LENGTH <+ <PMEM-STORE-LENGTH> 500>> <PMEM-STORE <SET STOR <ITABLE <PMEM-STORE-LENGTH> 0>>>) (T <RETURN <> .PA>)>> <COND (<G? .LENGTH .LEFT> <P-NO-MEM-ROUTINE .TYPE> ;<RETURN <> .PA>)> <SETG PMEM-WORDS-USED <+ ,PMEM-WORDS-USED .LENGTH>> <SETG PMEM-STORE-WORDS <- .LEFT .LENGTH>> <IF-P-DEBUGGING-PARSER <COND (<G? ,PMEM-STORE-WARN ,PMEM-STORE-WORDS> <SETG PMEM-STORE-WARN ,PMEM-STORE-WORDS> <PRINTI "[Debugging info: "> <PRINTI "PMEM: "> <PRINTN ,PMEM-STORE-WARN ;,PMEM-STORE-WORDS> <PRINTI " left!]|">)>> <SETG PMEM-STORE-POINTER <ZREST .STOR <* .LENGTH 2>>> <PM-LENGTH <CHTYPE-VAL STOR PMEM> <SET LENGTH <- .LENGTH 1>>> <PM-TYPE-CODE .STOR .TYPE> .STOR> <END-SEGMENT> <ENDPACKAGE>
{ "pile_set_name": "Github" }
.. _notebook_hexagonal: =========================== Modeling Hexagonal Lattices =========================== .. only:: html .. notebook:: ../../../examples/jupyter/hexagonal-lattice.ipynb .. only:: latex IPython notebooks must be viewed in the online HTML documentation.
{ "pile_set_name": "Github" }
<!-- please add a :book: (`:book:`) to the title of this PR, and delete this line and similar ones --> <!-- What docs does this change, and why? -->
{ "pile_set_name": "Github" }
<!-- # license: 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. --> # cordova-plugin-globalization [![Build Status](https://travis-ci.org/apache/cordova-plugin-globalization.svg)](https://travis-ci.org/apache/cordova-plugin-globalization) Ten plugin uzyskuje informacje i wykonuje operacje specyficzne dla użytkownika ustawienia regionalne, język i strefa czasowa. Zwróć uwagę na różnicę między ustawień regionalnych i językowych: regionalny kontroli jak liczby, daty i godziny są wyświetlane dla regionu, podczas gdy język określa, jaki tekst w języku pojawia się jako, niezależnie od ustawień regionalnych. Często Deweloperzy używają regionalny do zarówno ustawienia, ale nie ma żadnego powodu, które użytkownik nie mógł ustawić jej język "Polski" regionalny "Francuski", tak, że tekst jest wyświetlany w angielski, ale daty, godziny, itp., są wyświetlane są one we Francji. Niestety najbardziej mobilnych platform obecnie nie wprowadzają rozróżnienia tych ustawień. Ten plugin określa globalne `navigator.globalization` obiektu. Chociaż w globalnym zasięgu, to nie dostępne dopiero po `deviceready` imprezie. document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { console.log(navigator.globalization); } ## Instalacja cordova plugin add cordova-plugin-globalization ## Obiekty * GlobalizationError ## Metody * navigator.globalization.getPreferredLanguage * navigator.globalization.getLocaleName * navigator.globalization.dateToString * navigator.globalization.stringToDate * navigator.globalization.getDatePattern * navigator.globalization.getDateNames * navigator.globalization.isDayLightSavingsTime * navigator.globalization.getFirstDayOfWeek * navigator.globalization.numberToString * navigator.globalization.stringToNumber * navigator.globalization.getNumberPattern * navigator.globalization.getCurrencyPattern ## navigator.globalization.getPreferredLanguage Znacznik języka BCP 47 uzyskać bieżący język klienta. navigator.globalization.getPreferredLanguage(successCallback, errorCallback); ### Opis Zwraca BCP 47 język zgodny Identyfikator tagu do `successCallback` z `properties` obiektu jako parametr. Obiekt powinien mieć `wartość` Właściwość `ciąg`. Jeśli tu jest błąd w języku, następnie `errorCallback` wykonuje z `GlobalizationError` obiektu jako parametr. Oczekiwany kod błędu to `GlobalizationError.UNKNOWN_ERROR`. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * Firefox OS * iOS * Windows Phone 8 * Windows 8 * Windows * Przeglądarka ### Przykład Gdy przeglądarka jest ustawiony język `En US`, to należy wyświetlić wyskakujące okno z tekstem `Język: en US`: navigator.globalization.getPreferredLanguage( function (language) {alert('language: ' + language.value + '\n');}, function () {alert('Error getting language\n');} ); ### Dziwactwa Androida * Zwraca ISO 639-1 języka dwuliterowy kod, wielkie litery ISO 3166-1 kraj kod i wariant oddzielonych myślnikami. Przykłady: "pl", "pl", "US" ### Windows Phone 8 dziwactwa * Zwraca ISO 639-1 dwuliterowy kod języka i kod ISO 3166-1 kraju regionalne wariant odpowiadający "Język" ustawienie, oddzielone myślnikiem. * Należy zauważyć, że regionalne wariant jest Właściwość ustawieniem "Language" i nie określona przez ustawienie "Kraj" niepowiązanych na Windows Phone. ### Windows dziwactwa * Zwraca ISO 639-1 dwuliterowy kod języka i kod ISO 3166-1 kraju regionalne wariant odpowiadający "Język" ustawienie, oddzielone myślnikiem. ### Quirks przeglądarki * Falls back on getLocaleName ## navigator.globalization.getLocaleName Zwraca znacznik zgodny z BCP 47 dla klienta bieżące ustawienia regionalne. navigator.globalization.getLocaleName(successCallback, errorCallback); ### Opis Zwraca ciąg identyfikatora regionalny zgodny z BCP 47 `successCallback` z `properties` obiektu jako parametr. Obiekt powinien mieć `wartość` Właściwość `ciąg`. Tag regionalnych będzie się składać z ma³e dwuliterowy kod języka, dwie litery wielkie litery kodu kraju i (nieokreślone) kod wariantu, oddzielone myślnikiem. Jeśli tu jest błąd ustawienia regionalne, a następnie `errorCallback` wykonuje z `GlobalizationError` obiektu jako parametr. Oczekiwany kod błędu to `GlobalizationError.UNKNOWN_ERROR`. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * Firefox OS * iOS * Windows Phone 8 * Windows 8 * Windows * Przeglądarka ### Przykład Gdy przeglądarka jest ustawiona na `Pl pl` regionalne, wyświetla okno popup z tekstem `regionalny: en US`. navigator.globalization.getLocaleName( function (locale) {alert('locale: ' + locale.value + '\n');}, function () {alert('Error getting locale\n');} ); ### Dziwactwa Androida * Java nie rozróżnia się między zestaw "language" i ustaw "locale", więc ta metoda jest zasadniczo taka sama, jak `navigator.globalizatin.getPreferredLanguage()`. ### Windows Phone 8 dziwactwa * Zwraca ISO 639-1 dwuliterowy kod języka i kod ISO 3166-1 kraju regionalne wariant odpowiednie ustawienie "Format regionalny", oddzielone myślnikiem. ### Windows dziwactwa * Regionalny można zmienić w panelu sterowania-> zegar, język i Region-> w regionie-> formaty-> Format i w ustawieniach-> w regionie-> Format regionalny na Windows Phone 8.1. ### Quirks przeglądarki * IE zwraca ustawienia regionalne systemu operacyjnego. Chrome i Firefox zwraca znacznik języka przeglądarki. ## navigator.globalization.dateToString Zwraca daty sformatowane jako ciąg regionalny klient i strefa czasowa. navigator.globalization.dateToString(date, successCallback, errorCallback, options); ### Opis Zwraca datę sformatowany `ciąg` poprzez `wartość` Właściwość dostępne od obiektu przekazane jako parametr do `successCallback`. Parametr przychodzący `date` powinny być typu `Date`. Jeśli występuje błąd formatowania daty, a następnie `errorCallback` wykonuje z obiektu `GlobalizationError` jako parametr. Oczekiwany kod błędu to `GlobalizationError.FORMATTING_ERROR`. `Opcje` parametr jest opcjonalny, a jego wartości domyślne są: {formatLength:'short', selector:'date and time'} `options.formatLength` może być `short`, `medium`, `long` lub `full`. `options.selector` może być `date`, `time` lub `date and time`. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * Firefox OS * iOS * Windows Phone 8 * Windows 8 * Windows * Przeglądarka ### Przykład Jeśli przeglądarka jest ustawiona na `pl` regionalne, to wyświetla okno dialogowe popup z tekst podobny do `Data: 9/25/2012 4:21 PM` przy użyciu opcji domyślnych: navigator.globalization.dateToString( new Date(), function (date) { alert('date: ' + date.value + '\n'); }, function () { alert('Error getting dateString\n'); }, { formatLength: 'short', selector: 'date and time' } ); ### Dziwactwa Androida * `formatLength` opcje są podzbiorem Unicode [UTS #35](http://unicode.org/reports/tr35/tr35-4.html). Domyślnie opcja `Krótki` zależy od użytkownika format daty wybranej w `Ustawienia -> System -> Data i czas -> Wybierz format daty`, które zapewniają wzór `roku` tylko z 4 cyfr, nie 2 cyfry. Oznacza to, że nie jest to całkowicie dostosowane do [ICU](http://demo.icu-project.org/icu-bin/locexp?d_=en_US&_=en_US). ### Windows Phone 8 dziwactwa * Opcja `formatLength` obsługuje tylko `short` i `full` wartości. * Wzór dla selektora "date and time" jest zawsze pełna datetime format. * Zwracana wartość może być nie całkowicie dostosowane z ICU w zależności od ustawienia regionalne użytkownika. ### Windows dziwactwa * Opcja `formatLength` obsługuje tylko `short` i `full` wartości. * Wzór dla selektora "date and time" jest zawsze pełna datetime format. * Zwracana wartość może być nie całkowicie dostosowane z ICU w zależności od ustawienia regionalne użytkownika. ### Quirks przeglądarki * Tylko 79 ustawienia regionalne są obsługiwane, ponieważ moment.js jest używane w tej metodzie. * Zwracana wartość może być nie całkowicie dostosowane z ICU w zależności od ustawienia regionalne użytkownika. * `time` wyboru obsługuje `full` i `short` formatLength tylko. ### Firefox OS dziwactwa * `formatLength` nie jest rozróżnienie, `long` i `full` * tylko jedna metoda wyświetlania daty (nie `long` lub `full` wersja) ## navigator.globalization.getCurrencyPattern Zwraca ciąg wzór do formatu i analizy wartości walut według preferencji użytkownika klienta i kod waluty ISO 4217. navigator.globalization.getCurrencyPattern(currencyCode, successCallback, errorCallback); ### Opis Zwraca wzór do `successCallback` z `properties` obiektu jako parametr. Obiekt powinien zawierać następujące właściwości: * **pattern**: wzór waluty wobec układ graficzny i analizy wartości waluty. Wzory wykonaj [techniczny Standard Unicode #35](http://unicode.org/reports/tr35/tr35-4.html). *(String)* * **code**: kod waluty The ISO 4217 dla wzorca. *(String)* * **fraction**: liczba cyfr ułamkowych podczas analizowania i Formatowanie walutowe. *(Liczba)* * **rounding**: Zaokrąglenie przyrost podczas analizowania i formatowanie. *(Liczba)* * **decimal**: symbolu dziesiętnego używać do analizowania i formatowanie. *(String)* * **grouping**: symbol grupowania dla analizy i formatowanie. *(String)* Parametr przychodzący `currencyCode` powinna być `ciągiem` jednego z kodów ISO 4217 waluty, na przykład "USD". Jeśli występuje błąd uzyskania wzorzec, a następnie `errorCallback` wykonuje z obiektu `GlobalizationError` jako parametr. Oczekiwany kod błędu to `GlobalizationError.FORMATTING_ERROR`. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * iOS * Windows 8 * Windows ### Przykład Gdy przeglądarka jest ustawiona na `pl` regionalne i wybranej waluty dolarów amerykańskich, w tym przykładzie wyświetla wyskakujące okno z tekstem podobne do wyników, które należy wykonać: navigator.globalization.getCurrencyPattern( 'USD', function (pattern) { alert('pattern: ' + pattern.pattern + '\n' + 'code: ' + pattern.code + '\n' + 'fraction: ' + pattern.fraction + '\n' + 'rounding: ' + pattern.rounding + '\n' + 'decimal: ' + pattern.decimal + '\n' + 'grouping: ' + pattern.grouping); }, function () { alert('Error getting pattern\n'); } ); Oczekiwany wynik: pattern: $#,##0.##;($#,##0.##) code: USD fraction: 2 rounding: 0 decimal: . grouping: , ### Windows dziwactwa * Obsługiwane są tylko właściwości "code" i "fraction" ## navigator.globalization.getDateNames Zwraca tablicę nazwy miesięcy i dni tygodnia, w zależności od preferencji użytkownika klienta i kalendarz. navigator.globalization.getDateNames(successCallback, errorCallback, options); ### Opis Zwraca tablicę nazw do `successCallback` z `properties` obiektu jako parametr. Ten obiekt zawiera właściwość `wartość` z `tablicy` wartości `ciąg`. Nazwy funkcji Tablica albo od pierwszego miesiąca w roku lub pierwszego dnia tygodnia, w zależności od wybranej opcji. Jeśli występuje błąd uzyskiwania nazwy, a następnie `errorCallback` wykonuje z obiektu `GlobalizationError` jako parametr. Oczekiwany kod błędu to `GlobalizationError.UNKNOWN_ERROR`. `Opcje` parametr jest opcjonalny, a jego wartości domyślne są: {type:'wide', item:'months'} Wartość `options.type` może być `narrow` lub `wide`. Wartość `options.item` może być `months` lub `days`. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * Firefox OS * iOS * Windows Phone 8 * Windows 8 * Windows * Przeglądarka ### Przykład Gdy przeglądarka jest ustawiona na `pl_PL` ustawień regionalnych, w tym przykładzie wyświetla serię dwunastu lud dialogi, jeden raz na miesiąc, tekst podobny do `miesiąca: stycznia`: navigator.globalization.getDateNames( function (names) { for (var i = 0; i < names.value.length; i++) { alert('month: ' + names.value[i] + '\n'); } }, function () { alert('Error getting names\n'); }, { type: 'wide', item: 'months' } ); ### Firefox OS dziwactwa * `options.type` obsługuje wartość `genitive`, ważne dla niektórych języków ### Windows Phone 8 dziwactwa * Szereg miesięcy zawiera 13 elementów. * Zwróconej tablicy może nie całkowicie dostosowane z ICU w zależności od ustawienia regionalne użytkownika. ### Windows dziwactwa * Szereg miesięcy zawiera 12 elementów. * Zwróconej tablicy może nie całkowicie dostosowane z ICU w zależności od ustawienia regionalne użytkownika. ### Quirks przeglądarki * Data nazwy nie są całkowicie dostosowane do ICU * Szereg miesięcy zawiera 12 elementów. ## navigator.globalization.getDatePattern Zwraca ciąg wzór do formatu i analizy dat według preferencji użytkownika klienta. navigator.globalization.getDatePattern(successCallback, errorCallback, options); ### Opis Zwraca wzór do `successCallback`. Obiekt przekazywana jako parametr zawiera następujące właściwości: * **pattern**: data i godzina wzór do formatu i analizować daty. Wzory wykonaj [techniczny Standard Unicode #35](http://unicode.org/reports/tr35/tr35-4.html). *(String)* * **timezone**: skróconą nazwę strefy czasowej na klienta. *(String)* * **utc_offset**: aktualna różnica w sekundach między klienta strefy czasowej i skoordynowanego czasu uniwersalnego. *(Liczba)* * **dst_offset**: bieżącego przesunięcie czasu w sekundach między klienta nie uwzględniaj w strefę czasową i klienta światło dzienne oszczędności w strefa czasowa. *(Liczba)* Jeśli występuje błąd uzyskiwania wzór, `errorCallback` wykonuje się z obiektem `GlobalizationError` jako parametr. Oczekiwany kod błędu to `GlobalizationError.PATTERN_ERROR`. Parametr `options` jest opcjonalne i domyślnie następujące wartości: {formatLength:'short', selector:'date and time'} `options.formatLength` może być `short`, `medium`, `long` lub `full`. `options.selector` może być `date`, `time` lub `date and time`. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * iOS * Windows Phone 8 * Windows 8 * Windows * Przeglądarka ### Przykład Gdy przeglądarka jest ustawiona na `pl` regionalne, w tym przykładzie wyświetla lud dialog z tekstu takie jak `wzór: za/rrrr g: mm`: function checkDatePattern() { navigator.globalization.getDatePattern( function (date) { alert('pattern: ' + date.pattern + '\n'); }, function () { alert('Error getting pattern\n'); }, { formatLength: 'short', selector: 'date and time' } ); } ### Windows Phone 8 dziwactwa * Opcja `formatLength` obsługuje tylko `short` i `full` wartości. * `pattern` dla `date and time` wzór zwraca tylko pełne datetime format. * `timezone` zwraca nazwę strefy w pełnym wymiarze czasu. * Właściwość `dst_offset` nie jest obsługiwany, a zawsze zwraca zero. * Wzór może nie całkowicie dostosowane z ICU w zależności od ustawienia regionalne użytkownika. ### Windows dziwactwa * Opcja `formatLength` obsługuje tylko `short` i `full` wartości. * `pattern` dla `date and time` wzór zwraca tylko pełne datetime format. * `timezone` zwraca nazwę strefy w pełnym wymiarze czasu. * Właściwość `dst_offset` nie jest obsługiwany, a zawsze zwraca zero. * Wzór może nie całkowicie dostosowane z ICU w zależności od ustawienia regionalne użytkownika. ### Quirks przeglądarki * Właściwość 'pattern' nie jest obsługiwane i zwraca pusty ciąg. * Tylko chrom zwraca Właściwość 'strefa czasowa'. Jego format jest "Częścią świata/{City}". Inne przeglądarki zwraca pusty ciąg. ## navigator.globalization.getFirstDayOfWeek Zwraca pierwszy dzień tygodnia według kalendarza i preferencje użytkownika klienta. navigator.globalization.getFirstDayOfWeek(successCallback, errorCallback); ### Opis Dni tygodnia są numerowane począwszy od 1, gdzie 1 zakłada się niedziela. Zwraca dzień do `successCallback` z `properties` obiektu jako parametr. Obiekt powinien mieć `wartość` Właściwość z wartością `liczby`. Jeśli występuje błąd uzyskania wzorzec, a następnie `errorCallback` wykonuje z obiektu `GlobalizationError` jako parametr. Oczekiwany kod błędu to `GlobalizationError.UNKNOWN_ERROR`. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * Firefox OS * iOS * Windows Phone 8 * Windows 8 * Windows * Przeglądarka ### Przykład Gdy przeglądarka jest ustawiona na `pl` regionalne, wyświetla okno popup z tekst podobny do `dzień: 1`. navigator.globalization.getFirstDayOfWeek( function (day) {alert('day: ' + day.value + '\n');}, function () {alert('Error getting day\n');} ); ### Windows dziwactwa * Na Windows 8.0/8.1 wartości zależy od użytkownika "Kalendarz preferencje. Na Windows Phone 8.1 wartości zależy od bieżących ustawień regionalnych. ### Quirks przeglądarki * Tylko 79 ustawienia regionalne są obsługiwane, ponieważ moment.js jest używane w tej metodzie. ## navigator.globalization.getNumberPattern Zwraca ciąg wzór do formatu i analizować liczby preferencji użytkownika klienta. navigator.globalization.getNumberPattern(successCallback, errorCallback, options); ### Opis Zwraca wzór do `successCallback` z `Właściwości` obiektu jako parametr. Ten obiekt zawiera następujące właściwości: * **pattern**: wzorzec numeru do formatu i analizowania liczb. Wzory wykonaj [techniczny Standard Unicode #35](http://unicode.org/reports/tr35/tr35-4.html). *(String)* * **symbol**: symbolem podczas formatowania i analizy, takie jak procent lub waluta symbol. *(String)* * **fraction**: liczba cyfr ułamkowych podczas analizowania i Formatowanie walutowe. *(Liczba)* * **rounding**: Zaokrąglenie przyrost podczas analizowania i formatowanie. *(Liczba)* * **positive**: symbol dla liczb dodatnich, gdy formatowanie i analizy. *(String)* * **negative**: symbol liczb ujemnych podczas analizowania i formatowanie. *(String)* * **decimal**: symbolu dziesiętnego używać do analizowania i formatowanie. *(String)* * **grouping**: symbol grupowania dla analizy i formatowanie. *(String)* Jeśli występuje błąd uzyskania wzorzec, a następnie `errorCallback` wykonuje z obiektu `GlobalizationError` jako parametr. Oczekiwany kod błędu to `GlobalizationError.PATTERN_ERROR`. `options` parametr jest opcjonalny, a wartości domyślne są: {type:'decimal'} `Options.type` może być `decimal`, `percent` lub `currency`. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * iOS * Windows Phone 8 * Windows 8 * Windows * Przeglądarka ### Przykład Gdy przeglądarka jest ustawiona na `pl` regionalne, to należy wyświetlić wyskakujące okno z tekstem podobne do wyników, które należy wykonać: navigator.globalization.getNumberPattern( function (pattern) {alert('pattern: ' + pattern.pattern + '\n' + 'symbol: ' + pattern.symbol + '\n' + 'fraction: ' + pattern.fraction + '\n' + 'rounding: ' + pattern.rounding + '\n' + 'positive: ' + pattern.positive + '\n' + 'negative: ' + pattern.negative + '\n' + 'decimal: ' + pattern.decimal + '\n' + 'grouping: ' + pattern.grouping);}, function () {alert('Error getting pattern\n');}, {type:'decimal'} ); Wyniki: pattern: #,##0.### symbol: . fraction: 0 rounding: 0 positive: negative: - decimal: . grouping: , ### Windows Phone 8 dziwactwa * Właściwość `pattern` nie jest obsługiwane i zwraca pusty ciąg. * `fraction` Właściwość nie jest obsługiwany i zwraca zero. ### Windows dziwactwa * Właściwość `pattern` nie jest obsługiwane i zwraca pusty ciąg. ### Quirks przeglądarki * getNumberPattern jest obsługiwany w Chrome tylko; tylko właściwości zdefiniowane jest `pattern`. ## navigator.globalization.isDayLightSavingsTime Wskazuje, czy czas letni jest obowiązująca dla danej daty za pomocą klienta strefy czasowej i kalendarz. navigator.globalization.isDayLightSavingsTime(date, successCallback, errorCallback); ### Opis Wskazuje, czy czas letni jest w efekcie do `successCallback` z `properties` obiektu jako parametr. Obiekt powinien mieć wartość `Boolean` Właściwość `dst`. Wartość `true` wskazuje, że czas letni jest obowiązującą w danym dniu, a `wartość false` wskazuje, że to nie jest. Przychodzące parametr `date` powinny być typu `Date`. Jeśli występuje błąd odczytu daty, a następnie wykonuje `errorCallback`. Oczekiwany kod błędu to `GlobalizationError.UNKNOWN_ERROR`. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * Firefox OS * iOS * Windows Phone 8 * Windows 8 * Windows * Przeglądarka ### Przykład W okresie letnim i jeśli przeglądarka jest ustawiona na timezone DST-włączone, to należy wyświetlić wyskakujące okno z tekstem podobne do `dst: prawdziwe`: navigator.globalization.isDayLightSavingsTime( new Date(), function (date) {alert('dst: ' + date.dst + '\n');}, function () {alert('Error getting names\n');} ); ## navigator.globalization.numberToString Zwraca liczby sformatowane jako ciąg preferencji użytkownika klienta. navigator.globalization.numberToString(number, successCallback, errorCallback, options); ### Opis Zwraca sformatowany ciąg liczb do `successCallback` z `properties` obiektu jako parametr. Obiekt powinien mieć `wartość` Właściwość `ciąg`. Jeśli występuje błąd formatowanie numeru, a następnie `errorCallback` wykonuje z obiektu `GlobalizationError` jako parametr. Oczekiwany kod błędu to `GlobalizationError.FORMATTING_ERROR`. `Opcje` parametr jest opcjonalny, a jego wartości domyślne są: {type:'decimal'} `options.type` może być "decimal", "percent" lub "currency". ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * iOS * Windows Phone 8 * Windows 8 * Windows * Przeglądarka ### Przykład Gdy przeglądarka jest ustawiona na `pl` regionalne, wyświetla okno popup z tekst podobny do `numer: 3.142`: navigator.globalization.numberToString( 3.1415926, function (number) {alert('number: ' + number.value + '\n');}, function () {alert('Error getting number\n');}, {type:'decimal'} ); ### Windows dziwactwa * 8.0 systemu Windows nie obsługuje zaokrąglania liczb, więc wartości nie będzie być zaokrąglane automatycznie. * Windows 8.1 i Windows Phone 8.1 część ułamkowa jest obcinany zamiast zaokrąglone w przypadku `procent` liczby typu dlatego ułamkowe cyfr licznika jest równa 0. * `percent` liczby nie są pogrupowane, jak nie można analizować w stringToNumber, jeśli zgrupowane. ### Quirks przeglądarki * `currency` typ nie jest obsługiwany. ## navigator.globalization.stringToDate Analizuje daty sformatowane jako ciąg, według preferencji użytkownika i strefa czasowa klient, kalendarz klienta i zwraca odpowiedni obiekt date. navigator.globalization.stringToDate(dateString, successCallback, errorCallback, options); ### Opis Zwraca datę do sukcesu wywołanie zwrotne z `Właściwości` obiektu jako parametr. Obiekt powinien mieć następujące właściwości: * **year**: rok czterocyfrowy. *(Liczba)* * **month**: miesiąc od (0-11). *(Liczba)* * **day**: dzień z (1-31). *(Liczba)* * **hour**: godzina od (0-23). *(Liczba)* * **minute**: odległości od (0-59). *(Liczba)* * **second**: drugi od (0-59). *(Liczba)* * **milisecond**: milisekund (od 0-999), nie jest dostępna na wszystkich platformach. *(Liczba)* Parametr przychodzący `dateString` powinny być typu `String`. Parametr `options` jest opcjonalne i domyślnie następujące wartości: {formatLength:'short', selector:'date and time'} `options.formatLength` może być `short`, `medium`, `long` lub `full`. `options.selector` może być `date`, `time` lub `date and time`. Jeśli występuje błąd podczas analizowania ciągu daty, a następnie `errorCallback` wykonuje z obiektu `GlobalizationError` jako parametr. Oczekiwany kod błędu to `GlobalizationError.PARSING_ERROR`. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * Firefox OS * iOS * Windows Phone 8 * Windows 8 * Windows * Przeglądarka ### Przykład Gdy przeglądarka jest ustawiona na `pl` regionalne, to wyświetla wyskakujące okno z tekstem podobne do `miesiąca: 8 dzień: 25 rok: 2012`. Należy zauważyć, że miesiąc, liczba całkowita jest jeden mniej niż ciąg, jako miesiąc liczba całkowita reprezentuje indeks tablicy. navigator.globalization.stringToDate( '9/25/2012', function (date) {alert('month:' + date.month + ' day:' + date.day + ' year:' + date.year + '\n');}, function () {alert('Error getting date\n');}, {selector: 'date'} ); ### Windows Phone 8 dziwactwa * Opcja `formatLength` obsługuje tylko `short` i `full` wartości. * Wzór dla selektora "date and time" jest zawsze pełna datetime format. * Parametr przychodzący `dateString` powinna zostać utworzona zgodnie z wzorcem, zwrócony przez getDatePattern. Ten wzór może być nie całkowicie dostosowane z ICU w zależności od ustawienia regionalne użytkownika. ### Windows dziwactwa * Opcja `formatLength` obsługuje tylko `short` i `full` wartości. * Wzór dla selektora "date and time" jest zawsze pełna datetime format. * Parametr przychodzący `dateString` powinna zostać utworzona zgodnie z wzorcem, zwrócony przez getDatePattern. Ten wzór może być nie całkowicie dostosowane z ICU w zależności od ustawienia regionalne użytkownika. ### Quirks przeglądarki * Tylko 79 ustawienia regionalne są obsługiwane, ponieważ moment.js jest używane w tej metodzie. * Ciąg przychodzących powinny być dostosowane z `dateToString` format wyjściowy i może nie całkowicie dostosowane do ICU w zależności od ustawienia regionalne użytkownika. * `time` wyboru obsługuje `full` i `short` formatLength tylko. ## navigator.globalization.stringToNumber Analizuje liczby sformatowane jako ciąg preferencji użytkownika klienta i zwraca odpowiedni numer. navigator.globalization.stringToNumber(string, successCallback, errorCallback, options); ### Opis Zwraca liczbę do `successCallback` z `properties` obiektu jako parametr. Obiekt powinien mieć `wartość` Właściwość z wartością `liczby`. Jeśli występuje błąd podczas analizowania ciągu liczb, a następnie `errorCallback` wykonuje z obiektu `GlobalizationError` jako parametr. Oczekiwany kod błędu to `GlobalizationError.PARSING_ERROR`. Parametr `options` jest opcjonalne i domyślnie następujące wartości: {type:'decimal'} `Options.type` może być `decimal`, `percent` lub `currency`. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * iOS * Windows Phone 8 * Windows 8 * Windows ### Przykład Gdy przeglądarka jest ustawiona na `pl` regionalne, to należy wyświetlić wyskakujące okno z tekstem podobne do `numer: 1234.56`: navigator.globalization.stringToNumber( '1234.56', function (number) {alert('number: ' + number.value + '\n');}, function () {alert('Error getting number\n');}, {type:'decimal'} ); ### Windows Phone 8 dziwactwa * W przypadku `percent` typ zwracanej wartości jest nie dzielony przez 100. ### Windows dziwactwa * Ciąg musi ściśle odpowiadać format ustawień regionalnych. Na przykład symbol procentu powinny być oddzielone przez miejsce na "en US" ustawienia regionalne, jeśli typ parametru jest "procent". * `percent` liczby nie muszą być zgrupowane do być analizowany poprawnie. ## GlobalizationError Obiekt reprezentujący błąd z API globalizacji. ### Właściwości * **code**: Jeden z następujących kodów oznaczających typ błędu *(Liczba)* * GlobalizationError.UNKNOWN_ERROR: 0 * GlobalizationError.FORMATTING_ERROR: 1 * GlobalizationError.PARSING_ERROR: 2 * GlobalizationError.PATTERN_ERROR: 3 * **message**: komunikatu tekstowego, który zawiera wyjaśnienie błędu lub szczegóły *(String)* ### Opis Ten obiekt jest tworzona i wypełniane przez Cordova i wrócił do wywołania zwrotnego w przypadku błędu. ### Obsługiwane platformy * Amazon Fire OS * Android * BlackBerry 10 * Firefox OS * iOS * Windows Phone 8 * Windows 8 * Windows ### Przykład Gdy błąd wywołania zwrotnego następujące wykonuje, wyświetla okno popup z tekst podobny do `kod: 3` i `wiadomość:` function errorCallback(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); };
{ "pile_set_name": "Github" }
#!/bin/ksh -p # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # # Copyright (c) 2013, 2016 by Delphix. All rights reserved. # . $STF_SUITE/include/libtest.shlib # # DESCRIPTION: # Create as many directories with 50 big files each until the file system # is full. The zfs file system should be stable and works well. # # STRATEGY: # 1. Create a pool & dataset # 2. Make directories in the zfs file system # 3. Create 50 big files in each directories # 4. Test case exit when the disk is full. # verify_runnable "both" function cleanup { destroy_dataset $TESTPOOL/$TESTFS wait_freeing $TESTPOOL sync_pool $TESTPOOL zfs create -o mountpoint=$TESTDIR $TESTPOOL/$TESTFS } typeset -i retval=0 log_assert "Creating directories with 50 big files in each, until file system "\ "is full." log_onexit cleanup typeset -i bytes=8192 typeset -i num_writes=300000 typeset -i dirnum=50 typeset -i filenum=50 fill_fs "" $dirnum $filenum $bytes $num_writes retval=$? if (( retval == 28 )); then log_note "No space left on device." elif (( retval != 0 )); then log_fail "Unexpected exit: $retval" fi log_pass "Write big files in a directory succeeded."
{ "pile_set_name": "Github" }
<?php namespace Solarium\Tests\Core; use PHPUnit\Framework\TestCase; use Solarium\Core\Configurable; use Solarium\Exception\RuntimeException; class ConfigurableTest extends TestCase { public function testConstructorNoConfig() { $configTest = new ConfigTest(); $defaultOptions = [ 'option1' => 1, 'option2' => 'value 2', ]; $this->assertSame($configTest->getOptions(), $defaultOptions); } public function testConstructorWithObject() { $configTest = new ConfigTest(new MyConfigObject()); // the default options should be merged with the constructor values, // overwriting any default values. $expectedOptions = [ 'option1' => 1, 'option2' => 'newvalue2', 'option3' => 3, ]; $this->assertSame($expectedOptions, $configTest->getOptions()); } public function testConstructorWithArrayConfig() { $configTest = new ConfigTest( ['option2' => 'newvalue2', 'option3' => 3] ); // the default options should be merged with the constructor values, // overwriting any default values. $expectedOptions = [ 'option1' => 1, 'option2' => 'newvalue2', 'option3' => 3, ]; $this->assertSame($expectedOptions, $configTest->getOptions()); } public function testGetOption() { $configTest = new ConfigTest(); $this->assertSame(1, $configTest->getOption('option1')); } public function testGetOptionWIthInvalidName() { $configTest = new ConfigTest(); $this->assertNull($configTest->getOption('invalidoptionname')); } public function testInitialisation() { $this->expectException(RuntimeException::class); new ConfigTestInit(); } public function testSetOptions() { $configTest = new ConfigTest(); $configTest->setOptions(['option2' => 2, 'option3' => 3]); $this->assertSame( ['option1' => 1, 'option2' => 2, 'option3' => 3], $configTest->getOptions() ); } public function testSetOptionsWithOverride() { $configTest = new ConfigTest(); $configTest->setOptions(['option2' => 2, 'option3' => 3], true); $this->assertSame( ['option2' => 2, 'option3' => 3], $configTest->getOptions() ); } } class ConfigTest extends Configurable { protected $options = [ 'option1' => 1, 'option2' => 'value 2', ]; } class ConfigTestInit extends ConfigTest { protected function init() { throw new RuntimeException('test init'); } } class MyConfigObject { public function toArray() { return ['option2' => 'newvalue2', 'option3' => 3]; } }
{ "pile_set_name": "Github" }
/subsystem=datasources/jdbc-driver=db2:add(driver-name=db2,driver-module-name=com.ibm.db2) data-source add --name=pacsds --driver-name=db2 --jndi-name=java:/PacsDS \ --connection-url=jdbc:db2://localhost:50000/pacsdb \ --user-name=pacs --password=<user-password>
{ "pile_set_name": "Github" }
package govalidator import ( "encoding/json" "fmt" "reflect" "strconv" ) // ToString convert the input to a string. func ToString(obj interface{}) string { res := fmt.Sprintf("%v", obj) return string(res) } // ToJSON convert the input to a valid JSON string func ToJSON(obj interface{}) (string, error) { res, err := json.Marshal(obj) if err != nil { res = []byte("") } return string(res), err } // ToFloat convert the input string to a float, or 0.0 if the input is not a float. func ToFloat(str string) (float64, error) { res, err := strconv.ParseFloat(str, 64) if err != nil { res = 0.0 } return res, err } // ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer. func ToInt(value interface{}) (res int64, err error) { val := reflect.ValueOf(value) switch value.(type) { case int, int8, int16, int32, int64: res = val.Int() case uint, uint8, uint16, uint32, uint64: res = int64(val.Uint()) case string: if IsInt(val.String()) { res, err = strconv.ParseInt(val.String(), 0, 64) if err != nil { res = 0 } } else { err = fmt.Errorf("math: square root of negative number %g", value) res = 0 } default: err = fmt.Errorf("math: square root of negative number %g", value) res = 0 } return } // ToBoolean convert the input string to a boolean. func ToBoolean(str string) (bool, error) { return strconv.ParseBool(str) }
{ "pile_set_name": "Github" }
within ThermoSysPro.InstrumentationAndControl.Blocks.Tables; block Table1D parameter Real Table[:,2]=[0,0;0,0] "Table (entrées = première colonne, sorties = deuxième colonne)"; ThermoSysPro.InstrumentationAndControl.Connectors.InputReal u annotation(Placement(transformation(x=-110.0, y=0.0, scale=0.1, aspectRatio=1.0, flipHorizontal=false, flipVertical=false), iconTransformation(x=-110.0, y=0.0, scale=0.1, aspectRatio=1.0, flipHorizontal=false, flipVertical=false))); ThermoSysPro.InstrumentationAndControl.Connectors.OutputReal y annotation(Placement(transformation(x=110.0, y=0.0, scale=0.1, aspectRatio=1.0, flipHorizontal=false, flipVertical=false), iconTransformation(x=110.0, y=0.0, scale=0.1, aspectRatio=1.0, flipHorizontal=false, flipVertical=false))); protected parameter Real Tu[1,:]=transpose(matrix(Table[:,1])) "Entrées de la table"; parameter Real Ty[1,:]=transpose(matrix(Table[:,2])) "Sorties de la table"; parameter Integer n[1,1]=[size(Tu, 2)] "Taille de la table"; Real vu[1,1]; annotation(Diagram(coordinateSystem(extent={{-100,-100},{100,100}}), graphics={Rectangle(lineColor={0,0,255}, extent={{-80,80},{80,-80}}, fillPattern=FillPattern.None),Line(color={0,0,255}, points={{80,0},{100,0}}),Line(points={{28,40},{28,-40}}, color={0,0,0}),Rectangle(extent={{-26,40},{0,20}}, lineColor={0,0,0}, fillColor={255,255,0}, fillPattern=FillPattern.Solid),Rectangle(extent={{-26,20},{0,0}}, lineColor={0,0,0}, fillColor={255,255,0}, fillPattern=FillPattern.Solid),Rectangle(extent={{-26,0},{0,-20}}, lineColor={0,0,0}, fillColor={255,255,0}, fillPattern=FillPattern.Solid),Rectangle(extent={{-26,-20},{0,-40}}, lineColor={0,0,0}, fillColor={255,255,0}, fillPattern=FillPattern.Solid),Text(lineColor={0,0,255}, extent={{-24,56},{-6,44}}, textString="u"),Text(lineColor={0,0,255}, extent={{2,56},{26,44}}, textString="y"),Text(lineColor={0,0,255}, extent={{-98,14},{-80,2}}, textString="u"),Text(lineColor={0,0,255}, extent={{78,14},{102,2}}, textString="y"),Line(color={0,0,255}, points={{-80,0},{-100,0}}),Line(points={{0,40},{28,40}}, color={0,0,0}),Line(points={{0,20},{28,20}}, color={0,0,0}),Line(points={{0,0},{28,0}}, color={0,0,0}),Line(points={{0,-20},{28,-20}}, color={0,0,0}),Line(points={{0,-40},{28,-40}}, color={0,0,0})}), Icon(coordinateSystem(extent={{-100,-100},{100,100}}), graphics={Text(lineColor={0,0,255}, extent={{-150,150},{150,110}}, textString="%name"),Rectangle(lineColor={0,0,255}, extent={{-80,80},{80,-80}}, fillPattern=FillPattern.None),Line(color={0,0,255}, points={{80,0},{100,0}}),Line(points={{28,42},{28,-38}}, color={0,0,0}),Rectangle(extent={{-26,42},{0,22}}, lineColor={0,0,0}, fillColor={255,255,0}, fillPattern=FillPattern.Solid),Rectangle(extent={{-26,22},{0,2}}, lineColor={0,0,0}, fillColor={255,255,0}, fillPattern=FillPattern.Solid),Rectangle(extent={{-26,2},{0,-18}}, lineColor={0,0,0}, fillColor={255,255,0}, fillPattern=FillPattern.Solid),Rectangle(extent={{-26,-18},{0,-38}}, lineColor={0,0,0}, fillColor={255,255,0}, fillPattern=FillPattern.Solid),Text(lineColor={0,0,255}, extent={{-24,58},{-6,46}}, textString="u"),Text(lineColor={0,0,255}, extent={{2,58},{26,46}}, textString="y"),Text(lineColor={0,0,255}, extent={{-98,14},{-80,2}}, textString="u"),Text(lineColor={0,0,255}, extent={{78,14},{102,2}}, textString="y"),Line(color={0,0,255}, points={{-80,0},{-100,0}}),Line(points={{0,42},{28,42}}, color={0,0,0}),Line(points={{0,22},{28,22}}, color={0,0,0}),Line(points={{0,2},{28,2}}, color={0,0,0}),Line(points={{0,-18},{28,-18}}, color={0,0,0}),Line(points={{0,-38},{28,-38}}, color={0,0,0})}), Documentation(info="<html> <p><b>Adapted from the ModelicaAdditions.Blocks.Tables library</b></p> </HTML> <html> <p><b>Version 1.2</b></p> </HTML> ")); equation vu=[u.signal]; y.signal=Interpolate(n, Tu, Ty, vu); end Table1D;
{ "pile_set_name": "Github" }
define([ "./core", "./var/concat", "./var/push", "./core/access", "./manipulation/var/rcheckableType", "./manipulation/support", "./data/var/data_priv", "./data/var/data_user", "./core/init", "./data/accepts", "./traversing", "./selector", "./event" ], function( jQuery, concat, push, access, rcheckableType, support, data_priv, data_user ) { var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit, PhantomJS // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit, PhantomJS // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, type, key, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); return jQuery; });
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); /** * Part of Windwalker project. * * @copyright Copyright (C) 2019 LYRASOFT. * @license LGPL-2.0-or-later */ namespace Windwalker\Form\Field; use Windwalker\Dom\HtmlElement; /** * The TextareaField class. * * @method mixed|$this cols(string $value = null) * @method mixed|$this rows(string $value = null) * * @since 2.0 */ class TextareaField extends TextField { /** * Property type. * * @var string */ protected $type = 'textarea'; /** * Property element. * * @var string */ protected $element = 'textarea'; /** * prepareRenderInput * * @param array $attrs * * @return void */ public function prepare(&$attrs) { $attrs['name'] = $this->getFieldName(); $attrs['id'] = $this->getAttribute('id', $this->getId()); $attrs['class'] = $this->getAttribute('class'); $attrs['readonly'] = $this->getAttribute('readonly'); $attrs['disabled'] = $this->getAttribute('disabled'); $attrs['onchange'] = $this->getAttribute('onchange'); $attrs['onfocus'] = $this->getAttribute('onfocus'); $attrs['onblur'] = $this->getAttribute('onblur'); $attrs['placeholder'] = $this->getAttribute('placeholder'); $attrs['maxlength'] = $this->getAttribute('maxlength'); $attrs['required'] = $this->required; $attrs['cols'] = $this->getAttribute('cols'); $attrs['rows'] = $this->getAttribute('rows'); } /** * buildInput * * @param array $attrs * * @return mixed */ public function buildInput($attrs) { return new HtmlElement($this->element, $this->getValue(), $attrs); } /** * getAccessors * * @return array * * @since 3.1.2 */ protected function getAccessors() { return array_merge( parent::getAccessors(), [ 'cols' => 'cols', 'rows' => 'rows', ] ); } }
{ "pile_set_name": "Github" }
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES := bc895.c bc898.c bc245.c pro2052.c bc780.c bc250.c \ bcd396t.c bcd996t.c \ uniden.c uniden_digital.c LOCAL_MODULE := uniden LOCAL_CFLAGS := -DHAVE_CONFIG_H LOCAL_C_INCLUDES := android include src LOCAL_LDLIBS := -lhamlib -Lobj/local/armeabi include $(BUILD_STATIC_LIBRARY)
{ "pile_set_name": "Github" }