text
stringlengths 2
99k
| meta
dict |
---|---|
include_rules = [
"+crypto",
]
| {
"pile_set_name": "Github"
} |
program linkedlist2(input,output);
(* Example linked list Pascal Program *)
(* *)
(* The file list.data would be used as the data file. *)
(* If there was an executable, a.out, run: a.out < list.data *)
const
grades = 5; (* number of grades to be averaged *)
avgPosition = 6; (* position of grade average *)
size = 4; (* number of students *)
type
integerArray = array [1..avgPosition] of integer;
cellPtr = ^cell;
cell = record
id: integer;
info: integerArray;
next: cellPtr
end;
var
list, newrec: cellPtr;
count, classNum: integer;
(* ************************************************************************* *)
(* procedure insert *)
(* ************************************************************************* *)
procedure insert(var list: cellPtr; newrec: cellPtr);
var
current: cellPtr;
found: boolean;
begin
current := list;
found := false;
if (list = nil) then
begin
newrec^.next := list; (* fix bug so next is set to nil *)
list := newrec;
end
else if (newrec^.id < list^.id) then
begin
newrec^.next := list;
list := newrec;
end
else
begin
while (current <> nil) and (not found) do
begin
if (current^.next = nil) then
begin
newrec^.next := nil; (* fix bug so next is set to nil *)
current^.next := newrec;
found := true;
end
else if (newrec^.id < current^.next^.id) then
begin
newrec^.next := current^.next;
current^.next := newrec;
found := true;
end;
current := current^.next;
end;
end;
end;
(* ************************************************************************* *)
(* function average *)
(* ************************************************************************* *)
function average(newrec: cellPtr): integer;
var
i, sum : integer;
begin
sum := 0;
for i := 1 to grades do
sum:=sum + newrec^.info[i];
average:=sum div grades;
end;
(* ************************************************************************* *)
(* procedure makeNewrec *)
(* ************************************************************************* *)
procedure makeNewrec(var newrec : cellPtr);
var
i: integer;
begin
new(newrec);
read(newrec^.id);
for i := 1 to grades do
read(newrec^.info[i]);
newrec^.info[avgPosition] := average(newrec);
end;
(* ************************************************************************* *)
(* procedure displayInfo *)
(* ************************************************************************* *)
procedure displayInfo(var list : cellPtr);
var
i: integer;
current: cellPtr;
begin
current := list;
if (list <> nil) then
begin
write(' ');
for i := 1 to grades do
write('Grade ');
writeln;
write('Student');
for i := 1 to grades do
write(i);
writeln(' Average');
for i := 1 to grades+2 do
write('-----------');
writeln;
while (current <> nil) do
begin
write(current^.id);
for i := 1 to (grades + 1) do
write(current^.info[i]);
writeln;
current:= current^.next;
end;
end;
end;
(* ************************************************************************* *)
(* procedure cleanup *)
(* ************************************************************************* *)
procedure cleanup(var list : cellPtr);
var
current: cellPtr;
begin
while (list <> nil) do
begin
current := list;
list := list^.next;
current^.next := nil;
dispose(current);
end;
current := nil
end;
(* ************************************************************************** *)
(* main program *)
(* ************************************************************************** *)
begin
read(classNum);
list := nil;
for count := 1 to size do
begin
makeNewrec(newrec);
insert(list, newrec);
end;
writeln('Here are the class grades for class:', classNum); writeln;
displayInfo(list);
cleanup(list);
end. | {
"pile_set_name": "Github"
} |
/* xdcon - description
*
* Purpose:
*
* Written by: R. Mortensen
* Date:
*
* Calling Sequence:
*
* STATUS = xdcon( parameters )
*
* Parameter List:
*
* Unit: Display device unit number
*
* Possible Error Codes:
*
*/
#include "xvmaininc.h"
#include "ftnbridge.h"
#include "xdexterns.h"
#include "xdroutines.h"
#include "xderrors.h"
#include "xdfuncs.h"
#define DEFAULT_FORM 1
FUNCTION FTN_NAME(xdcon)( Unit, Cursor, Form, Blink )
INTEGER Unit, Cursor, Form, Blink;
{
return ( zdcon( *Unit, *Cursor, *Form, *Blink ) );
}
FUNCTION zdcon( unit, cursor, form, blink )
int unit, cursor, form, blink;
{
int status, tmpForm;
xd_current_call = CON;
if (!ZCHECK_UNIT_NUMBER) {
status = UNIT_OUT_OF_RANGE;
}
else if (!ZCHECK_DEVICE_OPEN) {
status = DEVICE_NOT_OPEN;
}
else if (!ZCHECK_DEVICE_ACTIVE) {
status = DEVICE_NOT_ACTIVE;
}
else if (!ZCHECK_CURSOR( cursor )) {
status = NO_SUCH_CURSOR;
}
else if (!ZCHECK_CURSOR_TYPE( form )) {
status = NO_SUCH_CURSOR_FORM;
}
else if ((form < 0) && (!ZMAY_RESIZE_CURSOR)) {
status = NO_SUCH_CURSOR_FORM;
}
else if (!ZCHECK_CURSOR_BLINK_RATE( blink )) {
status = NO_SUCH_CURSOR_RATE;
}
else {
tmpForm = (form == 0 ? DEFAULT_FORM : form );
ZCURSOR_FORM( cursor ) = tmpForm;
ZCURSOR_BLINK( cursor ) = blink;
ZCURSOR_ACTIVE( cursor ) = TRUE;
status = XD_Device_Interface( &unit, CURSOR_ON, cursor, tmpForm, blink );
}
xd_error_handler( &unit, status );
return (status);
}
| {
"pile_set_name": "Github"
} |
defmodule Backoffice.ExAdmin.AuthAccount do
use ExAdmin.Register
register_resource Auth.Account do
menu label: "Auth Accounts"
options resource_name: "auth_account", controller_route: "auth_accounts"
filter [:id, :email]
index do
column :id
column :email
end
show _account do
attributes_table do
row :id
row :email
row :inserted_at
row :updated_at
end
end
form account do
inputs do
input account, :email
unless account.id do
input account, :password
end
end
end
end
end
| {
"pile_set_name": "Github"
} |
/**
* Information about a raid.
*/
export interface ChatRitualInfo {
/**
* The name of the ritual.
*
* Currently, the only known ritual is "new_chatter".
*/
ritualName: string;
/**
* The message sent with the ritual.
*
* With the "new_chatter" ritual, you can choose between a set list of emotes to send.
*/
message: string;
}
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright 2016-2019 Francesco Benincasa ([email protected])
*
* 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 sqlite.feature.rx.model;
import com.abubusoft.kripton.annotation.BindType;
// TODO: Auto-generated Javadoc
/**
* The Class PrefixConfig.
*/
@BindType
public class PrefixConfig {
/** The id. */
public long id;
/** The default country. */
public String defaultCountry;
/** The dual billing prefix. */
public String dualBillingPrefix;
/** The enabled. */
public boolean enabled;
/** The dialog timeout. */
public long dialogTimeout;
}
| {
"pile_set_name": "Github"
} |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* DNS Library for handling lookups and updates.
*
* PHP Version 5
*
* Copyright (c) 2010, Mike Pultz <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of Mike Pultz nor the names of his 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 OWNER 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, STRIC
* 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.
*
* @category Networking
* @package Net_DNS2
* @author Mike Pultz <[email protected]>
* @copyright 2010 Mike Pultz <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version SVN: $Id$
* @link http://pear.php.net/package/Net_DNS2
* @since File available since Release 0.6.0
*
*/
/*
* register the auto-load function
*
*/
spl_autoload_register('Net_DNS2::autoload');
/**
* This is the base class for the Net_DNS2_Resolver and Net_DNS2_Updater
* classes.
*
* @category Networking
* @package Net_DNS2
* @author Mike Pultz <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://pear.php.net/package/Net_DNS2
* @see Net_DNS2_Resolver, Net_DNS2_Updater
*
*/
class Net_DNS2
{
/*
* the current version of this library
*/
const VERSION = '1.4.3';
/*
* the default path to a resolv.conf file
*/
const RESOLV_CONF = '/etc/resolv.conf';
/*
* override options from the resolv.conf file
*
* if this is set, then certain values from the resolv.conf file will override
* local settings. This is disabled by default to remain backwards compatible.
*
*/
public $use_resolv_options = false;
/*
* use TCP only (true/false)
*/
public $use_tcp = false;
/*
* DNS Port to use (53)
*/
public $dns_port = 53;
/*
* the ip/port for use as a local socket
*/
public $local_host = '';
public $local_port = 0;
/*
* timeout value for socket connections
*/
public $timeout = 5;
/*
* randomize the name servers list
*/
public $ns_random = false;
/*
* default domains
*/
public $domain = '';
/*
* domain search list - not actually used right now
*/
public $search_list = array();
/*
* enable cache; either "shared", "file" or "none"
*/
public $cache_type = 'none';
/*
* file name to use for shared memory segment or file cache
*/
public $cache_file = '/tmp/net_dns2.cache';
/*
* the max size of the cache file (in bytes)
*/
public $cache_size = 50000;
/*
* the method to use for storing cache data; either "serialize" or "json"
*
* json is faster, but can't remember the class names (everything comes back
* as a "stdClass Object"; all the data is the same though. serialize is
* slower, but will have all the class info.
*
* defaults to 'serialize'
*/
public $cache_serializer = 'serialize';
/*
* by default, according to RFC 1034
*
* CNAME RRs cause special action in DNS software. When a name server
* fails to find a desired RR in the resource set associated with the
* domain name, it checks to see if the resource set consists of a CNAME
* record with a matching class. If so, the name server includes the CNAME
* record in the response and restarts the query at the domain name
* specified in the data field of the CNAME record.
*
* this can cause "unexpected" behavious, since i'm sure *most* people
* don't know DNS does this; there may be cases where Net_DNS2 returns a
* positive response, even though the hostname the user looked up did not
* actually exist.
*
* strict_query_mode means that if the hostname that was looked up isn't
* actually in the answer section of the response, Net_DNS2 will return an
* empty answer section, instead of an answer section that could contain
* CNAME records.
*
*/
public $strict_query_mode = false;
/*
* if we should set the recursion desired bit to 1 or 0.
*
* by default this is set to true, we want the DNS server to perform a recursive
* request. If set to false, the RD bit will be set to 0, and the server will
* not perform recursion on the request.
*/
public $recurse = true;
/*
* request DNSSEC values, by setting the DO flag to 1; this actually makes
* the resolver add a OPT RR to the additional section, and sets the DO flag
* in this RR to 1
*
*/
public $dnssec = false;
/*
* set the DNSSEC AD (Authentic Data) bit on/off; the AD bit on the request
* side was previously undefined, and resolvers we instructed to always clear
* the AD bit when sending a request.
*
* RFC6840 section 5.7 defines setting the AD bit in the query as a signal to
* the server that it wants the value of the AD bit, without needed to request
* all the DNSSEC data via the DO bit.
*
*/
public $dnssec_ad_flag = false;
/*
* set the DNSSEC CD (Checking Disabled) bit on/off; turning this off, means
* that the DNS resolver will perform it's own signature validation- so the DNS
* servers simply pass through all the details.
*
*/
public $dnssec_cd_flag = false;
/*
* the EDNS(0) UDP payload size to use when making DNSSEC requests
* see RFC 4035 section 4.1 - EDNS Support.
*
* there is some different ideas on the suggest size to supprt; but it seems to
* be "at least 1220 bytes, but SHOULD support 4000 bytes.
*
* we'll just support 4000
*
*/
public $dnssec_payload_size = 4000;
/*
* the last exeception that was generated
*/
public $last_exception = null;
/*
* the list of exceptions by name server
*/
public $last_exception_list = array();
/*
* name server list
*/
public $nameservers = array();
/*
* local sockets
*/
protected $sock = array(Net_DNS2_Socket::SOCK_DGRAM => array(), Net_DNS2_Socket::SOCK_STREAM => array());
/*
* if the socket extension is loaded
*/
protected $sockets_enabled = false;
/*
* the TSIG or SIG RR object for authentication
*/
protected $auth_signature = null;
/*
* the shared memory segment id for the local cache
*/
protected $cache = null;
/*
* internal setting for enabling cache
*/
protected $use_cache = false;
/**
* Constructor - base constructor for the Resolver and Updater
*
* @param mixed $options array of options or null for none
*
* @throws Net_DNS2_Exception
* @access public
*
*/
public function __construct(array $options = null)
{
//
// check for the sockets extension; we no longer support the sockets library under
// windows- there have been too many errors related to sockets under windows-
// specifically inconsistent socket defines between versions of windows-
//
// and since I can't seem to find a way to get the actual windows version, it
// doesn't seem fixable in the code.
//
if ( (extension_loaded('sockets') == true) && (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') ) {
$this->sockets_enabled = true;
}
//
// load any options that were provided
//
if (!empty($options)) {
foreach ($options as $key => $value) {
if ($key == 'nameservers') {
$this->setServers($value);
} else {
$this->$key = $value;
}
}
}
//
// if we're set to use the local shared memory cache, then
// make sure it's been initialized
//
switch($this->cache_type) {
case 'shared':
if (extension_loaded('shmop')) {
$this->cache = new Net_DNS2_Cache_Shm;
$this->use_cache = true;
} else {
throw new Net_DNS2_Exception(
'shmop library is not available for cache',
Net_DNS2_Lookups::E_CACHE_SHM_UNAVAIL
);
}
break;
case 'file':
$this->cache = new Net_DNS2_Cache_File;
$this->use_cache = true;
break;
case 'none':
$this->use_cache = false;
break;
default:
throw new Net_DNS2_Exception(
'un-supported cache type: ' . $this->cache_type,
Net_DNS2_Lookups::E_CACHE_UNSUPPORTED
);
}
}
/**
* autoload call-back function; used to auto-load classes
*
* @param string $name the name of the class
*
* @return void
* @access public
*
*/
static public function autoload($name)
{
//
// only auto-load our classes
//
if (strncmp($name, 'Net_DNS2', 8) == 0) {
include str_replace('_', '/', $name) . '.php';
}
return;
}
/**
* sets the name servers to be used
*
* @param mixed $nameservers either an array of name servers, or a file name
* to parse, assuming it's in the resolv.conf format
*
* @return boolean
* @throws Net_DNS2_Exception
* @access public
*
*/
public function setServers($nameservers)
{
//
// if it's an array, then use it directly
//
// otherwise, see if it's a path to a resolv.conf file and if so, load it
//
if (is_array($nameservers)) {
$this->nameservers = $nameservers;
} else {
//
// temporary list of name servers; do it this way rather than just
// resetting the local nameservers value, just incase an exception
// is thrown here; this way we might avoid ending up with an empty
// namservers list.
//
$ns = array();
//
// check to see if the file is readable
//
if (is_readable($nameservers) === true) {
$data = file_get_contents($nameservers);
if ($data === false) {
throw new Net_DNS2_Exception(
'failed to read contents of file: ' . $nameservers,
Net_DNS2_Lookups::E_NS_INVALID_FILE
);
}
$lines = explode("\n", $data);
foreach ($lines as $line) {
$line = trim($line);
//
// ignore empty lines, and lines that are commented out
//
if ( (strlen($line) == 0)
|| ($line[0] == '#')
|| ($line[0] == ';')
) {
continue;
}
//
// ignore lines with no spaces in them.
//
if (strpos($line, ' ') === false) {
continue;
}
list($key, $value) = preg_split('/\s+/', $line, 2);
$key = trim(strtolower($key));
$value = trim(strtolower($value));
switch($key) {
case 'nameserver':
//
// nameserver can be a IPv4 or IPv6 address
//
if ( (self::isIPv4($value) == true)
|| (self::isIPv6($value) == true)
) {
$ns[] = $value;
} else {
throw new Net_DNS2_Exception(
'invalid nameserver entry: ' . $value,
Net_DNS2_Lookups::E_NS_INVALID_ENTRY
);
}
break;
case 'domain':
$this->domain = $value;
break;
case 'search':
$this->search_list = preg_split('/\s+/', $value);
break;
case 'options':
$this->parseOptions($value);
break;
default:
;
}
}
//
// if we don't have a domain, but we have a search list, then
// take the first entry on the search list as the domain
//
if ( (strlen($this->domain) == 0)
&& (count($this->search_list) > 0)
) {
$this->domain = $this->search_list[0];
}
} else {
throw new Net_DNS2_Exception(
'resolver file file provided is not readable: ' . $nameservers,
Net_DNS2_Lookups::E_NS_INVALID_FILE
);
}
//
// store the name servers locally
//
if (count($ns) > 0) {
$this->nameservers = $ns;
}
}
//
// remove any duplicates; not sure if we should bother with this- if people
// put duplicate name servers, who I am to stop them?
//
$this->nameservers = array_unique($this->nameservers);
//
// check the name servers
//
$this->checkServers();
return true;
}
/**
* parses the options line from a resolv.conf file; we don't support all the options
* yet, and using them is optional.
*
* @param string $value is the options string from the resolv.conf file.
*
* @return boolean
* @access private
*
*/
private function parseOptions($value)
{
//
// if overrides are disabled (the default), or the options list is empty for some
// reason, then we don't need to do any of this work.
//
if ( ($this->use_resolv_options == false) || (strlen($value) == 0) ) {
return true;
}
$options = preg_split('/\s+/', strtolower($value));
foreach ($options as $option) {
//
// override the timeout value from the resolv.conf file.
//
if ( (strncmp($option, 'timeout', 7) == 0) && (strpos($option, ':') !== false) ) {
list($key, $val) = explode(':', $option);
if ( ($val > 0) && ($val <= 30) ) {
$this->timeout = $val;
}
//
// the rotate option just enabled the ns_random option
//
} else if (strncmp($option, 'rotate', 6) == 0) {
$this->ns_random = true;
}
}
return true;
}
/**
* checks the list of name servers to make sure they're set
*
* @param mixed $default a path to a resolv.conf file or an array of servers.
*
* @return boolean
* @throws Net_DNS2_Exception
* @access protected
*
*/
protected function checkServers($default = null)
{
if (empty($this->nameservers)) {
if (isset($default)) {
$this->setServers($default);
} else {
throw new Net_DNS2_Exception(
'empty name servers list; you must provide a list of name '.
'servers, or the path to a resolv.conf file.',
Net_DNS2_Lookups::E_NS_INVALID_ENTRY
);
}
}
return true;
}
/**
* adds a TSIG RR object for authentication
*
* @param string $keyname the key name to use for the TSIG RR
* @param string $signature the key to sign the request.
* @param string $algorithm the algorithm to use
*
* @return boolean
* @access public
* @since function available since release 1.1.0
*
*/
public function signTSIG(
$keyname, $signature = '', $algorithm = Net_DNS2_RR_TSIG::HMAC_MD5
) {
//
// if the TSIG was pre-created and passed in, then we can just used
// it as provided.
//
if ($keyname instanceof Net_DNS2_RR_TSIG) {
$this->auth_signature = $keyname;
} else {
//
// otherwise create the TSIG RR, but don't add it just yet; TSIG needs
// to be added as the last additional entry- so we'll add it just
// before we send.
//
$this->auth_signature = Net_DNS2_RR::fromString(
strtolower(trim($keyname)) .
' TSIG '. $signature
);
//
// set the algorithm to use
//
$this->auth_signature->algorithm = $algorithm;
}
return true;
}
/**
* adds a SIG RR object for authentication
*
* @param string $filename the name of a file to load the signature from.
*
* @return boolean
* @throws Net_DNS2_Exception
* @access public
* @since function available since release 1.1.0
*
*/
public function signSIG0($filename)
{
//
// check for OpenSSL
//
if (extension_loaded('openssl') === false) {
throw new Net_DNS2_Exception(
'the OpenSSL extension is required to use SIG(0).',
Net_DNS2_Lookups::E_OPENSSL_UNAVAIL
);
}
//
// if the SIG was pre-created, then use it as-is
//
if ($filename instanceof Net_DNS2_RR_SIG) {
$this->auth_signature = $filename;
} else {
//
// otherwise, it's filename which needs to be parsed and processed.
//
$private = new Net_DNS2_PrivateKey($filename);
//
// create a new Net_DNS2_RR_SIG object
//
$this->auth_signature = new Net_DNS2_RR_SIG();
//
// reset some values
//
$this->auth_signature->name = $private->signname;
$this->auth_signature->ttl = 0;
$this->auth_signature->class = 'ANY';
//
// these values are pulled from the private key
//
$this->auth_signature->algorithm = $private->algorithm;
$this->auth_signature->keytag = $private->keytag;
$this->auth_signature->signname = $private->signname;
//
// these values are hard-coded for SIG0
//
$this->auth_signature->typecovered = 'SIG0';
$this->auth_signature->labels = 0;
$this->auth_signature->origttl = 0;
//
// generate the dates
//
$t = time();
$this->auth_signature->sigincep = gmdate('YmdHis', $t);
$this->auth_signature->sigexp = gmdate('YmdHis', $t + 500);
//
// store the private key in the SIG object for later.
//
$this->auth_signature->private_key = $private;
}
//
// only RSA algorithms are supported for SIG(0)
//
switch($this->auth_signature->algorithm) {
case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSAMD5:
case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA1:
case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256:
case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512:
case Net_DNS2_Lookups::DNSSEC_ALGORITHM_DSA:
break;
default:
throw new Net_DNS2_Exception(
'only asymmetric algorithms work with SIG(0)!',
Net_DNS2_Lookups::E_OPENSSL_INV_ALGO
);
}
return true;
}
/**
* a simple function to determine if the RR type is cacheable
*
* @param stream $_type the RR type string
*
* @return bool returns true/false if the RR type if cachable
* @access public
*
*/
public function cacheable($_type)
{
switch($_type) {
case 'AXFR':
case 'OPT':
return false;
}
return true;
}
/**
* PHP doesn't support unsigned integers, but many of the RR's return
* unsigned values (like SOA), so there is the possibility that the
* value will overrun on 32bit systems, and you'll end up with a
* negative value.
*
* 64bit systems are not affected, as their PHP_IN_MAX value should
* be 64bit (ie 9223372036854775807)
*
* This function returns a negative integer value, as a string, with
* the correct unsigned value.
*
* @param string $_int the unsigned integer value to check
*
* @return string returns the unsigned value as a string.
* @access public
*
*/
public static function expandUint32($_int)
{
if ( ($_int < 0) && (PHP_INT_MAX == 2147483647) ) {
return sprintf('%u', $_int);
} else {
return $_int;
}
}
/**
* returns true/false if the given address is a valid IPv4 address
*
* @param string $_address the IPv4 address to check
*
* @return boolean returns true/false if the address is IPv4 address
* @access public
*
*/
public static function isIPv4($_address)
{
//
// use filter_var() if it's available; it's faster than preg
//
if (extension_loaded('filter') == true) {
if (filter_var($_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) == false) {
return false;
}
} else {
//
// do the main check here;
//
if (inet_pton($_address) === false) {
return false;
}
//
// then make sure we're not a IPv6 address
//
if (preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $_address) == 0) {
return false;
}
}
return true;
}
/**
* returns true/false if the given address is a valid IPv6 address
*
* @param string $_address the IPv6 address to check
*
* @return boolean returns true/false if the address is IPv6 address
* @access public
*
*/
public static function isIPv6($_address)
{
//
// use filter_var() if it's available; it's faster than preg
//
if (extension_loaded('filter') == true) {
if (filter_var($_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) == false) {
return false;
}
} else {
//
// do the main check here
//
if (inet_pton($_address) === false) {
return false;
}
//
// then make sure it doesn't match a IPv4 address
//
if (preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $_address) == 1) {
return false;
}
}
return true;
}
/**
* formats the given IPv6 address as a fully expanded IPv6 address
*
* @param string $_address the IPv6 address to expand
*
* @return string the fully expanded IPv6 address
* @access public
*
*/
public static function expandIPv6($_address)
{
$hex = unpack('H*hex', inet_pton($_address));
return substr(preg_replace('/([A-f0-9]{4})/', "$1:", $hex['hex']), 0, -1);
}
/**
* sends a standard Net_DNS2_Packet_Request packet
*
* @param Net_DNS2_Packet $request a Net_DNS2_Packet_Request object
* @param boolean $use_tcp true/false if the function should
* use TCP for the request
*
* @return mixed returns a Net_DNS2_Packet_Response object, or false on error
* @throws Net_DNS2_Exception
* @access protected
*
*/
protected function sendPacket(Net_DNS2_Packet $request, $use_tcp)
{
//
// get the data from the packet
//
$data = $request->get();
if (strlen($data) < Net_DNS2_Lookups::DNS_HEADER_SIZE) {
throw new Net_DNS2_Exception(
'invalid or empty packet for sending!',
Net_DNS2_Lookups::E_PACKET_INVALID,
null,
$request
);
}
reset($this->nameservers);
//
// randomize the name server list if it's asked for
//
if ($this->ns_random == true) {
shuffle($this->nameservers);
}
//
// loop so we can handle server errors
//
$response = null;
$ns = '';
while (1) {
//
// grab the next DNS server
//
$ns = each($this->nameservers);
if ($ns === false) {
if (is_null($this->last_exception) == false) {
throw $this->last_exception;
} else {
throw new Net_DNS2_Exception(
'every name server provided has failed',
Net_DNS2_Lookups::E_NS_FAILED
);
}
}
$ns = $ns[1];
//
// if the use TCP flag (force TCP) is set, or the packet is bigger than our
// max allowed UDP size- which is either 512, or if this is DNSSEC request,
// then whatever the configured dnssec_payload_size is.
//
$max_udp_size = Net_DNS2_Lookups::DNS_MAX_UDP_SIZE;
if ($this->dnssec == true)
{
$max_udp_size = $this->dnssec_payload_size;
}
if ( ($use_tcp == true) || (strlen($data) > $max_udp_size) ) {
try
{
$response = $this->sendTCPRequest($ns, $data, ($request->question[0]->qtype == 'AXFR') ? true : false);
} catch(Net_DNS2_Exception $e) {
$this->last_exception = $e;
$this->last_exception_list[$ns] = $e;
continue;
}
//
// otherwise, send it using UDP
//
} else {
try
{
$response = $this->sendUDPRequest($ns, $data);
//
// check the packet header for a trucated bit; if it was truncated,
// then re-send the request as TCP.
//
if ($response->header->tc == 1) {
$response = $this->sendTCPRequest($ns, $data);
}
} catch(Net_DNS2_Exception $e) {
$this->last_exception = $e;
$this->last_exception_list[$ns] = $e;
continue;
}
}
//
// make sure header id's match between the request and response
//
if ($request->header->id != $response->header->id) {
$this->last_exception = new Net_DNS2_Exception(
'invalid header: the request and response id do not match.',
Net_DNS2_Lookups::E_HEADER_INVALID,
null,
$request,
$response
);
$this->last_exception_list[$ns] = $this->last_exception;
continue;
}
//
// make sure the response is actually a response
//
// 0 = query, 1 = response
//
if ($response->header->qr != Net_DNS2_Lookups::QR_RESPONSE) {
$this->last_exception = new Net_DNS2_Exception(
'invalid header: the response provided is not a response packet.',
Net_DNS2_Lookups::E_HEADER_INVALID,
null,
$request,
$response
);
$this->last_exception_list[$ns] = $this->last_exception;
continue;
}
//
// make sure the response code in the header is ok
//
if ($response->header->rcode != Net_DNS2_Lookups::RCODE_NOERROR) {
$this->last_exception = new Net_DNS2_Exception(
'DNS request failed: ' .
Net_DNS2_Lookups::$result_code_messages[$response->header->rcode],
$response->header->rcode,
null,
$request,
$response
);
$this->last_exception_list[$ns] = $this->last_exception;
continue;
}
break;
}
return $response;
}
/**
* cleans up a failed socket and throws the given exception
*
* @param string $_proto the protocol of the socket
* @param string $_ns the name server to use for the request
* @param string $_error the error message to throw at the end of the function
*
* @throws Net_DNS2_Exception
* @access private
*
*/
private function generateError($_proto, $_ns, $_error)
{
if (isset($this->sock[$_proto][$_ns]) == false)
{
throw new Net_DNS2_Exception('invalid socket referenced', Net_DNS2_Lookups::E_NS_INVALID_SOCKET);
}
//
// grab the last error message off the socket
//
$last_error = $this->sock[$_proto][$_ns]->last_error;
//
// close it
//
$this->sock[$_proto][$_ns]->close();
//
// remove it from the socket cache
//
unset($this->sock[$_proto][$_ns]);
//
// throw the error provided
//
throw new Net_DNS2_Exception($last_error, $_error);
}
/**
* sends a DNS request using TCP
*
* @param string $_ns the name server to use for the request
* @param string $_data the raw DNS packet data
* @param boolean $_axfr if this is a zone transfer request
*
* @return Net_DNS2_Packet_Response the reponse object
* @throws Net_DNS2_Exception
* @access private
*
*/
private function sendTCPRequest($_ns, $_data, $_axfr = false)
{
//
// grab the start time
//
$start_time = microtime(true);
//
// see if we already have an open socket from a previous request; if so, try to use
// that instead of opening a new one.
//
if ( (!isset($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]))
|| (!($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns] instanceof Net_DNS2_Socket))
) {
//
// if the socket library is available, then use that
//
if ($this->sockets_enabled === true) {
$this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns] = new Net_DNS2_Socket_Sockets(
Net_DNS2_Socket::SOCK_STREAM, $_ns, $this->dns_port, $this->timeout
);
//
// otherwise the streams library
//
} else {
$this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns] = new Net_DNS2_Socket_Streams(
Net_DNS2_Socket::SOCK_STREAM, $_ns, $this->dns_port, $this->timeout
);
}
//
// if a local IP address / port is set, then add it
//
if (strlen($this->local_host) > 0) {
$this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->bindAddress(
$this->local_host, $this->local_port
);
}
//
// open the socket
//
if ($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->open() === false) {
$this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED);
}
}
//
// write the data to the socket; if it fails, continue on
// the while loop
//
if ($this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->write($_data) === false) {
$this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED);
}
//
// read the content, using select to wait for a response
//
$size = 0;
$result = null;
$response = null;
//
// handle zone transfer requests differently than other requests.
//
if ($_axfr == true) {
$soa_count = 0;
while (1) {
//
// read the data off the socket
//
$result = $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->read($size, ($this->dnssec == true) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE);
if ( ($result === false) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE) ) {
//
// if we get an error, then keeping this socket around for a future request, could cause
// an error- for example, https://github.com/mikepultz/netdns2/issues/61
//
// in this case, the connection was timing out, which once it did finally respond, left
// data on the socket, which could be captured on a subsequent request.
//
// since there's no way to "reset" a socket, the only thing we can do it close it.
//
$this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED);
}
//
// parse the first chunk as a packet
//
$chunk = new Net_DNS2_Packet_Response($result, $size);
//
// if this is the first packet, then clone it directly, then
// go through it to see if there are two SOA records
// (indicating that it's the only packet)
//
if (is_null($response) == true) {
$response = clone $chunk;
//
// look for a failed response; if the zone transfer
// failed, then we don't need to do anything else at this
// point, and we should just break out.
//
if ($response->header->rcode != Net_DNS2_Lookups::RCODE_NOERROR) {
break;
}
//
// go through each answer
//
foreach ($response->answer as $index => $rr) {
//
// count the SOA records
//
if ($rr->type == 'SOA') {
$soa_count++;
}
}
//
// if we have 2 or more SOA records, then we're done;
// otherwise continue out so we read the rest of the
// packets off the socket
//
if ($soa_count >= 2) {
break;
} else {
continue;
}
} else {
//
// go through all these answers, and look for SOA records
//
foreach ($chunk->answer as $index => $rr) {
//
// count the number of SOA records we find
//
if ($rr->type == 'SOA') {
$soa_count++;
}
//
// add the records to a single response object
//
$response->answer[] = $rr;
}
//
// if we've found the second SOA record, we're done
//
if ($soa_count >= 2) {
break;
}
}
}
//
// everything other than a AXFR
//
} else {
$result = $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->read($size, ($this->dnssec == true) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE);
if ( ($result === false) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE) ) {
$this->generateError(Net_DNS2_Socket::SOCK_STREAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED);
}
//
// create the packet object
//
$response = new Net_DNS2_Packet_Response($result, $size);
}
//
// store the query time
//
$response->response_time = microtime(true) - $start_time;
//
// add the name server that the response came from to the response object,
// and the socket type that was used.
//
$response->answer_from = $_ns;
$response->answer_socket_type = Net_DNS2_Socket::SOCK_STREAM;
//
// return the Net_DNS2_Packet_Response object
//
return $response;
}
/**
* sends a DNS request using UDP
*
* @param string $_ns the name server to use for the request
* @param string $_data the raw DNS packet data
*
* @return Net_DNS2_Packet_Response the reponse object
* @throws Net_DNS2_Exception
* @access private
*
*/
private function sendUDPRequest($_ns, $_data)
{
//
// grab the start time
//
$start_time = microtime(true);
//
// see if we already have an open socket from a previous request; if so, try to use
// that instead of opening a new one.
//
if ( (!isset($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]))
|| (!($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns] instanceof Net_DNS2_Socket))
) {
//
// if the socket library is available, then use that
//
if ($this->sockets_enabled === true) {
$this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns] = new Net_DNS2_Socket_Sockets(
Net_DNS2_Socket::SOCK_DGRAM, $_ns, $this->dns_port, $this->timeout
);
//
// otherwise the streams library
//
} else {
$this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns] = new Net_DNS2_Socket_Streams(
Net_DNS2_Socket::SOCK_DGRAM, $_ns, $this->dns_port, $this->timeout
);
}
//
// if a local IP address / port is set, then add it
//
if (strlen($this->local_host) > 0) {
$this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->bindAddress(
$this->local_host, $this->local_port
);
}
//
// open the socket
//
if ($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->open() === false) {
$this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED);
}
}
//
// write the data to the socket
//
if ($this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->write($_data) === false) {
$this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED);
}
//
// read the content, using select to wait for a response
//
$size = 0;
$result = $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->read($size, ($this->dnssec == true) ? $this->dnssec_payload_size : Net_DNS2_Lookups::DNS_MAX_UDP_SIZE);
if (( $result === false) || ($size < Net_DNS2_Lookups::DNS_HEADER_SIZE)) {
$this->generateError(Net_DNS2_Socket::SOCK_DGRAM, $_ns, Net_DNS2_Lookups::E_NS_SOCKET_FAILED);
}
//
// create the packet object
//
$response = new Net_DNS2_Packet_Response($result, $size);
//
// store the query time
//
$response->response_time = microtime(true) - $start_time;
//
// add the name server that the response came from to the response object,
// and the socket type that was used.
//
$response->answer_from = $_ns;
$response->answer_socket_type = Net_DNS2_Socket::SOCK_DGRAM;
//
// return the Net_DNS2_Packet_Response object
//
return $response;
}
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/
?>
| {
"pile_set_name": "Github"
} |
import { isElement } from "lodash";
export default isElement;
| {
"pile_set_name": "Github"
} |
## Changelog
### v2.0.0
**Breaking changes**
- The main export now returns the compiled string, instead of the object returned from the compiler
**Added features**
- Adds a `.create` method to do what the main function did before v2.0.0
### v0.2.0
In addition to performance and matching improvements, the v0.2.0 refactor adds complete POSIX character class support, with the exception of equivalence classes and POSIX.2 collating symbols which are not relevant to node.js usage.
**Added features**
- parser is exposed, so that expand-brackets parsers can be used by upstream parsers (like [micromatch][])
- compiler is exposed, so that expand-brackets compilers can be used by upstream compilers
- source maps
**source map example**
```js
var brackets = require('expand-brackets');
var res = brackets('[:alpha:]');
console.log(res.map);
{ version: 3,
sources: [ 'brackets' ],
names: [],
mappings: 'AAAA,MAAS',
sourcesContent: [ '[:alpha:]' ] }
```
| {
"pile_set_name": "Github"
} |
/*
* net/sched/cls_basic.c Basic Packet Classifier.
*
* 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.
*
* Authors: Thomas Graf <[email protected]>
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/rtnetlink.h>
#include <linux/skbuff.h>
#include <net/netlink.h>
#include <net/act_api.h>
#include <net/pkt_cls.h>
struct basic_head {
u32 hgenerator;
struct list_head flist;
struct rcu_head rcu;
};
struct basic_filter {
u32 handle;
struct tcf_exts exts;
struct tcf_ematch_tree ematches;
struct tcf_result res;
struct tcf_proto *tp;
struct list_head link;
struct rcu_head rcu;
};
static int basic_classify(struct sk_buff *skb, const struct tcf_proto *tp,
struct tcf_result *res)
{
int r;
struct basic_head *head = rcu_dereference_bh(tp->root);
struct basic_filter *f;
list_for_each_entry_rcu(f, &head->flist, link) {
if (!tcf_em_tree_match(skb, &f->ematches, NULL))
continue;
*res = f->res;
r = tcf_exts_exec(skb, &f->exts, res);
if (r < 0)
continue;
return r;
}
return -1;
}
static unsigned long basic_get(struct tcf_proto *tp, u32 handle)
{
unsigned long l = 0UL;
struct basic_head *head = rtnl_dereference(tp->root);
struct basic_filter *f;
if (head == NULL)
return 0UL;
list_for_each_entry(f, &head->flist, link) {
if (f->handle == handle) {
l = (unsigned long) f;
break;
}
}
return l;
}
static int basic_init(struct tcf_proto *tp)
{
struct basic_head *head;
head = kzalloc(sizeof(*head), GFP_KERNEL);
if (head == NULL)
return -ENOBUFS;
INIT_LIST_HEAD(&head->flist);
rcu_assign_pointer(tp->root, head);
return 0;
}
static void basic_delete_filter(struct rcu_head *head)
{
struct basic_filter *f = container_of(head, struct basic_filter, rcu);
tcf_exts_destroy(&f->exts);
tcf_em_tree_destroy(&f->ematches);
kfree(f);
}
static void basic_destroy(struct tcf_proto *tp)
{
struct basic_head *head = rtnl_dereference(tp->root);
struct basic_filter *f, *n;
list_for_each_entry_safe(f, n, &head->flist, link) {
list_del_rcu(&f->link);
tcf_unbind_filter(tp, &f->res);
call_rcu(&f->rcu, basic_delete_filter);
}
RCU_INIT_POINTER(tp->root, NULL);
kfree_rcu(head, rcu);
}
static int basic_delete(struct tcf_proto *tp, unsigned long arg)
{
struct basic_filter *f = (struct basic_filter *) arg;
list_del_rcu(&f->link);
tcf_unbind_filter(tp, &f->res);
call_rcu(&f->rcu, basic_delete_filter);
return 0;
}
static const struct nla_policy basic_policy[TCA_BASIC_MAX + 1] = {
[TCA_BASIC_CLASSID] = { .type = NLA_U32 },
[TCA_BASIC_EMATCHES] = { .type = NLA_NESTED },
};
static int basic_set_parms(struct net *net, struct tcf_proto *tp,
struct basic_filter *f, unsigned long base,
struct nlattr **tb,
struct nlattr *est, bool ovr)
{
int err;
struct tcf_exts e;
struct tcf_ematch_tree t;
tcf_exts_init(&e, TCA_BASIC_ACT, TCA_BASIC_POLICE);
err = tcf_exts_validate(net, tp, tb, est, &e, ovr);
if (err < 0)
return err;
err = tcf_em_tree_validate(tp, tb[TCA_BASIC_EMATCHES], &t);
if (err < 0)
goto errout;
if (tb[TCA_BASIC_CLASSID]) {
f->res.classid = nla_get_u32(tb[TCA_BASIC_CLASSID]);
tcf_bind_filter(tp, &f->res, base);
}
tcf_exts_change(tp, &f->exts, &e);
tcf_em_tree_change(tp, &f->ematches, &t);
f->tp = tp;
return 0;
errout:
tcf_exts_destroy(&e);
return err;
}
static int basic_change(struct net *net, struct sk_buff *in_skb,
struct tcf_proto *tp, unsigned long base, u32 handle,
struct nlattr **tca, unsigned long *arg, bool ovr)
{
int err;
struct basic_head *head = rtnl_dereference(tp->root);
struct nlattr *tb[TCA_BASIC_MAX + 1];
struct basic_filter *fold = (struct basic_filter *) *arg;
struct basic_filter *fnew;
if (tca[TCA_OPTIONS] == NULL)
return -EINVAL;
err = nla_parse_nested(tb, TCA_BASIC_MAX, tca[TCA_OPTIONS],
basic_policy);
if (err < 0)
return err;
if (fold != NULL) {
if (handle && fold->handle != handle)
return -EINVAL;
}
fnew = kzalloc(sizeof(*fnew), GFP_KERNEL);
if (!fnew)
return -ENOBUFS;
tcf_exts_init(&fnew->exts, TCA_BASIC_ACT, TCA_BASIC_POLICE);
err = -EINVAL;
if (handle) {
fnew->handle = handle;
} else if (fold) {
fnew->handle = fold->handle;
} else {
unsigned int i = 0x80000000;
do {
if (++head->hgenerator == 0x7FFFFFFF)
head->hgenerator = 1;
} while (--i > 0 && basic_get(tp, head->hgenerator));
if (i <= 0) {
pr_err("Insufficient number of handles\n");
goto errout;
}
fnew->handle = head->hgenerator;
}
err = basic_set_parms(net, tp, fnew, base, tb, tca[TCA_RATE], ovr);
if (err < 0)
goto errout;
*arg = (unsigned long)fnew;
if (fold) {
list_replace_rcu(&fold->link, &fnew->link);
tcf_unbind_filter(tp, &fold->res);
call_rcu(&fold->rcu, basic_delete_filter);
} else {
list_add_rcu(&fnew->link, &head->flist);
}
return 0;
errout:
kfree(fnew);
return err;
}
static void basic_walk(struct tcf_proto *tp, struct tcf_walker *arg)
{
struct basic_head *head = rtnl_dereference(tp->root);
struct basic_filter *f;
list_for_each_entry(f, &head->flist, link) {
if (arg->count < arg->skip)
goto skip;
if (arg->fn(tp, (unsigned long) f, arg) < 0) {
arg->stop = 1;
break;
}
skip:
arg->count++;
}
}
static int basic_dump(struct net *net, struct tcf_proto *tp, unsigned long fh,
struct sk_buff *skb, struct tcmsg *t)
{
struct basic_filter *f = (struct basic_filter *) fh;
struct nlattr *nest;
if (f == NULL)
return skb->len;
t->tcm_handle = f->handle;
nest = nla_nest_start(skb, TCA_OPTIONS);
if (nest == NULL)
goto nla_put_failure;
if (f->res.classid &&
nla_put_u32(skb, TCA_BASIC_CLASSID, f->res.classid))
goto nla_put_failure;
if (tcf_exts_dump(skb, &f->exts) < 0 ||
tcf_em_tree_dump(skb, &f->ematches, TCA_BASIC_EMATCHES) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest);
if (tcf_exts_dump_stats(skb, &f->exts) < 0)
goto nla_put_failure;
return skb->len;
nla_put_failure:
nla_nest_cancel(skb, nest);
return -1;
}
static struct tcf_proto_ops cls_basic_ops __read_mostly = {
.kind = "basic",
.classify = basic_classify,
.init = basic_init,
.destroy = basic_destroy,
.get = basic_get,
.change = basic_change,
.delete = basic_delete,
.walk = basic_walk,
.dump = basic_dump,
.owner = THIS_MODULE,
};
static int __init init_basic(void)
{
return register_tcf_proto_ops(&cls_basic_ops);
}
static void __exit exit_basic(void)
{
unregister_tcf_proto_ops(&cls_basic_ops);
}
module_init(init_basic)
module_exit(exit_basic)
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var obj = {
name: 'test',
age: 3,
foo: function() {}
};
console.log('-------------for...in-------------');
// 利用for...in遍历,for...in会遍历所有可枚举的属性,包含原型对象上的
for (var prop in obj) {
console.log(prop, obj[prop]);
}
console.log('-------------使用hasOwnProperty过滤原型属性-------------');
// 使用hasOwnProperty过滤原型属性
for (var prop2 in obj) {
if (obj.hasOwnProperty(prop2)) {
console.log(prop2, obj[prop2]);
}
}
console.log('-------------es5支持(IE9+)-------------');
console.log('-------------keys-------------');
// 通过Object.keys获得对象的所有属性名组成的数组
console.log(Object.keys(obj));
console.log('-------------es6支持-------------');
console.log('-------------values-------------');
// 通过Object.values获得对象的所有值组成的数组
console.log(Object.values(obj));
console.log('-------------entries-------------');
// 通过Object.entries获得对象的键值对组成的的多维数组
console.log(Object.entries(obj));
</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<title>Api Documentation</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link type='text/css' rel='stylesheet' href='../../apidoc/stylesheets/bundled/bootstrap.min.css'/>
<link type='text/css' rel='stylesheet' href='../../apidoc/stylesheets/bundled/prettify.css'/>
<link type='text/css' rel='stylesheet' href='../../apidoc/stylesheets/bundled/bootstrap-responsive.min.css'/>
<link type='text/css' rel='stylesheet' href='../../apidoc/stylesheets/application.css'/>
<!-- IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div id='container'>
<ul class='breadcrumb'>
<li>
<a href='../../apidoc/v2.cs_CZ.html'>Foreman v2</a>
<span class='divider'>/</span>
</li>
<li class='active'>
Auth source externals
</li>
<li class='pull-right'>
[ <a href="../../apidoc/v2/auth_source_externals.pt_BR.html">pt_BR</a> | <a href="../../apidoc/v2/auth_source_externals.de.html">de</a> | <a href="../../apidoc/v2/auth_source_externals.it.html">it</a> | <a href="../../apidoc/v2/auth_source_externals.sv_SE.html">sv_SE</a> | <a href="../../apidoc/v2/auth_source_externals.zh_CN.html">zh_CN</a> | <a href="../../apidoc/v2/auth_source_externals.en_GB.html">en_GB</a> | <b><a href="../../apidoc/v2/auth_source_externals.cs_CZ.html">cs_CZ</a></b> | <a href="../../apidoc/v2/auth_source_externals.fr.html">fr</a> | <a href="../../apidoc/v2/auth_source_externals.ru.html">ru</a> | <a href="../../apidoc/v2/auth_source_externals.ja.html">ja</a> | <a href="../../apidoc/v2/auth_source_externals.es.html">es</a> | <a href="../../apidoc/v2/auth_source_externals.ko.html">ko</a> | <a href="../../apidoc/v2/auth_source_externals.ca.html">ca</a> | <a href="../../apidoc/v2/auth_source_externals.gl.html">gl</a> | <a href="../../apidoc/v2/auth_source_externals.en.html">en</a> | <a href="../../apidoc/v2/auth_source_externals.zh_TW.html">zh_TW</a> | <a href="../../apidoc/v2/auth_source_externals.nl_NL.html">nl_NL</a> | <a href="../../apidoc/v2/auth_source_externals.pl.html">pl</a> ]
</li>
</ul>
<div class='page-header'>
<h1>
Auth source externals
<br>
<small></small>
</h1>
</div>
<div class='accordion' id='accordion'>
<hr>
<div class='pull-right small'>
<a href='../../apidoc/v2/auth_source_externals/index.cs_CZ.html'> >>> </a>
</div>
<div>
<h2>
<a href='#description-index'
class='accordion-toggle'
data-toggle='collapse'
data-parent='#accordion'>
GET /api/auth_source_externals
</a>
<br>
<small>List external authentication sources</small>
</h2>
<h2>
<a href='#description-index'
class='accordion-toggle'
data-toggle='collapse'
data-parent='#accordion'>
GET /api/locations/:location_id/auth_source_externals
</a>
<br>
<small>List external authentication sources per location</small>
</h2>
<h2>
<a href='#description-index'
class='accordion-toggle'
data-toggle='collapse'
data-parent='#accordion'>
GET /api/organizations/:organization_id/auth_source_externals
</a>
<br>
<small>List external authentication sources per organization</small>
</h2>
</div>
<div id='description-index' class='collapse accordion-body'>
<h3><span class="translation_missing" title="translation missing: cs-CZ.apipie.examples">Examples</span></h3>
<pre class="prettyprint">GET /api/auth_source_externals
200
{
"total": 1,
"subtotal": 1,
"page": 1,
"per_page": 20,
"search": null,
"sort": {
"by": null,
"order": null
},
"results": [
{
"created_at": "2019-02-20 13:34:38 UTC",
"updated_at": "2019-02-20 13:34:38 UTC",
"id": 408068537,
"name": "External",
"locations": [],
"organizations": []
}
]
}</pre>
<h3><span class="translation_missing" title="translation missing: cs-CZ.apipie.params">Params</span></h3>
<table class='table'>
<thead>
<tr>
<th><span class="translation_missing" title="translation missing: cs-CZ.apipie.param_name">Param Name</span></th>
<th><span class="translation_missing" title="translation missing: cs-CZ.apipie.description">Description</span></th>
</tr>
</thead>
<tbody>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>location_id </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>Scope by locations</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>organization_id </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>Scope by organizations</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>search </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>výsledky filtru</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>order </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>Sort field and order, eg. ‘id DESC’</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>page </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>stránkovat výsledky</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>per_page </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>počet položek na požadavek</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
<hr>
<div class='pull-right small'>
<a href='../../apidoc/v2/auth_source_externals/show.cs_CZ.html'> >>> </a>
</div>
<div>
<h2>
<a href='#description-show'
class='accordion-toggle'
data-toggle='collapse'
data-parent='#accordion'>
GET /api/auth_source_externals/:id
</a>
<br>
<small>Show an external authentication source</small>
</h2>
</div>
<div id='description-show' class='collapse accordion-body'>
<h3><span class="translation_missing" title="translation missing: cs-CZ.apipie.examples">Examples</span></h3>
<pre class="prettyprint">GET /api/auth_source_externals/408068537
200
{
"created_at": "2019-02-20 13:34:38 UTC",
"updated_at": "2019-02-20 13:34:38 UTC",
"id": 408068537,
"name": "External",
"external_usergroups": [],
"locations": [
{
"id": 255093256,
"name": "Location 1",
"title": "Location 1",
"description": null
}
],
"organizations": [
{
"id": 447626438,
"name": "Organization 1",
"title": "Organization 1",
"description": null
}
]
}</pre>
<h3><span class="translation_missing" title="translation missing: cs-CZ.apipie.params">Params</span></h3>
<table class='table'>
<thead>
<tr>
<th><span class="translation_missing" title="translation missing: cs-CZ.apipie.param_name">Param Name</span></th>
<th><span class="translation_missing" title="translation missing: cs-CZ.apipie.description">Description</span></th>
</tr>
</thead>
<tbody>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>location_id </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>Scope by locations</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>organization_id </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>Scope by organizations</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>id </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.required">Required</span>
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be an identifier, string from 1 to 128 characters containing only alphanumeric characters, space, underscore(_), hypen(-) with no leading or trailing space.</p>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
<hr>
<div class='pull-right small'>
<a href='../../apidoc/v2/auth_source_externals/update.cs_CZ.html'> >>> </a>
</div>
<div>
<h2>
<a href='#description-update'
class='accordion-toggle'
data-toggle='collapse'
data-parent='#accordion'>
PUT /api/auth_source_externals/:id
</a>
<br>
<small>Update an external authentication source</small>
</h2>
</div>
<div id='description-update' class='collapse accordion-body'>
<h3><span class="translation_missing" title="translation missing: cs-CZ.apipie.examples">Examples</span></h3>
<pre class="prettyprint">PUT /api/auth_source_externals/408068537
{
"auth_source_external": {
"organization_names": [
"Organization 1"
],
"location_ids": [
255093256
]
}
}
200
{
"created_at": "2019-02-20 13:34:38 UTC",
"updated_at": "2019-02-20 13:34:38 UTC",
"id": 408068537,
"name": "External",
"external_usergroups": [],
"locations": [
{
"id": 255093256,
"name": "Location 1",
"title": "Location 1",
"description": null
}
],
"organizations": [
{
"id": 447626438,
"name": "Organization 1",
"title": "Organization 1",
"description": null
}
]
}</pre>
<h3><span class="translation_missing" title="translation missing: cs-CZ.apipie.params">Params</span></h3>
<table class='table'>
<thead>
<tr>
<th><span class="translation_missing" title="translation missing: cs-CZ.apipie.param_name">Param Name</span></th>
<th><span class="translation_missing" title="translation missing: cs-CZ.apipie.description">Description</span></th>
</tr>
</thead>
<tbody>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>location_id </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>Scope by locations</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>organization_id </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
</small>
</td>
<td>
<p>Scope by organizations</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>id </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.required">Required</span>
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be an identifier, string from 1 to 128 characters containing only alphanumeric characters, space, underscore(_), hypen(-) with no leading or trailing space.</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>auth_source_external </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.required">Required</span>
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Hash</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_external[name] </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_external[location_ids] </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
, <span class="translation_missing" title="translation missing: cs-CZ.apipie.nil_allowed">Nil Allowed</span>
</small>
</td>
<td>
<p>REPLACE locations with given ids</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be an array of any type</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_external[organization_ids] </strong><br>
<small>
<span class="translation_missing" title="translation missing: cs-CZ.apipie.optional">Optional</span>
, <span class="translation_missing" title="translation missing: cs-CZ.apipie.nil_allowed">Nil Allowed</span>
</small>
</td>
<td>
<p>REPLACE organizations with given ids.</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be an array of any type</p>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<hr>
<footer></footer>
</div>
<script type='text/javascript' src='../../apidoc/javascripts/bundled/jquery.js'></script>
<script type='text/javascript' src='../../apidoc/javascripts/bundled/bootstrap-collapse.js'></script>
<script type='text/javascript' src='../../apidoc/javascripts/bundled/prettify.js'></script>
<script type='text/javascript' src='../../apidoc/javascripts/apipie.js'></script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
//
// PieceAnimation.swift
// ADPuzzleLoader
//
// Created by Anton Domashnev on 1/9/16.
// Copyright © 2016 Anton Domashnev. All rights reserved.
//
import UIKit
extension CAAnimation {
//MARK: - Interface
static func basicForwardPieceAnimation(piece: Piece, velocity: Double, delay: CFTimeInterval, scale: Double) -> CAAnimation {
func setDefaultValuesForAnimation(animation: CAAnimation) {
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
}
func setAnimationDurationBasedOnVelocity(animation: CAAnimation, velocity: Double) {
animation.duration = 10.0 / velocity
}
let moveAnimation: CABasicAnimation = CABasicAnimation(keyPath: "position")
setDefaultValuesForAnimation(moveAnimation)
setAnimationDurationBasedOnVelocity(moveAnimation, velocity: velocity)
moveAnimation.fromValue = NSValue(CGPoint: piece.initialPosition)
moveAnimation.toValue = NSValue(CGPoint: piece.desiredPosition)
moveAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.0, 0.84, 0.49, 1.00)
let scaleAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.scale")
setDefaultValuesForAnimation(scaleAnimation)
setAnimationDurationBasedOnVelocity(scaleAnimation, velocity: velocity)
scaleAnimation.fromValue = scale
scaleAnimation.toValue = 1
scaleAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.0, 0.84, 0.49, 1.00)
let forwardAnimation = CAAnimationGroup()
setDefaultValuesForAnimation(forwardAnimation)
setAnimationDurationBasedOnVelocity(forwardAnimation, velocity: velocity)
forwardAnimation.animations = [moveAnimation, scaleAnimation]
forwardAnimation.beginTime = CACurrentMediaTime() + delay
return forwardAnimation
}
static func basicBackwardPieceAnimation(piece: Piece, velocity: Double, delay: CFTimeInterval, scale: Double) -> CAAnimation {
func setDefaultValuesForAnimation(animation: CAAnimation) {
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
}
func setAnimationDurationBasedOnVelocity(animation: CAAnimation, velocity: Double) {
animation.duration = 10.0 / velocity
}
let moveAnimation: CABasicAnimation = CABasicAnimation(keyPath: "position")
setDefaultValuesForAnimation(moveAnimation)
setAnimationDurationBasedOnVelocity(moveAnimation, velocity: velocity)
moveAnimation.fromValue = NSValue(CGPoint: piece.initialPosition)
moveAnimation.toValue = NSValue(CGPoint: piece.desiredPosition)
moveAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 1.0, 0.0, 1.0, 0.67)
let scaleAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.scale")
setDefaultValuesForAnimation(scaleAnimation)
setAnimationDurationBasedOnVelocity(scaleAnimation, velocity: velocity)
scaleAnimation.fromValue = 1
scaleAnimation.toValue = scale
scaleAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 1.0, 0.0, 1.0, 0.67)
let forwardAnimation = CAAnimationGroup()
setDefaultValuesForAnimation(forwardAnimation)
setAnimationDurationBasedOnVelocity(forwardAnimation, velocity: velocity)
forwardAnimation.animations = [moveAnimation, scaleAnimation]
forwardAnimation.beginTime = CACurrentMediaTime() + delay
return forwardAnimation
}
}
| {
"pile_set_name": "Github"
} |
/*
* dice_hwdep.c - a part of driver for DICE based devices
*
* Copyright (c) Clemens Ladisch <[email protected]>
* Copyright (c) 2014 Takashi Sakamoto <[email protected]>
*
* Licensed under the terms of the GNU General Public License, version 2.
*/
#include "dice.h"
static long hwdep_read(struct snd_hwdep *hwdep, char __user *buf,
long count, loff_t *offset)
{
struct snd_dice *dice = hwdep->private_data;
DEFINE_WAIT(wait);
union snd_firewire_event event;
spin_lock_irq(&dice->lock);
while (!dice->dev_lock_changed && dice->notification_bits == 0) {
prepare_to_wait(&dice->hwdep_wait, &wait, TASK_INTERRUPTIBLE);
spin_unlock_irq(&dice->lock);
schedule();
finish_wait(&dice->hwdep_wait, &wait);
if (signal_pending(current))
return -ERESTARTSYS;
spin_lock_irq(&dice->lock);
}
memset(&event, 0, sizeof(event));
if (dice->dev_lock_changed) {
event.lock_status.type = SNDRV_FIREWIRE_EVENT_LOCK_STATUS;
event.lock_status.status = dice->dev_lock_count > 0;
dice->dev_lock_changed = false;
count = min_t(long, count, sizeof(event.lock_status));
} else {
event.dice_notification.type =
SNDRV_FIREWIRE_EVENT_DICE_NOTIFICATION;
event.dice_notification.notification = dice->notification_bits;
dice->notification_bits = 0;
count = min_t(long, count, sizeof(event.dice_notification));
}
spin_unlock_irq(&dice->lock);
if (copy_to_user(buf, &event, count))
return -EFAULT;
return count;
}
static __poll_t hwdep_poll(struct snd_hwdep *hwdep, struct file *file,
poll_table *wait)
{
struct snd_dice *dice = hwdep->private_data;
__poll_t events;
poll_wait(file, &dice->hwdep_wait, wait);
spin_lock_irq(&dice->lock);
if (dice->dev_lock_changed || dice->notification_bits != 0)
events = EPOLLIN | EPOLLRDNORM;
else
events = 0;
spin_unlock_irq(&dice->lock);
return events;
}
static int hwdep_get_info(struct snd_dice *dice, void __user *arg)
{
struct fw_device *dev = fw_parent_device(dice->unit);
struct snd_firewire_get_info info;
memset(&info, 0, sizeof(info));
info.type = SNDRV_FIREWIRE_TYPE_DICE;
info.card = dev->card->index;
*(__be32 *)&info.guid[0] = cpu_to_be32(dev->config_rom[3]);
*(__be32 *)&info.guid[4] = cpu_to_be32(dev->config_rom[4]);
strlcpy(info.device_name, dev_name(&dev->device),
sizeof(info.device_name));
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
static int hwdep_lock(struct snd_dice *dice)
{
int err;
spin_lock_irq(&dice->lock);
if (dice->dev_lock_count == 0) {
dice->dev_lock_count = -1;
err = 0;
} else {
err = -EBUSY;
}
spin_unlock_irq(&dice->lock);
return err;
}
static int hwdep_unlock(struct snd_dice *dice)
{
int err;
spin_lock_irq(&dice->lock);
if (dice->dev_lock_count == -1) {
dice->dev_lock_count = 0;
err = 0;
} else {
err = -EBADFD;
}
spin_unlock_irq(&dice->lock);
return err;
}
static int hwdep_release(struct snd_hwdep *hwdep, struct file *file)
{
struct snd_dice *dice = hwdep->private_data;
spin_lock_irq(&dice->lock);
if (dice->dev_lock_count == -1)
dice->dev_lock_count = 0;
spin_unlock_irq(&dice->lock);
return 0;
}
static int hwdep_ioctl(struct snd_hwdep *hwdep, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct snd_dice *dice = hwdep->private_data;
switch (cmd) {
case SNDRV_FIREWIRE_IOCTL_GET_INFO:
return hwdep_get_info(dice, (void __user *)arg);
case SNDRV_FIREWIRE_IOCTL_LOCK:
return hwdep_lock(dice);
case SNDRV_FIREWIRE_IOCTL_UNLOCK:
return hwdep_unlock(dice);
default:
return -ENOIOCTLCMD;
}
}
#ifdef CONFIG_COMPAT
static int hwdep_compat_ioctl(struct snd_hwdep *hwdep, struct file *file,
unsigned int cmd, unsigned long arg)
{
return hwdep_ioctl(hwdep, file, cmd,
(unsigned long)compat_ptr(arg));
}
#else
#define hwdep_compat_ioctl NULL
#endif
int snd_dice_create_hwdep(struct snd_dice *dice)
{
static const struct snd_hwdep_ops ops = {
.read = hwdep_read,
.release = hwdep_release,
.poll = hwdep_poll,
.ioctl = hwdep_ioctl,
.ioctl_compat = hwdep_compat_ioctl,
};
struct snd_hwdep *hwdep;
int err;
err = snd_hwdep_new(dice->card, "DICE", 0, &hwdep);
if (err < 0)
return err;
strcpy(hwdep->name, "DICE");
hwdep->iface = SNDRV_HWDEP_IFACE_FW_DICE;
hwdep->ops = ops;
hwdep->private_data = dice;
hwdep->exclusive = true;
return 0;
}
| {
"pile_set_name": "Github"
} |
#!/bin/bash
#
# Script to run Shadowsocks in daemon mode at boot time.
# ScriptAuthor: icyboy
# Revision 1.0 - 14th Sep 2013
#====================================================================
# Run level information:
# chkconfig: 2345 99 99
# Description: lightweight secured socks5 proxy
# processname: ss-server
# Author: Max Lv <[email protected]>;
# Run "/sbin/chkconfig --add shadowsocks" to add the Run levels.
#====================================================================
#====================================================================
# Paths and variables and system checks.
# Source function library
. /etc/rc.d/init.d/functions
# Check that networking is up.
#
[ ${NETWORKING} ="yes" ] || exit 0
# Daemon
NAME=shadowsocks-server
DAEMON=/usr/bin/ss-server
# Path to the configuration file.
#
CONF=/etc/shadowsocks-libev/config.json
#USER="nobody"
#GROUP="nobody"
# Take care of pidfile permissions
mkdir /var/run/$NAME 2>/dev/null || true
#chown "$USER:$GROUP" /var/run/$NAME
# Check the configuration file exists.
#
if [ ! -f $CONF ] ; then
echo "The configuration file cannot be found!"
exit 0
fi
# Path to the lock file.
#
LOCK_FILE=/var/lock/subsys/shadowsocks
# Path to the pid file.
#
PID=/var/run/$NAME/pid
#====================================================================
#====================================================================
# Run controls:
RETVAL=0
# Start shadowsocks as daemon.
#
start() {
if [ -f $LOCK_FILE ]; then
echo "$NAME is already running!"
exit 0
else
echo -n $"Starting ${NAME}: "
#daemon --check $DAEMON --user $USER "$DAEMON -f $PID -c $CONF > /dev/null"
daemon $DAEMON -u -c $CONF -f $PID
fi
RETVAL=$?
[ $RETVAL -eq 0 ] && success
echo
[ $RETVAL -eq 0 ] && touch $LOCK_FILE
return $RETVAL
}
# Stop shadowsocks.
#
stop() {
echo -n $"Shutting down ${NAME}: "
killproc -p ${PID}
RETVAL=$?
[ $RETVAL -eq 0 ]
rm -f $LOCK_FILE
rm -f ${PID}
echo
return $RETVAL
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
condrestart)
if [ -f $LOCK_FILE ]; then
stop
start
RETVAL=$?
fi
;;
status)
status $DAEMON
RETVAL=$?
;;
*)
echo $"Usage: $0 {start|stop|restart|condrestart|status}"
RETVAL=1
esac
exit $RETVAL
| {
"pile_set_name": "Github"
} |
# Copyright (c) 2008-2013 Michael Dvorkin and contributors.
#
# Fat Free CRM is freely distributable under the terms of MIT license.
# See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
(($) ->
window.crm ||= {}
crm.init_sortables = ->
$('[data-sortable]').each ->
$el = $(this)
checkEmpty = ->
$el.children('.empty').toggle($el.sortable('toArray').length is 1)
$el.sortable(
forcePlaceholderSize: true
connectWith: $el.data('sortable-connect-with')
handle: $el.data('sortable-handle')
create: checkEmpty
update: ->
ids = []
for dom_id in $el.sortable('toArray')
ids.push dom_id.replace(/[^\d]/g, '')
data = {}
data[$el.attr('id')] = ids
$.post($el.attr('data-sortable'), data)
checkEmpty()
)
$(document).ready ->
crm.init_sortables()
$(document).ajaxComplete ->
crm.init_sortables()
) jQuery
| {
"pile_set_name": "Github"
} |
<!--{}-->
<template>
<div
v-on:b="
!function
(
a
,
b
)
{
;
}
"
></div>
</template>
| {
"pile_set_name": "Github"
} |
define([
'jquery',
'underscore',
'backbone',
'models/linkPeer',
'views/modal',
'text!templates/modalAddLocPeer.html'
], function($, _, Backbone, LinkPeerModel, ModalView,
modalAddLocPeerTemplate) {
'use strict';
var ModalAddLocPeerView = ModalView.extend({
className: 'add-location-peer-modal',
template: _.template(modalAddLocPeerTemplate),
title: 'Add Location Peer',
okText: 'Add',
initialize: function(options) {
this.link = options.link;
this.location = options.location;
this.locations = options.locations;
ModalAddLocPeerView.__super__.initialize.call(this);
},
body: function() {
return this.template({
location_id: this.location,
locations: this.locations.toJSON()
});
},
onOk: function() {
var peerId = this.$('.peer-id select').val();
if (!peerId) {
this.setAlert('danger', 'Missing peer.', '.peer-id');
return;
}
this.setLoading('Adding location peer...');
var model = new LinkPeerModel();
model.save({
link_id: this.link,
location_id: this.location,
peer_id: peerId
}, {
success: function() {
this.close(true);
}.bind(this),
error: function(model, response) {
this.clearLoading();
if (response.responseJSON) {
this.setAlert('danger', response.responseJSON.error_msg);
}
else {
this.setAlert('danger', this.errorMsg);
}
}.bind(this)
});
}
});
return ModalAddLocPeerView;
});
| {
"pile_set_name": "Github"
} |
{
"id": "stone-egg-outfit",
"name": "Stone-egg Outfit",
"games": {
"nh": {
"orderable": false,
"customizable": false,
"sellPrice": {
"currency": "bells",
"value": 1200
},
"recipe": {
"stone-egg": 3
},
"variations": {
"yellow": "Yellow"
}
}
},
"category": "Dresses"
} | {
"pile_set_name": "Github"
} |
-e ../datadog_checks_dev
| {
"pile_set_name": "Github"
} |
server:
port: 3344
spring:
application:
name: cloud-config-center
cloud:
config:
server:
git:
#uri: [email protected]:EiletXie/config-repo.git #Github上的git仓库名字
uri: https://github.com/EiletXie/config-repo.git
##搜索目录.这个目录指的是github上的目录
search-paths:
- config-repo
##读取分支
label: master
#rabbit相关配置 15672是web管理界面的端口,5672是MQ访问的端口
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/
#rabbitmq相关设置 ,暴露 bus刷新配置的端点
management:
endpoints:
web:
exposure:
include: 'bus-refresh'
| {
"pile_set_name": "Github"
} |
package integration
import (
"fmt"
"net/http"
"net/http/httptest"
"net/http/httputil"
"os/exec"
"strings"
"testing"
"github.com/sclevine/spec"
"github.com/stretchr/testify/require"
)
var _ = suite("projects/resources/get", func(t *testing.T, when spec.G, it spec.S) {
var (
expect *require.Assertions
server *httptest.Server
)
it.Before(func() {
expect = require.New(t)
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
switch req.URL.Path {
case "/v2/droplets/1111":
auth := req.Header.Get("Authorization")
if auth != "Bearer some-magic-token" {
w.WriteHeader(http.StatusUnauthorized)
return
}
if req.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Write([]byte(dropletGetResponse))
case "/v2/floating_ips/1111":
auth := req.Header.Get("Authorization")
if auth != "Bearer some-magic-token" {
w.WriteHeader(http.StatusUnauthorized)
return
}
if req.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Write([]byte(projectsResourcesGetFloatingIPResponse))
case "/v2/load_balancers/1111":
auth := req.Header.Get("Authorization")
if auth != "Bearer some-magic-token" {
w.WriteHeader(http.StatusUnauthorized)
return
}
if req.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Write([]byte(projectsResourcesGetLoadbalancerResponse))
case "/v2/domains/1111":
auth := req.Header.Get("Authorization")
if auth != "Bearer some-magic-token" {
w.WriteHeader(http.StatusUnauthorized)
return
}
if req.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Write([]byte(projectsResourcesGetDomainResponse))
case "/v2/volumes/1111":
auth := req.Header.Get("Authorization")
if auth != "Bearer some-magic-token" {
w.WriteHeader(http.StatusUnauthorized)
return
}
if req.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Write([]byte(projectsResourcesGetVolumeResponse))
default:
dump, err := httputil.DumpRequest(req, true)
if err != nil {
t.Fatal("failed to dump request")
}
t.Fatalf("received unknown request: %s", dump)
}
}))
})
when("passing a droplet urn", func() {
it("gets that resource for the project", func() {
cmd := exec.Command(builtBinaryPath,
"-t", "some-magic-token",
"-u", server.URL,
"projects",
"resources",
"get",
"do:droplet:1111",
)
output, err := cmd.CombinedOutput()
expect.NoError(err, fmt.Sprintf("received error output: %s", output))
expect.Equal(strings.TrimSpace(projectsResourcesGetDropletOutput), strings.TrimSpace(string(output)))
})
})
when("passing a floatingip urn", func() {
it("gets that resource for the project", func() {
cmd := exec.Command(builtBinaryPath,
"-t", "some-magic-token",
"-u", server.URL,
"projects",
"resources",
"get",
"do:floatingip:1111",
)
output, err := cmd.CombinedOutput()
expect.NoError(err, fmt.Sprintf("received error output: %s", output))
expect.Equal(strings.TrimSpace(projectsResourcesGetFloatingIPOutput), strings.TrimSpace(string(output)))
})
})
when("passing a loadbalancer urn", func() {
it("gets that resource for the project", func() {
cmd := exec.Command(builtBinaryPath,
"-t", "some-magic-token",
"-u", server.URL,
"projects",
"resources",
"get",
"do:loadbalancer:1111",
)
output, err := cmd.CombinedOutput()
expect.NoError(err, fmt.Sprintf("received error output: %s", output))
expect.Equal(strings.TrimSpace(projectsResourcesGetLoadbalancerOutput), strings.TrimSpace(string(output)))
})
})
when("passing a domain urn", func() {
it("gets that resource for the project", func() {
cmd := exec.Command(builtBinaryPath,
"-t", "some-magic-token",
"-u", server.URL,
"projects",
"resources",
"get",
"do:domain:1111",
)
output, err := cmd.CombinedOutput()
expect.NoError(err, fmt.Sprintf("received error output: %s", output))
expect.Equal(strings.TrimSpace(projectsResourcesGetDomainOutput), strings.TrimSpace(string(output)))
})
})
when("passing a volume urn", func() {
it("gets that resource for the project", func() {
cmd := exec.Command(builtBinaryPath,
"-t", "some-magic-token",
"-u", server.URL,
"projects",
"resources",
"get",
"do:volume:1111",
)
output, err := cmd.CombinedOutput()
expect.NoError(err, fmt.Sprintf("received error output: %s", output))
expect.Equal(strings.TrimSpace(projectsResourcesGetVolumeOutput), strings.TrimSpace(string(output)))
})
})
})
const (
projectsResourcesGetDropletOutput = `
ID Name Public IPv4 Private IPv4 Public IPv6 Memory VCPUs Disk Region Image VPC UUID Status Tags Features Volumes
5555 some-droplet-name 0 0 0 some-region-slug some-distro some-image-name active yes remotes some-volume-id
`
projectsResourcesGetFloatingIPOutput = `
IP Region Droplet ID Droplet Name
45.55.96.47 nyc3
`
projectsResourcesGetFloatingIPResponse = `
{
"floating_ip": {
"ip": "45.55.96.47",
"droplet": null,
"region": {
"name": "New York 3",
"slug": "nyc3",
"sizes": [ "s-1vcpu-1gb" ],
"features": [ "metadata" ],
"available": true
},
"locked": false
}
}
`
projectsResourcesGetLoadbalancerOutput = `
ID IP Name Status Created At Algorithm Region VPC UUID Tag Droplet IDs SSL Sticky Sessions Health Check Forwarding Rules
4de7ac8b-495b-4884-9a69-1050c6793cd6 104.131.186.241 example-lb-01 new 2017-02-01T22:22:58Z round_robin nyc3 00000000-0000-4000-8000-000000000000 3164445 false type:none,cookie_name:,cookie_ttl_seconds:0 protocol:,port:0,path:,check_interval_seconds:0,response_timeout_seconds:0,healthy_threshold:0,unhealthy_threshold:0 entry_protocol:https,entry_port:444,target_protocol:https,target_port:443,certificate_id:,tls_passthrough:true
`
projectsResourcesGetLoadbalancerResponse = `
{
"load_balancer": {
"id": "4de7ac8b-495b-4884-9a69-1050c6793cd6",
"name": "example-lb-01",
"ip": "104.131.186.241",
"algorithm": "round_robin",
"status": "new",
"created_at": "2017-02-01T22:22:58Z",
"forwarding_rules": [
{
"entry_protocol": "https",
"entry_port": 444,
"target_protocol": "https",
"target_port": 443,
"certificate_id": "",
"tls_passthrough": true
}
],
"health_check": {},
"sticky_sessions": {
"type": "none"
},
"region": {
"name": "New York 3",
"slug": "nyc3",
"sizes": [
"s-32vcpu-192gb"
],
"features": [ "install_agent" ],
"available": true
},
"vpc_uuid": "00000000-0000-4000-8000-000000000000",
"droplet_ids": [ 3164445 ],
"redirect_http_to_https": false,
"enable_proxy_protocol": false
}
}
`
projectsResourcesGetDomainOutput = `
Domain TTL
example.com 1800
`
projectsResourcesGetDomainResponse = `
{
"domain": {
"name": "example.com",
"ttl": 1800,
"zone_file": "some zone file with crazy data"
}
}
`
projectsResourcesGetVolumeOutput = `
ID Name Size Region Filesystem Type Filesystem Label Droplet IDs Tags
506f78a4-e098-11e5-ad9f-000f53306ae1 example 10 GiB nyc1 aninterestingtag
`
projectsResourcesGetVolumeResponse = `
{
"volume": {
"id": "506f78a4-e098-11e5-ad9f-000f53306ae1",
"region": {
"name": "New York 1",
"slug": "nyc1",
"sizes": [ "s-1vcpu-1gb" ],
"features": [ "metadata" ],
"available": true
},
"droplet_ids": [],
"name": "example",
"description": "Block store for examples",
"size_gigabytes": 10,
"created_at": "2016-03-02T17:00:49Z",
"tags": [ "aninterestingtag" ]
}
}
`
)
| {
"pile_set_name": "Github"
} |
// Copyright 2014 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.
// +build linux
// +build ppc64 ppc64le
// +build !gccgo
#include "textflag.h"
//
// System calls for ppc64, Linux
//
// Just jump to package syscall's implementation for all these functions.
// The runtime may know about them.
TEXT ·SyscallNoError(SB),NOSPLIT,$0-48
BL runtime·entersyscall(SB)
MOVD a1+8(FP), R3
MOVD a2+16(FP), R4
MOVD a3+24(FP), R5
MOVD R0, R6
MOVD R0, R7
MOVD R0, R8
MOVD trap+0(FP), R9 // syscall entry
SYSCALL R9
MOVD R3, r1+32(FP)
MOVD R4, r2+40(FP)
BL runtime·exitsyscall(SB)
RET
TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48
MOVD a1+8(FP), R3
MOVD a2+16(FP), R4
MOVD a3+24(FP), R5
MOVD R0, R6
MOVD R0, R7
MOVD R0, R8
MOVD trap+0(FP), R9 // syscall entry
SYSCALL R9
MOVD R3, r1+32(FP)
MOVD R4, r2+40(FP)
RET
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/FaceDetectorExample.iml" filepath="$PROJECT_DIR$/FaceDetectorExample.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
</modules>
</component>
</project> | {
"pile_set_name": "Github"
} |
# Locally calculated
sha256 ae22ef11c934364be4fd2a0a1a7aadf4495a0251ec6979da280d342a89ca3c2f lshw-B.02.18.tar.gz
| {
"pile_set_name": "Github"
} |
module.exports = function buildEnvironment(environment) {
const ENV = {
modulePrefix: 'ember-example',
environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
},
EXTEND_PROTOTYPES: {
// Prevent Ember Data from overriding Date.parse.
Date: false,
},
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
ENV.APP.autoboot = false;
}
if (environment === 'production') {
// here you can enable a production-specific feature
}
return ENV;
};
| {
"pile_set_name": "Github"
} |
import React from 'react';
import Grid from '@material-ui/core/Grid';
import * as PropTypes from 'prop-types';
import Box from '@material-ui/core/Box';
import Widget from '../components/Widget/Widget';
import DeploymentDetailsSection from '../components/DeploymentDetailsSection';
import { useDeploymentDetailsContext } from '../context/DeploymentDetailsContext';
import AlertsChartContainer from './AlertsChartContainer';
import AlertsIntegrationModal
from '../components/IntergationModals/AlertsIntegrationModal/AlertsIntegrationModal';
const Alerts = ({ kindIndex }) => {
const { data } = useDeploymentDetailsContext();
if (!data) {
return null;
}
const { alerts } = data.kinds[kindIndex];
let content;
// if no alerts configured
if (alerts.length === 0) {
content = (
<Grid item xs={12}>
<Widget>
<Box
mt={2}
mb={2}
display="flex"
justifyContent="space-around"
>
<AlertsIntegrationModal />
</Box>
</Widget>
</Grid>
);
} else {
content = (
<Grid container spacing={2}>
{
alerts.map(({ provider, tags }) => (
<Grid key={`${provider}-${tags}`} item xs={12}>
<Widget title={provider}>
<AlertsChartContainer deploymentTime={data.time} provider={provider} tags={tags} />
</Widget>
</Grid>
))
}
</Grid>
);
}
return (
<DeploymentDetailsSection title="Alerts" defaultExpanded>
{content}
</DeploymentDetailsSection>
);
};
Alerts.propTypes = {
kindIndex: PropTypes.number.isRequired,
};
export default Alerts;
| {
"pile_set_name": "Github"
} |
# Tests for special content of performance_schema.threads
#
# Show MySQL server related content in performance_schema.threads
--source include/freebsd.inc
# Every thread should be bound to an operating system thread
# (this test is not using the thread_pool)
# Note that this test will fail:
# - on platforms where my_thread_os_id() is not supported,
# which is not the case on FreeBSD
# - if some code in the server does not assign a THREAD_OS_ID
# to an instrumented thread, in which case this is a bug
# in the component instrumentation.
SELECT THREAD_ID, NAME, THREAD_OS_ID from performance_schema.threads
WHERE THREAD_OS_ID is NULL;
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<document xmlns="http://v8.1c.ru/8.2/data/spreadsheet" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<languageSettings>
<currentLanguage>ru</currentLanguage>
<defaultLanguage>ru</defaultLanguage>
<languageInfo>
<id>ru</id>
<code>Русский</code>
<description>Русский</description>
</languageInfo>
<languageInfo>
<id>en</id>
<code>English</code>
<description>English</description>
</languageInfo>
</languageSettings>
<columns>
<size>8</size>
</columns>
<rowsItem>
<index>0</index>
<row>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Тип</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Вид</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>ИмяПеременной</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>ТЧ</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Реквизит</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Значение</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Режим</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>ДополнительныйТипЗначения</v8:content>
</v8:item>
</tl>
</c>
</c>
</row>
</rowsItem>
<rowsItem>
<index>1</index>
<row>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Справочник</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>ИерархическийСправочник</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Группа1</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<i>5</i>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Группа1</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Предопределенный</v8:content>
</v8:item>
</tl>
</c>
</c>
</row>
</rowsItem>
<rowsItem>
<index>2</index>
<row>
<c>
<i>4</i>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Ссылка</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>b4ac232c-746a-11e8-9aa1-704d7b8af3d1</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<i>7</i>
<c>
<f>0</f>
<tl/>
</c>
</c>
</row>
</rowsItem>
<rowsItem>
<index>3</index>
<row>
<c>
<i>4</i>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Наименование</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Группа1</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
</c>
</c>
<c>
<c>
<f>0</f>
<tl/>
</c>
</c>
</row>
</rowsItem>
<rowsItem>
<index>4</index>
<row>
<c>
<i>3</i>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>xddMods</v8:content>
</v8:item>
</tl>
</c>
</c>
</row>
</rowsItem>
<rowsItem>
<index>5</index>
<row>
<c>
<i>4</i>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Режим</v8:content>
</v8:item>
</tl>
</c>
</c>
<c>
<c>
<f>0</f>
<tl>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Группа</v8:content>
</v8:item>
</tl>
</c>
</c>
</row>
</rowsItem>
<templateMode>true</templateMode>
<defaultFormatIndex>1</defaultFormatIndex>
<height>6</height>
<vgRows>6</vgRows>
<format>
<width>72</width>
</format>
</document> | {
"pile_set_name": "Github"
} |
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## This source file is part of the SwiftNIO open source project
##
## Copyright (c) 2019 Apple Inc. and the SwiftNIO project authors
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
## See CONTRIBUTORS.txt for the list of SwiftNIO project authors
##
## SPDX-License-Identifier: Apache-2.0
##
##===----------------------------------------------------------------------===##
set -eu
here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
tmp_dir="/tmp"
while getopts "t:" opt; do
case "$opt" in
t)
tmp_dir="$OPTARG"
;;
*)
exit 1
;;
esac
done
nio_checkout=$(mktemp -d "$tmp_dir/.swift-nio_XXXXXX")
(
cd "$nio_checkout"
git clone --depth 1 https://github.com/apple/swift-nio
)
shift $((OPTIND-1))
tests_to_run=("$here"/test_*.swift)
if [[ $# -gt 0 ]]; then
tests_to_run=("$@")
fi
"$nio_checkout/swift-nio/IntegrationTests/allocation-counter-tests-framework/run-allocation-counter.sh" \
-p "$here/../../.." \
-m NIO \
-m NIOHTTP1 \
-m NIOHTTP2 \
-t "$tmp_dir" \
-d <( echo '.package(url: "https://github.com/apple/swift-nio.git", from: "2.0.0"),' ) \
"${tests_to_run[@]}"
| {
"pile_set_name": "Github"
} |
2611.1.1 = {
holder = 1836031
}
2651.1.1 = {
holder = 1836000
}
| {
"pile_set_name": "Github"
} |
import os
import freeOrionAIInterface as fo
from common.timers import Timer
from common.option_tools import get_option_dict, check_bool, DEFAULT_SUB_DIR
from common.option_tools import TIMERS_TO_FILE, TIMERS_USE_TIMERS, TIMERS_DUMP_FOLDER
import sys
# setup module
options = get_option_dict()
try:
USE_TIMERS = check_bool(options[TIMERS_USE_TIMERS])
DUMP_TO_FILE = check_bool(options[TIMERS_TO_FILE])
TIMERS_DIR = os.path.join(fo.getUserDataDir(), DEFAULT_SUB_DIR, options[TIMERS_DUMP_FOLDER])
except KeyError:
USE_TIMERS = False
def make_header(*args):
return ['%-8s ' % x for x in args]
def _get_timers_dir():
try:
if os.path.isdir(fo.getUserDataDir()) and not os.path.isdir(TIMERS_DIR):
os.makedirs(TIMERS_DIR)
except OSError:
sys.stderr.write("AI Config Error: could not create path %s\n" % TIMERS_DIR)
return False
return TIMERS_DIR
class DummyTimer:
"""
Dummy timer to be used if timers are disabled.
"""
def __init__(self, *args, **kwargs):
pass
def stop(self, *args, **kwargs):
pass
def start(self, *args, **kwargs):
pass
def stop_and_print(self):
pass
def stop_print_and_clear(self):
pass
def clear_data(self):
pass
def print_flat(self):
pass
def print_aggregate(self):
pass
def print_statistics(self):
pass
class AILogTimer(Timer):
"""A Timer with a FO AI engine dependent extension that logs timer results to a file each turn.
"""
def __init__(self, timer_name, write_log=False):
"""
Creates timer. Timer name is name that will be in logs header and part of filename if write_log=True
If write_log true and timers logging enabled (DUMP_TO_FILE=True) save timer info to file.
"""
Timer.__init__(self, timer_name)
self.headers = None
self.write_log = write_log
self.log_name = None
def _write(self, text):
if not _get_timers_dir():
return
if not self.log_name:
empaire_id = fo.getEmpire().empireID - 1
self.log_name = os.path.join(_get_timers_dir(), '%s-%02d.txt' % (self.timer_name, empaire_id))
mode = 'w' # empty file
else:
mode = 'a'
with open(self.log_name, mode) as f:
f.write(text)
f.write('\n')
def stop_print_and_clear(self):
"""
Stop timer, output result, and clear timers.
If dumping to file, if headers are not match to prev, new header line will be added.
"""
Timer.stop_and_print(self)
if self.write_log and DUMP_TO_FILE:
turn = fo.currentTurn()
headers = make_header('Turn', *[x[0] for x in self.timers])
if self.headers != headers:
self._write(''.join(headers) + '\n' + ''.join(['-' * (len(x) - 2) + ' ' for x in headers]))
self.headers = headers
row = []
for header, val in zip(self.headers, [turn] + [x[1] for x in self.timers]):
row.append('%*s ' % (len(header) - 2, int(val)))
self._write(''.join(row))
AITimer = AILogTimer if USE_TIMERS else DummyTimer
| {
"pile_set_name": "Github"
} |
W
128
// -0.045024
0xFA3CAA88
// 0.046108
0x05E6DDC5
// -0.005518
0xFF4B3119
// -0.001981
0xFFBF12F3
// -0.038977
0xFB02CBE3
// 0.013770
0x01C33652
// 0.022191
0x02D72850
// -0.004936
0xFF5E45B8
// 0.004681
0x0099613E
// 0.005962
0x00C35D39
// -0.029572
0xFC36FBFC
// -0.013674
0xFE3FF0F0
// -0.008424
0xFEEBF8A9
// -0.002905
0xFFA0D307
// -0.004478
0xFF6D4301
// -0.017219
0xFDCBC382
// -0.032171
0xFBE1D49E
// 0.036714
0x04B30AD5
// 0.024556
0x0324A6E8
// -0.021022
0xFD4F2528
// 0.014041
0x01CC14A7
// 0.040050
0x05205AE8
// -0.000473
0xFFF08353
// -0.035016
0xFB84996D
// -0.021649
0xFD3A9CF3
// 0.000931
0x001E833F
// -0.022572
0xFD1C5D7A
// -0.011697
0xFE80B56B
// -0.026139
0xFCA779AC
// -0.062500
0xF8000000
// 0.014998
0x01EB7799
// -0.026607
0xFC9821A1
// 0.012617
0x019D6F20
// -0.013898
0xFE3897E2
// -0.016025
0xFDF2E106
// -0.007288
0xFF112DFD
// 0.002148
0x00465FCA
// 0.007141
0x00E9FC98
// 0.004629
0x0097AE22
// 0.006311
0x00CECDC1
// 0.019539
0x02803D08
// 0.020409
0x029CC704
// 0.007967
0x01050F39
// 0.038292
0x04E6BCCA
// -0.008905
0xFEDC3719
// 0.031910
0x0415A14E
// 0.009390
0x0133AEF4
// -0.007193
0xFF144BEB
// -0.036107
0xFB60D916
// -0.029846
0xFC2E0253
// -0.038256
0xFB1A69A3
// 0.043397
0x058E0821
// -0.036692
0xFB4DAB10
// 0.003615
0x007672DA
// 0.022644
0x02E5FFC3
// -0.008464
0xFEEAA618
// -0.027485
0xFC7B627E
// -0.001681
0xFFC8EDE0
// 0.001901
0x003E4B85
// 0.004249
0x008B3E95
// -0.001772
0xFFC5ED47
// 0.000738
0x00183283
// 0.032575
0x042B6C96
// -0.020489
0xFD60A15C
// -0.026118
0xFCA82E68
// -0.029348
0xFC3E52F8
// 0.015388
0x01F83BC6
// 0.006581
0x00D7A84C
// -0.008489
0xFEE9D528
// 0.009443
0x01356C14
// 0.022189
0x02D716F0
// 0.029608
0x03CA302D
// 0.011098
0x016BAC46
// -0.023327
0xFD039D90
// 0.011935
0x01871461
// 0.011493
0x01789A33
// 0.046769
0x05FC886A
// -0.009995
0xFEB87BEE
// 0.024153
0x031774C3
// 0.043754
0x0599B7D1
// 0.015782
0x0205239E
// 0.018761
0x0266BFA1
// 0.000344
0x000B47A5
// -0.017226
0xFDCB8DF3
// 0.035044
0x047C52BA
// 0.014161
0x01D003D2
// -0.021739
0xFD37A3DF
// 0.001891
0x003DF4B5
// 0.009611
0x013AECC7
// 0.023945
0x0310A4E0
// 0.036746
0x04B416BD
// 0.002962
0x006112D0
// -0.035411
0xFB77A7BD
// -0.027997
0xFC6A9BA3
// -0.005034
0xFF5B09AF
// -0.011976
0xFE779583
// -0.009062
0xFED70C93
// 0.001921
0x003EF485
// 0.017655
0x02428612
// -0.026215
0xFCA4FC89
// 0.005113
0x00A78DB3
// -0.042869
0xFA8346EB
// -0.007024
0xFF19D448
// 0.030816
0x03F1C3A2
// -0.039548
0xFAF01992
// 0.012374
0x01957808
// -0.002806
0xFFA40F85
// -0.017335
0xFDC7F6A0
// 0.019470
0x027DFF34
// 0.005651
0x00B92D06
// 0.021392
0x02BCF9AD
// 0.001910
0x003E97D0
// -0.008242
0xFEF1EB7C
// -0.012722
0xFE5F23D8
// -0.052280
0xF94EE3A8
// 0.010351
0x01532F10
// 0.008536
0x0117B83F
// 0.012385
0x0195D70A
// 0.008113
0x0109D5A7
// -0.012143
0xFE721548
// -0.027261
0xFC82B58B
// 0.007296
0x00EF16D3
// 0.013338
0x01B50F97
// 0.015936
0x020A313B
// -0.004867
0xFF608155
// -0.051131
0xF974890E
// -0.014064
0xFE33259C
// -0.038572
0xFB101099
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.net;
import java.io.IOException;
import java.io.FileDescriptor;
/*
* On Unix systems we simply delegate to native methods.
*
* @author Chris Hegarty
*/
class PlainSocketImpl extends AbstractPlainSocketImpl
{
static {
initProto();
}
/**
* Constructs an empty instance.
*/
PlainSocketImpl() { }
/**
* Constructs an instance with the given file descriptor.
*/
PlainSocketImpl(FileDescriptor fd) {
this.fd = fd;
}
native void socketCreate(boolean isServer) throws IOException;
native void socketConnect(InetAddress address, int port, int timeout)
throws IOException;
native void socketBind(InetAddress address, int port)
throws IOException;
native void socketListen(int count) throws IOException;
native void socketAccept(SocketImpl s) throws IOException;
native int socketAvailable() throws IOException;
native void socketClose0(boolean useDeferredClose) throws IOException;
native void socketShutdown(int howto) throws IOException;
static native void initProto();
native void socketSetOption(int cmd, boolean on, Object value)
throws SocketException;
native int socketGetOption(int opt, Object iaContainerObj) throws SocketException;
native void socketSendUrgentData(int data) throws IOException;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<title>class Celluloid::Task - celluloid-0.15.2 Documentation</title>
<link type="text/css" media="screen" href="../rdoc.css" rel="stylesheet">
<script type="text/javascript">
var rdoc_rel_prefix = "../";
</script>
<script type="text/javascript" charset="utf-8" src="../js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/navigation.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/search_index.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/search.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/searcher.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/darkfish.js"></script>
<body id="top" class="class">
<nav id="metadata">
<nav id="home-section" class="section">
<h3 class="section-header">
<a href="../index.html">Home</a>
<a href="../table_of_contents.html#classes">Classes</a>
<a href="../table_of_contents.html#methods">Methods</a>
</h3>
</nav>
<nav id="search-section" class="section project-section" class="initially-hidden">
<form action="#" method="get" accept-charset="utf-8">
<h3 class="section-header">
<input type="text" name="search" placeholder="Search" id="search-field"
title="Type to search, Up and Down to navigate, Enter to load">
</h3>
</form>
<ul id="search-results" class="initially-hidden"></ul>
</nav>
<div id="file-metadata">
<nav id="file-list-section" class="section">
<h3 class="section-header">Defined In</h3>
<ul>
<li>lib/celluloid/tasks.rb
<li>lib/celluloid/tasks/task_thread.rb
</ul>
</nav>
</div>
<div id="class-metadata">
<nav id="parent-class-section" class="section">
<h3 class="section-header">Parent</h3>
<p class="link">Object
</nav>
<!-- Method Quickref -->
<nav id="method-list-section" class="section">
<h3 class="section-header">Methods</h3>
<ul class="link-list">
<li ><a href="#method-c-current">::current</a>
<li ><a href="#method-c-new">::new</a>
<li ><a href="#method-c-suspend">::suspend</a>
<li ><a href="#method-i-backtrace">#backtrace</a>
<li ><a href="#method-i-create">#create</a>
<li ><a href="#method-i-exclusive">#exclusive</a>
<li ><a href="#method-i-exclusive-3F">#exclusive?</a>
<li ><a href="#method-i-guard">#guard</a>
<li ><a href="#method-i-inspect">#inspect</a>
<li ><a href="#method-i-resume">#resume</a>
<li ><a href="#method-i-running-3F">#running?</a>
<li ><a href="#method-i-suspend">#suspend</a>
<li ><a href="#method-i-terminate">#terminate</a>
</ul>
</nav>
</div>
<div id="project-metadata">
<nav id="classindex-section" class="section project-section">
<h3 class="section-header">Class and Module Index</h3>
<ul class="link-list">
<li><a href="../Celluloid.html">Celluloid</a>
<li><a href="../Celluloid/AbortError.html">Celluloid::AbortError</a>
<li><a href="../Celluloid/AbstractProxy.html">Celluloid::AbstractProxy</a>
<li><a href="../Celluloid/Actor.html">Celluloid::Actor</a>
<li><a href="../Celluloid/Actor/Sleeper.html">Celluloid::Actor::Sleeper</a>
<li><a href="../Celluloid/ActorProxy.html">Celluloid::ActorProxy</a>
<li><a href="../Celluloid/AsyncCall.html">Celluloid::AsyncCall</a>
<li><a href="../Celluloid/AsyncProxy.html">Celluloid::AsyncProxy</a>
<li><a href="../Celluloid/BlockCall.html">Celluloid::BlockCall</a>
<li><a href="../Celluloid/BlockProxy.html">Celluloid::BlockProxy</a>
<li><a href="../Celluloid/BlockResponse.html">Celluloid::BlockResponse</a>
<li><a href="../Celluloid/CPUCounter.html">Celluloid::CPUCounter</a>
<li><a href="../Celluloid/CPUCounter/RbConfig.html">Celluloid::CPUCounter::RbConfig</a>
<li><a href="../Celluloid/Call.html">Celluloid::Call</a>
<li><a href="../Celluloid/CallChain.html">Celluloid::CallChain</a>
<li><a href="../Celluloid/ClassMethods.html">Celluloid::ClassMethods</a>
<li><a href="../Celluloid/Condition.html">Celluloid::Condition</a>
<li><a href="../Celluloid/Condition/Waiter.html">Celluloid::Condition::Waiter</a>
<li><a href="../Celluloid/ConditionError.html">Celluloid::ConditionError</a>
<li><a href="../Celluloid/DeadActorError.html">Celluloid::DeadActorError</a>
<li><a href="../Celluloid/DeadTaskError.html">Celluloid::DeadTaskError</a>
<li><a href="../Celluloid/ErrorResponse.html">Celluloid::ErrorResponse</a>
<li><a href="../Celluloid/EventedMailbox.html">Celluloid::EventedMailbox</a>
<li><a href="../Celluloid/ExitEvent.html">Celluloid::ExitEvent</a>
<li><a href="../Celluloid/FSM.html">Celluloid::FSM</a>
<li><a href="../Celluloid/FSM/ClassMethods.html">Celluloid::FSM::ClassMethods</a>
<li><a href="../Celluloid/FSM/State.html">Celluloid::FSM::State</a>
<li><a href="../Celluloid/FSM/UnattachedError.html">Celluloid::FSM::UnattachedError</a>
<li><a href="../Celluloid/FiberStackError.html">Celluloid::FiberStackError</a>
<li><a href="../Celluloid/Future.html">Celluloid::Future</a>
<li><a href="../Celluloid/Future/Result.html">Celluloid::Future::Result</a>
<li><a href="../Celluloid/FutureProxy.html">Celluloid::FutureProxy</a>
<li><a href="../Celluloid/Incident.html">Celluloid::Incident</a>
<li><a href="../Celluloid/IncidentLogger.html">Celluloid::IncidentLogger</a>
<li><a href="../Celluloid/IncidentLogger/Severity.html">Celluloid::IncidentLogger::Severity</a>
<li><a href="../Celluloid/IncidentReporter.html">Celluloid::IncidentReporter</a>
<li><a href="../Celluloid/IncidentReporter/Formatter.html">Celluloid::IncidentReporter::Formatter</a>
<li><a href="../Celluloid/InstanceMethods.html">Celluloid::InstanceMethods</a>
<li><a href="../Celluloid/InternalPool.html">Celluloid::InternalPool</a>
<li><a href="../Celluloid/LinkingRequest.html">Celluloid::LinkingRequest</a>
<li><a href="../Celluloid/LinkingResponse.html">Celluloid::LinkingResponse</a>
<li><a href="../Celluloid/Links.html">Celluloid::Links</a>
<li><a href="../Celluloid/LogEvent.html">Celluloid::LogEvent</a>
<li><a href="../Celluloid/Logger.html">Celluloid::Logger</a>
<li><a href="../Celluloid/Mailbox.html">Celluloid::Mailbox</a>
<li><a href="../Celluloid/MailboxDead.html">Celluloid::MailboxDead</a>
<li><a href="../Celluloid/MailboxShutdown.html">Celluloid::MailboxShutdown</a>
<li><a href="../Celluloid/Method.html">Celluloid::Method</a>
<li><a href="../Celluloid/NamingRequest.html">Celluloid::NamingRequest</a>
<li><a href="../Celluloid/NotActorError.html">Celluloid::NotActorError</a>
<li><a href="../Celluloid/NotTaskError.html">Celluloid::NotTaskError</a>
<li><a href="../Celluloid/Notifications.html">Celluloid::Notifications</a>
<li><a href="../Celluloid/Notifications/Fanout.html">Celluloid::Notifications::Fanout</a>
<li><a href="../Celluloid/Notifications/Subscriber.html">Celluloid::Notifications::Subscriber</a>
<li><a href="../Celluloid/PoolManager.html">Celluloid::PoolManager</a>
<li><a href="../Celluloid/Properties.html">Celluloid::Properties</a>
<li><a href="../Celluloid/Receiver.html">Celluloid::Receiver</a>
<li><a href="../Celluloid/Receivers.html">Celluloid::Receivers</a>
<li><a href="../Celluloid/Registry.html">Celluloid::Registry</a>
<li><a href="../Celluloid/Registry/actor;.html">Celluloid::Registry::actor;</a>
<li><a href="../Celluloid/Response.html">Celluloid::Response</a>
<li><a href="../Celluloid/ResumableError.html">Celluloid::ResumableError</a>
<li><a href="../Celluloid/RingBuffer.html">Celluloid::RingBuffer</a>
<li><a href="../Celluloid/SignalConditionRequest.html">Celluloid::SignalConditionRequest</a>
<li><a href="../Celluloid/Signals.html">Celluloid::Signals</a>
<li><a href="../Celluloid/StackDump.html">Celluloid::StackDump</a>
<li><a href="../Celluloid/StackDump/ActorState.html">Celluloid::StackDump::ActorState</a>
<li><a href="../Celluloid/StackDump/DisplayBacktrace.html">Celluloid::StackDump::DisplayBacktrace</a>
<li><a href="../Celluloid/StackDump/TaskState.html">Celluloid::StackDump::TaskState</a>
<li><a href="../Celluloid/StackDump/ThreadState.html">Celluloid::StackDump::ThreadState</a>
<li><a href="../Celluloid/SuccessResponse.html">Celluloid::SuccessResponse</a>
<li><a href="../Celluloid/SupervisionGroup.html">Celluloid::SupervisionGroup</a>
<li><a href="../Celluloid/SupervisionGroup/Member.html">Celluloid::SupervisionGroup::Member</a>
<li><a href="../Celluloid/Supervisor.html">Celluloid::Supervisor</a>
<li><a href="../Celluloid/SyncCall.html">Celluloid::SyncCall</a>
<li><a href="../Celluloid/SyncProxy.html">Celluloid::SyncProxy</a>
<li><a href="../Celluloid/SystemEvent.html">Celluloid::SystemEvent</a>
<li><a href="../Celluloid/Task.html">Celluloid::Task</a>
<li><a href="../Celluloid/Task/TerminatedError.html">Celluloid::Task::TerminatedError</a>
<li><a href="../Celluloid/Task/TimeoutError.html">Celluloid::Task::TimeoutError</a>
<li><a href="../Celluloid/TaskFiber.html">Celluloid::TaskFiber</a>
<li><a href="../Celluloid/TaskSet.html">Celluloid::TaskSet</a>
<li><a href="../Celluloid/TaskThread.html">Celluloid::TaskThread</a>
<li><a href="../Celluloid/TerminationRequest.html">Celluloid::TerminationRequest</a>
<li><a href="../Celluloid/Thread.html">Celluloid::Thread</a>
<li><a href="../Celluloid/ThreadHandle.html">Celluloid::ThreadHandle</a>
<li><a href="../Celluloid/TimeoutError.html">Celluloid::TimeoutError</a>
<li><a href="../Celluloid/UUID.html">Celluloid::UUID</a>
<li><a href="../Fiber.html">Fiber</a>
<li><a href="../Thread.html">Thread</a>
<li><a href="../org.html">org</a>
<li><a href="../org/jruby.html">org::jruby</a>
<li><a href="../org/jruby/ext.html">org::jruby::ext</a>
<li><a href="../org/jruby/ext/fiber.html">org::jruby::ext::fiber</a>
<li><a href="../org/jruby/ext/fiber/ThreadFiber.html">org::jruby::ext::fiber::ThreadFiber</a>
</ul>
</nav>
</div>
</nav>
<div id="documentation">
<h1 class="class">class Celluloid::Task</h1>
<div id="description" class="description">
<p>Tasks are interruptable/resumable execution contexts used to run methods</p>
</div><!-- description -->
<section id="5Buntitled-5D" class="documentation-section">
<!-- Attributes -->
<section id="attribute-method-details" class="method-section section">
<h3 class="section-header">Attributes</h3>
<div id="attribute-i-chain_id" class="method-detail">
<div class="method-heading attribute-method-heading">
<span class="method-name">chain_id</span><span
class="attribute-access-type">[RW]</span>
</div>
<div class="method-description">
</div>
</div>
<div id="attribute-i-guard_warnings" class="method-detail">
<div class="method-heading attribute-method-heading">
<span class="method-name">guard_warnings</span><span
class="attribute-access-type">[RW]</span>
</div>
<div class="method-description">
</div>
</div>
<div id="attribute-i-meta" class="method-detail">
<div class="method-heading attribute-method-heading">
<span class="method-name">meta</span><span
class="attribute-access-type">[R]</span>
</div>
<div class="method-description">
</div>
</div>
<div id="attribute-i-status" class="method-detail">
<div class="method-heading attribute-method-heading">
<span class="method-name">status</span><span
class="attribute-access-type">[R]</span>
</div>
<div class="method-description">
</div>
</div>
<div id="attribute-i-type" class="method-detail">
<div class="method-heading attribute-method-heading">
<span class="method-name">type</span><span
class="attribute-access-type">[R]</span>
</div>
<div class="method-description">
</div>
</div>
</section><!-- attribute-method-details -->
<!-- Methods -->
<section id="public-class-5Buntitled-5D-method-details" class="method-section section">
<h3 class="section-header">Public Class Methods</h3>
<div id="method-c-current" class="method-detail ">
<div class="method-heading">
<span class="method-name">current</span><span
class="method-args">()</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Obtain the current task</p>
<div class="method-source-code" id="current-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 18</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword">self</span>.<span class="ruby-identifier">current</span>
<span class="ruby-constant">Thread</span>.<span class="ruby-identifier">current</span>[<span class="ruby-value">:celluloid_task</span>] <span class="ruby-keyword">or</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">NotTaskError</span>, <span class="ruby-string">"not within a task context"</span>
<span class="ruby-keyword">end</span></pre>
</div><!-- current-source -->
</div>
</div><!-- current-method -->
<div id="method-c-new" class="method-detail ">
<div class="method-heading">
<span class="method-name">new</span><span
class="method-args">(type, meta) { || ... }</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Create a new task</p>
<div class="method-source-code" id="new-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 31</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">initialize</span>(<span class="ruby-identifier">type</span>, <span class="ruby-identifier">meta</span>)
<span class="ruby-ivar">@type</span> = <span class="ruby-identifier">type</span>
<span class="ruby-ivar">@meta</span> = <span class="ruby-identifier">meta</span>
<span class="ruby-ivar">@status</span> = <span class="ruby-value">:new</span>
<span class="ruby-ivar">@exclusive</span> = <span class="ruby-keyword">false</span>
<span class="ruby-ivar">@dangerous_suspend</span> = <span class="ruby-ivar">@meta</span> <span class="ruby-operator">?</span> <span class="ruby-ivar">@meta</span>.<span class="ruby-identifier">delete</span>(<span class="ruby-value">:dangerous_suspend</span>) <span class="ruby-operator">:</span> <span class="ruby-keyword">false</span>
<span class="ruby-ivar">@guard_warnings</span> = <span class="ruby-keyword">false</span>
<span class="ruby-identifier">actor</span> = <span class="ruby-constant">Thread</span>.<span class="ruby-identifier">current</span>[<span class="ruby-value">:celluloid_actor</span>]
<span class="ruby-ivar">@chain_id</span> = <span class="ruby-constant">CallChain</span>.<span class="ruby-identifier">current_id</span>
<span class="ruby-identifier">raise</span> <span class="ruby-constant">NotActorError</span>, <span class="ruby-string">"can't create tasks outside of actors"</span> <span class="ruby-keyword">unless</span> <span class="ruby-identifier">actor</span>
<span class="ruby-identifier">guard</span> <span class="ruby-string">"can't create tasks inside of tasks"</span> <span class="ruby-keyword">if</span> <span class="ruby-constant">Thread</span>.<span class="ruby-identifier">current</span>[<span class="ruby-value">:celluloid_task</span>]
<span class="ruby-identifier">create</span> <span class="ruby-keyword">do</span>
<span class="ruby-keyword">begin</span>
<span class="ruby-ivar">@status</span> = <span class="ruby-value">:running</span>
<span class="ruby-identifier">actor</span>.<span class="ruby-identifier">setup_thread</span>
<span class="ruby-constant">Thread</span>.<span class="ruby-identifier">current</span>[<span class="ruby-value">:celluloid_task</span>] = <span class="ruby-keyword">self</span>
<span class="ruby-constant">CallChain</span>.<span class="ruby-identifier">current_id</span> = <span class="ruby-ivar">@chain_id</span>
<span class="ruby-identifier">actor</span>.<span class="ruby-identifier">tasks</span> <span class="ruby-operator"><<</span> <span class="ruby-keyword">self</span>
<span class="ruby-keyword">yield</span>
<span class="ruby-keyword">rescue</span> <span class="ruby-constant">Task</span><span class="ruby-operator">::</span><span class="ruby-constant">TerminatedError</span>
<span class="ruby-comment"># Task was explicitly terminated</span>
<span class="ruby-keyword">ensure</span>
<span class="ruby-ivar">@status</span> = <span class="ruby-value">:dead</span>
<span class="ruby-identifier">actor</span>.<span class="ruby-identifier">tasks</span>.<span class="ruby-identifier">delete</span> <span class="ruby-keyword">self</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div><!-- new-source -->
</div>
</div><!-- new-method -->
<div id="method-c-suspend" class="method-detail ">
<div class="method-heading">
<span class="method-name">suspend</span><span
class="method-args">(status)</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Suspend the running task, deferring to the scheduler</p>
<div class="method-source-code" id="suspend-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 23</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword">self</span>.<span class="ruby-identifier">suspend</span>(<span class="ruby-identifier">status</span>)
<span class="ruby-constant">Task</span>.<span class="ruby-identifier">current</span>.<span class="ruby-identifier">suspend</span>(<span class="ruby-identifier">status</span>)
<span class="ruby-keyword">end</span></pre>
</div><!-- suspend-source -->
</div>
</div><!-- suspend-method -->
</section><!-- public-class-method-details -->
<section id="public-instance-5Buntitled-5D-method-details" class="method-section section">
<h3 class="section-header">Public Instance Methods</h3>
<div id="method-i-backtrace" class="method-detail ">
<div class="method-heading">
<span class="method-name">backtrace</span><span
class="method-args">()</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<div class="method-source-code" id="backtrace-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 135</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">backtrace</span>
<span class="ruby-keyword">end</span></pre>
</div><!-- backtrace-source -->
</div>
</div><!-- backtrace-method -->
<div id="method-i-create" class="method-detail ">
<div class="method-heading">
<span class="method-name">create</span><span
class="method-args">(&block)</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<div class="method-source-code" id="create-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 65</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">create</span>(<span class="ruby-operator">&</span><span class="ruby-identifier">block</span>)
<span class="ruby-identifier">raise</span> <span class="ruby-node">"Implement #{self.class}#create"</span>
<span class="ruby-keyword">end</span></pre>
</div><!-- create-source -->
</div>
</div><!-- create-method -->
<div id="method-i-exclusive" class="method-detail ">
<div class="method-heading">
<span class="method-name">exclusive</span><span
class="method-args">() { || ... }</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Execute a code block in exclusive mode.</p>
<div class="method-source-code" id="exclusive-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 103</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">exclusive</span>
<span class="ruby-keyword">if</span> <span class="ruby-ivar">@exclusive</span>
<span class="ruby-keyword">yield</span>
<span class="ruby-keyword">else</span>
<span class="ruby-keyword">begin</span>
<span class="ruby-ivar">@exclusive</span> = <span class="ruby-keyword">true</span>
<span class="ruby-keyword">yield</span>
<span class="ruby-keyword">ensure</span>
<span class="ruby-ivar">@exclusive</span> = <span class="ruby-keyword">false</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div><!-- exclusive-source -->
</div>
</div><!-- exclusive-method -->
<div id="method-i-exclusive-3F" class="method-detail ">
<div class="method-heading">
<span class="method-name">exclusive?</span><span
class="method-args">()</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Is this task running in exclusive mode?</p>
<div class="method-source-code" id="exclusive-3F-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 131</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">exclusive?</span>
<span class="ruby-ivar">@exclusive</span>
<span class="ruby-keyword">end</span></pre>
</div><!-- exclusive-3F-source -->
</div>
</div><!-- exclusive-3F-method -->
<div id="method-i-guard" class="method-detail ">
<div class="method-heading">
<span class="method-name">guard</span><span
class="method-args">(message)</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<div class="method-source-code" id="guard-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 146</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">guard</span>(<span class="ruby-identifier">message</span>)
<span class="ruby-keyword">if</span> <span class="ruby-ivar">@guard_warnings</span>
<span class="ruby-constant">Logger</span>.<span class="ruby-identifier">warn</span> <span class="ruby-identifier">message</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">$CELLULOID_DEBUG</span>
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">raise</span> <span class="ruby-identifier">message</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">$CELLULOID_DEBUG</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div><!-- guard-source -->
</div>
</div><!-- guard-method -->
<div id="method-i-inspect" class="method-detail ">
<div class="method-heading">
<span class="method-name">inspect</span><span
class="method-args">()</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Nicer string inspect for tasks</p>
<div class="method-source-code" id="inspect-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 142</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">inspect</span>
<span class="ruby-node">"#<#{self.class}:0x#{object_id.to_s(16)} @type=#{@type.inspect}, @meta=#{@meta.inspect}, @status=#{@status.inspect}>"</span>
<span class="ruby-keyword">end</span></pre>
</div><!-- inspect-source -->
</div>
</div><!-- inspect-method -->
<div id="method-i-resume" class="method-detail ">
<div class="method-heading">
<span class="method-name">resume</span><span
class="method-args">(value = nil)</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Resume a suspended task, giving it a value to return if needed</p>
<div class="method-source-code" id="resume-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 96</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">resume</span>(<span class="ruby-identifier">value</span> = <span class="ruby-keyword">nil</span>)
<span class="ruby-identifier">guard</span> <span class="ruby-string">"Cannot resume a task from inside of a task"</span> <span class="ruby-keyword">if</span> <span class="ruby-constant">Thread</span>.<span class="ruby-identifier">current</span>[<span class="ruby-value">:celluloid_task</span>]
<span class="ruby-identifier">deliver</span>(<span class="ruby-identifier">value</span>)
<span class="ruby-keyword">nil</span>
<span class="ruby-keyword">end</span></pre>
</div><!-- resume-source -->
</div>
</div><!-- resume-method -->
<div id="method-i-running-3F" class="method-detail ">
<div class="method-heading">
<span class="method-name">running?</span><span
class="method-args">()</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Is the current task still running?</p>
<div class="method-source-code" id="running-3F-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 139</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">running?</span>; <span class="ruby-ivar">@status</span> <span class="ruby-operator">!=</span> <span class="ruby-value">:dead</span>; <span class="ruby-keyword">end</span></pre>
</div><!-- running-3F-source -->
</div>
</div><!-- running-3F-method -->
<div id="method-i-suspend" class="method-detail ">
<div class="method-heading">
<span class="method-name">suspend</span><span
class="method-args">(status)</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Suspend the current task, changing the status to the given argument</p>
<div class="method-source-code" id="suspend-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 70</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">suspend</span>(<span class="ruby-identifier">status</span>)
<span class="ruby-identifier">raise</span> <span class="ruby-string">"Cannot suspend while in exclusive mode"</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">exclusive?</span>
<span class="ruby-identifier">raise</span> <span class="ruby-string">"Cannot suspend a task from outside of itself"</span> <span class="ruby-keyword">unless</span> <span class="ruby-constant">Task</span>.<span class="ruby-identifier">current</span> <span class="ruby-operator">==</span> <span class="ruby-keyword">self</span>
<span class="ruby-ivar">@status</span> = <span class="ruby-identifier">status</span>
<span class="ruby-keyword">if</span> <span class="ruby-identifier">$CELLULOID_DEBUG</span> <span class="ruby-operator">&&</span> <span class="ruby-ivar">@dangerous_suspend</span>
<span class="ruby-identifier">warning</span> = <span class="ruby-string">"Dangerously suspending task: "</span>
<span class="ruby-identifier">warning</span> <span class="ruby-operator"><<</span> [
<span class="ruby-node">"type=#{@type.inspect}"</span>,
<span class="ruby-node">"meta=#{@meta.inspect}"</span>,
<span class="ruby-node">"status=#{@status.inspect}"</span>
].<span class="ruby-identifier">join</span>(<span class="ruby-string">", "</span>)
<span class="ruby-constant">Logger</span>.<span class="ruby-identifier">warn</span> [<span class="ruby-identifier">warning</span>, <span class="ruby-operator">*</span><span class="ruby-identifier">caller</span>[<span class="ruby-value">2</span><span class="ruby-operator">..</span><span class="ruby-value">8</span>]].<span class="ruby-identifier">join</span>(<span class="ruby-string">"\n\t"</span>)
<span class="ruby-keyword">end</span>
<span class="ruby-identifier">value</span> = <span class="ruby-identifier">signal</span>
<span class="ruby-ivar">@status</span> = <span class="ruby-value">:running</span>
<span class="ruby-identifier">raise</span> <span class="ruby-identifier">value</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">is_a?</span>(<span class="ruby-constant">Celluloid</span><span class="ruby-operator">::</span><span class="ruby-constant">ResumableError</span>)
<span class="ruby-identifier">value</span>
<span class="ruby-keyword">end</span></pre>
</div><!-- suspend-source -->
</div>
</div><!-- suspend-method -->
<div id="method-i-terminate" class="method-detail ">
<div class="method-heading">
<span class="method-name">terminate</span><span
class="method-args">()</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Terminate this task</p>
<div class="method-source-code" id="terminate-source">
<pre><span class="ruby-comment"># File lib/celluloid/tasks.rb, line 117</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">terminate</span>
<span class="ruby-identifier">raise</span> <span class="ruby-string">"Cannot terminate an exclusive task"</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">exclusive?</span>
<span class="ruby-keyword">if</span> <span class="ruby-identifier">running?</span>
<span class="ruby-constant">Celluloid</span>.<span class="ruby-identifier">logger</span>.<span class="ruby-identifier">warn</span> <span class="ruby-node">"Terminating task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}"</span>
<span class="ruby-identifier">exception</span> = <span class="ruby-constant">Task</span><span class="ruby-operator">::</span><span class="ruby-constant">TerminatedError</span>.<span class="ruby-identifier">new</span>(<span class="ruby-string">"task was terminated"</span>)
<span class="ruby-identifier">exception</span>.<span class="ruby-identifier">set_backtrace</span>(<span class="ruby-identifier">caller</span>)
<span class="ruby-identifier">resume</span> <span class="ruby-identifier">exception</span>
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">raise</span> <span class="ruby-constant">DeadTaskError</span>, <span class="ruby-string">"task is already dead"</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div><!-- terminate-source -->
</div>
</div><!-- terminate-method -->
</section><!-- public-instance-method-details -->
</section><!-- 5Buntitled-5D -->
</div><!-- documentation -->
<footer id="validator-badges">
<p><a href="http://validator.w3.org/check/referer">[Validate]</a>
<p>Generated by <a href="https://github.com/rdoc/rdoc">RDoc</a> 4.0.0.
<p>Generated with the <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish Rdoc Generator</a> 3.
</footer>
| {
"pile_set_name": "Github"
} |
# qt components used (also by qglviewer): Core Gui Xml OpenGL Widgets
include_directories(${CSPARSE_INCLUDE_DIR}
${QGLVIEWER_INCLUDE_DIR}
${Qt5Core_INCLUDE_DIRS}
${Qt5Gui_INCLUDE_DIRS}
${Qt5Xml_INCLUDE_DIRS}
${Qt5Widgets_INCLUDE_DIRS}
${Qt5OpenGL_INCLUDE_DIRS}
${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}
)
QT5_WRAP_UI(UI_HEADERS base_main_window.ui)
QT5_WRAP_CPP(UI_SOURCES main_window.h)
add_executable(slam2d_g2o
main_window.cpp
slam2d_viewer.cpp
slam2d_viewer.h
slam2d_g2o.cpp
draw_helpers.cpp
${UI_HEADERS}
${UI_SOURCES}
)
set_target_properties(slam2d_g2o PROPERTIES OUTPUT_NAME slam2d_g2o${EXE_POSTFIX})
if(Qt5_POSITION_INDEPENDENT_CODE)
set_property(TARGET slam2d_g2o PROPERTY COMPILE_FLAGS -fPIC)
message(STATUS "Generating position indpendent code for slam2d because Qt5 was built with -reduce-relocations")
# Note: using
# set(CMAKE_POSITION_INDEPENDENT_CODE ON)
# does not seem to work: This generates some libraries with -fPIE which is not enough for Qt...
endif()
target_link_libraries(slam2d_g2o core solver_csparse types_slam2d
${QGLVIEWER_LIBRARY}
${Qt5Core_LIBRARIES}
${Qt5Gui_LIBRARIES}
${Qt5Xml_LIBRARIES}
${Qt5Widgets_LIBRARIES}
${Qt5OpenGL_LIBRARIES}
${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}
)
| {
"pile_set_name": "Github"
} |
//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the common interface used by the various execution engine
// subclasses.
//
//===----------------------------------------------------------------------===//
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Mangler.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MutexGuard.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include <cmath>
#include <cstring>
using namespace llvm;
#define DEBUG_TYPE "jit"
STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
STATISTIC(NumGlobals , "Number of global vars initialized");
ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
std::unique_ptr<Module> M, std::string *ErrorStr,
std::shared_ptr<MCJITMemoryManager> MemMgr,
std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
std::unique_ptr<TargetMachine> TM) = nullptr;
ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)(
std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MemMgr,
std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
std::unique_ptr<TargetMachine> TM) = nullptr;
ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
std::string *ErrorStr) =nullptr;
void JITEventListener::anchor() {}
void ExecutionEngine::Init(std::unique_ptr<Module> M) {
CompilingLazily = false;
GVCompilationDisabled = false;
SymbolSearchingDisabled = false;
// IR module verification is enabled by default in debug builds, and disabled
// by default in release builds.
#ifndef NDEBUG
VerifyModules = true;
#else
VerifyModules = false;
#endif
assert(M && "Module is null?");
Modules.push_back(std::move(M));
}
ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
: DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {
Init(std::move(M));
}
ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)
: DL(std::move(DL)), LazyFunctionCreator(nullptr) {
Init(std::move(M));
}
ExecutionEngine::~ExecutionEngine() {
clearAllGlobalMappings();
}
namespace {
/// \brief Helper class which uses a value handler to automatically deletes the
/// memory block when the GlobalVariable is destroyed.
class GVMemoryBlock final : public CallbackVH {
GVMemoryBlock(const GlobalVariable *GV)
: CallbackVH(const_cast<GlobalVariable*>(GV)) {}
public:
/// \brief Returns the address the GlobalVariable should be written into. The
/// GVMemoryBlock object prefixes that.
static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Type *ElTy = GV->getType()->getElementType();
size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
void *RawMemory = ::operator new(
RoundUpToAlignment(sizeof(GVMemoryBlock),
TD.getPreferredAlignment(GV))
+ GVSize);
new(RawMemory) GVMemoryBlock(GV);
return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
}
void deleted() override {
// We allocated with operator new and with some extra memory hanging off the
// end, so don't just delete this. I'm not sure if this is actually
// required.
this->~GVMemoryBlock();
::operator delete(this);
}
};
} // anonymous namespace
char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
return GVMemoryBlock::Create(GV, getDataLayout());
}
void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
}
void
ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
}
void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
}
bool ExecutionEngine::removeModule(Module *M) {
for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
Module *Found = I->get();
if (Found == M) {
I->release();
Modules.erase(I);
clearGlobalMappingsFromModule(M);
return true;
}
}
return false;
}
Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Function *F = Modules[i]->getFunction(FnName);
if (F && !F->isDeclaration())
return F;
}
return nullptr;
}
GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
if (GV && !GV->isDeclaration())
return GV;
}
return nullptr;
}
uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
uint64_t OldVal;
// FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
// GlobalAddressMap.
if (I == GlobalAddressMap.end())
OldVal = 0;
else {
GlobalAddressReverseMap.erase(I->second);
OldVal = I->second;
GlobalAddressMap.erase(I);
}
return OldVal;
}
std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
assert(GV->hasName() && "Global must have name.");
MutexGuard locked(lock);
SmallString<128> FullName;
const DataLayout &DL =
GV->getParent()->getDataLayout().isDefault()
? getDataLayout()
: GV->getParent()->getDataLayout();
Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
return FullName.str();
}
void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
MutexGuard locked(lock);
addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
}
void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
MutexGuard locked(lock);
assert(!Name.empty() && "Empty GlobalMapping symbol name!");
DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
assert((!CurVal || !Addr) && "GlobalMapping already established!");
CurVal = Addr;
// If we are using the reverse mapping, add it too.
if (!EEState.getGlobalAddressReverseMap().empty()) {
std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
assert((!V.empty() || !Name.empty()) &&
"GlobalMapping already established!");
V = Name;
}
}
void ExecutionEngine::clearAllGlobalMappings() {
MutexGuard locked(lock);
EEState.getGlobalAddressMap().clear();
EEState.getGlobalAddressReverseMap().clear();
}
void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
MutexGuard locked(lock);
for (Function &FI : *M)
EEState.RemoveMapping(getMangledName(&FI));
for (GlobalVariable &GI : M->globals())
EEState.RemoveMapping(getMangledName(&GI));
}
uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
void *Addr) {
MutexGuard locked(lock);
return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
}
uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
MutexGuard locked(lock);
ExecutionEngineState::GlobalAddressMapTy &Map =
EEState.getGlobalAddressMap();
// Deleting from the mapping?
if (!Addr)
return EEState.RemoveMapping(Name);
uint64_t &CurVal = Map[Name];
uint64_t OldVal = CurVal;
if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
EEState.getGlobalAddressReverseMap().erase(CurVal);
CurVal = Addr;
// If we are using the reverse mapping, add it too.
if (!EEState.getGlobalAddressReverseMap().empty()) {
std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
assert((!V.empty() || !Name.empty()) &&
"GlobalMapping already established!");
V = Name;
}
return OldVal;
}
uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
MutexGuard locked(lock);
uint64_t Address = 0;
ExecutionEngineState::GlobalAddressMapTy::iterator I =
EEState.getGlobalAddressMap().find(S);
if (I != EEState.getGlobalAddressMap().end())
Address = I->second;
return Address;
}
void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
MutexGuard locked(lock);
if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
return Address;
return nullptr;
}
void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
MutexGuard locked(lock);
return getPointerToGlobalIfAvailable(getMangledName(GV));
}
const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
MutexGuard locked(lock);
// If we haven't computed the reverse mapping yet, do so first.
if (EEState.getGlobalAddressReverseMap().empty()) {
for (ExecutionEngineState::GlobalAddressMapTy::iterator
I = EEState.getGlobalAddressMap().begin(),
E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
StringRef Name = I->first();
uint64_t Addr = I->second;
EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Addr, Name));
}
}
std::map<uint64_t, std::string>::iterator I =
EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
if (I != EEState.getGlobalAddressReverseMap().end()) {
StringRef Name = I->second;
for (unsigned i = 0, e = Modules.size(); i != e; ++i)
if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
return GV;
}
return nullptr;
}
namespace {
class ArgvArray {
std::unique_ptr<char[]> Array;
std::vector<std::unique_ptr<char[]>> Values;
public:
/// Turn a vector of strings into a nice argv style array of pointers to null
/// terminated strings.
void *reset(LLVMContext &C, ExecutionEngine *EE,
const std::vector<std::string> &InputArgv);
};
} // anonymous namespace
void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
const std::vector<std::string> &InputArgv) {
Values.clear(); // Free the old contents.
Values.reserve(InputArgv.size());
unsigned PtrSize = EE->getDataLayout().getPointerSize();
Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
Type *SBytePtr = Type::getInt8PtrTy(C);
for (unsigned i = 0; i != InputArgv.size(); ++i) {
unsigned Size = InputArgv[i].size()+1;
auto Dest = make_unique<char[]>(Size);
DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
Dest[Size-1] = 0;
// Endian safe: Array[i] = (PointerTy)Dest;
EE->StoreValueToMemory(PTOGV(Dest.get()),
(GenericValue*)(&Array[i*PtrSize]), SBytePtr);
Values.push_back(std::move(Dest));
}
// Null terminate it
EE->StoreValueToMemory(PTOGV(nullptr),
(GenericValue*)(&Array[InputArgv.size()*PtrSize]),
SBytePtr);
return Array.get();
}
void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
bool isDtors) {
const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
GlobalVariable *GV = module.getNamedGlobal(Name);
// If this global has internal linkage, or if it has a use, then it must be
// an old-style (llvmgcc3) static ctor with __main linked in and in use. If
// this is the case, don't execute any of the global ctors, __main will do
// it.
if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
// Should be an array of '{ i32, void ()* }' structs. The first value is
// the init priority, which we ignore.
ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
if (!InitList)
return;
for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
if (!CS) continue;
Constant *FP = CS->getOperand(1);
if (FP->isNullValue())
continue; // Found a sentinal value, ignore.
// Strip off constant expression casts.
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
if (CE->isCast())
FP = CE->getOperand(0);
// Execute the ctor/dtor function!
if (Function *F = dyn_cast<Function>(FP))
runFunction(F, None);
// FIXME: It is marginally lame that we just do nothing here if we see an
// entry we don't recognize. It might not be unreasonable for the verifier
// to not even allow this and just assert here.
}
}
void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
// Execute global ctors/dtors for each module in the program.
for (std::unique_ptr<Module> &M : Modules)
runStaticConstructorsDestructors(*M, isDtors);
}
#ifndef NDEBUG
/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
unsigned PtrSize = EE->getDataLayout().getPointerSize();
for (unsigned i = 0; i < PtrSize; ++i)
if (*(i + (uint8_t*)Loc))
return false;
return true;
}
#endif
int ExecutionEngine::runFunctionAsMain(Function *Fn,
const std::vector<std::string> &argv,
const char * const * envp) {
std::vector<GenericValue> GVArgs;
GenericValue GVArgc;
GVArgc.IntVal = APInt(32, argv.size());
// Check main() type
unsigned NumArgs = Fn->getFunctionType()->getNumParams();
FunctionType *FTy = Fn->getFunctionType();
Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
// Check the argument types.
if (NumArgs > 3)
report_fatal_error("Invalid number of arguments of main() supplied");
if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
report_fatal_error("Invalid type for third argument of main() supplied");
if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
report_fatal_error("Invalid type for second argument of main() supplied");
if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
report_fatal_error("Invalid type for first argument of main() supplied");
if (!FTy->getReturnType()->isIntegerTy() &&
!FTy->getReturnType()->isVoidTy())
report_fatal_error("Invalid return type of main() supplied");
ArgvArray CArgv;
ArgvArray CEnv;
if (NumArgs) {
GVArgs.push_back(GVArgc); // Arg #0 = argc.
if (NumArgs > 1) {
// Arg #1 = argv.
GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
"argv[0] was null after CreateArgv");
if (NumArgs > 2) {
std::vector<std::string> EnvVars;
for (unsigned i = 0; envp[i]; ++i)
EnvVars.emplace_back(envp[i]);
// Arg #2 = envp.
GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
}
}
}
return runFunction(Fn, GVArgs).IntVal.getZExtValue();
}
EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
: M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
RelocModel(Reloc::Default), CMModel(CodeModel::JITDefault),
UseOrcMCJITReplacement(false) {
// IR module verification is enabled by default in debug builds, and disabled
// by default in release builds.
#ifndef NDEBUG
VerifyModules = true;
#else
VerifyModules = false;
#endif
}
EngineBuilder::~EngineBuilder() = default;
EngineBuilder &EngineBuilder::setMCJITMemoryManager(
std::unique_ptr<RTDyldMemoryManager> mcjmm) {
auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
MemMgr = SharedMM;
Resolver = SharedMM;
return *this;
}
EngineBuilder&
EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
return *this;
}
EngineBuilder&
EngineBuilder::setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR) {
Resolver = std::shared_ptr<RuntimeDyld::SymbolResolver>(std::move(SR));
return *this;
}
ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
// Make sure we can resolve symbols in the program as well. The zero arg
// to the function tells DynamicLibrary to load the program, not a library.
if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
return nullptr;
// If the user specified a memory manager but didn't specify which engine to
// create, we assume they only want the JIT, and we fail if they only want
// the interpreter.
if (MemMgr) {
if (WhichEngine & EngineKind::JIT)
WhichEngine = EngineKind::JIT;
else {
if (ErrorStr)
*ErrorStr = "Cannot create an interpreter with a memory manager.";
return nullptr;
}
}
// Unless the interpreter was explicitly selected or the JIT is not linked,
// try making a JIT.
if ((WhichEngine & EngineKind::JIT) && TheTM) {
Triple TT(M->getTargetTriple());
if (!TM->getTarget().hasJIT()) {
errs() << "WARNING: This target JIT is not designed for the host"
<< " you are running. If bad things happen, please choose"
<< " a different -march switch.\n";
}
ExecutionEngine *EE = nullptr;
if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
std::move(Resolver),
std::move(TheTM));
EE->addModule(std::move(M));
} else if (ExecutionEngine::MCJITCtor)
EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
std::move(Resolver), std::move(TheTM));
if (EE) {
EE->setVerifyModules(VerifyModules);
return EE;
}
}
// If we can't make a JIT and we didn't request one specifically, try making
// an interpreter instead.
if (WhichEngine & EngineKind::Interpreter) {
if (ExecutionEngine::InterpCtor)
return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
if (ErrorStr)
*ErrorStr = "Interpreter has not been linked in.";
return nullptr;
}
if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
if (ErrorStr)
*ErrorStr = "JIT has not been linked in.";
}
return nullptr;
}
void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
return getPointerToFunction(F);
MutexGuard locked(lock);
if (void* P = getPointerToGlobalIfAvailable(GV))
return P;
// Global variable might have been added since interpreter started.
if (GlobalVariable *GVar =
const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
EmitGlobalVariable(GVar);
else
llvm_unreachable("Global hasn't had an address allocated yet!");
return getPointerToGlobalIfAvailable(GV);
}
/// \brief Converts a Constant* into a GenericValue, including handling of
/// ConstantExpr values.
GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
// If its undefined, return the garbage.
if (isa<UndefValue>(C)) {
GenericValue Result;
switch (C->getType()->getTypeID()) {
default:
break;
case Type::IntegerTyID:
case Type::X86_FP80TyID:
case Type::FP128TyID:
case Type::PPC_FP128TyID:
// Although the value is undefined, we still have to construct an APInt
// with the correct bit width.
Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
break;
case Type::StructTyID: {
// if the whole struct is 'undef' just reserve memory for the value.
if(StructType *STy = dyn_cast<StructType>(C->getType())) {
unsigned int elemNum = STy->getNumElements();
Result.AggregateVal.resize(elemNum);
for (unsigned int i = 0; i < elemNum; ++i) {
Type *ElemTy = STy->getElementType(i);
if (ElemTy->isIntegerTy())
Result.AggregateVal[i].IntVal =
APInt(ElemTy->getPrimitiveSizeInBits(), 0);
else if (ElemTy->isAggregateType()) {
const Constant *ElemUndef = UndefValue::get(ElemTy);
Result.AggregateVal[i] = getConstantValue(ElemUndef);
}
}
}
}
break;
case Type::VectorTyID:
// if the whole vector is 'undef' just reserve memory for the value.
auto* VTy = dyn_cast<VectorType>(C->getType());
Type *ElemTy = VTy->getElementType();
unsigned int elemNum = VTy->getNumElements();
Result.AggregateVal.resize(elemNum);
if (ElemTy->isIntegerTy())
for (unsigned int i = 0; i < elemNum; ++i)
Result.AggregateVal[i].IntVal =
APInt(ElemTy->getPrimitiveSizeInBits(), 0);
break;
}
return Result;
}
// Otherwise, if the value is a ConstantExpr...
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Constant *Op0 = CE->getOperand(0);
switch (CE->getOpcode()) {
case Instruction::GetElementPtr: {
// Compute the index
GenericValue Result = getConstantValue(Op0);
APInt Offset(DL.getPointerSizeInBits(), 0);
cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
char* tmp = (char*) Result.PointerVal;
Result = PTOGV(tmp + Offset.getSExtValue());
return Result;
}
case Instruction::Trunc: {
GenericValue GV = getConstantValue(Op0);
uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
GV.IntVal = GV.IntVal.trunc(BitWidth);
return GV;
}
case Instruction::ZExt: {
GenericValue GV = getConstantValue(Op0);
uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
GV.IntVal = GV.IntVal.zext(BitWidth);
return GV;
}
case Instruction::SExt: {
GenericValue GV = getConstantValue(Op0);
uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
GV.IntVal = GV.IntVal.sext(BitWidth);
return GV;
}
case Instruction::FPTrunc: {
// FIXME long double
GenericValue GV = getConstantValue(Op0);
GV.FloatVal = float(GV.DoubleVal);
return GV;
}
case Instruction::FPExt:{
// FIXME long double
GenericValue GV = getConstantValue(Op0);
GV.DoubleVal = double(GV.FloatVal);
return GV;
}
case Instruction::UIToFP: {
GenericValue GV = getConstantValue(Op0);
if (CE->getType()->isFloatTy())
GV.FloatVal = float(GV.IntVal.roundToDouble());
else if (CE->getType()->isDoubleTy())
GV.DoubleVal = GV.IntVal.roundToDouble();
else if (CE->getType()->isX86_FP80Ty()) {
APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
(void)apf.convertFromAPInt(GV.IntVal,
false,
APFloat::rmNearestTiesToEven);
GV.IntVal = apf.bitcastToAPInt();
}
return GV;
}
case Instruction::SIToFP: {
GenericValue GV = getConstantValue(Op0);
if (CE->getType()->isFloatTy())
GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
else if (CE->getType()->isDoubleTy())
GV.DoubleVal = GV.IntVal.signedRoundToDouble();
else if (CE->getType()->isX86_FP80Ty()) {
APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
(void)apf.convertFromAPInt(GV.IntVal,
true,
APFloat::rmNearestTiesToEven);
GV.IntVal = apf.bitcastToAPInt();
}
return GV;
}
case Instruction::FPToUI: // double->APInt conversion handles sign
case Instruction::FPToSI: {
GenericValue GV = getConstantValue(Op0);
uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
if (Op0->getType()->isFloatTy())
GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
else if (Op0->getType()->isDoubleTy())
GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
else if (Op0->getType()->isX86_FP80Ty()) {
APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
uint64_t v;
bool ignored;
(void)apf.convertToInteger(&v, BitWidth,
CE->getOpcode()==Instruction::FPToSI,
APFloat::rmTowardZero, &ignored);
GV.IntVal = v; // endian?
}
return GV;
}
case Instruction::PtrToInt: {
GenericValue GV = getConstantValue(Op0);
uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
assert(PtrWidth <= 64 && "Bad pointer width");
GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
return GV;
}
case Instruction::IntToPtr: {
GenericValue GV = getConstantValue(Op0);
uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
return GV;
}
case Instruction::BitCast: {
GenericValue GV = getConstantValue(Op0);
Type* DestTy = CE->getType();
switch (Op0->getType()->getTypeID()) {
default: llvm_unreachable("Invalid bitcast operand");
case Type::IntegerTyID:
assert(DestTy->isFloatingPointTy() && "invalid bitcast");
if (DestTy->isFloatTy())
GV.FloatVal = GV.IntVal.bitsToFloat();
else if (DestTy->isDoubleTy())
GV.DoubleVal = GV.IntVal.bitsToDouble();
break;
case Type::FloatTyID:
assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
GV.IntVal = APInt::floatToBits(GV.FloatVal);
break;
case Type::DoubleTyID:
assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
break;
case Type::PointerTyID:
assert(DestTy->isPointerTy() && "Invalid bitcast");
break; // getConstantValue(Op0) above already converted it
}
return GV;
}
case Instruction::Add:
case Instruction::FAdd:
case Instruction::Sub:
case Instruction::FSub:
case Instruction::Mul:
case Instruction::FMul:
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::URem:
case Instruction::SRem:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor: {
GenericValue LHS = getConstantValue(Op0);
GenericValue RHS = getConstantValue(CE->getOperand(1));
GenericValue GV;
switch (CE->getOperand(0)->getType()->getTypeID()) {
default: llvm_unreachable("Bad add type!");
case Type::IntegerTyID:
switch (CE->getOpcode()) {
default: llvm_unreachable("Invalid integer opcode");
case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
}
break;
case Type::FloatTyID:
switch (CE->getOpcode()) {
default: llvm_unreachable("Invalid float opcode");
case Instruction::FAdd:
GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
case Instruction::FSub:
GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
case Instruction::FMul:
GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
case Instruction::FDiv:
GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
case Instruction::FRem:
GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
}
break;
case Type::DoubleTyID:
switch (CE->getOpcode()) {
default: llvm_unreachable("Invalid double opcode");
case Instruction::FAdd:
GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
case Instruction::FSub:
GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
case Instruction::FMul:
GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
case Instruction::FDiv:
GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
case Instruction::FRem:
GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
}
break;
case Type::X86_FP80TyID:
case Type::PPC_FP128TyID:
case Type::FP128TyID: {
const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
APFloat apfLHS = APFloat(Sem, LHS.IntVal);
switch (CE->getOpcode()) {
default: llvm_unreachable("Invalid long double opcode");
case Instruction::FAdd:
apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
GV.IntVal = apfLHS.bitcastToAPInt();
break;
case Instruction::FSub:
apfLHS.subtract(APFloat(Sem, RHS.IntVal),
APFloat::rmNearestTiesToEven);
GV.IntVal = apfLHS.bitcastToAPInt();
break;
case Instruction::FMul:
apfLHS.multiply(APFloat(Sem, RHS.IntVal),
APFloat::rmNearestTiesToEven);
GV.IntVal = apfLHS.bitcastToAPInt();
break;
case Instruction::FDiv:
apfLHS.divide(APFloat(Sem, RHS.IntVal),
APFloat::rmNearestTiesToEven);
GV.IntVal = apfLHS.bitcastToAPInt();
break;
case Instruction::FRem:
apfLHS.mod(APFloat(Sem, RHS.IntVal));
GV.IntVal = apfLHS.bitcastToAPInt();
break;
}
}
break;
}
return GV;
}
default:
break;
}
SmallString<256> Msg;
raw_svector_ostream OS(Msg);
OS << "ConstantExpr not handled: " << *CE;
report_fatal_error(OS.str());
}
// Otherwise, we have a simple constant.
GenericValue Result;
switch (C->getType()->getTypeID()) {
case Type::FloatTyID:
Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
break;
case Type::DoubleTyID:
Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
break;
case Type::X86_FP80TyID:
case Type::FP128TyID:
case Type::PPC_FP128TyID:
Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
break;
case Type::IntegerTyID:
Result.IntVal = cast<ConstantInt>(C)->getValue();
break;
case Type::PointerTyID:
if (isa<ConstantPointerNull>(C))
Result.PointerVal = nullptr;
else if (const Function *F = dyn_cast<Function>(C))
Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
else
llvm_unreachable("Unknown constant pointer type!");
break;
case Type::VectorTyID: {
unsigned elemNum;
Type* ElemTy;
const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
const ConstantVector *CV = dyn_cast<ConstantVector>(C);
const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
if (CDV) {
elemNum = CDV->getNumElements();
ElemTy = CDV->getElementType();
} else if (CV || CAZ) {
VectorType* VTy = dyn_cast<VectorType>(C->getType());
elemNum = VTy->getNumElements();
ElemTy = VTy->getElementType();
} else {
llvm_unreachable("Unknown constant vector type!");
}
Result.AggregateVal.resize(elemNum);
// Check if vector holds floats.
if(ElemTy->isFloatTy()) {
if (CAZ) {
GenericValue floatZero;
floatZero.FloatVal = 0.f;
std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
floatZero);
break;
}
if(CV) {
for (unsigned i = 0; i < elemNum; ++i)
if (!isa<UndefValue>(CV->getOperand(i)))
Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
CV->getOperand(i))->getValueAPF().convertToFloat();
break;
}
if(CDV)
for (unsigned i = 0; i < elemNum; ++i)
Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
break;
}
// Check if vector holds doubles.
if (ElemTy->isDoubleTy()) {
if (CAZ) {
GenericValue doubleZero;
doubleZero.DoubleVal = 0.0;
std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
doubleZero);
break;
}
if(CV) {
for (unsigned i = 0; i < elemNum; ++i)
if (!isa<UndefValue>(CV->getOperand(i)))
Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
CV->getOperand(i))->getValueAPF().convertToDouble();
break;
}
if(CDV)
for (unsigned i = 0; i < elemNum; ++i)
Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
break;
}
// Check if vector holds integers.
if (ElemTy->isIntegerTy()) {
if (CAZ) {
GenericValue intZero;
intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
intZero);
break;
}
if(CV) {
for (unsigned i = 0; i < elemNum; ++i)
if (!isa<UndefValue>(CV->getOperand(i)))
Result.AggregateVal[i].IntVal = cast<ConstantInt>(
CV->getOperand(i))->getValue();
else {
Result.AggregateVal[i].IntVal =
APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
}
break;
}
if(CDV)
for (unsigned i = 0; i < elemNum; ++i)
Result.AggregateVal[i].IntVal = APInt(
CDV->getElementType()->getPrimitiveSizeInBits(),
CDV->getElementAsInteger(i));
break;
}
llvm_unreachable("Unknown constant pointer type!");
}
break;
default:
SmallString<256> Msg;
raw_svector_ostream OS(Msg);
OS << "ERROR: Constant unimplemented for type: " << *C->getType();
report_fatal_error(OS.str());
}
return Result;
}
/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
/// with the integer held in IntVal.
static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
unsigned StoreBytes) {
assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
if (sys::IsLittleEndianHost) {
// Little-endian host - the source is ordered from LSB to MSB. Order the
// destination from LSB to MSB: Do a straight copy.
memcpy(Dst, Src, StoreBytes);
} else {
// Big-endian host - the source is an array of 64 bit words ordered from
// LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
// from MSB to LSB: Reverse the word order, but not the bytes in a word.
while (StoreBytes > sizeof(uint64_t)) {
StoreBytes -= sizeof(uint64_t);
// May not be aligned so use memcpy.
memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
Src += sizeof(uint64_t);
}
memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
}
}
void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
GenericValue *Ptr, Type *Ty) {
const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
switch (Ty->getTypeID()) {
default:
dbgs() << "Cannot store value of type " << *Ty << "!\n";
break;
case Type::IntegerTyID:
StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
break;
case Type::FloatTyID:
*((float*)Ptr) = Val.FloatVal;
break;
case Type::DoubleTyID:
*((double*)Ptr) = Val.DoubleVal;
break;
case Type::X86_FP80TyID:
memcpy(Ptr, Val.IntVal.getRawData(), 10);
break;
case Type::PointerTyID:
// Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
if (StoreBytes != sizeof(PointerTy))
memset(&(Ptr->PointerVal), 0, StoreBytes);
*((PointerTy*)Ptr) = Val.PointerVal;
break;
case Type::VectorTyID:
for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
*(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
*(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
StoreIntToMemory(Val.AggregateVal[i].IntVal,
(uint8_t*)Ptr + numOfBytes*i, numOfBytes);
}
}
break;
}
if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
// Host and target are different endian - reverse the stored bytes.
std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
}
/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
uint8_t *Dst = reinterpret_cast<uint8_t *>(
const_cast<uint64_t *>(IntVal.getRawData()));
if (sys::IsLittleEndianHost)
// Little-endian host - the destination must be ordered from LSB to MSB.
// The source is ordered from LSB to MSB: Do a straight copy.
memcpy(Dst, Src, LoadBytes);
else {
// Big-endian - the destination is an array of 64 bit words ordered from
// LSW to MSW. Each word must be ordered from MSB to LSB. The source is
// ordered from MSB to LSB: Reverse the word order, but not the bytes in
// a word.
while (LoadBytes > sizeof(uint64_t)) {
LoadBytes -= sizeof(uint64_t);
// May not be aligned so use memcpy.
memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
Dst += sizeof(uint64_t);
}
memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
}
}
/// FIXME: document
///
void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
GenericValue *Ptr,
Type *Ty) {
const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
switch (Ty->getTypeID()) {
case Type::IntegerTyID:
// An APInt with all words initially zero.
Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
break;
case Type::FloatTyID:
Result.FloatVal = *((float*)Ptr);
break;
case Type::DoubleTyID:
Result.DoubleVal = *((double*)Ptr);
break;
case Type::PointerTyID:
Result.PointerVal = *((PointerTy*)Ptr);
break;
case Type::X86_FP80TyID: {
// This is endian dependent, but it will only work on x86 anyway.
// FIXME: Will not trap if loading a signaling NaN.
uint64_t y[2];
memcpy(y, Ptr, 10);
Result.IntVal = APInt(80, y);
break;
}
case Type::VectorTyID: {
auto *VT = cast<VectorType>(Ty);
Type *ElemT = VT->getElementType();
const unsigned numElems = VT->getNumElements();
if (ElemT->isFloatTy()) {
Result.AggregateVal.resize(numElems);
for (unsigned i = 0; i < numElems; ++i)
Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
}
if (ElemT->isDoubleTy()) {
Result.AggregateVal.resize(numElems);
for (unsigned i = 0; i < numElems; ++i)
Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
}
if (ElemT->isIntegerTy()) {
GenericValue intZero;
const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
intZero.IntVal = APInt(elemBitWidth, 0);
Result.AggregateVal.resize(numElems, intZero);
for (unsigned i = 0; i < numElems; ++i)
LoadIntFromMemory(Result.AggregateVal[i].IntVal,
(uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
}
break;
}
default:
SmallString<256> Msg;
raw_svector_ostream OS(Msg);
OS << "Cannot load value of type " << *Ty << "!";
report_fatal_error(OS.str());
}
}
void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
DEBUG(Init->dump());
if (isa<UndefValue>(Init))
return;
if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
unsigned ElementSize =
getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
return;
}
if (isa<ConstantAggregateZero>(Init)) {
memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
return;
}
if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
unsigned ElementSize =
getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
return;
}
if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
const StructLayout *SL =
getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
return;
}
if (const ConstantDataSequential *CDS =
dyn_cast<ConstantDataSequential>(Init)) {
// CDS is already laid out in host memory order.
StringRef Data = CDS->getRawDataValues();
memcpy(Addr, Data.data(), Data.size());
return;
}
if (Init->getType()->isFirstClassType()) {
GenericValue Val = getConstantValue(Init);
StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
return;
}
DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
llvm_unreachable("Unknown constant type to initialize memory with!");
}
/// EmitGlobals - Emit all of the global variables to memory, storing their
/// addresses into GlobalAddress. This must make sure to copy the contents of
/// their initializers into the memory.
void ExecutionEngine::emitGlobals() {
// Loop over all of the global variables in the program, allocating the memory
// to hold them. If there is more than one module, do a prepass over globals
// to figure out how the different modules should link together.
std::map<std::pair<std::string, Type*>,
const GlobalValue*> LinkedGlobalsMap;
if (Modules.size() != 1) {
for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Module &M = *Modules[m];
for (const auto &GV : M.globals()) {
if (GV.hasLocalLinkage() || GV.isDeclaration() ||
GV.hasAppendingLinkage() || !GV.hasName())
continue;// Ignore external globals and globals with internal linkage.
const GlobalValue *&GVEntry =
LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
// If this is the first time we've seen this global, it is the canonical
// version.
if (!GVEntry) {
GVEntry = &GV;
continue;
}
// If the existing global is strong, never replace it.
if (GVEntry->hasExternalLinkage())
continue;
// Otherwise, we know it's linkonce/weak, replace it if this is a strong
// symbol. FIXME is this right for common?
if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
GVEntry = &GV;
}
}
}
std::vector<const GlobalValue*> NonCanonicalGlobals;
for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Module &M = *Modules[m];
for (const auto &GV : M.globals()) {
// In the multi-module case, see what this global maps to.
if (!LinkedGlobalsMap.empty()) {
if (const GlobalValue *GVEntry =
LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
// If something else is the canonical global, ignore this one.
if (GVEntry != &GV) {
NonCanonicalGlobals.push_back(&GV);
continue;
}
}
}
if (!GV.isDeclaration()) {
addGlobalMapping(&GV, getMemoryForGV(&GV));
} else {
// External variable reference. Try to use the dynamic loader to
// get a pointer to it.
if (void *SymAddr =
sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
addGlobalMapping(&GV, SymAddr);
else {
report_fatal_error("Could not resolve external global address: "
+GV.getName());
}
}
}
// If there are multiple modules, map the non-canonical globals to their
// canonical location.
if (!NonCanonicalGlobals.empty()) {
for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
const GlobalValue *GV = NonCanonicalGlobals[i];
const GlobalValue *CGV =
LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
void *Ptr = getPointerToGlobalIfAvailable(CGV);
assert(Ptr && "Canonical global wasn't codegen'd!");
addGlobalMapping(GV, Ptr);
}
}
// Now that all of the globals are set up in memory, loop through them all
// and initialize their contents.
for (const auto &GV : M.globals()) {
if (!GV.isDeclaration()) {
if (!LinkedGlobalsMap.empty()) {
if (const GlobalValue *GVEntry =
LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
if (GVEntry != &GV) // Not the canonical variable.
continue;
}
EmitGlobalVariable(&GV);
}
}
}
}
// EmitGlobalVariable - This method emits the specified global variable to the
// address specified in GlobalAddresses, or allocates new memory if it's not
// already in the map.
void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
void *GA = getPointerToGlobalIfAvailable(GV);
if (!GA) {
// If it's not already specified, allocate memory for the global.
GA = getMemoryForGV(GV);
// If we failed to allocate memory for this global, return.
if (!GA) return;
addGlobalMapping(GV, GA);
}
// Don't initialize if it's thread local, let the client do it.
if (!GV->isThreadLocal())
InitializeMemory(GV->getInitializer(), GA);
Type *ElTy = GV->getType()->getElementType();
size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
NumInitBytes += (unsigned)GVSize;
++NumGlobals;
}
| {
"pile_set_name": "Github"
} |
/*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2019 Asqatasun.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa22;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.rules.rgaa22.test.Rgaa22RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 5.34 of the referential RGAA 2.2.
*
* @author jkowalczyk
*/
public class Rgaa22Rule05341Test extends Rgaa22RuleImplementationTestCase {
/**
* Default constructor
*/
public Rgaa22Rule05341Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.asqatasun.rules.rgaa22.Rgaa22Rule05341");
}
@Override
protected void setUpWebResourceMap() {
// getWebResourceMap().put("Rgaa22.Test.5.34-1Passed-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule05341/RGAA22.Test.5.34-1Passed-01.html"));
// getWebResourceMap().put("Rgaa22.Test.5.34-2Failed-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule05341/RGAA22.Test.5.34-2Failed-01.html"));
// getWebResourceMap().put("Rgaa22.Test.5.34-3NMI-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule05341/RGAA22.Test.5.34-3NMI-01.html"));
// getWebResourceMap().put("Rgaa22.Test.5.34-4NA-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule05341/RGAA22.Test.5.34-4NA-01.html"));
getWebResourceMap().put("Rgaa22.Test.5.34-5NT-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "rgaa22/Rgaa22Rule05341/RGAA22.Test.5.34-5NT-01.html"));
}
@Override
protected void setProcess() {
// assertEquals(TestSolution.PASSED,
// processPageTest("Rgaa22.Test.5.34-1Passed-01").getValue());
// assertEquals(TestSolution.FAILED,
// processPageTest("Rgaa22.Test.5.34-2Failed-01").getValue());
// assertEquals(TestSolution.NEED_MORE_INFO,
// processPageTest("Rgaa22.Test.5.34-3NMI-01").getValue());
// assertEquals(TestSolution.NOT_APPLICABLE,
// processPageTest("Rgaa22.Test.5.34-4NA-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
processPageTest("Rgaa22.Test.5.34-5NT-01").getValue());
}
@Override
protected void setConsolidate() {
// assertEquals(TestSolution.PASSED,
// consolidate("Rgaa22.Test.5.34-1Passed-01").getValue());
// assertEquals(TestSolution.FAILED,
// consolidate("Rgaa22.Test.5.34-2Failed-01").getValue());
// assertEquals(TestSolution.NEED_MORE_INFO,
// consolidate("Rgaa22.Test.5.34-3NMI-01").getValue());
// assertEquals(TestSolution.NOT_APPLICABLE,
// consolidate("Rgaa22.Test.5.34-4NA-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
consolidate("Rgaa22.Test.5.34-5NT-01").getValue());
}
}
| {
"pile_set_name": "Github"
} |
function anorm = update_gbound(anorm,alpha,beta,j)
%UPDATE_GBOUND Update Gerscgorin estimate of 2-norm
% ANORM = UPDATE_GBOUND(ANORM,ALPHA,BETA,J) updates the Gersgorin bound
% for the tridiagonal in the Lanczos process after the J'th step.
% Applies Gerscgorins circles to T_K'*T_k instead of T_k itself
% since this gives a tighter bound.
if j==1 % Apply Gerscgorin circles to T_k'*T_k to estimate || A ||_2
i=j;
% scale to avoid overflow
scale = max(abs(alpha(i)),abs(beta(i+1)));
alpha(i) = alpha(i)/scale;
beta(i) = beta(i)/scale;
anorm = 1.01*scale*sqrt(alpha(i)^2+beta(i+1)^2 + abs(alpha(i)*beta(i+1)));
elseif j==2
i=1;
% scale to avoid overflow
scale = max(max(abs(alpha(1:2)),max(abs(beta(2:3)))));
alpha(1:2) = alpha(1:2)/scale;
beta(2:3) = beta(2:3)/scale;
anorm = max(anorm, scale*sqrt(alpha(i)^2+beta(i+1)^2 + ...
abs(alpha(i)*beta(i+1) + alpha(i+1)*beta(i+1)) + ...
abs(beta(i+1)*beta(i+2))));
i=2;
anorm = max(anorm,scale*sqrt(abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...
beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...
abs(alpha(i)*beta(i+1))) );
elseif j==3
% scale to avoid overflow
scale = max(max(abs(alpha(1:3)),max(abs(beta(2:4)))));
alpha(1:3) = alpha(1:3)/scale;
beta(2:4) = beta(2:4)/scale;
i=2;
anorm = max(anorm,scale*sqrt(abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...
beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...
abs(alpha(i)*beta(i+1) + alpha(i+1)*beta(i+1)) + ...
abs(beta(i+1)*beta(i+2))) );
i=3;
anorm = max(anorm,scale*sqrt(abs(beta(i)*beta(i-1)) + ...
abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...
beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...
abs(alpha(i)*beta(i+1))) );
else
% scale to avoid overflow
% scale = max(max(abs(alpha(j-2:j)),max(abs(beta(j-2:j+1)))));
% alpha(j-2:j) = alpha(j-2:j)/scale;
% beta(j-2:j+1) = beta(j-2:j+1)/scale;
% Avoid scaling, which is slow. At j>3 the estimate is usually quite good
% so just make sure that anorm is not made infinite by overflow.
i = j-1;
anorm1 = sqrt(abs(beta(i)*beta(i-1)) + ...
abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...
beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...
abs(alpha(i)*beta(i+1) + alpha(i+1)*beta(i+1)) + ...
abs(beta(i+1)*beta(i+2)));
if isfinite(anorm1)
anorm = max(anorm,anorm1);
end
i = j;
anorm1 = sqrt(abs(beta(i)*beta(i-1)) + ...
abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...
beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...
abs(alpha(i)*beta(i+1)));
if isfinite(anorm1)
anorm = max(anorm,anorm1);
end
end
| {
"pile_set_name": "Github"
} |
package task
import (
"fmt"
"io"
"time"
"github.com/spf13/pflag"
"github.com/taskcluster/slugid-go/slugid"
tcclient "github.com/taskcluster/taskcluster/v37/clients/client-go"
"github.com/taskcluster/taskcluster/v37/clients/client-go/tcqueue"
)
// runCancel cancels the runs of a given task.
func runCancel(credentials *tcclient.Credentials, args []string, out io.Writer, flagSet *pflag.FlagSet) error {
noop, _ := flagSet.GetBool("noop")
confirm, _ := flagSet.GetBool("confirm")
q := makeQueue(credentials)
taskID := args[0]
if noop {
return displayNoopMsg("Would cancel", credentials, args)
}
if confirm {
var confirm = confirmMsg("Cancels", credentials, args)
if !confirm {
return nil
}
}
c, err := q.CancelTask(taskID)
if err != nil {
log.Error(err)
return fmt.Errorf("could not cancel the task %s: %v", taskID, err)
}
run := c.Status.Runs[len(c.Status.Runs)-1]
fmt.Fprintln(out, getRunStatusString(run.State, run.ReasonResolved))
return nil
}
// runRerun re-runs a given task.
func runRerun(credentials *tcclient.Credentials, args []string, out io.Writer, flagSet *pflag.FlagSet) error {
noop, _ := flagSet.GetBool("noop")
confirm, _ := flagSet.GetBool("confirm")
force, _ := flagSet.GetBool("force")
q := makeQueue(credentials)
taskID := args[0]
if noop {
return displayNoopMsg("Would re-run", credentials, args)
}
if confirm {
var confirm = confirmMsg("Will re-run", credentials, args)
if !confirm {
return nil
}
}
if !force {
s, err := q.Status(taskID)
if err != nil {
return fmt.Errorf("could not get status of the task %s: %v", taskID, err)
}
if s.Status.State != "failed" && s.Status.State != "exception" {
return fmt.Errorf("Task %s is in state %s. Disallowing rerun of a non-failed and non-exception task without --force", taskID, s.Status.State)
}
}
c, err := q.RerunTask(taskID)
if err != nil {
return fmt.Errorf("could not rerun the task %s: %v", taskID, err)
}
run := c.Status.Runs[len(c.Status.Runs)-1]
fmt.Fprintln(out, getRunStatusString(run.State, run.ReasonResolved))
return nil
}
// runRetrigger re-triggers a given task.
// It will generate a new taskId, update timestamps and retries to 0
// Optionnally, you can pass '--exact' to keep stuff like:
// - routes,
// - dependencies,
// - ...
//
// Otherwise, default behavior is to omit those as taskcluster-tools does:
// https://github.com/taskcluster/taskcluster-tools/blob/e8b6d45f10e7520f717b7a9f5db87d550c74d15e/src/views/UnifiedInspector/ActionsMenu.jsx#L141-L158
func runRetrigger(credentials *tcclient.Credentials, args []string, out io.Writer, flagSet *pflag.FlagSet) error {
q := makeQueue(credentials)
taskID := args[0]
t, err := q.Task(taskID)
if err != nil {
return fmt.Errorf("could not get the task %s: %v", taskID, err)
}
exactRetrigger, _ := flagSet.GetBool("exact")
newTaskID := slugid.Nice()
now := time.Now().UTC()
origCreated, err := time.Parse(time.RFC3339, t.Created.String())
if err != nil {
return fmt.Errorf("could not parse created date: %s", t.Created)
}
origDeadline, err := time.Parse(time.RFC3339, t.Deadline.String())
if err != nil {
return fmt.Errorf("could not parse deadline date: %s", t.Deadline)
}
origExpires, err := time.Parse(time.RFC3339, t.Expires.String())
if err != nil {
return fmt.Errorf("could not parse created date: %s", t.Expires)
}
// TaskDefinitionRequest: https://github.com/taskcluster/taskcluster-client-go/blob/88cfe471bfe2eb8fc9bc22d9cde6a65e74a9f3e5/tcqueue/types.go#L1368-L1549
// TaskDefinitionResponse: https://github.com/taskcluster/taskcluster-client-go/blob/88cfe471bfe2eb8fc9bc22d9cde6a65e74a9f3e5/tcqueue/types.go#L1554-L1716
newDependencies := []string{}
newRoutes := []string{}
if exactRetrigger {
newDependencies = t.Dependencies
newRoutes = t.Routes
}
newT := &tcqueue.TaskDefinitionRequest{
Created: tcclient.Time(now),
Deadline: tcclient.Time(now.Add(origDeadline.Sub(origCreated))),
Expires: tcclient.Time(now.Add(origExpires.Sub(origCreated))),
TaskGroupID: t.TaskGroupID,
SchedulerID: t.SchedulerID,
WorkerType: t.WorkerType,
ProvisionerID: t.ProvisionerID,
Priority: t.Priority,
Dependencies: newDependencies,
Extra: t.Extra,
Metadata: t.Metadata,
Payload: t.Payload,
Requires: t.Requires,
Retries: 0,
Routes: newRoutes,
Scopes: t.Scopes,
Tags: t.Tags,
}
c, err := q.CreateTask(newTaskID, newT)
if err != nil {
return fmt.Errorf("could not create task: %v", err)
}
// If we got no error, that means the task was successfully submitted
fmt.Fprintf(out, "Task %s created\n", c.Status.TaskID)
return nil
}
// runComplete completes a given task.
func runComplete(credentials *tcclient.Credentials, args []string, out io.Writer, flagSet *pflag.FlagSet) error {
noop, _ := flagSet.GetBool("noop")
confirm, _ := flagSet.GetBool("confirm")
q := makeQueue(credentials)
taskID := args[0]
s, err := q.Status(taskID)
if err != nil {
return fmt.Errorf("could not get the status of the task %s: %v", taskID, err)
}
if noop {
return displayNoopMsg("Would complete", credentials, args)
}
if confirm {
var confirm = confirmMsg("Will complete", credentials, args)
if !confirm {
return nil
}
}
c, err := q.ClaimTask(taskID, fmt.Sprint(len(s.Status.Runs)-1), &tcqueue.TaskClaimRequest{
WorkerGroup: s.Status.WorkerType,
WorkerID: "taskcluster-cli",
})
if err != nil {
return fmt.Errorf("could not claim the task %s: %v", taskID, err)
}
wq := makeQueue(&tcclient.Credentials{
ClientID: c.Credentials.ClientID,
AccessToken: c.Credentials.AccessToken,
Certificate: c.Credentials.Certificate,
})
r, err := wq.ReportCompleted(taskID, fmt.Sprint(c.RunID))
if err != nil {
return fmt.Errorf("could not complete the task %s: %v", taskID, err)
}
fmt.Fprintln(out, getRunStatusString(r.Status.Runs[c.RunID].State, r.Status.Runs[c.RunID].ReasonResolved))
return nil
}
| {
"pile_set_name": "Github"
} |
/*
* -
* #%L
* Pipeline: AWS Steps
* %%
* Copyright (C) 2016 Taimos GmbH
* %%
* 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.
* #L%
*/
package de.taimos.pipeline.aws;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.nio.charset.Charset;
import org.jenkinsci.plugins.workflow.steps.Step;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkinsci.plugins.workflow.steps.StepDescriptor;
import org.jenkinsci.plugins.workflow.steps.StepExecution;
import org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.AmazonCloudFormationClientBuilder;
import com.amazonaws.services.cloudformation.model.DescribeStackResourcesRequest;
import com.amazonaws.services.cloudformation.model.DescribeStackResourcesResult;
import com.amazonaws.services.cloudformation.model.StackResource;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.AWSLambdaClientBuilder;
import com.amazonaws.services.lambda.model.ListVersionsByFunctionRequest;
import com.amazonaws.services.lambda.model.ListVersionsByFunctionResult;
import com.amazonaws.services.lambda.model.DeleteFunctionRequest;
import com.amazonaws.services.lambda.model.FunctionConfiguration;
import com.amazonaws.services.lambda.model.ListAliasesRequest;
import com.amazonaws.services.lambda.model.ListAliasesResult;
import com.amazonaws.event.ProgressEventType;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.services.s3.Headers;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.SSEAlgorithm;
import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams;
import com.amazonaws.services.s3.transfer.MultipleFileUpload;
import com.amazonaws.services.s3.transfer.ObjectMetadataProvider;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;
import com.google.common.base.Preconditions;
import java.util.Date;
import java.util.LinkedList;
import de.taimos.pipeline.aws.utils.StepUtils;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.TaskListener;
import hudson.remoting.VirtualChannel;
import jenkins.MasterToSlaveFileCallable;
import java.time.ZonedDateTime;
import java.time.Period;
public class LambdaVersionCleanupStep extends Step {
private String functionName;
private String stackName;
private final ZonedDateTime versionCutoff;
@DataBoundConstructor
public LambdaVersionCleanupStep(int daysAgo) {
this.versionCutoff = ZonedDateTime.now().minus(Period.ofDays(daysAgo));
}
@DataBoundSetter
public void setFunctionName(String functionName) {
this.functionName = functionName;
}
@DataBoundSetter
public void setStackName(String stackName) {
this.stackName = stackName;
}
@Override
public StepExecution start(StepContext context) throws Exception {
return new LambdaVersionCleanupStep.Execution(this, context);
}
@Extension
public static class DescriptorImpl extends StepDescriptor {
@Override
public Set<? extends Class<?>> getRequiredContext() {
return StepUtils.requiresDefault();
}
@Override
public String getFunctionName() {
return "lambdaVersionCleanup";
}
@Override
public String getDisplayName() {
return "Cleanup old lambda versions";
}
}
public static class Execution extends SynchronousNonBlockingStepExecution<String> {
protected static final long serialVersionUID = 1L;
protected final transient LambdaVersionCleanupStep step;
public Execution(LambdaVersionCleanupStep step, StepContext context) {
super(context);
this.step = step;
}
private List<FunctionConfiguration> findAllVersions(AWSLambda client, String functionName) {
List<FunctionConfiguration> list = new LinkedList<>();
ListVersionsByFunctionRequest request = new ListVersionsByFunctionRequest()
.withFunctionName(functionName);
do {
ListVersionsByFunctionResult result = client.listVersionsByFunction(request);
list.addAll(result.getVersions());
request.setMarker(result.getNextMarker());
} while (request.getMarker() != null);
return list;
}
private void deleteAllVersions(AWSLambda client, String functionName) throws Exception {
TaskListener listener = Execution.this.getContext().get(TaskListener.class);
listener.getLogger().format("Looking for old versions functionName=%s%n", functionName);
List<String> aliasedVersions = client.listAliases(new ListAliasesRequest()
.withFunctionName(functionName)).getAliases().stream()
.map( (alias) -> alias.getFunctionVersion())
.collect(Collectors.toList());
listener.getLogger().format("Found alises functionName=%s alias=%s%n", functionName, aliasedVersions);
List<FunctionConfiguration> allVersions = findAllVersions(client, functionName);
listener.getLogger().format("Found old versions functionName=%s count=%d%n", functionName, allVersions.size());
List<FunctionConfiguration> filteredVersions = allVersions.stream()
.filter( (function) -> {
ZonedDateTime parsedDateTime = DateTimeUtils.parse(function.getLastModified());
return parsedDateTime.isBefore(this.step.versionCutoff);
})
.filter( (function) -> !"$LATEST".equals(function.getVersion()))
.filter( (function) -> !aliasedVersions.contains(function.getVersion()))
.collect(Collectors.toList());
for (FunctionConfiguration functionConfiguration : filteredVersions) {
listener.getLogger().format("Deleting old version functionName=%s version=%s lastModified=%s%n", functionName, functionConfiguration.getVersion(), functionConfiguration.getLastModified());
client.deleteFunction(new DeleteFunctionRequest()
.withFunctionName(functionName)
.withQualifier(functionConfiguration.getVersion())
);
}
}
private void deleteAllStackFunctionVersions(AWSLambda client, String stackName) throws Exception {
TaskListener listener = Execution.this.getContext().get(TaskListener.class);
listener.getLogger().format("Deleting old versions from stackName=%s%n", stackName);
AmazonCloudFormation cloudformation = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), this.getContext());
DescribeStackResourcesResult result = cloudformation.describeStackResources(new DescribeStackResourcesRequest()
.withStackName(stackName)
);
for (StackResource stackResource : result.getStackResources()) {
if ("AWS::Lambda::Function".equals(stackResource.getResourceType())) {
deleteAllVersions(client, stackResource.getPhysicalResourceId());
}
}
}
@Override
public String run() throws Exception {
AWSLambda client = AWSClientFactory.create(AWSLambdaClientBuilder.standard(), this.getContext());
if (this.step.functionName != null) {
deleteAllVersions(client, this.step.functionName);
}
if (this.step.stackName != null) {
deleteAllStackFunctionVersions(client, this.step.stackName);
}
return null;
}
}
}
| {
"pile_set_name": "Github"
} |
# A6:2017 Security Misconfiguration
| Threat agents/Attack vectors | Security Weakness | Impacts |
| -- | -- | -- |
| Access Lvl : Exploitability 3 | Prevalence 3 : Detectability 3 | Technical 2 : Business |
| Attackers will often attempt to exploit unpatched flaws or access default accounts, unused pages, unprotected files and directories, etc to gain unauthorized access or knowledge of the system. | Security misconfiguration can happen at any level of an application stack, including the network services, platform, web server, application server, database, frameworks, custom code, and pre-installed virtual machines, containers, or storage. Automated scanners are useful for detecting misconfigurations, use of default accounts or configurations, unnecessary services, legacy options, etc. | Such flaws frequently give attackers unauthorized access to some system data or functionality. Occasionally, such flaws result in a complete system compromise. The business impact depends on the protection needs of the application and data. |
## Is the Application Vulnerable?
The application might be vulnerable if the application is:
* Missing appropriate security hardening across any part of the application stack, or improperly configured permissions on cloud services.
* Unnecessary features are enabled or installed (e.g. unnecessary ports, services, pages, accounts, or privileges).
* Default accounts and their passwords still enabled and unchanged.
* Error handling reveals stack traces or other overly informative error messages to users.
* For upgraded systems, latest security features are disabled or not configured securely.
* The security settings in the application servers, application frameworks (e.g. Struts, Spring, ASP.NET), libraries, databases, etc. not set to secure values.
* The server does not send security headers or directives or they are not set to secure values.
* The software is out of date or vulnerable (see **A9:2017-Using Components with Known Vulnerabilities**).
Without a concerted, repeatable application security configuration process, systems are at a higher risk.
## How To Prevent
Secure installation processes should be implemented, including:
* A repeatable hardening process that makes it fast and easy to deploy another environment that is properly locked down. Development, QA, and production environments should all be configured identically, with different credentials used in each environment. This process should be automated to minimize the effort required to setup a new secure environment.
* A minimal platform without any unnecessary features, components, documentation, and samples. Remove or do not install unused features and frameworks.
* A task to review and update the configurations appropriate to all security notes, updates and patches as part of the patch management process (see **A9:2017-Using Components with Known Vulnerabilities**). In particular, review cloud storage permissions (e.g. S3 bucket permissions).
* A segmented application architecture that provides effective, secure separation between components or tenants, with segmentation, containerization, or cloud security groups (ACLs).
* Sending security directives to clients, e.g. [Security Headers](https://www.owasp.org/index.php/OWASP_Secure_Headers_Project).
* An automated process to verify the effectiveness of the configurations and settings in all environments.
## Example Attack Scenarios
**Scenario #1**: The application server comes with sample applications that are not removed from the production server. These sample applications have known security flaws attackers use to compromise the server. If one of these applications is the admin console, and default accounts weren't changed the attacker logs in with default passwords and takes over.
**Scenario #2**: Directory listing is not disabled on the server. An attacker discovers they can simply list directories. The attacker finds and downloads the compiled Java classes, which they decompile and reverse engineer to view the code. The attacker then finds a serious access control flaw in the application.
**Scenario #3**: The application server's configuration allows detailed error messages, e.g. stack traces, to be returned to users. This potentially exposes sensitive information or underlying flaws such as component versions that are known to be vulnerable.
**Scenario #4**: A cloud service provider has default sharing permissions open to the Internet by other CSP users. This allows sensitive data stored within cloud storage to be accessed.
## References
### OWASP
* [OWASP Testing Guide: Configuration Management](https://www.owasp.org/index.php/Testing_for_configuration_management)
* [OWASP Testing Guide: Testing for Error Codes](https://www.owasp.org/index.php/Testing_for_Error_Code_(OWASP-IG-006))
* [OWASP Security Headers Project](https://www.owasp.org/index.php/OWASP_Secure_Headers_Project)
For additional requirements in this area, see the Application Security Verification Standard [V19 Configuration](https://www.owasp.org/index.php/ASVS_V19_Configuration).
### External
* [NIST Guide to General Server Hardening](https://csrc.nist.gov/publications/detail/sp/800-123/final)
* [CWE-2: Environmental Security Flaws](https://cwe.mitre.org/data/definitions/2.html)
* [CWE-16: Configuration](https://cwe.mitre.org/data/definitions/16.html)
* [CWE-388: Error Handling](https://cwe.mitre.org/data/definitions/388.html)
* [CIS Security Configuration Guides/Benchmarks](https://www.cisecurity.org/cis-benchmarks/)
* [Amazon S3 Bucket Discovery and Enumeration](https://blog.websecurify.com/2017/10/aws-s3-bucket-discovery.html)
| {
"pile_set_name": "Github"
} |
/*! jQuery UI - v1.11.4 - 2015-03-11
* http://jqueryui.com
* Includes: core.css, accordion.css, autocomplete.css, button.css, datepicker.css, dialog.css, draggable.css, menu.css, progressbar.css, resizable.css, selectable.css, selectmenu.css, slider.css, sortable.css, spinner.css, tabs.css, tooltip.css, theme.css
* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Verdana%2CArial%2Csans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=333333&bgTextureHeader=diagonals_thick&bgImgOpacityHeader=8&borderColorHeader=a3a3a3&fcHeader=eeeeee&iconColorHeader=bbbbbb&bgColorContent=f9f9f9&bgTextureContent=highlight_hard&bgImgOpacityContent=100&borderColorContent=cccccc&fcContent=222222&iconColorContent=222222&bgColorDefault=111111&bgTextureDefault=glass&bgImgOpacityDefault=40&borderColorDefault=777777&fcDefault=e3e3e3&iconColorDefault=ededed&bgColorHover=1c1c1c&bgTextureHover=glass&bgImgOpacityHover=55&borderColorHover=000000&fcHover=ffffff&iconColorHover=ffffff&bgColorActive=ffffff&bgTextureActive=flat&bgImgOpacityActive=65&borderColorActive=cccccc&fcActive=222222&iconColorActive=222222&bgColorHighlight=ffeb80&bgTextureHighlight=inset_hard&bgImgOpacityHighlight=55&borderColorHighlight=ffde2e&fcHighlight=363636&iconColorHighlight=4ca300&bgColorError=cd0a0a&bgTextureError=inset_hard&bgImgOpacityError=45&borderColorError=9e0505&fcError=ffffff&iconColorError=ffcf29&bgColorOverlay=aaaaaa&bgTextureOverlay=highlight_hard&bgImgOpacityOverlay=40&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=highlight_soft&bgImgOpacityShadow=50&opacityShadow=20&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px
* Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */
/* Layout helpers
----------------------------------*/
.ui-helper-hidden {
display: none;
}
.ui-helper-hidden-accessible {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
.ui-helper-reset {
margin: 0;
padding: 0;
border: 0;
outline: 0;
line-height: 1.3;
text-decoration: none;
font-size: 100%;
list-style: none;
}
.ui-helper-clearfix:before,
.ui-helper-clearfix:after {
content: "";
display: table;
border-collapse: collapse;
}
.ui-helper-clearfix:after {
clear: both;
}
.ui-helper-clearfix {
min-height: 0; /* support: IE7 */
}
.ui-helper-zfix {
width: 100%;
height: 100%;
top: 0;
left: 0;
position: absolute;
opacity: 0;
filter:Alpha(Opacity=0); /* support: IE8 */
}
.ui-front {
z-index: 100;
}
/* Interaction Cues
----------------------------------*/
.ui-state-disabled {
cursor: default !important;
}
/* Icons
----------------------------------*/
/* states and images */
.ui-icon {
display: block;
text-indent: -99999px;
overflow: hidden;
background-repeat: no-repeat;
}
/* Misc visuals
----------------------------------*/
/* Overlays */
.ui-widget-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.ui-accordion .ui-accordion-header {
display: block;
cursor: pointer;
position: relative;
margin: 2px 0 0 0;
padding: .5em .5em .5em .7em;
min-height: 0; /* support: IE7 */
font-size: 100%;
}
.ui-accordion .ui-accordion-icons {
padding-left: 2.2em;
}
.ui-accordion .ui-accordion-icons .ui-accordion-icons {
padding-left: 2.2em;
}
.ui-accordion .ui-accordion-header .ui-accordion-header-icon {
position: absolute;
left: .5em;
top: 50%;
margin-top: -8px;
}
.ui-accordion .ui-accordion-content {
padding: 1em 2.2em;
border-top: 0;
overflow: auto;
}
.ui-autocomplete {
position: absolute;
top: 0;
left: 0;
cursor: default;
}
.ui-button {
display: inline-block;
position: relative;
padding: 0;
line-height: normal;
margin-right: .1em;
cursor: pointer;
vertical-align: middle;
text-align: center;
overflow: visible; /* removes extra width in IE */
}
.ui-button,
.ui-button:link,
.ui-button:visited,
.ui-button:hover,
.ui-button:active {
text-decoration: none;
}
/* to make room for the icon, a width needs to be set here */
.ui-button-icon-only {
width: 2.2em;
}
/* button elements seem to need a little more width */
button.ui-button-icon-only {
width: 2.4em;
}
.ui-button-icons-only {
width: 3.4em;
}
button.ui-button-icons-only {
width: 3.7em;
}
/* button text element */
.ui-button .ui-button-text {
display: block;
line-height: normal;
}
.ui-button-text-only .ui-button-text {
padding: .4em 1em;
}
.ui-button-icon-only .ui-button-text,
.ui-button-icons-only .ui-button-text {
padding: .4em;
text-indent: -9999999px;
}
.ui-button-text-icon-primary .ui-button-text,
.ui-button-text-icons .ui-button-text {
padding: .4em 1em .4em 2.1em;
}
.ui-button-text-icon-secondary .ui-button-text,
.ui-button-text-icons .ui-button-text {
padding: .4em 2.1em .4em 1em;
}
.ui-button-text-icons .ui-button-text {
padding-left: 2.1em;
padding-right: 2.1em;
}
/* no icon support for input elements, provide padding by default */
input.ui-button {
padding: .4em 1em;
}
/* button icon element(s) */
.ui-button-icon-only .ui-icon,
.ui-button-text-icon-primary .ui-icon,
.ui-button-text-icon-secondary .ui-icon,
.ui-button-text-icons .ui-icon,
.ui-button-icons-only .ui-icon {
position: absolute;
top: 50%;
margin-top: -8px;
}
.ui-button-icon-only .ui-icon {
left: 50%;
margin-left: -8px;
}
.ui-button-text-icon-primary .ui-button-icon-primary,
.ui-button-text-icons .ui-button-icon-primary,
.ui-button-icons-only .ui-button-icon-primary {
left: .5em;
}
.ui-button-text-icon-secondary .ui-button-icon-secondary,
.ui-button-text-icons .ui-button-icon-secondary,
.ui-button-icons-only .ui-button-icon-secondary {
right: .5em;
}
/* button sets */
.ui-buttonset {
margin-right: 7px;
}
.ui-buttonset .ui-button {
margin-left: 0;
margin-right: -.3em;
}
/* workarounds */
/* reset extra padding in Firefox, see h5bp.com/l */
input.ui-button::-moz-focus-inner,
button.ui-button::-moz-focus-inner {
border: 0;
padding: 0;
}
.ui-datepicker {
width: 17em;
padding: .2em .2em 0;
display: none;
}
.ui-datepicker .ui-datepicker-header {
position: relative;
padding: .2em 0;
}
.ui-datepicker .ui-datepicker-prev,
.ui-datepicker .ui-datepicker-next {
position: absolute;
top: 2px;
width: 1.8em;
height: 1.8em;
}
.ui-datepicker .ui-datepicker-prev-hover,
.ui-datepicker .ui-datepicker-next-hover {
top: 1px;
}
.ui-datepicker .ui-datepicker-prev {
left: 2px;
}
.ui-datepicker .ui-datepicker-next {
right: 2px;
}
.ui-datepicker .ui-datepicker-prev-hover {
left: 1px;
}
.ui-datepicker .ui-datepicker-next-hover {
right: 1px;
}
.ui-datepicker .ui-datepicker-prev span,
.ui-datepicker .ui-datepicker-next span {
display: block;
position: absolute;
left: 50%;
margin-left: -8px;
top: 50%;
margin-top: -8px;
}
.ui-datepicker .ui-datepicker-title {
margin: 0 2.3em;
line-height: 1.8em;
text-align: center;
}
.ui-datepicker .ui-datepicker-title select {
font-size: 1em;
margin: 1px 0;
}
.ui-datepicker select.ui-datepicker-month,
.ui-datepicker select.ui-datepicker-year {
width: 45%;
}
.ui-datepicker table {
width: 100%;
font-size: .9em;
border-collapse: collapse;
margin: 0 0 .4em;
}
.ui-datepicker th {
padding: .7em .3em;
text-align: center;
font-weight: bold;
border: 0;
}
.ui-datepicker td {
border: 0;
padding: 1px;
}
.ui-datepicker td span,
.ui-datepicker td a {
display: block;
padding: .2em;
text-align: right;
text-decoration: none;
}
.ui-datepicker .ui-datepicker-buttonpane {
background-image: none;
margin: .7em 0 0 0;
padding: 0 .2em;
border-left: 0;
border-right: 0;
border-bottom: 0;
}
.ui-datepicker .ui-datepicker-buttonpane button {
float: right;
margin: .5em .2em .4em;
cursor: pointer;
padding: .2em .6em .3em .6em;
width: auto;
overflow: visible;
}
.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current {
float: left;
}
/* with multiple calendars */
.ui-datepicker.ui-datepicker-multi {
width: auto;
}
.ui-datepicker-multi .ui-datepicker-group {
float: left;
}
.ui-datepicker-multi .ui-datepicker-group table {
width: 95%;
margin: 0 auto .4em;
}
.ui-datepicker-multi-2 .ui-datepicker-group {
width: 50%;
}
.ui-datepicker-multi-3 .ui-datepicker-group {
width: 33.3%;
}
.ui-datepicker-multi-4 .ui-datepicker-group {
width: 25%;
}
.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header,
.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header {
border-left-width: 0;
}
.ui-datepicker-multi .ui-datepicker-buttonpane {
clear: left;
}
.ui-datepicker-row-break {
clear: both;
width: 100%;
font-size: 0;
}
/* RTL support */
.ui-datepicker-rtl {
direction: rtl;
}
.ui-datepicker-rtl .ui-datepicker-prev {
right: 2px;
left: auto;
}
.ui-datepicker-rtl .ui-datepicker-next {
left: 2px;
right: auto;
}
.ui-datepicker-rtl .ui-datepicker-prev:hover {
right: 1px;
left: auto;
}
.ui-datepicker-rtl .ui-datepicker-next:hover {
left: 1px;
right: auto;
}
.ui-datepicker-rtl .ui-datepicker-buttonpane {
clear: right;
}
.ui-datepicker-rtl .ui-datepicker-buttonpane button {
float: left;
}
.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current,
.ui-datepicker-rtl .ui-datepicker-group {
float: right;
}
.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header,
.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header {
border-right-width: 0;
border-left-width: 1px;
}
.ui-dialog {
overflow: hidden;
position: absolute;
top: 0;
left: 0;
padding: .2em;
outline: 0;
}
.ui-dialog .ui-dialog-titlebar {
padding: .4em 1em;
position: relative;
}
.ui-dialog .ui-dialog-title {
float: left;
margin: .1em 0;
white-space: nowrap;
width: 90%;
overflow: hidden;
text-overflow: ellipsis;
}
.ui-dialog .ui-dialog-titlebar-close {
position: absolute;
right: .3em;
top: 50%;
width: 20px;
margin: -10px 0 0 0;
padding: 1px;
height: 20px;
}
.ui-dialog .ui-dialog-content {
position: relative;
border: 0;
padding: .5em 1em;
background: none;
overflow: auto;
}
.ui-dialog .ui-dialog-buttonpane {
text-align: left;
border-width: 1px 0 0 0;
background-image: none;
margin-top: .5em;
padding: .3em 1em .5em .4em;
}
.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset {
float: right;
}
.ui-dialog .ui-dialog-buttonpane button {
margin: .5em .4em .5em 0;
cursor: pointer;
}
.ui-dialog .ui-resizable-se {
width: 12px;
height: 12px;
right: -5px;
bottom: -5px;
background-position: 16px 16px;
}
.ui-draggable .ui-dialog-titlebar {
cursor: move;
}
.ui-draggable-handle {
-ms-touch-action: none;
touch-action: none;
}
.ui-menu {
list-style: none;
padding: 0;
margin: 0;
display: block;
outline: none;
}
.ui-menu .ui-menu {
position: absolute;
}
.ui-menu .ui-menu-item {
position: relative;
margin: 0;
padding: 3px 1em 3px .4em;
cursor: pointer;
min-height: 0; /* support: IE7 */
/* support: IE10, see #8844 */
list-style-image: url("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7");
}
.ui-menu .ui-menu-divider {
margin: 5px 0;
height: 0;
font-size: 0;
line-height: 0;
border-width: 1px 0 0 0;
}
.ui-menu .ui-state-focus,
.ui-menu .ui-state-active {
margin: -1px;
}
/* icon support */
.ui-menu-icons {
position: relative;
}
.ui-menu-icons .ui-menu-item {
padding-left: 2em;
}
/* left-aligned */
.ui-menu .ui-icon {
position: absolute;
top: 0;
bottom: 0;
left: .2em;
margin: auto 0;
}
/* right-aligned */
.ui-menu .ui-menu-icon {
left: auto;
right: 0;
}
.ui-progressbar {
height: 2em;
text-align: left;
overflow: hidden;
}
.ui-progressbar .ui-progressbar-value {
margin: -1px;
height: 100%;
}
.ui-progressbar .ui-progressbar-overlay {
background: url("data:image/gif;base64,R0lGODlhKAAoAIABAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJAQABACwAAAAAKAAoAAACkYwNqXrdC52DS06a7MFZI+4FHBCKoDeWKXqymPqGqxvJrXZbMx7Ttc+w9XgU2FB3lOyQRWET2IFGiU9m1frDVpxZZc6bfHwv4c1YXP6k1Vdy292Fb6UkuvFtXpvWSzA+HycXJHUXiGYIiMg2R6W459gnWGfHNdjIqDWVqemH2ekpObkpOlppWUqZiqr6edqqWQAAIfkECQEAAQAsAAAAACgAKAAAApSMgZnGfaqcg1E2uuzDmmHUBR8Qil95hiPKqWn3aqtLsS18y7G1SzNeowWBENtQd+T1JktP05nzPTdJZlR6vUxNWWjV+vUWhWNkWFwxl9VpZRedYcflIOLafaa28XdsH/ynlcc1uPVDZxQIR0K25+cICCmoqCe5mGhZOfeYSUh5yJcJyrkZWWpaR8doJ2o4NYq62lAAACH5BAkBAAEALAAAAAAoACgAAAKVDI4Yy22ZnINRNqosw0Bv7i1gyHUkFj7oSaWlu3ovC8GxNso5fluz3qLVhBVeT/Lz7ZTHyxL5dDalQWPVOsQWtRnuwXaFTj9jVVh8pma9JjZ4zYSj5ZOyma7uuolffh+IR5aW97cHuBUXKGKXlKjn+DiHWMcYJah4N0lYCMlJOXipGRr5qdgoSTrqWSq6WFl2ypoaUAAAIfkECQEAAQAsAAAAACgAKAAAApaEb6HLgd/iO7FNWtcFWe+ufODGjRfoiJ2akShbueb0wtI50zm02pbvwfWEMWBQ1zKGlLIhskiEPm9R6vRXxV4ZzWT2yHOGpWMyorblKlNp8HmHEb/lCXjcW7bmtXP8Xt229OVWR1fod2eWqNfHuMjXCPkIGNileOiImVmCOEmoSfn3yXlJWmoHGhqp6ilYuWYpmTqKUgAAIfkECQEAAQAsAAAAACgAKAAAApiEH6kb58biQ3FNWtMFWW3eNVcojuFGfqnZqSebuS06w5V80/X02pKe8zFwP6EFWOT1lDFk8rGERh1TTNOocQ61Hm4Xm2VexUHpzjymViHrFbiELsefVrn6XKfnt2Q9G/+Xdie499XHd2g4h7ioOGhXGJboGAnXSBnoBwKYyfioubZJ2Hn0RuRZaflZOil56Zp6iioKSXpUAAAh+QQJAQABACwAAAAAKAAoAAACkoQRqRvnxuI7kU1a1UU5bd5tnSeOZXhmn5lWK3qNTWvRdQxP8qvaC+/yaYQzXO7BMvaUEmJRd3TsiMAgswmNYrSgZdYrTX6tSHGZO73ezuAw2uxuQ+BbeZfMxsexY35+/Qe4J1inV0g4x3WHuMhIl2jXOKT2Q+VU5fgoSUI52VfZyfkJGkha6jmY+aaYdirq+lQAACH5BAkBAAEALAAAAAAoACgAAAKWBIKpYe0L3YNKToqswUlvznigd4wiR4KhZrKt9Upqip61i9E3vMvxRdHlbEFiEXfk9YARYxOZZD6VQ2pUunBmtRXo1Lf8hMVVcNl8JafV38aM2/Fu5V16Bn63r6xt97j09+MXSFi4BniGFae3hzbH9+hYBzkpuUh5aZmHuanZOZgIuvbGiNeomCnaxxap2upaCZsq+1kAACH5BAkBAAEALAAAAAAoACgAAAKXjI8By5zf4kOxTVrXNVlv1X0d8IGZGKLnNpYtm8Lr9cqVeuOSvfOW79D9aDHizNhDJidFZhNydEahOaDH6nomtJjp1tutKoNWkvA6JqfRVLHU/QUfau9l2x7G54d1fl995xcIGAdXqMfBNadoYrhH+Mg2KBlpVpbluCiXmMnZ2Sh4GBqJ+ckIOqqJ6LmKSllZmsoq6wpQAAAh+QQJAQABACwAAAAAKAAoAAAClYx/oLvoxuJDkU1a1YUZbJ59nSd2ZXhWqbRa2/gF8Gu2DY3iqs7yrq+xBYEkYvFSM8aSSObE+ZgRl1BHFZNr7pRCavZ5BW2142hY3AN/zWtsmf12p9XxxFl2lpLn1rseztfXZjdIWIf2s5dItwjYKBgo9yg5pHgzJXTEeGlZuenpyPmpGQoKOWkYmSpaSnqKileI2FAAACH5BAkBAAEALAAAAAAoACgAAAKVjB+gu+jG4kORTVrVhRlsnn2dJ3ZleFaptFrb+CXmO9OozeL5VfP99HvAWhpiUdcwkpBH3825AwYdU8xTqlLGhtCosArKMpvfa1mMRae9VvWZfeB2XfPkeLmm18lUcBj+p5dnN8jXZ3YIGEhYuOUn45aoCDkp16hl5IjYJvjWKcnoGQpqyPlpOhr3aElaqrq56Bq7VAAAOw==");
height: 100%;
filter: alpha(opacity=25); /* support: IE8 */
opacity: 0.25;
}
.ui-progressbar-indeterminate .ui-progressbar-value {
background-image: none;
}
.ui-resizable {
position: relative;
}
.ui-resizable-handle {
position: absolute;
font-size: 0.1px;
display: block;
-ms-touch-action: none;
touch-action: none;
}
.ui-resizable-disabled .ui-resizable-handle,
.ui-resizable-autohide .ui-resizable-handle {
display: none;
}
.ui-resizable-n {
cursor: n-resize;
height: 7px;
width: 100%;
top: -5px;
left: 0;
}
.ui-resizable-s {
cursor: s-resize;
height: 7px;
width: 100%;
bottom: -5px;
left: 0;
}
.ui-resizable-e {
cursor: e-resize;
width: 7px;
right: -5px;
top: 0;
height: 100%;
}
.ui-resizable-w {
cursor: w-resize;
width: 7px;
left: -5px;
top: 0;
height: 100%;
}
.ui-resizable-se {
cursor: se-resize;
width: 12px;
height: 12px;
right: 1px;
bottom: 1px;
}
.ui-resizable-sw {
cursor: sw-resize;
width: 9px;
height: 9px;
left: -5px;
bottom: -5px;
}
.ui-resizable-nw {
cursor: nw-resize;
width: 9px;
height: 9px;
left: -5px;
top: -5px;
}
.ui-resizable-ne {
cursor: ne-resize;
width: 9px;
height: 9px;
right: -5px;
top: -5px;
}
.ui-selectable {
-ms-touch-action: none;
touch-action: none;
}
.ui-selectable-helper {
position: absolute;
z-index: 100;
border: 1px dotted black;
}
.ui-selectmenu-menu {
padding: 0;
margin: 0;
position: absolute;
top: 0;
left: 0;
display: none;
}
.ui-selectmenu-menu .ui-menu {
overflow: auto;
/* Support: IE7 */
overflow-x: hidden;
padding-bottom: 1px;
}
.ui-selectmenu-menu .ui-menu .ui-selectmenu-optgroup {
font-size: 1em;
font-weight: bold;
line-height: 1.5;
padding: 2px 0.4em;
margin: 0.5em 0 0 0;
height: auto;
border: 0;
}
.ui-selectmenu-open {
display: block;
}
.ui-selectmenu-button {
display: inline-block;
overflow: hidden;
position: relative;
text-decoration: none;
cursor: pointer;
}
.ui-selectmenu-button span.ui-icon {
right: 0.5em;
left: auto;
margin-top: -8px;
position: absolute;
top: 50%;
}
.ui-selectmenu-button span.ui-selectmenu-text {
text-align: left;
padding: 0.4em 2.1em 0.4em 1em;
display: block;
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ui-slider {
position: relative;
text-align: left;
}
.ui-slider .ui-slider-handle {
position: absolute;
z-index: 2;
width: 1.2em;
height: 1.2em;
cursor: default;
-ms-touch-action: none;
touch-action: none;
}
.ui-slider .ui-slider-range {
position: absolute;
z-index: 1;
font-size: .7em;
display: block;
border: 0;
background-position: 0 0;
}
/* support: IE8 - See #6727 */
.ui-slider.ui-state-disabled .ui-slider-handle,
.ui-slider.ui-state-disabled .ui-slider-range {
filter: inherit;
}
.ui-slider-horizontal {
height: .8em;
}
.ui-slider-horizontal .ui-slider-handle {
top: -.3em;
margin-left: -.6em;
}
.ui-slider-horizontal .ui-slider-range {
top: 0;
height: 100%;
}
.ui-slider-horizontal .ui-slider-range-min {
left: 0;
}
.ui-slider-horizontal .ui-slider-range-max {
right: 0;
}
.ui-slider-vertical {
width: .8em;
height: 100px;
}
.ui-slider-vertical .ui-slider-handle {
left: -.3em;
margin-left: 0;
margin-bottom: -.6em;
}
.ui-slider-vertical .ui-slider-range {
left: 0;
width: 100%;
}
.ui-slider-vertical .ui-slider-range-min {
bottom: 0;
}
.ui-slider-vertical .ui-slider-range-max {
top: 0;
}
.ui-sortable-handle {
-ms-touch-action: none;
touch-action: none;
}
.ui-spinner {
position: relative;
display: inline-block;
overflow: hidden;
padding: 0;
vertical-align: middle;
}
.ui-spinner-input {
border: none;
background: none;
color: inherit;
padding: 0;
margin: .2em 0;
vertical-align: middle;
margin-left: .4em;
margin-right: 22px;
}
.ui-spinner-button {
width: 16px;
height: 50%;
font-size: .5em;
padding: 0;
margin: 0;
text-align: center;
position: absolute;
cursor: default;
display: block;
overflow: hidden;
right: 0;
}
/* more specificity required here to override default borders */
.ui-spinner a.ui-spinner-button {
border-top: none;
border-bottom: none;
border-right: none;
}
/* vertically center icon */
.ui-spinner .ui-icon {
position: absolute;
margin-top: -8px;
top: 50%;
left: 0;
}
.ui-spinner-up {
top: 0;
}
.ui-spinner-down {
bottom: 0;
}
/* TR overrides */
.ui-spinner .ui-icon-triangle-1-s {
/* need to fix icons sprite */
background-position: -65px -16px;
}
.ui-tabs {
position: relative;/* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */
padding: .2em;
}
.ui-tabs .ui-tabs-nav {
margin: 0;
padding: .2em .2em 0;
}
.ui-tabs .ui-tabs-nav li {
list-style: none;
float: left;
position: relative;
top: 0;
margin: 1px .2em 0 0;
border-bottom-width: 0;
padding: 0;
white-space: nowrap;
}
.ui-tabs .ui-tabs-nav .ui-tabs-anchor {
float: left;
padding: .5em 1em;
text-decoration: none;
}
.ui-tabs .ui-tabs-nav li.ui-tabs-active {
margin-bottom: -1px;
padding-bottom: 1px;
}
.ui-tabs .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor,
.ui-tabs .ui-tabs-nav li.ui-state-disabled .ui-tabs-anchor,
.ui-tabs .ui-tabs-nav li.ui-tabs-loading .ui-tabs-anchor {
cursor: text;
}
.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor {
cursor: pointer;
}
.ui-tabs .ui-tabs-panel {
display: block;
border-width: 0;
padding: 1em 1.4em;
background: none;
}
.ui-tooltip {
padding: 8px;
position: absolute;
z-index: 9999;
max-width: 300px;
-webkit-box-shadow: 0 0 5px #aaa;
box-shadow: 0 0 5px #aaa;
}
body .ui-tooltip {
border-width: 2px;
}
/* Component containers
----------------------------------*/
.ui-widget {
font-family: Verdana,Arial,sans-serif;
font-size: 1.1em;
}
.ui-widget .ui-widget {
font-size: 1em;
}
.ui-widget input,
.ui-widget select,
.ui-widget textarea,
.ui-widget button {
font-family: Verdana,Arial,sans-serif;
font-size: 1em;
}
.ui-widget-content {
border: 1px solid #cccccc;
background: #f9f9f9 url("images/ui-bg_highlight-hard_100_f9f9f9_1x100.png") 50% top repeat-x;
color: #222222;
}
.ui-widget-content a {
color: #222222;
}
.ui-widget-header {
border: 1px solid #a3a3a3;
background: #333333 url("images/ui-bg_diagonals-thick_8_333333_40x40.png") 50% 50% repeat;
color: #eeeeee;
font-weight: bold;
}
.ui-widget-header a {
color: #eeeeee;
}
/* Interaction states
----------------------------------*/
.ui-state-default,
.ui-widget-content .ui-state-default,
.ui-widget-header .ui-state-default {
border: 1px solid #777777;
background: #111111 url("images/ui-bg_glass_40_111111_1x400.png") 50% 50% repeat-x;
font-weight: normal;
color: #e3e3e3;
}
.ui-state-default a,
.ui-state-default a:link,
.ui-state-default a:visited {
color: #e3e3e3;
text-decoration: none;
}
.ui-state-hover,
.ui-widget-content .ui-state-hover,
.ui-widget-header .ui-state-hover,
.ui-state-focus,
.ui-widget-content .ui-state-focus,
.ui-widget-header .ui-state-focus {
border: 1px solid #000000;
background: #1c1c1c url("images/ui-bg_glass_55_1c1c1c_1x400.png") 50% 50% repeat-x;
font-weight: normal;
color: #ffffff;
}
.ui-state-hover a,
.ui-state-hover a:hover,
.ui-state-hover a:link,
.ui-state-hover a:visited,
.ui-state-focus a,
.ui-state-focus a:hover,
.ui-state-focus a:link,
.ui-state-focus a:visited {
color: #ffffff;
text-decoration: none;
}
.ui-state-active,
.ui-widget-content .ui-state-active,
.ui-widget-header .ui-state-active {
border: 1px solid #cccccc;
background: #ffffff url("images/ui-bg_flat_65_ffffff_40x100.png") 50% 50% repeat-x;
font-weight: normal;
color: #222222;
}
.ui-state-active a,
.ui-state-active a:link,
.ui-state-active a:visited {
color: #222222;
text-decoration: none;
}
/* Interaction Cues
----------------------------------*/
.ui-state-highlight,
.ui-widget-content .ui-state-highlight,
.ui-widget-header .ui-state-highlight {
border: 1px solid #ffde2e;
background: #ffeb80 url("images/ui-bg_inset-hard_55_ffeb80_1x100.png") 50% bottom repeat-x;
color: #363636;
}
.ui-state-highlight a,
.ui-widget-content .ui-state-highlight a,
.ui-widget-header .ui-state-highlight a {
color: #363636;
}
.ui-state-error,
.ui-widget-content .ui-state-error,
.ui-widget-header .ui-state-error {
border: 1px solid #9e0505;
background: #cd0a0a url("images/ui-bg_inset-hard_45_cd0a0a_1x100.png") 50% bottom repeat-x;
color: #ffffff;
}
.ui-state-error a,
.ui-widget-content .ui-state-error a,
.ui-widget-header .ui-state-error a {
color: #ffffff;
}
.ui-state-error-text,
.ui-widget-content .ui-state-error-text,
.ui-widget-header .ui-state-error-text {
color: #ffffff;
}
.ui-priority-primary,
.ui-widget-content .ui-priority-primary,
.ui-widget-header .ui-priority-primary {
font-weight: bold;
}
.ui-priority-secondary,
.ui-widget-content .ui-priority-secondary,
.ui-widget-header .ui-priority-secondary {
opacity: .7;
filter:Alpha(Opacity=70); /* support: IE8 */
font-weight: normal;
}
.ui-state-disabled,
.ui-widget-content .ui-state-disabled,
.ui-widget-header .ui-state-disabled {
opacity: .35;
filter:Alpha(Opacity=35); /* support: IE8 */
background-image: none;
}
.ui-state-disabled .ui-icon {
filter:Alpha(Opacity=35); /* support: IE8 - See #6059 */
}
/* Icons
----------------------------------*/
/* states and images */
.ui-icon {
width: 16px;
height: 16px;
}
.ui-icon,
.ui-widget-content .ui-icon {
background-image: url("images/ui-icons_222222_256x240.png");
}
.ui-widget-header .ui-icon {
background-image: url("images/ui-icons_bbbbbb_256x240.png");
}
.ui-state-default .ui-icon {
background-image: url("images/ui-icons_ededed_256x240.png");
}
.ui-state-hover .ui-icon,
.ui-state-focus .ui-icon {
background-image: url("images/ui-icons_ffffff_256x240.png");
}
.ui-state-active .ui-icon {
background-image: url("images/ui-icons_222222_256x240.png");
}
.ui-state-highlight .ui-icon {
background-image: url("images/ui-icons_4ca300_256x240.png");
}
.ui-state-error .ui-icon,
.ui-state-error-text .ui-icon {
background-image: url("images/ui-icons_ffcf29_256x240.png");
}
/* positioning */
.ui-icon-blank { background-position: 16px 16px; }
.ui-icon-carat-1-n { background-position: 0 0; }
.ui-icon-carat-1-ne { background-position: -16px 0; }
.ui-icon-carat-1-e { background-position: -32px 0; }
.ui-icon-carat-1-se { background-position: -48px 0; }
.ui-icon-carat-1-s { background-position: -64px 0; }
.ui-icon-carat-1-sw { background-position: -80px 0; }
.ui-icon-carat-1-w { background-position: -96px 0; }
.ui-icon-carat-1-nw { background-position: -112px 0; }
.ui-icon-carat-2-n-s { background-position: -128px 0; }
.ui-icon-carat-2-e-w { background-position: -144px 0; }
.ui-icon-triangle-1-n { background-position: 0 -16px; }
.ui-icon-triangle-1-ne { background-position: -16px -16px; }
.ui-icon-triangle-1-e { background-position: -32px -16px; }
.ui-icon-triangle-1-se { background-position: -48px -16px; }
.ui-icon-triangle-1-s { background-position: -64px -16px; }
.ui-icon-triangle-1-sw { background-position: -80px -16px; }
.ui-icon-triangle-1-w { background-position: -96px -16px; }
.ui-icon-triangle-1-nw { background-position: -112px -16px; }
.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
.ui-icon-arrow-1-n { background-position: 0 -32px; }
.ui-icon-arrow-1-ne { background-position: -16px -32px; }
.ui-icon-arrow-1-e { background-position: -32px -32px; }
.ui-icon-arrow-1-se { background-position: -48px -32px; }
.ui-icon-arrow-1-s { background-position: -64px -32px; }
.ui-icon-arrow-1-sw { background-position: -80px -32px; }
.ui-icon-arrow-1-w { background-position: -96px -32px; }
.ui-icon-arrow-1-nw { background-position: -112px -32px; }
.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
.ui-icon-arrow-4 { background-position: 0 -80px; }
.ui-icon-arrow-4-diag { background-position: -16px -80px; }
.ui-icon-extlink { background-position: -32px -80px; }
.ui-icon-newwin { background-position: -48px -80px; }
.ui-icon-refresh { background-position: -64px -80px; }
.ui-icon-shuffle { background-position: -80px -80px; }
.ui-icon-transfer-e-w { background-position: -96px -80px; }
.ui-icon-transferthick-e-w { background-position: -112px -80px; }
.ui-icon-folder-collapsed { background-position: 0 -96px; }
.ui-icon-folder-open { background-position: -16px -96px; }
.ui-icon-document { background-position: -32px -96px; }
.ui-icon-document-b { background-position: -48px -96px; }
.ui-icon-note { background-position: -64px -96px; }
.ui-icon-mail-closed { background-position: -80px -96px; }
.ui-icon-mail-open { background-position: -96px -96px; }
.ui-icon-suitcase { background-position: -112px -96px; }
.ui-icon-comment { background-position: -128px -96px; }
.ui-icon-person { background-position: -144px -96px; }
.ui-icon-print { background-position: -160px -96px; }
.ui-icon-trash { background-position: -176px -96px; }
.ui-icon-locked { background-position: -192px -96px; }
.ui-icon-unlocked { background-position: -208px -96px; }
.ui-icon-bookmark { background-position: -224px -96px; }
.ui-icon-tag { background-position: -240px -96px; }
.ui-icon-home { background-position: 0 -112px; }
.ui-icon-flag { background-position: -16px -112px; }
.ui-icon-calendar { background-position: -32px -112px; }
.ui-icon-cart { background-position: -48px -112px; }
.ui-icon-pencil { background-position: -64px -112px; }
.ui-icon-clock { background-position: -80px -112px; }
.ui-icon-disk { background-position: -96px -112px; }
.ui-icon-calculator { background-position: -112px -112px; }
.ui-icon-zoomin { background-position: -128px -112px; }
.ui-icon-zoomout { background-position: -144px -112px; }
.ui-icon-search { background-position: -160px -112px; }
.ui-icon-wrench { background-position: -176px -112px; }
.ui-icon-gear { background-position: -192px -112px; }
.ui-icon-heart { background-position: -208px -112px; }
.ui-icon-star { background-position: -224px -112px; }
.ui-icon-link { background-position: -240px -112px; }
.ui-icon-cancel { background-position: 0 -128px; }
.ui-icon-plus { background-position: -16px -128px; }
.ui-icon-plusthick { background-position: -32px -128px; }
.ui-icon-minus { background-position: -48px -128px; }
.ui-icon-minusthick { background-position: -64px -128px; }
.ui-icon-close { background-position: -80px -128px; }
.ui-icon-closethick { background-position: -96px -128px; }
.ui-icon-key { background-position: -112px -128px; }
.ui-icon-lightbulb { background-position: -128px -128px; }
.ui-icon-scissors { background-position: -144px -128px; }
.ui-icon-clipboard { background-position: -160px -128px; }
.ui-icon-copy { background-position: -176px -128px; }
.ui-icon-contact { background-position: -192px -128px; }
.ui-icon-image { background-position: -208px -128px; }
.ui-icon-video { background-position: -224px -128px; }
.ui-icon-script { background-position: -240px -128px; }
.ui-icon-alert { background-position: 0 -144px; }
.ui-icon-info { background-position: -16px -144px; }
.ui-icon-notice { background-position: -32px -144px; }
.ui-icon-help { background-position: -48px -144px; }
.ui-icon-check { background-position: -64px -144px; }
.ui-icon-bullet { background-position: -80px -144px; }
.ui-icon-radio-on { background-position: -96px -144px; }
.ui-icon-radio-off { background-position: -112px -144px; }
.ui-icon-pin-w { background-position: -128px -144px; }
.ui-icon-pin-s { background-position: -144px -144px; }
.ui-icon-play { background-position: 0 -160px; }
.ui-icon-pause { background-position: -16px -160px; }
.ui-icon-seek-next { background-position: -32px -160px; }
.ui-icon-seek-prev { background-position: -48px -160px; }
.ui-icon-seek-end { background-position: -64px -160px; }
.ui-icon-seek-start { background-position: -80px -160px; }
/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */
.ui-icon-seek-first { background-position: -80px -160px; }
.ui-icon-stop { background-position: -96px -160px; }
.ui-icon-eject { background-position: -112px -160px; }
.ui-icon-volume-off { background-position: -128px -160px; }
.ui-icon-volume-on { background-position: -144px -160px; }
.ui-icon-power { background-position: 0 -176px; }
.ui-icon-signal-diag { background-position: -16px -176px; }
.ui-icon-signal { background-position: -32px -176px; }
.ui-icon-battery-0 { background-position: -48px -176px; }
.ui-icon-battery-1 { background-position: -64px -176px; }
.ui-icon-battery-2 { background-position: -80px -176px; }
.ui-icon-battery-3 { background-position: -96px -176px; }
.ui-icon-circle-plus { background-position: 0 -192px; }
.ui-icon-circle-minus { background-position: -16px -192px; }
.ui-icon-circle-close { background-position: -32px -192px; }
.ui-icon-circle-triangle-e { background-position: -48px -192px; }
.ui-icon-circle-triangle-s { background-position: -64px -192px; }
.ui-icon-circle-triangle-w { background-position: -80px -192px; }
.ui-icon-circle-triangle-n { background-position: -96px -192px; }
.ui-icon-circle-arrow-e { background-position: -112px -192px; }
.ui-icon-circle-arrow-s { background-position: -128px -192px; }
.ui-icon-circle-arrow-w { background-position: -144px -192px; }
.ui-icon-circle-arrow-n { background-position: -160px -192px; }
.ui-icon-circle-zoomin { background-position: -176px -192px; }
.ui-icon-circle-zoomout { background-position: -192px -192px; }
.ui-icon-circle-check { background-position: -208px -192px; }
.ui-icon-circlesmall-plus { background-position: 0 -208px; }
.ui-icon-circlesmall-minus { background-position: -16px -208px; }
.ui-icon-circlesmall-close { background-position: -32px -208px; }
.ui-icon-squaresmall-plus { background-position: -48px -208px; }
.ui-icon-squaresmall-minus { background-position: -64px -208px; }
.ui-icon-squaresmall-close { background-position: -80px -208px; }
.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
/* Misc visuals
----------------------------------*/
/* Corner radius */
.ui-corner-all,
.ui-corner-top,
.ui-corner-left,
.ui-corner-tl {
border-top-left-radius: 4px;
}
.ui-corner-all,
.ui-corner-top,
.ui-corner-right,
.ui-corner-tr {
border-top-right-radius: 4px;
}
.ui-corner-all,
.ui-corner-bottom,
.ui-corner-left,
.ui-corner-bl {
border-bottom-left-radius: 4px;
}
.ui-corner-all,
.ui-corner-bottom,
.ui-corner-right,
.ui-corner-br {
border-bottom-right-radius: 4px;
}
/* Overlays */
.ui-widget-overlay {
background: #aaaaaa url("images/ui-bg_highlight-hard_40_aaaaaa_1x100.png") 50% top repeat-x;
opacity: .3;
filter: Alpha(Opacity=30); /* support: IE8 */
}
.ui-widget-shadow {
margin: -8px 0 0 -8px;
padding: 8px;
background: #aaaaaa url("images/ui-bg_highlight-soft_50_aaaaaa_1x100.png") 50% top repeat-x;
opacity: .2;
filter: Alpha(Opacity=20); /* support: IE8 */
border-radius: 8px;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples: Visitors</title>
<link href="../examples.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.time.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.selection.js"></script>
<script type="text/javascript">
$(function() {
var d = [[1196463600000, 0], [1196550000000, 0], [1196636400000, 0], [1196722800000, 77], [1196809200000, 3636], [1196895600000, 3575], [1196982000000, 2736], [1197068400000, 1086], [1197154800000, 676], [1197241200000, 1205], [1197327600000, 906], [1197414000000, 710], [1197500400000, 639], [1197586800000, 540], [1197673200000, 435], [1197759600000, 301], [1197846000000, 575], [1197932400000, 481], [1198018800000, 591], [1198105200000, 608], [1198191600000, 459], [1198278000000, 234], [1198364400000, 1352], [1198450800000, 686], [1198537200000, 279], [1198623600000, 449], [1198710000000, 468], [1198796400000, 392], [1198882800000, 282], [1198969200000, 208], [1199055600000, 229], [1199142000000, 177], [1199228400000, 374], [1199314800000, 436], [1199401200000, 404], [1199487600000, 253], [1199574000000, 218], [1199660400000, 476], [1199746800000, 462], [1199833200000, 448], [1199919600000, 442], [1200006000000, 403], [1200092400000, 204], [1200178800000, 194], [1200265200000, 327], [1200351600000, 374], [1200438000000, 507], [1200524400000, 546], [1200610800000, 482], [1200697200000, 283], [1200783600000, 221], [1200870000000, 483], [1200956400000, 523], [1201042800000, 528], [1201129200000, 483], [1201215600000, 452], [1201302000000, 270], [1201388400000, 222], [1201474800000, 439], [1201561200000, 559], [1201647600000, 521], [1201734000000, 477], [1201820400000, 442], [1201906800000, 252], [1201993200000, 236], [1202079600000, 525], [1202166000000, 477], [1202252400000, 386], [1202338800000, 409], [1202425200000, 408], [1202511600000, 237], [1202598000000, 193], [1202684400000, 357], [1202770800000, 414], [1202857200000, 393], [1202943600000, 353], [1203030000000, 364], [1203116400000, 215], [1203202800000, 214], [1203289200000, 356], [1203375600000, 399], [1203462000000, 334], [1203548400000, 348], [1203634800000, 243], [1203721200000, 126], [1203807600000, 157], [1203894000000, 288]];
// first correct the timestamps - they are recorded as the daily
// midnights in UTC+0100, but Flot always displays dates in UTC
// so we have to add one hour to hit the midnights in the plot
for (var i = 0; i < d.length; ++i) {
d[i][0] += 60 * 60 * 1000;
}
// helper for returning the weekends in a period
function weekendAreas(axes) {
var markings = [],
d = new Date(axes.xaxis.min);
// go to the first Saturday
d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
d.setUTCSeconds(0);
d.setUTCMinutes(0);
d.setUTCHours(0);
var i = d.getTime();
// when we don't set yaxis, the rectangle automatically
// extends to infinity upwards and downwards
do {
markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } });
i += 7 * 24 * 60 * 60 * 1000;
} while (i < axes.xaxis.max);
return markings;
}
var options = {
xaxis: {
mode: "time",
tickLength: 5
},
selection: {
mode: "x"
},
grid: {
markings: weekendAreas
}
};
var plot = $.plot("#placeholder", [d], options);
var overview = $.plot("#overview", [d], {
series: {
lines: {
show: true,
lineWidth: 1
},
shadowSize: 0
},
xaxis: {
ticks: [],
mode: "time"
},
yaxis: {
ticks: [],
min: 0,
autoscaleMargin: 0.1
},
selection: {
mode: "x"
}
});
// now connect the two
$("#placeholder").bind("plotselected", function (event, ranges) {
// do the zooming
$.each(plot.getXAxes(), function(_, axis) {
var opts = axis.options;
opts.min = ranges.xaxis.from;
opts.max = ranges.xaxis.to;
});
plot.setupGrid();
plot.draw();
plot.clearSelection();
// don't fire event on the overview to prevent eternal loop
overview.setSelection(ranges, true);
});
$("#overview").bind("plotselected", function (event, ranges) {
plot.setSelection(ranges);
});
// Add the Flot version string to the footer
$("#footer").prepend("Flot " + $.plot.version + " – ");
});
</script>
</head>
<body>
<div id="header">
<h2>Visitors</h2>
</div>
<div id="content">
<div class="demo-container">
<div id="placeholder" class="demo-placeholder"></div>
</div>
<div class="demo-container" style="height:150px;">
<div id="overview" class="demo-placeholder"></div>
</div>
<p>This plot shows visitors per day to the Flot homepage, with weekends colored.</p>
<p>The smaller plot is linked to the main plot, so it acts as an overview. Try dragging a selection on either plot, and watch the behavior of the other.</p>
</div>
<div id="footer">
Copyright © 2007 - 2014 IOLA and Ole Laursen
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
> 本文作者来自 [华尔街见闻技术团队](https://www.zhihu.com/org/hua-er-jie-jian-wen-ji-zhu-tuan-dui-92/activities) - [花裤衩](https://github.com/PanJiaChen)
前几天 webpack 作者 [Tobias Koppers](https://github.com/sokra) 发布了一篇新的文章 [webpack 4.0 to 4.16: Did you know?](https://medium.com/webpack/webpack-4-0-to-4-16-did-you-know-71e25a57fa6b)(需翻墙),总结了一下`webpack 4`发布以来,做了哪些调整和优化。
并且说自己正在着手开发 `webpack 5`。
> Oh you are still on webpack 3. I’m sorry, what is blocking you? We already working on webpack 5, so your stack might be outdated soon…
翻译成中文就是:
![](https://user-gold-cdn.xitu.io/2018/7/27/164db1a2e089c151?w=690&h=200&f=jpeg&s=22433)
正好我也在使用一个文档生成工具 [docz](https://github.com/pedronauck/docz)(安利一波) 也最低需要`webpack 4+`,新版`webpack`性能提高了不少,而且`webpack 4` 都已经发布五个多月了,想必应该已经没什么坑了,应该可以安心的按照别人写的升级攻略升级了。之前一直迟迟不升级完全是被去年被 `webpack 3` 坑怕了。它在 `code splitting` 的情况下 `CommonsChunkPlugin`会完全失效。过了好一段时间才修复,欲哭无泪。
所以这次我等了快大半年才准备升级到`webpack 4` **但万万没想到还是遇到了不少的问题!** 有很多之前遗留的问题还是没有很好地解决。但最主要的问题还是它的文档有所欠缺,已经废除了的东西如`commonsChunkPlugin`还在官方文档中到处出现,很多重要的东西却一笔带过,甚至没写,需要用户自己去看源码才能解决。
还比如在`v4.16.0`版本中废除了`optimization.occurrenceOrder`、`optimization.namedChunks`、`optimization.hashedModuleIds`、`optimization.namedModules` 这几个配置项,替换成了`optimization.moduleIds` 和 `optimization.chunkIds`,但文档完中全没有任何体现,所以你在新版本中还按照文档那样配置其实是没有任何效果的。
最新最完整的文档还是看他项目的配置[WebpackOptions.json](https://github.com/webpack/webpack/blob/master/schemas/WebpackOptions.json),强烈建议遇到不清楚的配置项可以看这个,因为它一定保证是和最新代码同步的。
吐槽了这么多,我们言归正传。由于本次手摸手篇幅有些长,所以拆解成了上下两篇文章:
- 上篇 -- 就是普通的在`webpack 3`的基础上升级,要做哪些操作和遇到了哪些坑
- 下篇 -- 是在`webpack 4`下怎么合理的打包和拆包,并且如何最大化利用 `long term caching`
**本文章不是手摸手从零教你 webpack 配置,所以并不会讲太多很基础的配置问题**。比如如何处理 css 文件,如何配置 webpack-dev-server,讲述 file-loader 和 url-loader 之间的区别等等,有需求的推荐看 [官方文档](https://webpack.js.org/concepts/) 或者 [survivejs](https://survivejs.com/webpack/developing/webpack-dev-server/) 出的一个系列教程。或者推荐看我司的另一篇 wbepack 入门文章,已同步到 webpack4 [传送门](https://github.com/wallstreetcn/webpack-and-spa-guide)。
## 升级篇
### 前言
我一直认为模仿和借鉴是学习一个新东西最高效的方法。所以我建议还是通过借鉴一些成熟的 webpack 配置比较好。比如你项目是基于 react 生态圈的话可以借鉴 [create-react-app](https://github.com/facebook/create-react-app) ,下载之后`npm run eject` 就可以看到它详细的 webpack 配置了。vue 的话由于新版`vue cli`不支持 `eject`了,而且改用 [webpack-chain](https://github.com/mozilla-neutrino/webpack-chain)来配置,所以借鉴起来可能会不太方便,主要配置 [地址](https://github.com/vuejs/vue-cli/tree/dev/packages/@vue/cli-service/lib/config)。觉得麻烦的话你可以直接借鉴 `vue-element-admin` 的 [配置](https://github.com/PanJiaChen/vue-element-admin/pull/889)。或者你想自己发挥,你可以借鉴 webpack 官方的各种 [examples](https://github.com/webpack/webpack/tree/master/examples),来组合你的配置。
### 升级 webpack
首先将 webpack 升级到 4 之后,直接运行`webpack --xxx`是不行的,因为新版本将命令行相关的东西单独拆了出去封装成了`webpack-cli`。会报如下错误:
> The CLI moved into a separate package: webpack-cli.
> Please install `webpack-cli` in addition to webpack itself to use the CLI.
所有你需要安装`npm install webpack-cli -D -S`。你也可将它安装在全局。
同时新版 webpack 需要`Node.js 的最低支持版本为 6.11.5`不要忘了升级。如果还需要维护老项目可以使用 [nvm](https://github.com/creationix/nvm) 来做一下 node 版本管理。
**升级所有依赖**
因为`webpack4`改了 它的`hook` api ,所以所有的`loaders`、`plugins`都需要升级才能够适配。
可以使用命令行 `npm outdated`,列出所以可以更新的包。免得再一个个去`npm`找相对于的可用版本了。
![](https://user-gold-cdn.xitu.io/2018/7/27/164da832e18a97ef?w=890&h=346&f=jpeg&s=105563)
反正把`devDependencies`的依赖都升级一下,总归不会有错。
### 带来的变化
其实这次升级带来了不少改变,但大部分其实对于普通用户来说是不需要关注的,比如这次升级带来的功能`SideEffects`、`Module Type’s Introduced`、`WebAssembly Support`,基本平时是用不到的。我们主要关注那些对我们影响比较大的改动如:`optimization.splitChunks`代替原有的`CommonsChunkPlugin`(下篇文章会着重介绍),和`Better Defaults-mode`更好的默认配置,这是大家稍微需要关注一下的。
![](https://user-gold-cdn.xitu.io/2018/8/7/16513e81dfa85cbc?w=1460&h=398&f=jpeg&s=93966)
> 如果想进一步了解 `Tree Shaking`和`SideEffects`的可见文末拓展阅读。
> _上图参考 [Webpack 4 进阶](https://zhuanlan.zhihu.com/p/35407642)_
### 默认配置
webpack 4 引入了`零配置`的概念,被 [parcel](https://github.com/parcel-bundler/parcel) 刺激到了。 不管效果怎样,这改变还是值得称赞的。
> 最近又新出了 [Fastpack](http://fastpack.io/) 可以关注一下。
言归正题,我们来看看 webpack 默认帮我们做了些什么?
`development` 模式下,默认开启了`NamedChunksPlugin` 和`NamedModulesPlugin`方便调试,提供了更完整的错误信息,更快的重新编译的速度。
```diff
module.exports = {
+ mode: 'development'
- devtool: 'eval',
- plugins: [
- new webpack.NamedModulesPlugin(),
- new webpack.NamedChunksPlugin(),
- new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("development") }),
- ]
}
```
`production` 模式下,由于提供了`splitChunks`和`minimize`,所以基本零配置,代码就会自动分割、压缩、优化,同时 webpack 也会自动帮你 `Scope hoisting` 和 `Tree-shaking`。
```diff
module.exports = {
+ mode: 'production',
- plugins: [
- new UglifyJsPlugin(/* ... */),
- new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }),
- new webpack.optimize.ModuleConcatenationPlugin(),
- new webpack.NoEmitOnErrorsPlugin()
- ]
}
```
webpack 一直以来最饱受诟病的就是其配置门槛极高,配置内容极其复杂和繁琐,容易让人从入门到放弃,而它的后起之秀如 rollup、parcel 等均在配置流程上做了极大的优化,做到开箱即用,所以`webpack 4` 也从中借鉴了不少经验来提升自身的配置效率。**愿世间再也不需要 webpack 配置工程师**。
## html-webpack-plugin
用最新版本的的 `html-webpack-plugin`你可能还会遇到如下的错误:
`throw new Error('Cyclic dependency' + nodeRep)`
产生这个 bug 的原因是循环引用依赖,如果你没有这个问题可以忽略。
目前解决方案可以使用 Alpha 版本,`npm i --save-dev html-webpack-plugin@next`
或者加入`chunksSortMode: 'none'`就可以了。
但仔细查看文档发现设置成`chunksSortMode: 'none'`这样是会有问题的。
> Allows to control how chunks should be sorted before they are included to the HTML.
这属性会决定你 chunks 的加载顺序,如果设置为`none`,你的 chunk 加载在页面中加载的顺序就不能够保证了,可能会出现样式被覆盖的情况。比如我在`app.css`里面修改了一个第三方库`element-ui`的样式,通过加载顺序的先后来覆盖它,但由于设置为了`none`,打包出来的结果变成了这样:
```html
<link href="/app.8945fbfc.css" rel="stylesheet" />
<link href="/chunk-elementUI.2db88087.css" rel="stylesheet" />
```
`app.css`被先加载了,之前写的样式覆盖就失效了,除非你使用`important`或者其它 css 权重的方式覆盖它,但这明显是不太合理的。
`vue-cli`正好也有这个相关 [issue](https://github.com/vuejs/vue-cli/issues/1978#issuecomment-409267484),尤雨溪也在不使用`@next`版本的基础上 hack 了它,有兴趣的可以自己研究一下,本人在项目中直接使用了`@next`版本,也没遇到其它什么问题(除了不兼容 webpack 的 `prefetch/preload` 相关 [issue](https://github.com/jantimon/html-webpack-plugin/issues/934))。两种方案都可以,自行选择。
其它 `html-webpack-plugin` 的配置和之前使用没有什么区别。
## mini-css-extract-plugin
### 与 extract-text-webpack-plugin 区别
由于`webpack4`对 css 模块支持的完善以及在处理 css 文件提取的方式上也做了些调整,所以之前我们一直使用的`extract-text-webpack-plugin`也完成了它的历史使命,将让位于`mini-css-extract-plugin`。
使用方式也很简单,大家看着 [文档](https://github.com/webpack-contrib/mini-css-extract-plugin#minimal-example) 抄就可以了。
它与`extract-text-webpack-plugin`最大的区别是:它在`code spliting`的时候会将原先内联写在每一个 js `chunk bundle`的 css,单独拆成了一个个 css 文件。
原先 css 是这样内联在 js 文件里的:
![](https://user-gold-cdn.xitu.io/2018/7/24/164cb85b234d224a?w=2534&h=98&f=jpeg&s=50714)
将 css 独立拆包最大的好处就是 js 和 css 的改动,不会影响对方。比如我改了 js 文件并不会导致 css 文件的缓存失效。而且现在它自动会配合`optimization.splitChunks`的配置,可以自定义拆分 css 文件,比如我单独配置了`element-ui`作为单独一个`bundle`,它会自动也将它的样式单独打包成一个 css 文件,不会像以前默认将第三方的 css 全部打包成一个几十甚至上百 KB 的`app.xxx.css`文件了。
![](https://user-gold-cdn.xitu.io/2018/7/24/164cbd49dc148656?w=516&h=254&f=png&s=73856)
### 压缩与优化
打包 css 之后查看源码,我们发现它并没有帮我们做代码压缩,这时候需要使用 [optimize-css-assets-webpack-plugin](https://github.com/NMFR/optimize-css-assets-webpack-plugin) 这个插件,它不仅能帮你压缩 css 还能优化你的代码。
```js
//配置
optimization: {
minimizer: [new OptimizeCSSAssetsPlugin()]
}
```
![](https://user-gold-cdn.xitu.io/2018/7/30/164e93dc299d7062?w=1778&h=764&f=jpeg&s=198182)
如上图测试用例所示,由于`optimize-css-assets-webpack-plugin`这个插件默认使用了 [cssnano](https://github.com/cssnano/cssnano) 来作 css 优化,
所以它不仅压缩了代码、删掉了代码中无用的注释、还去除了冗余的 css、优化了 css 的书写顺序,优化了你的代码 `margin: 10px 20px 10px 20px;` =>`margin:10px 20px;`。同时大大减小了你 css 的文件大小。更多优化的细节见[文档](https://cssnano.co/guides/optimisations)。
### contenthash
但使用 `MiniCssExtractPlugin` 有一个需求特别注意的地方,在默认文档中它是这样配置的:
```js
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: devMode ? '[name].css' : '[name].[hash].css',
chunkFilename: devMode ? '[id].css' : '[id].[hash].css'
})
```
> 简单说明一下: `filename` 是指在你入口文件`entry`中引入生成出来的文件名,而`chunkname`是指那些未被在入口文件`entry`引入,但又通过按需加载(异步)模块的时候引入的文件。
在 **copy** 如上代码使用之后发现情况不对!每次改动一个`xx.js`文件,它对应的 css 虽然没做任何改动,但它的 文件 hash 还是会发生变化。仔细对比发现原来是 `hash` 惹的祸。 `6.f3bfa3af.css` => `6.40bc56f6.css`
![](https://user-gold-cdn.xitu.io/2018/7/24/164cbe27801ebf69?w=1214&h=308&f=png&s=162463)
但我这是根据官方文档来写的!为什么还有问题!后来在文档的**最最最**下面发下了这么一段话!
> For long term caching use filename: `[contenthash].css`. Optionally add [name].
非常的不理解,这么关键的一句话会放在 `Maintainers` 还后面的地方,默认写在配置里面提示大家不是更好?有热心群众已经开了一个`pr`,将文档默认配置为 `contenthash`。`chunkhash` => `contenthash`相关 [issue](https://github.com/webpack/webpack.js.org/issues/2096)。
这个真的蛮过分的,稍不注意就会让自己的 css 文件缓存无效。而且很多用户平时修改代码的时候都不会在意自己最终打包出来的 `dist`文件夹中到底有哪些变化。所以这个问题可能就一直存在了。浪费了多少资源!人艰不拆!大家觉得 webpack 难用不是没道理的。
**补充一点**:目前`MiniCssExtractPlugin`也不是非常完美的,它现在默认会将每个 bundle 的 css 独立于 js 文件, 单独拆成一个 css 文件。但这样会产生一个新的问题。比如我有一个页面它只有一行 css,但也会被拆成了一个独立的 css 文件,还需要额外的一次 http 请求,非常的不合理。所以我就给官方提了一个 [issue](https://github.com/webpack-contrib/mini-css-extract-plugin/issues/234),呼吁增加一个`minSize`,当 css 的内容小于这个`size`的时候还是内联到 js 文件中,期待官方增加这个功能。
### 这里再简单说明一下几种 hash 的区别:
- **hash**
`hash` 和每次 `build`有关,没有任何改变的情况下,每次编译出来的 `hash`都是一样的,但当你改变了任何一点东西,它的`hash`就会发生改变。
简单理解,你改了任何东西,`hash` 就会和上次不一样了。
- **chunkhash**
`chunkhash`是根据具体每一个模块文件自己的的内容包括它的依赖计算所得的`hash`,所以某个文件的改动只会影响它本身的`hash`,不会影响其它文件。
- **contenthash**
它的出现主要是为了解决,让`css`文件不受`js`文件的影响。比如`foo.css`被`foo.js`引用了,所以它们共用相同的`chunkhash`值。但这样子是有问题的,如果`foo.js`修改了代码,`css`文件就算内容没有任何改变,由于是该模块的 `hash` 发生了改变,其`css`文件的`hash`也会随之改变。
这个时候我们就可以使用`contenthash`了,保证即使`css`文件所处的模块里有任何内容的改变,只要 css 文件内容不变,那么它的`hash`就不会发生变化。
`contenthash` 你可以简单理解为是 `moduleId` + `content` 所生成的 `hash`。
## 热更新速度
其实相对 webpack 线上打包速度,我更关心的本地开发热更新速度,毕竟这才是和我们每一个程序员每天真正打交道的东西,打包一般都会扔给`CI`自动执行,而且一般项目每天也不会打包很多次。
`webpack 4`一直说自己更好的利用了`cache`提高了编译速度,但实测发现是有一定的提升,但当你一个项目,路由懒加载的页面多了之后,50+之后,热更新慢的问题会很明显,之前的[文章](https://juejin.im/post/595b4d776fb9a06bbe7dba56#heading-1)中也提到过这个问题,原以为新版本会解决这个问题,但并没有。
不过你首先要排斥你的热更新慢不是,如:
- 没有使用合理的 [Devtool](https://webpack.js.org/configuration/devtool/#devtool) souce map 导致
- 没有正确使用 [exclude/include](https://webpack.js.org/configuration/module/#rule-include) 处理了不需要处理的如`node_modules`
- 在开发环境不要压缩代码`UglifyJs`、提取 css、babel polyfill、计算文件 hash 等不需要的操作
**旧方案**
最早的方案是开发环境中不是用路由懒加载了,只在线上环境中使用。封装一个`_import`函数,通过环境变区分是否需要懒加载。
开发环境:
```js
module.exports = file => require('@/views/' + file + '.vue').default
```
生成环境:
```js
module.exports = file => () => import('@/views/' + file + '.vue')
```
但由于 webpack `import`实现机制问题,会产生一定的副作用。如上面的写法就会导致`@/views/`下的 所有`.vue` 文件都会被打包。不管你是否被依赖引用了,会多打包一些可能永远都用不到 js 代码。 [相关 issue](https://github.com/PanJiaChen/vue-element-admin/issues/292)
目前新的解决方案思路还是一样的,只在生成模式中使用路由懒加载,本地开发不使用懒加载。但换了一种没副作用的实现方式。
**新方案**
使用`babel` 的 `plugins` [babel-plugin-dynamic-import-node](https://github.com/airbnb/babel-plugin-dynamic-import-node)。它只做一件事就是:将所有的`import()`转化为`require()`,这样就可以用这个插件将所有异步组件都用同步的方式引入了,并结合 [BABEL_ENV](https://babeljs.io/docs/usage/babelrc/#env-option) 这个`bebel`环境变量,让它只作用于开发环境下。将开发环境中所有`import()`转化为`require()`,这种方案解决了之前重复打包的问题,同时对代码的侵入性也很小,你平时写路由的时候只需要按照官方[文档](https://router.vuejs.org/zh/guide/advanced/lazy-loading.html)路由懒加载的方式就可以了,其它的都交给`babel`来处理,当你不想用这个方案的时候,也只需要将它从`babel` 的 `plugins`中移除就可以了。
**具体代码:**
首先在`package.json`中增加`BABEL_ENV`
```json
"dev": "BABEL_ENV=development webpack-dev-server XXXX"
```
接着在`.babelrc`只能加入`babel-plugin-dynamic-import-node`这个`plugins`,并让它只有在`development`模式中才生效。
```json
{
"env": {
"development": {
"plugins": ["dynamic-import-node"]
}
}
}
```
之后就大功告成了,路由只要像平时一样写就可以了。[文档](https://panjiachen.github.io/vue-element-admin-site/zh/guide/advanced/lazy-loading.html#%E6%96%B0%E6%96%B9%E6%A1%88)
```js
{ path: '/login', component: () => import('@/views/login/index')}
```
这样能大大提升你热更新的速度。基本两百加页面也能在`2000ms`的热跟新完成,基本做到无感刷新。当然你的项目本身就不大页面也不多,完全没必要搞这些。**当你的页面变化跟不是你写代码速度的时候再考虑也不迟。**
## 打包速度
`webpack 4` 在项目中实际测了下,普遍能提高 20%~30%的打包速度。
本文不准备太深入的讲解这部分内容,详细的打包优化速度可以参考[ slack 团队的这篇文章](https://slack.engineering/keep-webpack-fast-a-field-guide-for-better-build-performance-f56a5995e8f1),掘金还有[译文](https://github.com/xitu/gold-miner/blob/master/TODO/keep-webpack-fast-a-field-guide-for-better-build-performance.md).
这里有几个建议来帮你加速 webpack 的打包速度。
首先你需要知道你目前打包慢,是慢在哪里。
我们可以用 [speed-measure-webpack-plugin](https://github.com/stephencookdev/speed-measure-webpack-plugin#readme) 这个插件,它能监控 webpack 每一步操作的耗时。如下图:
![](https://user-gold-cdn.xitu.io/2018/7/31/164eee200ebc1911?w=554&h=492&f=jpeg&s=92342)
可以看出其实大部分打包花费的时间是在`Uglifyjs`压缩代码。和前面的提升热更新的切入点差不多,查看`source map`的正确与否,`exclude/include`的正确使用等等。
使用新版的`UglifyJsPlugin`的时候记住可以加上`cache: true`、`parall: true`,可以提搞代码打包压缩速度。更多配置可以参考 [文档](https://github.com/webpack-contrib/uglifyjs-webpack-plugin) 或者 vue-cli 的 [配置](https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/uglifyOptions.js)。
编译的时候还有还有一个很慢的原因是那些第三方库。比如`echarts`、`element-ui`其实都非常的大,比如`echarts`打包完也还有 775kb。所以你想大大提高编译速度,可以将这些第三方库 `externals` 出去,使用`script`的方式引入,或者使用 `dll`的方式打包。经测试一般如`echarts`这样大的包可以节省十几秒到几十秒不等。
还有可以使用一些并行执行 webpack 的库:如[parallel-webpack](https://github.com/trivago/parallel-webpack)、[happypack](https://github.com/amireh/happypack)。
**顺便说一下,升级一下`node`可能有惊喜。前不久将`CI`里面的 node 版本依赖从 `6.9.2` => `8.11.3`,打包速度直接提升了一分多钟。**
总之我觉得打包时间控制在差不多的范围内就可以了,没必要过分的优化。可能你研究了半天,改了一堆参数发现其实也就提升了几秒,但维护成本上去了,得不偿失。还不如升级 node、升级 webpack、升级你的编译环境的硬件水平来的实在和简单。
比如我司`CI`使用的是腾讯云普通的的 8 核 16g 的机器,这个项目也是一个很大的后台管理项目 200+页面,引用了很多第三方的库,但没有使用什么`happypack`、`dll`,只是用了最新版的`webpack4`,`[email protected]`。
编译速度稳定在两分多钟,完全不觉得有什么要优化的必要。
![](https://user-gold-cdn.xitu.io/2018/7/29/164e5366dd1d9dec?w=896&h=236&f=jpeg&s=22563)
## Tree-Shaking
这其实并不是 webpack 4 才提出来的概念,最早是 [rollup](https://github.com/rollup/rollup) 提出来并实现的,后来在 webpack 2 中就实现了,本次在 webpack 4 只是增加了 `JSON Tree Shaking`和`sideEffects`能让你能更好的**摇**。
不过这里还是要提一下,默认 webpack 是支持`Tree-Shaking`的,但在你的项目中可能会因为`babel`的原因导致它失效。
因为`Tree Shaking`这个功能是基于`ES6 modules` 的静态特性检测,来找出未使用的代码,所以如果你使用了 babel 插件的时候,如:[babel-preset-env](https://babeljs.io/docs/en/babel-preset-env/),它默认会将模块打包成`commonjs`,这样就会让`Tree Shaking`失效了。
其实在 webpack 2 之后它自己就支持模块化处理。所以只要让 babel 不`transform modules`就可以了。配置如下:
```js
// .babelrc
{
"presets": [
["env", {
modules: false,
...
}]
]
}
```
顺便说一下都 8102 年了,请不要在使用`babel-preset-esxxxx`系列了,请用`babel-preset-env`,相关文章 [再见,babel-preset-2015](https://zhuanlan.zhihu.com/p/29506685)。
## 下部分内容
- [手摸手,带你用合理的姿势使用 webpack4 (下)](https://juejin.im/post/5b5d6d6f6fb9a04fea58aabc)
## 拓展阅读
- [Webpack 4 和单页应用入门](https://github.com/wallstreetcn/webpack-and-spa-guide)
- [Webpack 中的 sideEffects 到底该怎么用?](https://zhuanlan.zhihu.com/p/40052192)
- [你的 Tree-Shaking 并没什么卵用](https://zhuanlan.zhihu.com/p/32831172)
- [对 webpack 文档的吐槽](https://zhuanlan.zhihu.com/p/32148338)
- [Tree-Shaking 性能优化实践 - 原理篇](https://zhuanlan.zhihu.com/p/32554436)
- [再见,babel-preset-2015](https://zhuanlan.zhihu.com/p/29506685)
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2017 SAP SE or an SAP affiliate company. 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 options is used to specify options to MCM
package options
import (
"time"
mcmoptions "github.com/gardener/machine-controller-manager/pkg/options"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// ClientConnectionConfiguration contains details for constructing a client.
type ClientConnectionConfiguration struct {
// kubeConfigFile is the path to a kubeconfig file.
KubeConfigFile string
// acceptContentTypes defines the Accept header sent by clients when connecting to a server, overriding the
// default value of 'application/json'. This field will control all connections to the server used by a particular
// client.
AcceptContentTypes string
// contentType is the content type used when sending data to the server from this client.
ContentType string
// qps controls the number of queries per second allowed for this connection.
QPS float32
// burst allows extra queries to accumulate when a client is exceeding its rate.
Burst int
}
// MachineControllerConfiguration contains machine configurations
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type MachineControllerConfiguration struct {
metav1.TypeMeta
// namespace in seed cluster in which controller would look for the resources.
Namespace string
// port is the port that the controller-manager's http service runs on.
Port int32
// address is the IP address to serve on (set to 0.0.0.0 for all interfaces).
Address string
// CloudProvider is the provider for cloud services.
CloudProvider string
// ConcurrentNodeSyncs is the number of node objects that are
// allowed to sync concurrently. Larger number = more responsive nodes,
// but more CPU (and network) load.
ConcurrentNodeSyncs int32
// enableProfiling enables profiling via web interface host:port/debug/pprof/
EnableProfiling bool
// enableContentionProfiling enables lock contention profiling, if enableProfiling is true.
EnableContentionProfiling bool
// contentType is contentType of requests sent to apiserver.
ContentType string
// kubeAPIQPS is the QPS to use while talking with kubernetes apiserver.
KubeAPIQPS float32
// kubeAPIBurst is the burst to use while talking with kubernetes apiserver.
KubeAPIBurst int32
// leaderElection defines the configuration of leader election client.
LeaderElection mcmoptions.LeaderElectionConfiguration
// How long to wait between starting controller managers
ControllerStartInterval metav1.Duration
// minResyncPeriod is the resync period in reflectors; will be random between
// minResyncPeriod and 2*minResyncPeriod.
MinResyncPeriod metav1.Duration
// SafetyOptions is the set of options to set to ensure safety of controller
SafetyOptions SafetyOptions
//NodeCondition is the string of known NodeConditions. If any of these NodeCondition is set for a timeout period, the machine will be declared failed and will replaced.
NodeConditions string
//BootstrapTokenAuthExtraGroups is a comma-separated string of groups to set bootstrap token's "auth-extra-groups" field to.
BootstrapTokenAuthExtraGroups string
}
// SafetyOptions are used to configure the upper-limit and lower-limit
// while configuring freezing of machineSet objects
type SafetyOptions struct {
// Timeout (in durartion) used while creation of
// a machine before it is declared as failed
MachineCreationTimeout metav1.Duration
// Timeout (in durartion) used while health-check of
// a machine before it is declared as failed
MachineHealthTimeout metav1.Duration
// Deprecated. No effect. Timeout (in durartion) used while draining of machine before deletion,
// beyond which it forcefully deletes machine
MachineDrainTimeout metav1.Duration
// Maximum number of times evicts would be attempted on a pod for it is forcibly deleted
// during draining of a machine.
MaxEvictRetries int32
// Timeout (in duration) used while waiting for PV to detach
PvDetachTimeout metav1.Duration
// Timeout (in duration) for which the APIServer can be down before
// declare the machine controller frozen by safety controller
MachineSafetyAPIServerStatusCheckTimeout metav1.Duration
// Period (in durartion) used to poll for orphan VMs
// by safety controller
MachineSafetyOrphanVMsPeriod metav1.Duration
// Period (in duration) used to poll for APIServer's health
// by safety controller
MachineSafetyAPIServerStatusCheckPeriod metav1.Duration
// APIserverInactiveStartTime to keep track of the
// start time of when the APIServers were not reachable
APIserverInactiveStartTime time.Time
// MachineControllerFrozen indicates if the machine controller
// is frozen due to Unreachable APIServers
MachineControllerFrozen bool
}
// LeaderElectionConfiguration defines the configuration of leader election
// clients for components that can run with leader election enabled.
type LeaderElectionConfiguration struct {
// leaderElect enables a leader election client to gain leadership
// before executing the main loop. Enable this when running replicated
// components for high availability.
LeaderElect bool
// leaseDuration is the duration that non-leader candidates will wait
// after observing a leadership renewal until attempting to acquire
// leadership of a led but unrenewed leader slot. This is effectively the
// maximum duration that a leader can be stopped before it is replaced
// by another candidate. This is only applicable if leader election is
// enabled.
LeaseDuration metav1.Duration
// renewDeadline is the interval between attempts by the acting master to
// renew a leadership slot before it stops leading. This must be less
// than or equal to the lease duration. This is only applicable if leader
// election is enabled.
RenewDeadline metav1.Duration
// retryPeriod is the duration the clients should wait between attempting
// acquisition and renewal of a leadership. This is only applicable if
// leader election is enabled.
RetryPeriod metav1.Duration
// resourceLock indicates the resource object type that will be used to lock
// during leader election cycles.
ResourceLock string
}
| {
"pile_set_name": "Github"
} |
.modal {
align-items: flex-start;
display: block;
&.is-superimposed {
.modal-background {
z-index: 20;
}
.modal-container {
z-index: 21;
}
}
}
.modal-background {
top: 0;
left: 0;
width: 100vw;
height: 100vh;
position: fixed;
background-color: rgba(0,0,0,0.85);
z-index: 10;
&-enter-active {
animation: .4s ease fadeIn;
}
&-leave-active {
animation: .4s ease fadeOut;
}
}
.modal-container {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 11;
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
width: 600px;
background-color: #FFF;
&-enter-active {
animation: .3s ease zoomIn;
}
&-leave-active {
animation: .3s ease zoomOut;
}
&.is-expanded {
align-self: stretch;
width: 100%;
margin: 20px;
display: flex;
flex-direction: column;
> section {
flex-grow: 1;
}
}
header {
background-color: mc('teal', '600');
color: #FFF;
display: flex;
flex-shrink: 0;
height: 40px;
align-items: center;
font-weight: 400;
font-size: 16px;
padding: 0 20px;
position: relative;
@each $color, $colorvalue in $material-colors {
&.is-#{$color} {
background-color: mc($color, '600');
}
}
.modal-notify {
position: absolute;
display: none;
align-items: center;
height: 40px;
right: 20px;
top: 0;
&.is-active {
display: flex;
}
span {
font-size: 12px;
letter-spacing: 1px;
text-transform: uppercase;
}
i {
margin-left: 15px;
display: inline-block;
@include spinner(#FFF, .5s, 20px);
}
}
}
section {
padding: 20px;
border-top: 1px dotted mc('grey', '300');
&:first-of-type {
border-top: none;
padding-top: 20px;
}
&:last-of-type {
padding-bottom: 20px;
}
&.is-gapless {
padding: 10px;
display: flex;
}
&.modal-loading {
display: flex;
flex-direction: column;
align-items: center;
> i {
display: block;
@include spinner(mc('blue','500'), .4s, 32px);
margin-bottom: 10px;
}
> span {
color: mc('grey', '600');
}
> em {
font-size: 12px;
color: mc('grey', '500');
font-style: normal;
}
}
&.modal-instructions {
display: flex;
flex-direction: column;
align-items: center;
color: mc('grey', '800');
img {
height: 100px;
& + * {
margin-top: 10px;
}
}
i.is-huge {
font-size: 72px;
margin-bottom: 10px;
}
> span {
color: mc('grey', '800');
}
> em {
font-size: 12px;
color: mc('grey', '600');
font-style: normal;
margin-top: 10px;
display: block;
}
}
.bullets {
list-style-type: square;
padding: 5px 0 0 30px;
font-size: 14px;
color: mc('grey', '800');
}
.note {
display: block;
margin-top: 10px;
font-size: 14px;
color: mc('grey', '800');
&:first-child {
margin-top: 0;
}
ul {
color: mc('grey', '800');
padding-left: 10px;
li {
margin-top: 5px;
display: flex;
align-items: center;
> i {
margin-right: 8px;
font-size: 18px;
}
}
}
}
}
footer {
padding: 20px;
text-align: right;
.button {
margin-left: 10px;
}
}
}
.modal-toolbar {
background-color: mc('teal', '700');
padding: 7px 20px;
display: flex;
flex-shrink: 0;
justify-content: center;
@each $color, $colorvalue in $material-colors {
&.is-#{$color} {
background-color: mc($color, '700');
.button {
border-color: mc($color, '900');
background-color: mc($color, '900');
&:hover {
border-color: mc($color, '900');
background-color: mc($color, '800');
}
}
}
}
// BUTTONS
.button {
border: 1px solid mc('teal', '900');
background-color: mc('teal', '900');
transition: all .4s ease;
color: #FFF;
border-radius: 0;
&:first-child {
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
&:last-child {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
&:hover {
border-color: mc('teal', '900');
background-color: mc('teal', '800');
color: #FFF;
}
}
.button + .button {
margin-left: 1px;
}
}
.modal-sidebar {
background-color: mc('teal', '50');
padding: 0;
overflow-y:auto;
//padding: 7px 20px;
@each $color, $colorvalue in $material-colors {
&.is-#{$color} {
background-color: mc($color, '50');
.model-sidebar-header {
background-color: mc($color, '100');
color: mc($color, '800');
}
.model-sidebar-list > li a {
&:hover {
background-color: mc($color, '200');
}
&.is-active {
background-color: mc($color, '500');
}
}
}
}
.model-sidebar-header {
padding: 7px 20px;
}
.model-sidebar-content {
padding: 7px 20px;
}
.model-sidebar-list {
> li {
padding: 0;
a {
display: flex;
align-items: center;
height: 34px;
padding: 0 20px;
cursor: pointer;
color: mc('grey', '800');
&:hover {
background-color: mc('teal', '200');
}
&.is-active {
color: #FFF;
}
i {
margin-right: 7px;
}
}
}
}
}
.modal-content .card-footer-item.featured {
animation: flash 4s ease 0 infinite;
}
| {
"pile_set_name": "Github"
} |
[
["0","\u0000",127],
["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"],
["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"],
["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"],
["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5],
["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"],
["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18],
["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7],
["8361","긝",18,"긲긳긵긶긹긻긼"],
["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8],
["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8],
["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18],
["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"],
["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4],
["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"],
["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"],
["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"],
["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10],
["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"],
["8741","놞",9,"놩",15],
["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"],
["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4],
["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4],
["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"],
["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"],
["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"],
["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"],
["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15],
["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"],
["8a61","둧",4,"둭",18,"뒁뒂"],
["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"],
["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"],
["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8],
["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18],
["8c41","똀",15,"똒똓똕똖똗똙",4],
["8c61","똞",6,"똦",5,"똭",6,"똵",5],
["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16],
["8d41","뛃",16,"뛕",8],
["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"],
["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"],
["8e41","랟랡",6,"랪랮",5,"랶랷랹",8],
["8e61","럂",4,"럈럊",19],
["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7],
["8f41","뢅",7,"뢎",17],
["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4],
["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5],
["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"],
["9061","륾",5,"릆릈릋릌릏",15],
["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"],
["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5],
["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5],
["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6],
["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"],
["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4],
["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"],
["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"],
["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8],
["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"],
["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8],
["9461","봞",5,"봥",6,"봭",12],
["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24],
["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"],
["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"],
["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14],
["9641","뺸",23,"뻒뻓"],
["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8],
["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44],
["9741","뾃",16,"뾕",8],
["9761","뾞",17,"뾱",7],
["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"],
["9841","쁀",16,"쁒",5,"쁙쁚쁛"],
["9861","쁝쁞쁟쁡",6,"쁪",15],
["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"],
["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"],
["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"],
["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"],
["9a41","숤숥숦숧숪숬숮숰숳숵",16],
["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"],
["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"],
["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8],
["9b61","쌳",17,"썆",7],
["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"],
["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5],
["9c61","쏿",8,"쐉",6,"쐑",9],
["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12],
["9d41","쒪",13,"쒹쒺쒻쒽",8],
["9d61","쓆",25],
["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"],
["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"],
["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"],
["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"],
["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"],
["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"],
["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"],
["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"],
["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13],
["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"],
["a141","좥좦좧좩",18,"좾좿죀죁"],
["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"],
["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"],
["a241","줐줒",5,"줙",18],
["a261","줭",6,"줵",18],
["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"],
["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"],
["a361","즑",6,"즚즜즞",16],
["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"],
["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"],
["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12],
["a481","쨦쨧쨨쨪",28,"ㄱ",93],
["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"],
["a561","쩫",17,"쩾",5,"쪅쪆"],
["a581","쪇",16,"쪙",14,"ⅰ",9],
["a5b0","Ⅰ",9],
["a5c1","Α",16,"Σ",6],
["a5e1","α",16,"σ",6],
["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"],
["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6],
["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7],
["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7],
["a761","쬪",22,"쭂쭃쭄"],
["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"],
["a841","쭭",10,"쭺",14],
["a861","쮉",18,"쮝",6],
["a881","쮤",19,"쮹",11,"ÆЪĦ"],
["a8a6","IJ"],
["a8a8","ĿŁØŒºÞŦŊ"],
["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"],
["a941","쯅",14,"쯕",10],
["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18],
["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"],
["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"],
["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"],
["aa81","챳챴챶",29,"ぁ",82],
["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"],
["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5],
["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85],
["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"],
["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4],
["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25],
["acd1","а",5,"ёж",25],
["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7],
["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"],
["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"],
["ae41","췆",5,"췍췎췏췑",16],
["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4],
["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"],
["af41","츬츭츮츯츲츴츶",19],
["af61","칊",13,"칚칛칝칞칢",5,"칪칬"],
["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"],
["b041","캚",5,"캢캦",5,"캮",12],
["b061","캻",5,"컂",19],
["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"],
["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"],
["b161","켥",6,"켮켲",5,"켹",11],
["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"],
["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"],
["b261","쾎",18,"쾢",5,"쾩"],
["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"],
["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"],
["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5],
["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"],
["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5],
["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"],
["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"],
["b541","킕",14,"킦킧킩킪킫킭",5],
["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4],
["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"],
["b641","턅",7,"턎",17],
["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"],
["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"],
["b741","텮",13,"텽",6,"톅톆톇톉톊"],
["b761","톋",20,"톢톣톥톦톧"],
["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"],
["b841","퇐",7,"퇙",17],
["b861","퇫",8,"퇵퇶퇷퇹",13],
["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"],
["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"],
["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"],
["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"],
["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"],
["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5],
["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"],
["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"],
["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"],
["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"],
["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"],
["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"],
["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"],
["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"],
["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13],
["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"],
["be41","퐸",7,"푁푂푃푅",14],
["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"],
["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"],
["bf41","풞",10,"풪",14],
["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"],
["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"],
["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5],
["c061","픞",25],
["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"],
["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"],
["c161","햌햍햎햏햑",19,"햦햧"],
["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"],
["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"],
["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"],
["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"],
["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4],
["c361","홢",4,"홨홪",5,"홲홳홵",11],
["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"],
["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"],
["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4],
["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"],
["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"],
["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4],
["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"],
["c641","힍힎힏힑",6,"힚힜힞",5],
["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"],
["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"],
["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"],
["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"],
["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"],
["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"],
["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"],
["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"],
["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"],
["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"],
["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"],
["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"],
["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"],
["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"],
["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"],
["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"],
["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"],
["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"],
["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"],
["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"],
["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"],
["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"],
["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"],
["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"],
["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"],
["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"],
["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"],
["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"],
["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"],
["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"],
["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"],
["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"],
["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"],
["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"],
["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"],
["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"],
["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"],
["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"],
["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"],
["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"],
["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"],
["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"],
["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"],
["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"],
["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"],
["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"],
["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"],
["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"],
["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"],
["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"],
["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"],
["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"],
["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"],
["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"],
["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"]
]
| {
"pile_set_name": "Github"
} |
Bag Attributes
localKeyID: 05 3C 6A 9D 6D EC A0 FA 2F AE 41 32 0D 24 3A 21 34 F6 08 15
subject=/C=US/ST=Maryland/L=Forest Hill/O=The Apache Software Foundation/OU=Apache Thrift/CN=localhost/[email protected]
issuer=/C=US/ST=Maryland/L=Forest Hill/O=The Apache Software Foundation/OU=Apache Thrift/CN=localhost/[email protected]
-----BEGIN CERTIFICATE-----
MIIDVDCCAjwCAQEwDQYJKoZIhvcNAQEFBQAwgbExCzAJBgNVBAYTAlVTMREwDwYD
VQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0IEhpbGwxJzAlBgNVBAoMHlRo
ZSBBcGFjaGUgU29mdHdhcmUgRm91bmRhdGlvbjEWMBQGA1UECwwNQXBhY2hlIFRo
cmlmdDESMBAGA1UEAwwJbG9jYWxob3N0MSQwIgYJKoZIhvcNAQkBFhVkZXZAdGhy
aWZ0LmFwYWNoZS5vcmcwHhcNMTQwNDA3MTkwMDMzWhcNMTUwNDA3MTkwMDMzWjCB
sTELMAkGA1UEBhMCVVMxETAPBgNVBAgMCE1hcnlsYW5kMRQwEgYDVQQHDAtGb3Jl
c3QgSGlsbDEnMCUGA1UECgweVGhlIEFwYWNoZSBTb2Z0d2FyZSBGb3VuZGF0aW9u
MRYwFAYDVQQLDA1BcGFjaGUgVGhyaWZ0MRIwEAYDVQQDDAlsb2NhbGhvc3QxJDAi
BgkqhkiG9w0BCQEWFWRldkB0aHJpZnQuYXBhY2hlLm9yZzCBnzANBgkqhkiG9w0B
AQEFAAOBjQAwgYkCgYEArrM2HiTf5LT1Qh1JAALWUlJxVJNc1uC8//wZIW8Ekk6z
H2XkrAOW8Cs7rVfz6Q+x00q7xSH825v9RL6pv4l7sPDSGK5lvc+WkTxDpiR2EjIm
uWStUzCRq7EXhV50pUno6MFABVtqpRP87TiE1l7Yb8S33v+gAVdsrpJewYIDwWcC
AwEAATANBgkqhkiG9w0BAQUFAAOCAQEAbGjHLamDm1FQpgatYiZ/ic7Z8DFB+CJo
FcZH4hww27BD/WpQLsj6T1540B35hsmZ73yev4xgLybc/SEIducT9BHyc1DrDZtf
CFeSq6OOJu/1pJZ9m/d0i+sBJaWg5w1yT8+aEKJaWYfF+C9jZ6+3+I9agID5OplE
Wwwzg3xXllz3jfmtNlc0f+hE1/XLWFE2nY+5cBhlxReWH3HAhU/qZL9n/WdxCjHd
NyeWxlDlmzc2+uOeVF5sIGzFOj/qjGxc+UyUXaaEuSvh7j3rvYlZtnhvhJ+tMkoR
Kbxl1VUYxx+jzfhBy+bKu5uGZB3F1qtyY9fI5DQut75nNbueQPG+qw==
-----END CERTIFICATE-----
Bag Attributes
localKeyID: 05 3C 6A 9D 6D EC A0 FA 2F AE 41 32 0D 24 3A 21 34 F6 08 15
Key Attributes: <No Attributes>
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIWyeYAGRBWvwCAggA
MBQGCCqGSIb3DQMHBAjXHlBG+NmWDwSCAoBRgIb2Ni8qGhruYW7BiKMlVKPnDdnr
sMgSTgzelwALUazd59B7pA1mdCVazTZ2bqPZYJ0vRomnu4uosn24sXSNwdYg7pJd
CRnttE2BGlxC4PqFrVM1J7oO5Tfno1rrXVsRi0J4Qr6Gtj5xwZRZiGnLGtnQ9G/X
TsRtNH/pNRncmu+20xmTC2F8Es8q//4sco5YeEclcmcBr7goO+TusIH3ghlf0jbd
M9oTvEG7WY3lSarhZp4QYlWWkGfGfkd7rP3yxhLChijdVEOLL6gftDOs0ALBntAR
NYeSxFoyTEBCz8F+WjVt7QQzAyRNSKNDI8qMxMm/KDKaE92hS76K8PcBlbdy118s
LfHNb3v/v4WFdjmRJqPdWx5x3cTwGWwOF4MqZd9+Xn+/isu8SfQd2WmSm2qawbQP
BrjoQSuUQrZyL5AQmFKkdQ875fLfNw3I2ckhpgMi+WCWx11/8k2dYZoP9VTZ1/yT
l32FM4unt7wafU0vUU2tPcsEq4STdwWR5Q4FBPF3JRiMiNy8KzvFeUtnSX08m/sB
B3Uiw1jKwwoBx1gfPpq3/UBvmBlvGmwBx+7V+hMfXBAiIoFZFAMruWVgo4GcO8Zv
se9crOObipcR8r/q9VOF4OlwCyhkl2yDwEjQlRBPkQ1cpO4FWke7VAoRRtaCov8K
oQYExRwc141jjhlZvkXIa0TstZpHGZZmByFqbrpcAhyRwDJY+wqC3UFk+MALT6Gw
TcbQO3yIIAzfeaMYkw6isiAa94dOjrYHqOKAbXrw0btt3vKETV5Xx0jognuOcCC8
i1R5S0cLsZm2j4kWV8mXuCvXkvuq/WgPC162+/GRrhEp1wCsSo8DwG2I
-----END ENCRYPTED PRIVATE KEY-----
| {
"pile_set_name": "Github"
} |
ANTLR 2 License
We reserve no legal rights to the ANTLR--it is fully in the public domain.
An individual or company may do whatever they wish with source code distributed
with ANTLR or the code generated by ANTLR, including the incorporation of
ANTLR, or its output, into commerical software.
We encourage users to develop software with ANTLR. However, we do ask that
credit is given to us for developing ANTLR. By "credit", we mean that if you
use ANTLR or incorporate any source code into one of your programs (commercial
product, research project, or otherwise) that you acknowledge this fact somewhere
in the documentation, research report, etc... If you like ANTLR and have developed
a nice tool with the output, please mention that you developed it using ANTLR.
In addition, we ask that the headers remain intact in our source code. As
long as these guidelines are kept, we expect to continue enhancing this system
and expect to make other tools available as they are completed.
| {
"pile_set_name": "Github"
} |
;; Copyright (c) 2009 Derick Eddington
;;
;; 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.
;;
;; Except as contained in this notice, the name(s) of the above copyright
;; holders shall not be used in advertising or otherwise to promote the sale,
;; use or other dealings in this Software without prior written authorization.
;;
;; 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.
#!r6rs
(library (srfi :26 cut)
(export cut cute)
(import
(only (rnrs) ... _ begin define-syntax syntax-rules lambda begin let
apply
)
(only (srfi private include) include/resolve)
)
(include/resolve ("srfi" "26") "cut.scm")
)
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/ssl_config/ssl_config_service_manager.h"
#include <stdint.h>
#include <algorithm>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/feature_list.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "components/content_settings/core/browser/content_settings_utils.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/prefs/pref_change_registrar.h"
#include "components/prefs/pref_member.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/ssl_config/ssl_config_prefs.h"
#include "components/ssl_config/ssl_config_switches.h"
#include "net/ssl/ssl_cipher_suite_names.h"
#include "net/ssl/ssl_config_service.h"
namespace base {
class SingleThreadTaskRunner;
}
namespace {
// Converts a ListValue of StringValues into a vector of strings. Any Values
// which cannot be converted will be skipped.
std::vector<std::string> ListValueToStringVector(const base::ListValue* value) {
std::vector<std::string> results;
results.reserve(value->GetSize());
std::string s;
for (base::ListValue::const_iterator it = value->begin(); it != value->end();
++it) {
if (!(*it)->GetAsString(&s))
continue;
results.push_back(s);
}
return results;
}
// Parses a vector of cipher suite strings, returning a sorted vector
// containing the underlying SSL/TLS cipher suites. Unrecognized/invalid
// cipher suites will be ignored.
std::vector<uint16_t> ParseCipherSuites(
const std::vector<std::string>& cipher_strings) {
std::vector<uint16_t> cipher_suites;
cipher_suites.reserve(cipher_strings.size());
for (std::vector<std::string>::const_iterator it = cipher_strings.begin();
it != cipher_strings.end(); ++it) {
uint16_t cipher_suite = 0;
if (!net::ParseSSLCipherString(*it, &cipher_suite)) {
LOG(ERROR) << "Ignoring unrecognized or unparsable cipher suite: " << *it;
continue;
}
cipher_suites.push_back(cipher_suite);
}
std::sort(cipher_suites.begin(), cipher_suites.end());
return cipher_suites;
}
// Returns the SSL protocol version (as a uint16_t) represented by a string.
// Returns 0 if the string is invalid.
uint16_t SSLProtocolVersionFromString(const std::string& version_str) {
uint16_t version = 0; // Invalid.
if (version_str == switches::kSSLVersionTLSv1) {
version = net::SSL_PROTOCOL_VERSION_TLS1;
} else if (version_str == switches::kSSLVersionTLSv11) {
version = net::SSL_PROTOCOL_VERSION_TLS1_1;
} else if (version_str == switches::kSSLVersionTLSv12) {
version = net::SSL_PROTOCOL_VERSION_TLS1_2;
}
return version;
}
const base::Feature kDHECiphersFeature{
"DHECiphers", base::FEATURE_DISABLED_BY_DEFAULT,
};
} // namespace
////////////////////////////////////////////////////////////////////////////////
// SSLConfigServicePref
// An SSLConfigService which stores a cached version of the current SSLConfig
// prefs, which are updated by SSLConfigServiceManagerPref when the prefs
// change.
class SSLConfigServicePref : public net::SSLConfigService {
public:
explicit SSLConfigServicePref(
const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner);
// Store SSL config settings in |config|. Must only be called from IO thread.
void GetSSLConfig(net::SSLConfig* config) override;
private:
// Allow the pref watcher to update our internal state.
friend class SSLConfigServiceManagerPref;
~SSLConfigServicePref() override {}
// This method is posted to the IO thread from the browser thread to carry the
// new config information.
void SetNewSSLConfig(const net::SSLConfig& new_config);
// Cached value of prefs, should only be accessed from IO thread.
net::SSLConfig cached_config_;
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
DISALLOW_COPY_AND_ASSIGN(SSLConfigServicePref);
};
SSLConfigServicePref::SSLConfigServicePref(
const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner)
: io_task_runner_(io_task_runner) {}
void SSLConfigServicePref::GetSSLConfig(net::SSLConfig* config) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
*config = cached_config_;
}
void SSLConfigServicePref::SetNewSSLConfig(const net::SSLConfig& new_config) {
net::SSLConfig orig_config = cached_config_;
cached_config_ = new_config;
ProcessConfigUpdate(orig_config, new_config);
}
////////////////////////////////////////////////////////////////////////////////
// SSLConfigServiceManagerPref
// The manager for holding and updating an SSLConfigServicePref instance.
class SSLConfigServiceManagerPref : public ssl_config::SSLConfigServiceManager {
public:
SSLConfigServiceManagerPref(
PrefService* local_state,
const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner);
~SSLConfigServiceManagerPref() override {}
// Register local_state SSL preferences.
static void RegisterPrefs(PrefRegistrySimple* registry);
net::SSLConfigService* Get() override;
private:
// Callback for preference changes. This will post the changes to the IO
// thread with SetNewSSLConfig.
void OnPreferenceChanged(PrefService* prefs, const std::string& pref_name);
// Store SSL config settings in |config|, directly from the preferences. Must
// only be called from UI thread.
void GetSSLConfigFromPrefs(net::SSLConfig* config);
// Processes changes to the disabled cipher suites preference, updating the
// cached list of parsed SSL/TLS cipher suites that are disabled.
void OnDisabledCipherSuitesChange(PrefService* local_state);
PrefChangeRegistrar local_state_change_registrar_;
// The local_state prefs (should only be accessed from UI thread)
BooleanPrefMember rev_checking_enabled_;
BooleanPrefMember rev_checking_required_local_anchors_;
StringPrefMember ssl_version_min_;
StringPrefMember ssl_version_max_;
BooleanPrefMember dhe_enabled_;
// The cached list of disabled SSL cipher suites.
std::vector<uint16_t> disabled_cipher_suites_;
scoped_refptr<SSLConfigServicePref> ssl_config_service_;
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
DISALLOW_COPY_AND_ASSIGN(SSLConfigServiceManagerPref);
};
SSLConfigServiceManagerPref::SSLConfigServiceManagerPref(
PrefService* local_state,
const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner)
: ssl_config_service_(new SSLConfigServicePref(io_task_runner)),
io_task_runner_(io_task_runner) {
DCHECK(local_state);
// Restore DHE-based ciphers if enabled via features.
// TODO(davidben): Remove this when the removal has succeeded.
// https://crbug.com/619194.
if (base::FeatureList::IsEnabled(kDHECiphersFeature)) {
local_state->SetDefaultPrefValue(ssl_config::prefs::kDHEEnabled,
new base::FundamentalValue(true));
}
PrefChangeRegistrar::NamedChangeCallback local_state_callback =
base::Bind(&SSLConfigServiceManagerPref::OnPreferenceChanged,
base::Unretained(this), local_state);
rev_checking_enabled_.Init(ssl_config::prefs::kCertRevocationCheckingEnabled,
local_state, local_state_callback);
rev_checking_required_local_anchors_.Init(
ssl_config::prefs::kCertRevocationCheckingRequiredLocalAnchors,
local_state, local_state_callback);
ssl_version_min_.Init(ssl_config::prefs::kSSLVersionMin, local_state,
local_state_callback);
ssl_version_max_.Init(ssl_config::prefs::kSSLVersionMax, local_state,
local_state_callback);
dhe_enabled_.Init(ssl_config::prefs::kDHEEnabled, local_state,
local_state_callback);
local_state_change_registrar_.Init(local_state);
local_state_change_registrar_.Add(ssl_config::prefs::kCipherSuiteBlacklist,
local_state_callback);
OnDisabledCipherSuitesChange(local_state);
// Initialize from UI thread. This is okay as there shouldn't be anything on
// the IO thread trying to access it yet.
GetSSLConfigFromPrefs(&ssl_config_service_->cached_config_);
}
// static
void SSLConfigServiceManagerPref::RegisterPrefs(PrefRegistrySimple* registry) {
net::SSLConfig default_config;
registry->RegisterBooleanPref(
ssl_config::prefs::kCertRevocationCheckingEnabled,
default_config.rev_checking_enabled);
registry->RegisterBooleanPref(
ssl_config::prefs::kCertRevocationCheckingRequiredLocalAnchors,
default_config.rev_checking_required_local_anchors);
registry->RegisterStringPref(ssl_config::prefs::kSSLVersionMin,
std::string());
registry->RegisterStringPref(ssl_config::prefs::kSSLVersionMax,
std::string());
registry->RegisterListPref(ssl_config::prefs::kCipherSuiteBlacklist);
registry->RegisterBooleanPref(ssl_config::prefs::kDHEEnabled,
default_config.dhe_enabled);
}
net::SSLConfigService* SSLConfigServiceManagerPref::Get() {
return ssl_config_service_.get();
}
void SSLConfigServiceManagerPref::OnPreferenceChanged(
PrefService* prefs,
const std::string& pref_name_in) {
DCHECK(prefs);
if (pref_name_in == ssl_config::prefs::kCipherSuiteBlacklist)
OnDisabledCipherSuitesChange(prefs);
net::SSLConfig new_config;
GetSSLConfigFromPrefs(&new_config);
// Post a task to |io_loop| with the new configuration, so it can
// update |cached_config_|.
io_task_runner_->PostTask(FROM_HERE,
base::Bind(&SSLConfigServicePref::SetNewSSLConfig,
ssl_config_service_.get(), new_config));
}
void SSLConfigServiceManagerPref::GetSSLConfigFromPrefs(
net::SSLConfig* config) {
// rev_checking_enabled was formerly a user-settable preference, but now
// it is managed-only.
if (rev_checking_enabled_.IsManaged())
config->rev_checking_enabled = rev_checking_enabled_.GetValue();
else
config->rev_checking_enabled = false;
config->rev_checking_required_local_anchors =
rev_checking_required_local_anchors_.GetValue();
std::string version_min_str = ssl_version_min_.GetValue();
std::string version_max_str = ssl_version_max_.GetValue();
config->version_min = net::kDefaultSSLVersionMin;
config->version_max = net::kDefaultSSLVersionMax;
uint16_t version_min = SSLProtocolVersionFromString(version_min_str);
uint16_t version_max = SSLProtocolVersionFromString(version_max_str);
if (version_min) {
config->version_min = version_min;
}
if (version_max) {
uint16_t supported_version_max = config->version_max;
config->version_max = std::min(supported_version_max, version_max);
}
config->disabled_cipher_suites = disabled_cipher_suites_;
config->dhe_enabled = dhe_enabled_.GetValue();
}
void SSLConfigServiceManagerPref::OnDisabledCipherSuitesChange(
PrefService* local_state) {
const base::ListValue* value =
local_state->GetList(ssl_config::prefs::kCipherSuiteBlacklist);
disabled_cipher_suites_ = ParseCipherSuites(ListValueToStringVector(value));
}
////////////////////////////////////////////////////////////////////////////////
// SSLConfigServiceManager
namespace ssl_config {
// static
SSLConfigServiceManager* SSLConfigServiceManager::CreateDefaultManager(
PrefService* local_state,
const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner) {
return new SSLConfigServiceManagerPref(local_state, io_task_runner);
}
// static
void SSLConfigServiceManager::RegisterPrefs(PrefRegistrySimple* registry) {
SSLConfigServiceManagerPref::RegisterPrefs(registry);
}
} // namespace ssl_config
| {
"pile_set_name": "Github"
} |
require "test_helper"
class MessagesChannelTest < ActionCable::Channel::TestCase
# test "subscribes" do
# subscribe
# assert subscription.confirmed?
# end
end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11201" systemVersion="15G1004" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11161"/>
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="Colors" customModuleProvider="target" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" tag="1" contentMode="left" text="UIColor+Expression allows you to set colours using strings. Either with hex values in various formats..." textAlignment="center" lineBreakMode="wordWrap" numberOfLines="0" minimumFontSize="10" preferredMaxLayoutWidth="280" translatesAutoresizingMaskIntoConstraints="NO" id="q2J-8i-1LC">
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" tag="1" contentMode="left" text="Or using predefined color constant names (case insensitive)..." textAlignment="center" lineBreakMode="wordWrap" numberOfLines="0" minimumFontSize="10" preferredMaxLayoutWidth="280" translatesAutoresizingMaskIntoConstraints="NO" id="kQK-Xm-4SX">
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" tag="1" contentMode="left" text="Or using the rgb() and rgba() functions..." textAlignment="center" lineBreakMode="wordWrap" numberOfLines="0" minimumFontSize="10" preferredMaxLayoutWidth="280" translatesAutoresizingMaskIntoConstraints="NO" id="cvB-p5-ToR">
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="#fff" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="xM5-YQ-x05" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="56" minY="117" width="42" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="#ff0000" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="cFV-zY-qq7" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="80" minY="158.5" width="58" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="#555" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="wet-tq-CE0" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="52" minY="200" width="58" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="#00Ff00" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="pbR-dv-SbZ" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="142" minY="119" width="67" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="#ff5500" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="HD5-uQ-8LZ" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="270.5" minY="190" width="63" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="#ffff00" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="dqx-9j-QOs" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="266" minY="117" width="58" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="#000000FF" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="drN-Q7-VbA" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="201" minY="150.5" width="91" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="#FF000055" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="4ss-na-n6H" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="156" minY="199" width="90.5" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="RED" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="r4x-6M-Js6" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="56" minY="315.5" width="42" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="rgb(255, 127, 0)" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="9zb-re-lYq" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="51" minY="524.5" width="120" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="rgb(0, 127, 0)" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="PCo-VT-2Au" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="52" minY="608.5" width="100" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="rgba(255, 0, 0, 0.5)" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="xV5-IP-Z5C" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="102" minY="571" width="146.5" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="rgba(255, 0, 127, 0.9)" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="XI1-Q8-g3p" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="180" minY="619.5" width="161.5" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="cyan" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="Sjo-fP-Jcg" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="111" minY="325" width="44" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="bLuE" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="T1l-25-mP2" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="159.5" minY="362" width="42" height="19"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="Gray" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="ayM-ju-3CW" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="280" minY="391.5" width="40" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="PINK" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="7j4-aW-xzL" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="247" minY="352" width="42" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="black" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="54q-ZL-kVM" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="170" minY="313.5" width="42" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="white" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="DTG-eK-5uS" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="75" minY="360.5" width="41.5" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="green" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="z5Q-CD-HNe" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="233" minY="415" width="44" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="Orange" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="Ew9-q1-ghJ" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="268" minY="315.5" width="57" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="Purple" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="esu-ao-AvY" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="140.5" minY="396" width="49.5" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="ERROR" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="B3O-mt-9JE" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="51" minY="410" width="57.5" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" fixedFrame="YES" text="rgb(0, 127, 255)" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="FQL-ua-0kG" customClass="ColorLabel" customModule="Colors" customModuleProvider="target">
<frame key="frameInset" minX="210" minY="533.5" width="120" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" red="0.78431372549019607" green="0.78431372549019607" blue="0.78431372549019607" alpha="1" colorSpace="calibratedRGB"/>
<constraints>
<constraint firstItem="kQK-Xm-4SX" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leadingMargin" id="54j-FB-ORC"/>
<constraint firstItem="q2J-8i-1LC" firstAttribute="top" secondItem="8bC-Xf-vdC" secondAttribute="topMargin" constant="32" id="6CA-w2-V9C"/>
<constraint firstItem="q2J-8i-1LC" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leadingMargin" id="Ay0-kz-Tln"/>
<constraint firstItem="cvB-p5-ToR" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leadingMargin" id="JGK-0D-qAh"/>
<constraint firstItem="q2J-8i-1LC" firstAttribute="trailing" secondItem="8bC-Xf-vdC" secondAttribute="trailingMargin" id="ZfY-iS-aZm"/>
<constraint firstItem="kQK-Xm-4SX" firstAttribute="top" secondItem="8bC-Xf-vdC" secondAttribute="topMargin" constant="249" id="eCV-MN-w3K"/>
<constraint firstItem="cvB-p5-ToR" firstAttribute="top" secondItem="8bC-Xf-vdC" secondAttribute="top" constant="463" id="kHb-VB-Daj"/>
<constraint firstItem="cvB-p5-ToR" firstAttribute="trailing" secondItem="8bC-Xf-vdC" secondAttribute="trailingMargin" id="ljs-BC-IDN"/>
<constraint firstItem="kQK-Xm-4SX" firstAttribute="trailing" secondItem="8bC-Xf-vdC" secondAttribute="trailingMargin" id="pKe-YD-rIZ"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="77.599999999999994" y="37.331334332833585"/>
</scene>
</scenes>
</document>
| {
"pile_set_name": "Github"
} |
#!/bin/bash
DIR=`dirname $0`
python $DIR/../shadysim/shadysim.py $@
| {
"pile_set_name": "Github"
} |
#pragma once
#include <QFile>
#include <QNetworkReply>
#include "masterdialog.h"
namespace Ui {
class AttachmentDialog;
}
class AttachmentDialog : public MasterDialog {
Q_OBJECT
public:
explicit AttachmentDialog(QWidget *parent = nullptr);
~AttachmentDialog();
QFile *getFile();
QString getTitle();
public slots:
void accept();
private slots:
void on_openButton_clicked();
void on_fileEdit_textChanged(const QString &arg1);
void on_downloadButton_clicked();
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
void slotReplyFinished(QNetworkReply *reply);
private:
Ui::AttachmentDialog *ui;
QNetworkAccessManager *_networkManager;
bool _accept = false;
};
| {
"pile_set_name": "Github"
} |
public class LeetCode_169_085 {
}
/**
* @Package:
* @ClassName: MajorityElement
* @Description: 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
* *************你可以假设数组是非空的,并且给定的数组总是存在众数。
* @leetcode_url:https://leetcode-cn.com/problems/majority-element/
* @Author: wangzhao
* @Date: 2019-05-12 09:49:03
* @Version: 1.0.0
* @Since: 1.8
**/
class MajorityElement {
public int majorityElement(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
int count = 0;
int majority = -1;
for (int num : nums) {
if (count == 0) {
majority = num;
count++;
} else {
if (majority == num) {
count++;
} else {
count--;
}
}
}
if (count <= 0) {
return -1;
}
int counter = 0;
for (int num : nums) {
if (num == majority) {
counter++;
}
}
if (counter > nums.length / 2) {
return majority;
}
return -1;
}
public static void main(String[] args) {
int[] nums = {2, 2, 1, 1, 1, 2, 2};
int num = new MajorityElement().majorityElement(nums);
System.out.println(num);
}
}
| {
"pile_set_name": "Github"
} |
package api
import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"errors"
"flag"
"net/url"
"os"
squarejwt "gopkg.in/square/go-jose.v2/jwt"
"github.com/hashicorp/errwrap"
)
var (
// PluginMetadataModeEnv is an ENV name used to disable TLS communication
// to bootstrap mounting plugins.
PluginMetadataModeEnv = "VAULT_PLUGIN_METADATA_MODE"
// PluginUnwrapTokenEnv is the ENV name used to pass unwrap tokens to the
// plugin.
PluginUnwrapTokenEnv = "VAULT_UNWRAP_TOKEN"
)
// PluginAPIClientMeta is a helper that plugins can use to configure TLS connections
// back to Vault.
type PluginAPIClientMeta struct {
// These are set by the command line flags.
flagCACert string
flagCAPath string
flagClientCert string
flagClientKey string
flagInsecure bool
}
// FlagSet returns the flag set for configuring the TLS connection
func (f *PluginAPIClientMeta) FlagSet() *flag.FlagSet {
fs := flag.NewFlagSet("vault plugin settings", flag.ContinueOnError)
fs.StringVar(&f.flagCACert, "ca-cert", "", "")
fs.StringVar(&f.flagCAPath, "ca-path", "", "")
fs.StringVar(&f.flagClientCert, "client-cert", "", "")
fs.StringVar(&f.flagClientKey, "client-key", "", "")
fs.BoolVar(&f.flagInsecure, "tls-skip-verify", false, "")
return fs
}
// GetTLSConfig will return a TLSConfig based off the values from the flags
func (f *PluginAPIClientMeta) GetTLSConfig() *TLSConfig {
// If we need custom TLS configuration, then set it
if f.flagCACert != "" || f.flagCAPath != "" || f.flagClientCert != "" || f.flagClientKey != "" || f.flagInsecure {
t := &TLSConfig{
CACert: f.flagCACert,
CAPath: f.flagCAPath,
ClientCert: f.flagClientCert,
ClientKey: f.flagClientKey,
TLSServerName: "",
Insecure: f.flagInsecure,
}
return t
}
return nil
}
// VaultPluginTLSProvider is run inside a plugin and retrieves the response
// wrapped TLS certificate from vault. It returns a configured TLS Config.
func VaultPluginTLSProvider(apiTLSConfig *TLSConfig) func() (*tls.Config, error) {
if os.Getenv(PluginMetadataModeEnv) == "true" {
return nil
}
return func() (*tls.Config, error) {
unwrapToken := os.Getenv(PluginUnwrapTokenEnv)
parsedJWT, err := squarejwt.ParseSigned(unwrapToken)
if err != nil {
return nil, errwrap.Wrapf("error parsing wrapping token: {{err}}", err)
}
var allClaims = make(map[string]interface{})
if err = parsedJWT.UnsafeClaimsWithoutVerification(&allClaims); err != nil {
return nil, errwrap.Wrapf("error parsing claims from wrapping token: {{err}}", err)
}
addrClaimRaw, ok := allClaims["addr"]
if !ok {
return nil, errors.New("could not validate addr claim")
}
vaultAddr, ok := addrClaimRaw.(string)
if !ok {
return nil, errors.New("could not parse addr claim")
}
if vaultAddr == "" {
return nil, errors.New(`no vault api_addr found`)
}
// Sanity check the value
if _, err := url.Parse(vaultAddr); err != nil {
return nil, errwrap.Wrapf("error parsing the vault api_addr: {{err}}", err)
}
// Unwrap the token
clientConf := DefaultConfig()
clientConf.Address = vaultAddr
if apiTLSConfig != nil {
err := clientConf.ConfigureTLS(apiTLSConfig)
if err != nil {
return nil, errwrap.Wrapf("error configuring api client {{err}}", err)
}
}
client, err := NewClient(clientConf)
if err != nil {
return nil, errwrap.Wrapf("error during api client creation: {{err}}", err)
}
secret, err := client.Logical().Unwrap(unwrapToken)
if err != nil {
return nil, errwrap.Wrapf("error during token unwrap request: {{err}}", err)
}
if secret == nil {
return nil, errors.New("error during token unwrap request: secret is nil")
}
// Retrieve and parse the server's certificate
serverCertBytesRaw, ok := secret.Data["ServerCert"].(string)
if !ok {
return nil, errors.New("error unmarshalling certificate")
}
serverCertBytes, err := base64.StdEncoding.DecodeString(serverCertBytesRaw)
if err != nil {
return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err)
}
serverCert, err := x509.ParseCertificate(serverCertBytes)
if err != nil {
return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err)
}
// Retrieve and parse the server's private key
serverKeyB64, ok := secret.Data["ServerKey"].(string)
if !ok {
return nil, errors.New("error unmarshalling certificate")
}
serverKeyRaw, err := base64.StdEncoding.DecodeString(serverKeyB64)
if err != nil {
return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err)
}
serverKey, err := x509.ParseECPrivateKey(serverKeyRaw)
if err != nil {
return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err)
}
// Add CA cert to the cert pool
caCertPool := x509.NewCertPool()
caCertPool.AddCert(serverCert)
// Build a certificate object out of the server's cert and private key.
cert := tls.Certificate{
Certificate: [][]byte{serverCertBytes},
PrivateKey: serverKey,
Leaf: serverCert,
}
// Setup TLS config
tlsConfig := &tls.Config{
ClientCAs: caCertPool,
RootCAs: caCertPool,
ClientAuth: tls.RequireAndVerifyClientCert,
// TLS 1.2 minimum
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cert},
ServerName: serverCert.Subject.CommonName,
}
tlsConfig.BuildNameToCertificate()
return tlsConfig, nil
}
}
| {
"pile_set_name": "Github"
} |
"""
Headless Site Navigation and File Download (Using Selenium) to S3
This example demonstrates using Selenium (via Firefox/GeckoDriver) to:
1) Log into a website w/ credentials stored in connection labeled 'selenium_conn_id'
2) Download a file (initiated on login)
3) Transform the CSV into JSON formatting
4) Append the current data to each record
5) Load the corresponding file into S3
To use this DAG, you will need to have the following installed:
[XVFB](https://www.x.org/archive/X11R7.6/doc/man/man1/Xvfb.1.xhtml)
[GeckoDriver](https://github.com/mozilla/geckodriver/releases/download)
selenium==3.11.0
xvfbwrapper==0.2.9
"""
from datetime import datetime, timedelta
import os
import boa
import csv
import json
import time
import logging
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from xvfbwrapper import Xvfb
from airflow import DAG
from airflow.models import Connection
from airflow.utils.db import provide_session
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from airflow.hooks import S3Hook
S3_CONN_ID = ''
S3_BUCKET = ''
S3_KEY = ''
date = '{{ ds }}'
default_args = {
'start_date': datetime(2018, 2, 10, 0, 0),
'email': [],
'email_on_failure': True,
'email_on_retry': False,
'retries': 2,
'retry_delay': timedelta(minutes=5),
'catchup': False
}
dag = DAG(
'selenium_extraction_to_s3',
schedule_interval='@daily',
default_args=default_args,
catchup=False
)
def imap_py(**kwargs):
selenium_conn_id = kwargs.get('templates_dict', None).get('selenium_conn_id', None)
filename = kwargs.get('templates_dict', None).get('filename', None)
s3_conn_id = kwargs.get('templates_dict', None).get('s3_conn_id', None)
s3_bucket = kwargs.get('templates_dict', None).get('s3_bucket', None)
s3_key = kwargs.get('templates_dict', None).get('s3_key', None)
date = kwargs.get('templates_dict', None).get('date', None)
@provide_session
def get_conn(conn_id, session=None):
conn = (
session.query(Connection)
.filter(Connection.conn_id == conn_id)
.first()
)
return conn
url = get_conn(selenium_conn_id).host
email = get_conn(selenium_conn_id).user
pwd = get_conn(selenium_conn_id).password
vdisplay = Xvfb()
vdisplay.start()
caps = webdriver.DesiredCapabilities.FIREFOX
caps["marionette"] = True
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', "text/csv")
logging.info('Profile set...')
options = Options()
options.set_headless(headless=True)
logging.info('Options set...')
logging.info('Initializing Driver...')
driver = webdriver.Firefox(firefox_profile=profile,
firefox_options=options,
capabilities=caps)
logging.info('Driver Intialized...')
driver.get(url)
logging.info('Authenticating...')
elem = driver.find_element_by_id("email")
elem.send_keys(email)
elem = driver.find_element_by_id("password")
elem.send_keys(pwd)
elem.send_keys(Keys.RETURN)
logging.info('Successfully authenticated.')
sleep_time = 15
logging.info('Downloading File....Sleeping for {} Seconds.'.format(str(sleep_time)))
time.sleep(sleep_time)
driver.close()
vdisplay.stop()
dest_s3 = S3Hook(s3_conn_id=s3_conn_id)
os.chdir('/root/Downloads')
csvfile = open(filename, 'r')
output_json = 'file.json'
with open(output_json, 'w') as jsonfile:
reader = csv.DictReader(csvfile)
for row in reader:
row = dict((boa.constrict(k), v) for k, v in row.items())
row['run_date'] = date
json.dump(row, jsonfile)
jsonfile.write('\n')
dest_s3.load_file(
filename=output_json,
key=s3_key,
bucket_name=s3_bucket,
replace=True
)
dest_s3.connection.close()
with dag:
kick_off_dag = DummyOperator(task_id='kick_off_dag')
selenium = PythonOperator(
task_id='selenium_retrieval_to_s3',
python_callable=imap_py,
templates_dict={"s3_conn_id": S3_CONN_ID,
"s3_bucket": S3_BUCKET,
"s3_key": S3_KEY,
"date": date},
provide_context=True
)
kick_off_dag >> selenium
| {
"pile_set_name": "Github"
} |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2012, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Ajax.org B.V. 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
/* This file was autogenerated from https://raw.github.com/JuliaLang/julia/master/contrib/Julia.tmbundle/Syntaxes/Julia.tmLanguage (uuid: ) */
/****************************************************************************************
* IT MIGHT NOT BE PERFECT ...But it's a good start from an existing *.tmlanguage file. *
* fileTypes *
****************************************************************************************/
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var JuliaHighlightRules = function() {
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = { start:
[ { include: '#function_decl' },
{ include: '#function_call' },
{ include: '#type_decl' },
{ include: '#keyword' },
{ include: '#operator' },
{ include: '#number' },
{ include: '#string' },
{ include: '#comment' } ],
'#bracket':
[ { token: 'keyword.bracket.julia',
regex: '\\(|\\)|\\[|\\]|\\{|\\}|,' } ],
'#comment':
[ { token:
[ 'punctuation.definition.comment.julia',
'comment.line.number-sign.julia' ],
regex: '(#)(?!\\{)(.*$)'} ],
'#function_call':
[ { token: [ 'support.function.julia', 'text' ],
regex: '([a-zA-Z0-9_]+!?)([\\w\\xff-\\u218e\\u2455-\\uffff]*\\()'} ],
'#function_decl':
[ { token: [ 'keyword.other.julia', 'meta.function.julia',
'entity.name.function.julia', 'meta.function.julia','text' ],
regex: '(function|macro)(\\s*)([a-zA-Z0-9_\\{]+!?)([\\w\\xff-\\u218e\\u2455-\\uffff]*)([(\\\\{])'} ],
'#keyword':
[ { token: 'keyword.other.julia',
regex: '\\b(?:function|type|immutable|macro|quote|abstract|bitstype|typealias|module|baremodule|new)\\b' },
{ token: 'keyword.control.julia',
regex: '\\b(?:if|else|elseif|while|for|in|begin|let|end|do|try|catch|finally|return|break|continue)\\b' },
{ token: 'storage.modifier.variable.julia',
regex: '\\b(?:global|local|const|export|import|importall|using)\\b' },
{ token: 'variable.macro.julia', regex: '@[\\w\\xff-\\u218e\\u2455-\\uffff]+\\b' } ],
'#number':
[ { token: 'constant.numeric.julia',
regex: '\\b0(?:x|X)[0-9a-fA-F]*|(?:\\b[0-9]+\\.?[0-9]*|\\.[0-9]+)(?:(?:e|E)(?:\\+|-)?[0-9]*)?(?:im)?|\\bInf(?:32)?\\b|\\bNaN(?:32)?\\b|\\btrue\\b|\\bfalse\\b' } ],
'#operator':
[ { token: 'keyword.operator.update.julia',
regex: '=|:=|\\+=|-=|\\*=|/=|//=|\\.//=|\\.\\*=|\\\\=|\\.\\\\=|^=|\\.^=|%=|\\|=|&=|\\$=|<<=|>>=' },
{ token: 'keyword.operator.ternary.julia', regex: '\\?|:' },
{ token: 'keyword.operator.boolean.julia',
regex: '\\|\\||&&|!' },
{ token: 'keyword.operator.arrow.julia', regex: '->|<-|-->' },
{ token: 'keyword.operator.relation.julia',
regex: '>|<|>=|<=|==|!=|\\.>|\\.<|\\.>=|\\.>=|\\.==|\\.!=|\\.=|\\.!|<:|:>' },
{ token: 'keyword.operator.range.julia', regex: ':' },
{ token: 'keyword.operator.shift.julia', regex: '<<|>>' },
{ token: 'keyword.operator.bitwise.julia', regex: '\\||\\&|~' },
{ token: 'keyword.operator.arithmetic.julia',
regex: '\\+|-|\\*|\\.\\*|/|\\./|//|\\.//|%|\\.%|\\\\|\\.\\\\|\\^|\\.\\^' },
{ token: 'keyword.operator.isa.julia', regex: '::' },
{ token: 'keyword.operator.dots.julia',
regex: '\\.(?=[a-zA-Z])|\\.\\.+' },
{ token: 'keyword.operator.interpolation.julia',
regex: '\\$#?(?=.)' },
{ token: [ 'variable', 'keyword.operator.transposed-variable.julia' ],
regex: '([\\w\\xff-\\u218e\\u2455-\\uffff]+)((?:\'|\\.\')*\\.?\')' },
{ token: 'text',
regex: '\\[|\\('},
{ token: [ 'text', 'keyword.operator.transposed-matrix.julia' ],
regex: "([\\]\\)])((?:'|\\.')*\\.?')"} ],
'#string':
[ { token: 'punctuation.definition.string.begin.julia',
regex: '\'',
push:
[ { token: 'punctuation.definition.string.end.julia',
regex: '\'',
next: 'pop' },
{ include: '#string_escaped_char' },
{ defaultToken: 'string.quoted.single.julia' } ] },
{ token: 'punctuation.definition.string.begin.julia',
regex: '"',
push:
[ { token: 'punctuation.definition.string.end.julia',
regex: '"',
next: 'pop' },
{ include: '#string_escaped_char' },
{ defaultToken: 'string.quoted.double.julia' } ] },
{ token: 'punctuation.definition.string.begin.julia',
regex: '\\b[\\w\\xff-\\u218e\\u2455-\\uffff]+"',
push:
[ { token: 'punctuation.definition.string.end.julia',
regex: '"[\\w\\xff-\\u218e\\u2455-\\uffff]*',
next: 'pop' },
{ include: '#string_custom_escaped_char' },
{ defaultToken: 'string.quoted.custom-double.julia' } ] },
{ token: 'punctuation.definition.string.begin.julia',
regex: '`',
push:
[ { token: 'punctuation.definition.string.end.julia',
regex: '`',
next: 'pop' },
{ include: '#string_escaped_char' },
{ defaultToken: 'string.quoted.backtick.julia' } ] } ],
'#string_custom_escaped_char': [ { token: 'constant.character.escape.julia', regex: '\\\\"' } ],
'#string_escaped_char':
[ { token: 'constant.character.escape.julia',
regex: '\\\\(?:\\\\|[0-3]\\d{,2}|[4-7]\\d?|x[a-fA-F0-9]{,2}|u[a-fA-F0-9]{,4}|U[a-fA-F0-9]{,8}|.)' } ],
'#type_decl':
[ { token:
[ 'keyword.control.type.julia',
'meta.type.julia',
'entity.name.type.julia',
'entity.other.inherited-class.julia',
'punctuation.separator.inheritance.julia',
'entity.other.inherited-class.julia' ],
regex: '(type|immutable)(\\s+)([a-zA-Z0-9_]+)(?:(\\s*)(<:)(\\s*[.a-zA-Z0-9_:]+))?' },
{ token: [ 'other.typed-variable.julia', 'support.type.julia' ],
regex: '([a-zA-Z0-9_]+)(::[a-zA-Z0-9_{}]+)' } ] }
this.normalizeRules();
};
JuliaHighlightRules.metaData = { fileTypes: [ 'jl' ],
firstLineMatch: '^#!.*\\bjulia\\s*$',
foldingStartMarker: '^\\s*(?:if|while|for|begin|function|macro|module|baremodule|type|immutable|let)\\b(?!.*\\bend\\b).*$',
foldingStopMarker: '^\\s*(?:end)\\b.*$',
name: 'Julia',
scopeName: 'source.julia' }
oop.inherits(JuliaHighlightRules, TextHighlightRules);
exports.JuliaHighlightRules = JuliaHighlightRules;
}); | {
"pile_set_name": "Github"
} |
var TodoController = function($scope, $http){
$scope.editMode = false;
$scope.position = '';
$scope.getAllTodos = function(){
$scope.resetError();
$http.get('todo/all.json').success(function(response){
$scope.todos = response;
}).error(function() {
$scope.setError('Could not display all todos');
});
}
$scope.addTodo = function(newTodo){
$scope.resetError();
$http.post('todo/add/' + newTodo).success(function(response){
$scope.getAllTodos();
}).error(function() {
$scope.setError('Could add todo');
});
$scope.todoName = '';
}
$scope.deleteTodo = function(deleteTodo){
$scope.resetError();
$http.delete('todo/delete/'+deleteTodo).success(function(response){
$scope.getAllTodos();
}).error(function() {
$scope.setError('Could not delete todo');
});
}
$scope.deleteAllTodo = function(){
$scope.resetError();
$http.delete('todo/deleteAll').success(function(response){
$scope.getAllTodos();
}).error(function() {
$scope.setError('Could not delete all todos');
})
}
$scope.editTodo = function(position, todo){
$scope.resetError();
$scope.todoName = todo;
$scope.position = position;
$scope.editMode = true;
}
$scope.updateTodo = function(updateTodo){
$scope.resetError();
$http.put('todo/update/'+ $scope.position +'/'+updateTodo).success(function(response){
$scope.getAllTodos();
$scope.position = '';
$scope.todoName = '';
$scope.editMode = false;
}).error(function(){
$scope.setError('Could not update todo');
})
}
$scope.resetTodoField = function() {
$scope.resetError();
$scope.todoName = '';
$scope.editMode = false;
};
$scope.resetError = function() {
$scope.error = false;
$scope.errorMessage = '';
};
$scope.setError = function(message) {
$scope.error = true;
$scope.errorMessage = message;
};
$scope.getAllTodos();
} | {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>YMNewfeatureViewController Class Reference</title>
<link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../css/highlight.css" />
<meta charset='utf-8'>
<script src="../js/jquery.min.js" defer></script>
<script src="../js/jazzy.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Class/YMNewfeatureViewController" class="dashAnchor"></a>
<a title="YMNewfeatureViewController Class Reference"></a>
<header>
<div class="content-wrapper">
<p><a href="../index.html"> Docs</a> (18% documented)</p>
</div>
</header>
<div class="content-wrapper">
<p id="breadcrumbs">
<a href="../index.html"> Reference</a>
<img id="carat" src="../img/carat.png" />
YMNewfeatureViewController Class Reference
</p>
</div>
<div class="content-wrapper">
<nav class="sidebar">
<ul class="nav-groups">
<li class="nav-group-name">
<a href="../Classes.html">Classes</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Classes/AppDelegate.html">AppDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Classes/User.html">User</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMActionSheet.html">YMActionSheet</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMBaseViewController.html">YMBaseViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMCategoryBottomView.html">YMCategoryBottomView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMCategoryCollectionViewCell.html">YMCategoryCollectionViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMCategoryHeaderViewController.html">YMCategoryHeaderViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMCategoryViewController.html">YMCategoryViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMChannel.html">YMChannel</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMCollection.html">YMCollection</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMCollectionDetailController.html">YMCollectionDetailController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMCollectionPost.html">YMCollectionPost</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMCollectionTableViewCell.html">YMCollectionTableViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMCollectionViewCell.html">YMCollectionViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMComment.html">YMComment</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMCommentCell.html">YMCommentCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMDanTangViewController.html">YMDanTangViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMDetailChoiceButtonView.html">YMDetailChoiceButtonView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMDetailCollectionViewCell.html">YMDetailCollectionViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMDetailLayout.html">YMDetailLayout</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMDetailScrollView.html">YMDetailScrollView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMDetailViewController.html">YMDetailViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMGroup.html">YMGroup</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMHomeCell.html">YMHomeCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMHomeItem.html">YMHomeItem</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMLoginViewController.html">YMLoginViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMMeChoiceView.html">YMMeChoiceView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMMeFooterView.html">YMMeFooterView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMMeViewController.html">YMMeViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMMessageViewController.html">YMMessageViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMMineHeaderView.html">YMMineHeaderView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMNavigationController.html">YMNavigationController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMNetworkTool.html">YMNetworkTool</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMNewfeatureCell.html">YMNewfeatureCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMNewfeatureLayout.html">YMNewfeatureLayout</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMNewfeatureViewController.html">YMNewfeatureViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMPostDetailViewController.html">YMPostDetailViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMProduct.html">YMProduct</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMProductDetail.html">YMProductDetail</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMProductDetailBottomView.html">YMProductDetailBottomView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMProductDetailToolBar.html">YMProductDetailToolBar</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMProductDetailTopView.html">YMProductDetailTopView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMProductDetailViewController.html">YMProductDetailViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMProductViewController.html">YMProductViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMRefreshControl.html">YMRefreshControl</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMRefreshView.html">YMRefreshView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMRegisterViewController.html">YMRegisterViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMSearchRecordView.html">YMSearchRecordView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMSearchResult.html">YMSearchResult</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMSearchViewController.html">YMSearchViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMSeeAllController.html">YMSeeAllController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMSeeAllTopicCell.html">YMSeeAllTopicCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMSetting.html">YMSetting</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMSettingCell.html">YMSettingCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMSettingViewController.html">YMSettingViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMShareButtonView.html">YMShareButtonView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMSortCell.html">YMSortCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMSortTableView.html">YMSortTableView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMTMALLViewController.html">YMTMALLViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMTabBarController.html">YMTabBarController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMTopHeaderView.html">YMTopHeaderView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMTopicViewController.html">YMTopicViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/YMVerticalButton.html">YMVerticalButton</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Global Variables.html">Global Variables</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang8BASE_URLSS">BASE_URL</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang9RETURN_OKSi">RETURN_OK</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang7SCREENHV12CoreGraphics7CGFloat">SCREENH</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang7SCREENWV12CoreGraphics7CGFloat">SCREENW</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang13YMFirstLaunchSS">YMFirstLaunch</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang24categoryCollectionCellIDSS">categoryCollectionCellID</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang16collectionCellIDSS">collectionCellID</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang21collectionTableCellIDSS">collectionTableCellID</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang13commentCellIDSS">commentCellID</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang26detailCollectionViewCellIDSS">detailCollectionViewCellID</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang10homeCellIDSS">homeCellID</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang9isIPhone5Sb">isIPhone5</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang9isIPhone6Sb">isIPhone6</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang10isIPhone6PSb">isIPhone6P</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang7isLoginSS">isLogin</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang18kAnimationDurationSd">kAnimationDuration</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang13kCornerRadiusV12CoreGraphics7CGFloat">kCornerRadius</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang15kIndicatorViewHV12CoreGraphics7CGFloat">kIndicatorViewH</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang7kMarginV12CoreGraphics7CGFloat">kMargin</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang16kNewFeatureCountSi">kNewFeatureCount</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang12kTitlesViewHV12CoreGraphics7CGFloat">kTitlesViewH</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang12kTitlesViewYV12CoreGraphics7CGFloat">kTitlesViewY</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang9kTopViewHV12CoreGraphics7CGFloat">kTopViewH</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang24kYMMineHeaderImageHeightV12CoreGraphics7CGFloat">kYMMineHeaderImageHeight</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang6kitemHV12CoreGraphics7CGFloat">kitemH</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang6kitemWV12CoreGraphics7CGFloat">kitemW</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang10klineWidthV12CoreGraphics7CGFloat">klineWidth</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang13messageCellIDSS">messageCellID</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang12newFeatureIDSS">newFeatureID</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang22searchCollectionCellIDSS">searchCollectionCellID</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang12seeAllcellIDSS">seeAllcellID</a>
</li>
<li class="nav-group-task">
<a href="../Global Variables.html#/s:v7DanTang19sortTableViewCellIDSS">sortTableViewCellID</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Enums.html">Enums</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Enums/YMOtherLoginButtonType.html">YMOtherLoginButtonType</a>
</li>
<li class="nav-group-task">
<a href="../Enums/YMShareButtonType.html">YMShareButtonType</a>
</li>
<li class="nav-group-task">
<a href="../Enums/YMTopicType.html">YMTopicType</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Extensions.html">Extensions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Extensions/String.html">String</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UITableView.html">UITableView</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIView.html">UIView</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Functions.html">Functions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Functions.html#/s:F7DanTang7YMColorFTV12CoreGraphics7CGFloat1gS1_1bS1_1aS1__CSo7UIColor">YMColor(_:g:b:a:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:F7DanTang13YMGlobalColorFT_CSo7UIColor">YMGlobalColor()</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:F7DanTang16YMGlobalRedColorFT_CSo7UIColor">YMGlobalRedColor()</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Protocols.html">Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Protocols/YMCategoryBottomViewDelegate.html">YMCategoryBottomViewDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/YMCollectionViewCellDelegate.html">YMCollectionViewCellDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/YMDetailChoiceButtonViewDegegate.html">YMDetailChoiceButtonViewDegegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/YMHomeCellDelegate.html">YMHomeCellDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/YMProductDetailToolBarDelegate.html">YMProductDetailToolBarDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/YMSortTableViewDelegate.html">YMSortTableViewDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/YMTopHeaderViewDelegate.html">YMTopHeaderViewDelegate</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section>
<section class="section">
<h1>YMNewfeatureViewController</h1>
<p>Undocumented</p>
</section>
<section class="section task-group-section">
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:vC7DanTang26YMNewfeatureViewControllerP33_4AFD823B18308A4A4614B6C4D5FA0EAF6layoutCSo26UICollectionViewFlowLayout"></a>
<a name="//apple_ref/swift/Property/layout" class="dashAnchor"></a>
<a class="token" href="#/s:vC7DanTang26YMNewfeatureViewControllerP33_4AFD823B18308A4A4614B6C4D5FA0EAF6layoutCSo26UICollectionViewFlowLayout">layout</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>布局对象</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="kd">private</span> <span class="k">var</span> <span class="nv">layout</span><span class="p">:</span> <span class="kt">UICollectionViewFlowLayout</span> <span class="o">=</span> <span class="kt">YMNewfeatureLayout</span><span class="p">()</span></code></pre>
</div>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:FC7DanTang26YMNewfeatureViewControllercFT_S0_"></a>
<a name="//apple_ref/swift/Method/init()" class="dashAnchor"></a>
<a class="token" href="#/s:FC7DanTang26YMNewfeatureViewControllercFT_S0_">init()</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:FC7DanTang26YMNewfeatureViewControllercFT5coderCSo7NSCoder_GSqS0__"></a>
<a name="//apple_ref/swift/Method/init(coder:)" class="dashAnchor"></a>
<a class="token" href="#/s:FC7DanTang26YMNewfeatureViewControllercFT5coderCSo7NSCoder_GSqS0__">init(coder:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:FC7DanTang26YMNewfeatureViewController11viewDidLoadFT_T_"></a>
<a name="//apple_ref/swift/Method/viewDidLoad()" class="dashAnchor"></a>
<a class="token" href="#/s:FC7DanTang26YMNewfeatureViewController11viewDidLoadFT_T_">viewDidLoad()</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
</ul>
</div>
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:FC7DanTang26YMNewfeatureViewController14collectionViewFTCSo16UICollectionView22numberOfItemsInSectionSi_Si"></a>
<a name="//apple_ref/swift/Method/collectionView(_:numberOfItemsInSection:)" class="dashAnchor"></a>
<a class="token" href="#/s:FC7DanTang26YMNewfeatureViewController14collectionViewFTCSo16UICollectionView22numberOfItemsInSectionSi_Si">collectionView(_:numberOfItemsInSection:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:FC7DanTang26YMNewfeatureViewController14collectionViewFTCSo16UICollectionView22cellForItemAtIndexPathCSo11NSIndexPath_CSo20UICollectionViewCell"></a>
<a name="//apple_ref/swift/Method/collectionView(_:cellForItemAtIndexPath:)" class="dashAnchor"></a>
<a class="token" href="#/s:FC7DanTang26YMNewfeatureViewController14collectionViewFTCSo16UICollectionView22cellForItemAtIndexPathCSo11NSIndexPath_CSo20UICollectionViewCell">collectionView(_:cellForItemAtIndexPath:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:FC7DanTang26YMNewfeatureViewController14collectionViewFTCSo16UICollectionView20didEndDisplayingCellCSo20UICollectionViewCell18forItemAtIndexPathCSo11NSIndexPath_T_"></a>
<a name="//apple_ref/swift/Method/collectionView(_:didEndDisplayingCell:forItemAtIndexPath:)" class="dashAnchor"></a>
<a class="token" href="#/s:FC7DanTang26YMNewfeatureViewController14collectionViewFTCSo16UICollectionView20didEndDisplayingCellCSo20UICollectionViewCell18forItemAtIndexPathCSo11NSIndexPath_T_">collectionView(_:didEndDisplayingCell:forItemAtIndexPath:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
</ul>
</div>
</section>
</section>
<section id="footer">
<p>© 2016 <a class="link" href="" target="_blank" rel="external"></a>. All rights reserved. (Last updated: 2016-07-27)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.6.2</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</article>
</div>
</body>
</div>
</html>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" ?>
<!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>DEFINE_STACK_OF</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:" />
</head>
<body>
<ul id="index">
<li><a href="#NAME">NAME</a></li>
<li><a href="#SYNOPSIS">SYNOPSIS</a></li>
<li><a href="#DESCRIPTION">DESCRIPTION</a></li>
<li><a href="#NOTES">NOTES</a></li>
<li><a href="#RETURN-VALUES">RETURN VALUES</a></li>
<li><a href="#HISTORY">HISTORY</a></li>
<li><a href="#COPYRIGHT">COPYRIGHT</a></li>
</ul>
<h1 id="NAME">NAME</h1>
<p>DEFINE_STACK_OF, DEFINE_STACK_OF_CONST, DEFINE_SPECIAL_STACK_OF, DEFINE_SPECIAL_STACK_OF_CONST, sk_TYPE_num, sk_TYPE_value, sk_TYPE_new, sk_TYPE_new_null, sk_TYPE_reserve, sk_TYPE_free, sk_TYPE_zero, sk_TYPE_delete, sk_TYPE_delete_ptr, sk_TYPE_push, sk_TYPE_unshift, sk_TYPE_pop, sk_TYPE_shift, sk_TYPE_pop_free, sk_TYPE_insert, sk_TYPE_set, sk_TYPE_find, sk_TYPE_find_ex, sk_TYPE_sort, sk_TYPE_is_sorted, sk_TYPE_dup, sk_TYPE_deep_copy, sk_TYPE_set_cmp_func, sk_TYPE_new_reserve - stack container</p>
<h1 id="SYNOPSIS">SYNOPSIS</h1>
<pre><code> <span class="comment">#include <openssl/safestack.h></span>
<span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span>
<span class="variable">DEFINE_STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span>
<span class="variable">DEFINE_STACK_OF_CONST</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span>
<span class="variable">DEFINE_SPECIAL_STACK_OF</span><span class="operator">(</span><span class="variable">FUNCTYPE</span><span class="operator">,</span> <span class="variable">TYPE</span><span class="operator">)</span>
<span class="variable">DEFINE_SPECIAL_STACK_OF_CONST</span><span class="operator">(</span><span class="variable">FUNCTYPE</span><span class="operator">,</span> <span class="variable">TYPE</span><span class="operator">)</span>
<span class="variable">typedef</span> <span class="keyword">int</span> <span class="operator">(</span><span class="variable">*sk_TYPE_compfunc</span><span class="operator">)(</span><span class="variable">const</span> <span class="variable">TYPE</span> <span class="variable">*const</span> <span class="variable">*a</span><span class="operator">,</span> <span class="variable">const</span> <span class="variable">TYPE</span> <span class="variable">*const</span> <span class="variable">*b</span><span class="operator">);</span>
<span class="variable">typedef</span> <span class="variable">TYPE</span> <span class="operator">*</span> <span class="operator">(</span><span class="variable">*sk_TYPE_copyfunc</span><span class="operator">)(</span><span class="variable">const</span> <span class="variable">TYPE</span> <span class="variable">*a</span><span class="operator">);</span>
<span class="variable">typedef</span> <span class="variable">void</span> <span class="operator">(</span><span class="variable">*sk_TYPE_freefunc</span><span class="operator">)(</span><span class="variable">TYPE</span> <span class="variable">*a</span><span class="operator">);</span>
<span class="keyword">int</span> <span class="variable">sk_TYPE_num</span><span class="operator">(</span><span class="variable">const</span> <span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">);</span>
<span class="variable">TYPE</span> <span class="variable">*sk_TYPE_value</span><span class="operator">(</span><span class="variable">const</span> <span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="keyword">int</span> <span class="variable">idx</span><span class="operator">);</span>
<span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk_TYPE_new</span><span class="operator">(</span><span class="variable">sk_TYPE_compfunc</span> <span class="variable">compare</span><span class="operator">);</span>
<span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk_TYPE_new_null</span><span class="operator">(</span><span class="variable">void</span><span class="operator">);</span>
<span class="keyword">int</span> <span class="variable">sk_TYPE_reserve</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="keyword">int</span> <span class="variable">n</span><span class="operator">);</span>
<span class="variable">void</span> <span class="variable">sk_TYPE_free</span><span class="operator">(</span><span class="variable">const</span> <span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">);</span>
<span class="variable">void</span> <span class="variable">sk_TYPE_zero</span><span class="operator">(</span><span class="variable">const</span> <span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">);</span>
<span class="variable">TYPE</span> <span class="variable">*sk_TYPE_delete</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="keyword">int</span> <span class="variable">i</span><span class="operator">);</span>
<span class="variable">TYPE</span> <span class="variable">*sk_TYPE_delete_ptr</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="variable">TYPE</span> <span class="variable">*ptr</span><span class="operator">);</span>
<span class="keyword">int</span> <span class="variable">sk_TYPE_push</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="variable">const</span> <span class="variable">TYPE</span> <span class="variable">*ptr</span><span class="operator">);</span>
<span class="keyword">int</span> <span class="variable">sk_TYPE_unshift</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="variable">const</span> <span class="variable">TYPE</span> <span class="variable">*ptr</span><span class="operator">);</span>
<span class="variable">TYPE</span> <span class="variable">*sk_TYPE_pop</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">);</span>
<span class="variable">TYPE</span> <span class="variable">*sk_TYPE_shift</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">);</span>
<span class="variable">void</span> <span class="variable">sk_TYPE_pop_free</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="variable">sk_TYPE_freefunc</span> <span class="variable">freefunc</span><span class="operator">);</span>
<span class="keyword">int</span> <span class="variable">sk_TYPE_insert</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="variable">TYPE</span> <span class="variable">*ptr</span><span class="operator">,</span> <span class="keyword">int</span> <span class="variable">idx</span><span class="operator">);</span>
<span class="variable">TYPE</span> <span class="variable">*sk_TYPE_set</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="keyword">int</span> <span class="variable">idx</span><span class="operator">,</span> <span class="variable">const</span> <span class="variable">TYPE</span> <span class="variable">*ptr</span><span class="operator">);</span>
<span class="keyword">int</span> <span class="variable">sk_TYPE_find</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="variable">TYPE</span> <span class="variable">*ptr</span><span class="operator">);</span>
<span class="keyword">int</span> <span class="variable">sk_TYPE_find_ex</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="variable">TYPE</span> <span class="variable">*ptr</span><span class="operator">);</span>
<span class="variable">void</span> <span class="variable">sk_TYPE_sort</span><span class="operator">(</span><span class="variable">const</span> <span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">);</span>
<span class="keyword">int</span> <span class="variable">sk_TYPE_is_sorted</span><span class="operator">(</span><span class="variable">const</span> <span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">);</span>
<span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk_TYPE_dup</span><span class="operator">(</span><span class="variable">const</span> <span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">);</span>
<span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk_TYPE_deep_copy</span><span class="operator">(</span><span class="variable">const</span> <span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span>
<span class="variable">sk_TYPE_copyfunc</span> <span class="variable">copyfunc</span><span class="operator">,</span>
<span class="variable">sk_TYPE_freefunc</span> <span class="variable">freefunc</span><span class="operator">);</span>
<span class="variable">sk_TYPE_compfunc</span> <span class="operator">(</span><span class="variable">*sk_TYPE_set_cmp_func</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span>
<span class="variable">sk_TYPE_compfunc</span> <span class="variable">compare</span><span class="operator">));</span>
<span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk_TYPE_new_reserve</span><span class="operator">(</span><span class="variable">sk_TYPE_compfunc</span> <span class="variable">compare</span><span class="operator">,</span> <span class="keyword">int</span> <span class="variable">n</span><span class="operator">);</span>
</code></pre>
<h1 id="DESCRIPTION">DESCRIPTION</h1>
<p>Applications can create and use their own stacks by placing any of the macros described below in a header file. These macros define typesafe inline functions that wrap around the utility <b>OPENSSL_sk_</b> API. In the description here, <i>TYPE</i> is used as a placeholder for any of the OpenSSL datatypes, such as <i>X509</i>.</p>
<p>STACK_OF() returns the name for a stack of the specified <b>TYPE</b>. DEFINE_STACK_OF() creates set of functions for a stack of <b>TYPE</b>. This will mean that type <b>TYPE</b> is stored in each stack, the type is referenced by STACK_OF(TYPE) and each function name begins with <i>sk_TYPE_</i>. For example:</p>
<pre><code> <span class="variable">TYPE</span> <span class="variable">*sk_TYPE_value</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="keyword">int</span> <span class="variable">idx</span><span class="operator">);</span>
</code></pre>
<p>DEFINE_STACK_OF_CONST() is identical to DEFINE_STACK_OF() except each element is constant. For example:</p>
<pre><code> <span class="variable">const</span> <span class="variable">TYPE</span> <span class="variable">*sk_TYPE_value</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="keyword">int</span> <span class="variable">idx</span><span class="operator">);</span>
</code></pre>
<p>DEFINE_SPECIAL_STACK_OF() defines a stack of <b>TYPE</b> but each function uses <b>FUNCNAME</b> in the function name. For example:</p>
<pre><code> <span class="variable">TYPE</span> <span class="variable">*sk_FUNCNAME_value</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="keyword">int</span> <span class="variable">idx</span><span class="operator">);</span>
</code></pre>
<p>DEFINE_SPECIAL_STACK_OF_CONST() is similar except that each element is constant:</p>
<pre><code> <span class="variable">const</span> <span class="variable">TYPE</span> <span class="variable">*sk_FUNCNAME_value</span><span class="operator">(</span><span class="variable">STACK_OF</span><span class="operator">(</span><span class="variable">TYPE</span><span class="operator">)</span> <span class="variable">*sk</span><span class="operator">,</span> <span class="keyword">int</span> <span class="variable">idx</span><span class="operator">);</span>
</code></pre>
<p>sk_TYPE_num() returns the number of elements in <b>sk</b> or -1 if <b>sk</b> is <b>NULL</b>.</p>
<p>sk_TYPE_value() returns element <b>idx</b> in <b>sk</b>, where <b>idx</b> starts at zero. If <b>idx</b> is out of range then <b>NULL</b> is returned.</p>
<p>sk_TYPE_new() allocates a new empty stack using comparison function <b>compare</b>. If <b>compare</b> is <b>NULL</b> then no comparison function is used. This function is equivalent to sk_TYPE_new_reserve(compare, 0).</p>
<p>sk_TYPE_new_null() allocates a new empty stack with no comparison function. This function is equivalent to sk_TYPE_new_reserve(NULL, 0).</p>
<p>sk_TYPE_reserve() allocates additional memory in the <b>sk</b> structure such that the next <b>n</b> calls to sk_TYPE_insert(), sk_TYPE_push() or sk_TYPE_unshift() will not fail or cause memory to be allocated or reallocated. If <b>n</b> is zero, any excess space allocated in the <b>sk</b> structure is freed. On error <b>sk</b> is unchanged.</p>
<p>sk_TYPE_new_reserve() allocates a new stack. The new stack will have additional memory allocated to hold <b>n</b> elements if <b>n</b> is positive. The next <b>n</b> calls to sk_TYPE_insert(), sk_TYPE_push() or sk_TYPE_unshift() will not fail or cause memory to be allocated or reallocated. If <b>n</b> is zero or less than zero, no memory is allocated. sk_TYPE_new_reserve() also sets the comparison function <b>compare</b> to the newly created stack. If <b>compare</b> is <b>NULL</b> then no comparison function is used.</p>
<p>sk_TYPE_set_cmp_func() sets the comparison function of <b>sk</b> to <b>compare</b>. The previous comparison function is returned or <b>NULL</b> if there was no previous comparison function.</p>
<p>sk_TYPE_free() frees up the <b>sk</b> structure. It does <b>not</b> free up any elements of <b>sk</b>. After this call <b>sk</b> is no longer valid.</p>
<p>sk_TYPE_zero() sets the number of elements in <b>sk</b> to zero. It does not free <b>sk</b> so after this call <b>sk</b> is still valid.</p>
<p>sk_TYPE_pop_free() frees up all elements of <b>sk</b> and <b>sk</b> itself. The free function freefunc() is called on each element to free it.</p>
<p>sk_TYPE_delete() deletes element <b>i</b> from <b>sk</b>. It returns the deleted element or <b>NULL</b> if <b>i</b> is out of range.</p>
<p>sk_TYPE_delete_ptr() deletes element matching <b>ptr</b> from <b>sk</b>. It returns the deleted element or <b>NULL</b> if no element matching <b>ptr</b> was found.</p>
<p>sk_TYPE_insert() inserts <b>ptr</b> into <b>sk</b> at position <b>idx</b>. Any existing elements at or after <b>idx</b> are moved downwards. If <b>idx</b> is out of range the new element is appended to <b>sk</b>. sk_TYPE_insert() either returns the number of elements in <b>sk</b> after the new element is inserted or zero if an error (such as memory allocation failure) occurred.</p>
<p>sk_TYPE_push() appends <b>ptr</b> to <b>sk</b> it is equivalent to:</p>
<pre><code> <span class="variable">sk_TYPE_insert</span><span class="operator">(</span><span class="variable">sk</span><span class="operator">,</span> <span class="variable">ptr</span><span class="operator">,</span> <span class="operator">-</span><span class="number">1</span><span class="operator">);</span>
</code></pre>
<p>sk_TYPE_unshift() inserts <b>ptr</b> at the start of <b>sk</b> it is equivalent to:</p>
<pre><code> <span class="variable">sk_TYPE_insert</span><span class="operator">(</span><span class="variable">sk</span><span class="operator">,</span> <span class="variable">ptr</span><span class="operator">,</span> <span class="number">0</span><span class="operator">);</span>
</code></pre>
<p>sk_TYPE_pop() returns and removes the last element from <b>sk</b>.</p>
<p>sk_TYPE_shift() returns and removes the first element from <b>sk</b>.</p>
<p>sk_TYPE_set() sets element <b>idx</b> of <b>sk</b> to <b>ptr</b> replacing the current element. The new element value is returned or <b>NULL</b> if an error occurred: this will only happen if <b>sk</b> is <b>NULL</b> or <b>idx</b> is out of range.</p>
<p>sk_TYPE_find() searches <b>sk</b> for the element <b>ptr</b>. In the case where no comparison function has been specified, the function performs a linear search for a pointer equal to <b>ptr</b>. The index of the first matching element is returned or <b>-1</b> if there is no match. In the case where a comparison function has been specified, <b>sk</b> is sorted then sk_TYPE_find() returns the index of a matching element or <b>-1</b> if there is no match. Note that, in this case, the matching element returned is not guaranteed to be the first; the comparison function will usually compare the values pointed to rather than the pointers themselves and the order of elements in <b>sk</b> could change.</p>
<p>sk_TYPE_find_ex() operates like sk_TYPE_find() except when a comparison function has been specified and no matching element is found. Instead of returning <b>-1</b>, sk_TYPE_find_ex() returns the index of the element either before or after the location where <b>ptr</b> would be if it were present in <b>sk</b>.</p>
<p>sk_TYPE_sort() sorts <b>sk</b> using the supplied comparison function.</p>
<p>sk_TYPE_is_sorted() returns <b>1</b> if <b>sk</b> is sorted and <b>0</b> otherwise.</p>
<p>sk_TYPE_dup() returns a copy of <b>sk</b>. Note the pointers in the copy are identical to the original.</p>
<p>sk_TYPE_deep_copy() returns a new stack where each element has been copied. Copying is performed by the supplied copyfunc() and freeing by freefunc(). The function freefunc() is only called if an error occurs.</p>
<h1 id="NOTES">NOTES</h1>
<p>Care should be taken when accessing stacks in multi-threaded environments. Any operation which increases the size of a stack such as sk_TYPE_insert() or sk_push() can "grow" the size of an internal array and cause race conditions if the same stack is accessed in a different thread. Operations such as sk_find() and sk_sort() can also reorder the stack.</p>
<p>Any comparison function supplied should use a metric suitable for use in a binary search operation. That is it should return zero, a positive or negative value if <b>a</b> is equal to, greater than or less than <b>b</b> respectively.</p>
<p>Care should be taken when checking the return values of the functions sk_TYPE_find() and sk_TYPE_find_ex(). They return an index to the matching element. In particular <b>0</b> indicates a matching first element. A failed search is indicated by a <b>-1</b> return value.</p>
<p>STACK_OF(), DEFINE_STACK_OF(), DEFINE_STACK_OF_CONST(), and DEFINE_SPECIAL_STACK_OF() are implemented as macros.</p>
<p>The underlying utility <b>OPENSSL_sk_</b> API should not be used directly. It defines these functions: OPENSSL_sk_deep_copy(), OPENSSL_sk_delete(), OPENSSL_sk_delete_ptr(), OPENSSL_sk_dup(), OPENSSL_sk_find(), OPENSSL_sk_find_ex(), OPENSSL_sk_free(), OPENSSL_sk_insert(), OPENSSL_sk_is_sorted(), OPENSSL_sk_new(), OPENSSL_sk_new_null(), OPENSSL_sk_num(), OPENSSL_sk_pop(), OPENSSL_sk_pop_free(), OPENSSL_sk_push(), OPENSSL_sk_reserve(), OPENSSL_sk_set(), OPENSSL_sk_set_cmp_func(), OPENSSL_sk_shift(), OPENSSL_sk_sort(), OPENSSL_sk_unshift(), OPENSSL_sk_value(), OPENSSL_sk_zero().</p>
<h1 id="RETURN-VALUES">RETURN VALUES</h1>
<p>sk_TYPE_num() returns the number of elements in the stack or <b>-1</b> if the passed stack is <b>NULL</b>.</p>
<p>sk_TYPE_value() returns a pointer to a stack element or <b>NULL</b> if the index is out of range.</p>
<p>sk_TYPE_new(), sk_TYPE_new_null() and sk_TYPE_new_reserve() return an empty stack or <b>NULL</b> if an error occurs.</p>
<p>sk_TYPE_reserve() returns <b>1</b> on successful allocation of the required memory or <b>0</b> on error.</p>
<p>sk_TYPE_set_cmp_func() returns the old comparison function or <b>NULL</b> if there was no old comparison function.</p>
<p>sk_TYPE_free(), sk_TYPE_zero(), sk_TYPE_pop_free() and sk_TYPE_sort() do not return values.</p>
<p>sk_TYPE_pop(), sk_TYPE_shift(), sk_TYPE_delete() and sk_TYPE_delete_ptr() return a pointer to the deleted element or <b>NULL</b> on error.</p>
<p>sk_TYPE_insert(), sk_TYPE_push() and sk_TYPE_unshift() return the total number of elements in the stack and 0 if an error occurred.</p>
<p>sk_TYPE_set() returns a pointer to the replacement element or <b>NULL</b> on error.</p>
<p>sk_TYPE_find() and sk_TYPE_find_ex() return an index to the found element or <b>-1</b> on error.</p>
<p>sk_TYPE_is_sorted() returns <b>1</b> if the stack is sorted and <b>0</b> if it is not.</p>
<p>sk_TYPE_dup() and sk_TYPE_deep_copy() return a pointer to the copy of the stack.</p>
<h1 id="HISTORY">HISTORY</h1>
<p>Before OpenSSL 1.1.0, this was implemented via macros and not inline functions and was not a public API.</p>
<p>sk_TYPE_reserve() and sk_TYPE_new_reserve() were added in OpenSSL 1.1.1.</p>
<h1 id="COPYRIGHT">COPYRIGHT</h1>
<p>Copyright 2000-2017 The OpenSSL Project Authors. All Rights Reserved.</p>
<p>Licensed under the OpenSSL license (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at <a href="https://www.openssl.org/source/license.html">https://www.openssl.org/source/license.html</a>.</p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/* ../netlib/ctgevc.f -- translated by f2c (version 20100827). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */
#include "FLA_f2c.h" /* Table of constant values */
static complex c_b1 =
{
0.f,0.f
}
;
static complex c_b2 =
{
1.f,0.f
}
;
static integer c__1 = 1;
/* > \brief \b CTGEVC */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download CTGEVC + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/ctgevc. f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/ctgevc. f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/ctgevc. f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE CTGEVC( SIDE, HOWMNY, SELECT, N, S, LDS, P, LDP, VL, */
/* LDVL, VR, LDVR, MM, M, WORK, RWORK, INFO ) */
/* .. Scalar Arguments .. */
/* CHARACTER HOWMNY, SIDE */
/* INTEGER INFO, LDP, LDS, LDVL, LDVR, M, MM, N */
/* .. */
/* .. Array Arguments .. */
/* LOGICAL SELECT( * ) */
/* REAL RWORK( * ) */
/* COMPLEX P( LDP, * ), S( LDS, * ), VL( LDVL, * ), */
/* $ VR( LDVR, * ), WORK( * ) */
/* .. */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > CTGEVC computes some or all of the right and/or left eigenvectors of */
/* > a pair of complex matrices (S,P), where S and P are upper triangular. */
/* > Matrix pairs of this type are produced by the generalized Schur */
/* > factorization of a complex matrix pair (A,B): */
/* > */
/* > A = Q*S*Z**H, B = Q*P*Z**H */
/* > */
/* > as computed by CGGHRD + CHGEQZ. */
/* > */
/* > The right eigenvector x and the left eigenvector y of (S,P) */
/* > corresponding to an eigenvalue w are defined by: */
/* > */
/* > S*x = w*P*x, (y**H)*S = w*(y**H)*P, */
/* > */
/* > where y**H denotes the conjugate tranpose of y. */
/* > The eigenvalues are not input to this routine, but are computed */
/* > directly from the diagonal elements of S and P. */
/* > */
/* > This routine returns the matrices X and/or Y of right and left */
/* > eigenvectors of (S,P), or the products Z*X and/or Q*Y, */
/* > where Z and Q are input matrices. */
/* > If Q and Z are the unitary factors from the generalized Schur */
/* > factorization of a matrix pair (A,B), then Z*X and Q*Y */
/* > are the matrices of right and left eigenvectors of (A,B). */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] SIDE */
/* > \verbatim */
/* > SIDE is CHARACTER*1 */
/* > = 'R': compute right eigenvectors only;
*/
/* > = 'L': compute left eigenvectors only;
*/
/* > = 'B': compute both right and left eigenvectors. */
/* > \endverbatim */
/* > */
/* > \param[in] HOWMNY */
/* > \verbatim */
/* > HOWMNY is CHARACTER*1 */
/* > = 'A': compute all right and/or left eigenvectors;
*/
/* > = 'B': compute all right and/or left eigenvectors, */
/* > backtransformed by the matrices in VR and/or VL;
*/
/* > = 'S': compute selected right and/or left eigenvectors, */
/* > specified by the logical array SELECT. */
/* > \endverbatim */
/* > */
/* > \param[in] SELECT */
/* > \verbatim */
/* > SELECT is LOGICAL array, dimension (N) */
/* > If HOWMNY='S', SELECT specifies the eigenvectors to be */
/* > computed. The eigenvector corresponding to the j-th */
/* > eigenvalue is computed if SELECT(j) = .TRUE.. */
/* > Not referenced if HOWMNY = 'A' or 'B'. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The order of the matrices S and P. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] S */
/* > \verbatim */
/* > S is COMPLEX array, dimension (LDS,N) */
/* > The upper triangular matrix S from a generalized Schur */
/* > factorization, as computed by CHGEQZ. */
/* > \endverbatim */
/* > */
/* > \param[in] LDS */
/* > \verbatim */
/* > LDS is INTEGER */
/* > The leading dimension of array S. LDS >= max(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in] P */
/* > \verbatim */
/* > P is COMPLEX array, dimension (LDP,N) */
/* > The upper triangular matrix P from a generalized Schur */
/* > factorization, as computed by CHGEQZ. P must have real */
/* > diagonal elements. */
/* > \endverbatim */
/* > */
/* > \param[in] LDP */
/* > \verbatim */
/* > LDP is INTEGER */
/* > The leading dimension of array P. LDP >= max(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in,out] VL */
/* > \verbatim */
/* > VL is COMPLEX array, dimension (LDVL,MM) */
/* > On entry, if SIDE = 'L' or 'B' and HOWMNY = 'B', VL must */
/* > contain an N-by-N matrix Q (usually the unitary matrix Q */
/* > of left Schur vectors returned by CHGEQZ). */
/* > On exit, if SIDE = 'L' or 'B', VL contains: */
/* > if HOWMNY = 'A', the matrix Y of left eigenvectors of (S,P);
*/
/* > if HOWMNY = 'B', the matrix Q*Y;
*/
/* > if HOWMNY = 'S', the left eigenvectors of (S,P) specified by */
/* > SELECT, stored consecutively in the columns of */
/* > VL, in the same order as their eigenvalues. */
/* > Not referenced if SIDE = 'R'. */
/* > \endverbatim */
/* > */
/* > \param[in] LDVL */
/* > \verbatim */
/* > LDVL is INTEGER */
/* > The leading dimension of array VL. LDVL >= 1, and if */
/* > SIDE = 'L' or 'l' or 'B' or 'b', LDVL >= N. */
/* > \endverbatim */
/* > */
/* > \param[in,out] VR */
/* > \verbatim */
/* > VR is COMPLEX array, dimension (LDVR,MM) */
/* > On entry, if SIDE = 'R' or 'B' and HOWMNY = 'B', VR must */
/* > contain an N-by-N matrix Q (usually the unitary matrix Z */
/* > of right Schur vectors returned by CHGEQZ). */
/* > On exit, if SIDE = 'R' or 'B', VR contains: */
/* > if HOWMNY = 'A', the matrix X of right eigenvectors of (S,P);
*/
/* > if HOWMNY = 'B', the matrix Z*X;
*/
/* > if HOWMNY = 'S', the right eigenvectors of (S,P) specified by */
/* > SELECT, stored consecutively in the columns of */
/* > VR, in the same order as their eigenvalues. */
/* > Not referenced if SIDE = 'L'. */
/* > \endverbatim */
/* > */
/* > \param[in] LDVR */
/* > \verbatim */
/* > LDVR is INTEGER */
/* > The leading dimension of the array VR. LDVR >= 1, and if */
/* > SIDE = 'R' or 'B', LDVR >= N. */
/* > \endverbatim */
/* > */
/* > \param[in] MM */
/* > \verbatim */
/* > MM is INTEGER */
/* > The number of columns in the arrays VL and/or VR. MM >= M. */
/* > \endverbatim */
/* > */
/* > \param[out] M */
/* > \verbatim */
/* > M is INTEGER */
/* > The number of columns in the arrays VL and/or VR actually */
/* > used to store the eigenvectors. If HOWMNY = 'A' or 'B', M */
/* > is set to N. Each selected eigenvector occupies one column. */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is COMPLEX array, dimension (2*N) */
/* > \endverbatim */
/* > */
/* > \param[out] RWORK */
/* > \verbatim */
/* > RWORK is REAL array, dimension (2*N) */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit. */
/* > < 0: if INFO = -i, the i-th argument had an illegal value. */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date November 2011 */
/* > \ingroup complexGEcomputational */
/* ===================================================================== */
/* Subroutine */
int ctgevc_(char *side, char *howmny, logical *select, integer *n, complex *s, integer *lds, complex *p, integer *ldp, complex *vl, integer *ldvl, complex *vr, integer *ldvr, integer *mm, integer *m, complex *work, real *rwork, integer *info)
{
/* System generated locals */
integer p_dim1, p_offset, s_dim1, s_offset, vl_dim1, vl_offset, vr_dim1, vr_offset, i__1, i__2, i__3, i__4, i__5;
real r__1, r__2, r__3, r__4, r__5, r__6;
complex q__1, q__2, q__3, q__4;
/* Builtin functions */
double r_imag(complex *);
void r_cnjg(complex *, complex *);
/* Local variables */
complex d__;
integer i__, j;
complex ca, cb;
integer je, im, jr;
real big;
logical lsa, lsb;
real ulp;
complex sum;
integer ibeg, ieig, iend;
real dmin__;
integer isrc;
real temp;
complex suma, sumb;
real xmax, scale;
logical ilall;
integer iside;
real sbeta;
extern logical lsame_(char *, char *);
extern /* Subroutine */
int cgemv_(char *, integer *, integer *, complex * , complex *, integer *, complex *, integer *, complex *, complex * , integer *);
real small;
logical compl;
real anorm, bnorm;
logical compr, ilbbad;
real acoefa, bcoefa, acoeff;
complex bcoeff;
logical ilback;
extern /* Subroutine */
int slabad_(real *, real *);
real ascale, bscale;
extern /* Complex */
VOID cladiv_(complex *, complex *, complex *);
extern real slamch_(char *);
complex salpha;
real safmin;
extern /* Subroutine */
int xerbla_(char *, integer *);
real bignum;
logical ilcomp;
integer ihwmny;
/* -- LAPACK computational routine (version 3.4.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* November 2011 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Statement Functions .. */
/* .. */
/* .. Statement Function definitions .. */
/* .. */
/* .. Executable Statements .. */
/* Decode and Test the input parameters */
/* Parameter adjustments */
--select;
s_dim1 = *lds;
s_offset = 1 + s_dim1;
s -= s_offset;
p_dim1 = *ldp;
p_offset = 1 + p_dim1;
p -= p_offset;
vl_dim1 = *ldvl;
vl_offset = 1 + vl_dim1;
vl -= vl_offset;
vr_dim1 = *ldvr;
vr_offset = 1 + vr_dim1;
vr -= vr_offset;
--work;
--rwork;
/* Function Body */
if (lsame_(howmny, "A"))
{
ihwmny = 1;
ilall = TRUE_;
ilback = FALSE_;
}
else if (lsame_(howmny, "S"))
{
ihwmny = 2;
ilall = FALSE_;
ilback = FALSE_;
}
else if (lsame_(howmny, "B"))
{
ihwmny = 3;
ilall = TRUE_;
ilback = TRUE_;
}
else
{
ihwmny = -1;
}
if (lsame_(side, "R"))
{
iside = 1;
compl = FALSE_;
compr = TRUE_;
}
else if (lsame_(side, "L"))
{
iside = 2;
compl = TRUE_;
compr = FALSE_;
}
else if (lsame_(side, "B"))
{
iside = 3;
compl = TRUE_;
compr = TRUE_;
}
else
{
iside = -1;
}
*info = 0;
if (iside < 0)
{
*info = -1;
}
else if (ihwmny < 0)
{
*info = -2;
}
else if (*n < 0)
{
*info = -4;
}
else if (*lds < max(1,*n))
{
*info = -6;
}
else if (*ldp < max(1,*n))
{
*info = -8;
}
if (*info != 0)
{
i__1 = -(*info);
xerbla_("CTGEVC", &i__1);
return 0;
}
/* Count the number of eigenvectors */
if (! ilall)
{
im = 0;
i__1 = *n;
for (j = 1;
j <= i__1;
++j)
{
if (select[j])
{
++im;
}
/* L10: */
}
}
else
{
im = *n;
}
/* Check diagonal of B */
ilbbad = FALSE_;
i__1 = *n;
for (j = 1;
j <= i__1;
++j)
{
if (r_imag(&p[j + j * p_dim1]) != 0.f)
{
ilbbad = TRUE_;
}
/* L20: */
}
if (ilbbad)
{
*info = -7;
}
else if (compl && *ldvl < *n || *ldvl < 1)
{
*info = -10;
}
else if (compr && *ldvr < *n || *ldvr < 1)
{
*info = -12;
}
else if (*mm < im)
{
*info = -13;
}
if (*info != 0)
{
i__1 = -(*info);
xerbla_("CTGEVC", &i__1);
return 0;
}
/* Quick return if possible */
*m = im;
if (*n == 0)
{
return 0;
}
/* Machine Constants */
safmin = slamch_("Safe minimum");
big = 1.f / safmin;
slabad_(&safmin, &big);
ulp = slamch_("Epsilon") * slamch_("Base");
small = safmin * *n / ulp;
big = 1.f / small;
bignum = 1.f / (safmin * *n);
/* Compute the 1-norm of each column of the strictly upper triangular */
/* part of A and B to check for possible overflow in the triangular */
/* solver. */
i__1 = s_dim1 + 1;
anorm = (r__1 = s[i__1].r, f2c_abs(r__1)) + (r__2 = r_imag(&s[s_dim1 + 1]), f2c_abs(r__2));
i__1 = p_dim1 + 1;
bnorm = (r__1 = p[i__1].r, f2c_abs(r__1)) + (r__2 = r_imag(&p[p_dim1 + 1]), f2c_abs(r__2));
rwork[1] = 0.f;
rwork[*n + 1] = 0.f;
i__1 = *n;
for (j = 2;
j <= i__1;
++j)
{
rwork[j] = 0.f;
rwork[*n + j] = 0.f;
i__2 = j - 1;
for (i__ = 1;
i__ <= i__2;
++i__)
{
i__3 = i__ + j * s_dim1;
rwork[j] += (r__1 = s[i__3].r, f2c_abs(r__1)) + (r__2 = r_imag(&s[i__ + j * s_dim1]), f2c_abs(r__2));
i__3 = i__ + j * p_dim1;
rwork[*n + j] += (r__1 = p[i__3].r, f2c_abs(r__1)) + (r__2 = r_imag(& p[i__ + j * p_dim1]), f2c_abs(r__2));
/* L30: */
}
/* Computing MAX */
i__2 = j + j * s_dim1;
r__3 = anorm;
r__4 = rwork[j] + ((r__1 = s[i__2].r, f2c_abs(r__1)) + ( r__2 = r_imag(&s[j + j * s_dim1]), f2c_abs(r__2))); // , expr subst
anorm = max(r__3,r__4);
/* Computing MAX */
i__2 = j + j * p_dim1;
r__3 = bnorm;
r__4 = rwork[*n + j] + ((r__1 = p[i__2].r, f2c_abs(r__1)) + (r__2 = r_imag(&p[j + j * p_dim1]), f2c_abs(r__2))); // , expr subst
bnorm = max(r__3,r__4);
/* L40: */
}
ascale = 1.f / max(anorm,safmin);
bscale = 1.f / max(bnorm,safmin);
/* Left eigenvectors */
if (compl)
{
ieig = 0;
/* Main loop over eigenvalues */
i__1 = *n;
for (je = 1;
je <= i__1;
++je)
{
if (ilall)
{
ilcomp = TRUE_;
}
else
{
ilcomp = select[je];
}
if (ilcomp)
{
++ieig;
i__2 = je + je * s_dim1;
i__3 = je + je * p_dim1;
if ((r__2 = s[i__2].r, f2c_abs(r__2)) + (r__3 = r_imag(&s[je + je * s_dim1]), f2c_abs(r__3)) <= safmin && (r__1 = p[i__3].r, f2c_abs(r__1)) <= safmin)
{
/* Singular matrix pencil -- return unit eigenvector */
i__2 = *n;
for (jr = 1;
jr <= i__2;
++jr)
{
i__3 = jr + ieig * vl_dim1;
vl[i__3].r = 0.f;
vl[i__3].i = 0.f; // , expr subst
/* L50: */
}
i__2 = ieig + ieig * vl_dim1;
vl[i__2].r = 1.f;
vl[i__2].i = 0.f; // , expr subst
goto L140;
}
/* Non-singular eigenvalue: */
/* Compute coefficients a and b in */
/* H */
/* y ( a A - b B ) = 0 */
/* Computing MAX */
i__2 = je + je * s_dim1;
i__3 = je + je * p_dim1;
r__4 = ((r__2 = s[i__2].r, f2c_abs(r__2)) + (r__3 = r_imag(&s[je + je * s_dim1]), f2c_abs(r__3))) * ascale;
r__5 = (r__1 = p[i__3].r, f2c_abs(r__1)) * bscale;
r__4 = max(r__4,r__5); // ; expr subst
temp = 1.f / max(r__4,safmin);
i__2 = je + je * s_dim1;
q__2.r = temp * s[i__2].r;
q__2.i = temp * s[i__2].i; // , expr subst
q__1.r = ascale * q__2.r;
q__1.i = ascale * q__2.i; // , expr subst
salpha.r = q__1.r;
salpha.i = q__1.i; // , expr subst
i__2 = je + je * p_dim1;
sbeta = temp * p[i__2].r * bscale;
acoeff = sbeta * ascale;
q__1.r = bscale * salpha.r;
q__1.i = bscale * salpha.i; // , expr subst
bcoeff.r = q__1.r;
bcoeff.i = q__1.i; // , expr subst
/* Scale to avoid underflow */
lsa = f2c_abs(sbeta) >= safmin && f2c_abs(acoeff) < small;
lsb = (r__1 = salpha.r, f2c_abs(r__1)) + (r__2 = r_imag(&salpha), f2c_abs(r__2)) >= safmin && (r__3 = bcoeff.r, f2c_abs(r__3)) + (r__4 = r_imag(&bcoeff), f2c_abs(r__4)) < small;
scale = 1.f;
if (lsa)
{
scale = small / f2c_abs(sbeta) * min(anorm,big);
}
if (lsb)
{
/* Computing MAX */
r__3 = scale;
r__4 = small / ((r__1 = salpha.r, f2c_abs(r__1)) + (r__2 = r_imag(&salpha), f2c_abs(r__2))) * min( bnorm,big); // , expr subst
scale = max(r__3,r__4);
}
if (lsa || lsb)
{
/* Computing MIN */
/* Computing MAX */
r__5 = 1.f, r__6 = f2c_abs(acoeff);
r__5 = max(r__5,r__6);
r__6 = (r__1 = bcoeff.r, f2c_abs(r__1)) + (r__2 = r_imag(&bcoeff), f2c_abs(r__2)); // ; expr subst
r__3 = scale;
r__4 = 1.f / (safmin * max(r__5,r__6)); // , expr subst
scale = min(r__3,r__4);
if (lsa)
{
acoeff = ascale * (scale * sbeta);
}
else
{
acoeff = scale * acoeff;
}
if (lsb)
{
q__2.r = scale * salpha.r;
q__2.i = scale * salpha.i; // , expr subst
q__1.r = bscale * q__2.r;
q__1.i = bscale * q__2.i; // , expr subst
bcoeff.r = q__1.r;
bcoeff.i = q__1.i; // , expr subst
}
else
{
q__1.r = scale * bcoeff.r;
q__1.i = scale * bcoeff.i; // , expr subst
bcoeff.r = q__1.r;
bcoeff.i = q__1.i; // , expr subst
}
}
acoefa = f2c_abs(acoeff);
bcoefa = (r__1 = bcoeff.r, f2c_abs(r__1)) + (r__2 = r_imag(& bcoeff), f2c_abs(r__2));
xmax = 1.f;
i__2 = *n;
for (jr = 1;
jr <= i__2;
++jr)
{
i__3 = jr;
work[i__3].r = 0.f;
work[i__3].i = 0.f; // , expr subst
/* L60: */
}
i__2 = je;
work[i__2].r = 1.f;
work[i__2].i = 0.f; // , expr subst
/* Computing MAX */
r__1 = ulp * acoefa * anorm;
r__2 = ulp * bcoefa * bnorm;
r__1 = max(r__1,r__2); // ; expr subst
dmin__ = max(r__1,safmin);
/* H */
/* Triangular solve of (a A - b B) y = 0 */
/* H */
/* (rowwise in (a A - b B) , or columnwise in a A - b B) */
i__2 = *n;
for (j = je + 1;
j <= i__2;
++j)
{
/* Compute */
/* j-1 */
/* SUM = sum conjg( a*S(k,j) - b*P(k,j) )*x(k) */
/* k=je */
/* (Scale if necessary) */
temp = 1.f / xmax;
if (acoefa * rwork[j] + bcoefa * rwork[*n + j] > bignum * temp)
{
i__3 = j - 1;
for (jr = je;
jr <= i__3;
++jr)
{
i__4 = jr;
i__5 = jr;
q__1.r = temp * work[i__5].r;
q__1.i = temp * work[i__5].i; // , expr subst
work[i__4].r = q__1.r;
work[i__4].i = q__1.i; // , expr subst
/* L70: */
}
xmax = 1.f;
}
suma.r = 0.f;
suma.i = 0.f; // , expr subst
sumb.r = 0.f;
sumb.i = 0.f; // , expr subst
i__3 = j - 1;
for (jr = je;
jr <= i__3;
++jr)
{
r_cnjg(&q__3, &s[jr + j * s_dim1]);
i__4 = jr;
q__2.r = q__3.r * work[i__4].r - q__3.i * work[i__4] .i;
q__2.i = q__3.r * work[i__4].i + q__3.i * work[i__4].r; // , expr subst
q__1.r = suma.r + q__2.r;
q__1.i = suma.i + q__2.i; // , expr subst
suma.r = q__1.r;
suma.i = q__1.i; // , expr subst
r_cnjg(&q__3, &p[jr + j * p_dim1]);
i__4 = jr;
q__2.r = q__3.r * work[i__4].r - q__3.i * work[i__4] .i;
q__2.i = q__3.r * work[i__4].i + q__3.i * work[i__4].r; // , expr subst
q__1.r = sumb.r + q__2.r;
q__1.i = sumb.i + q__2.i; // , expr subst
sumb.r = q__1.r;
sumb.i = q__1.i; // , expr subst
/* L80: */
}
q__2.r = acoeff * suma.r;
q__2.i = acoeff * suma.i; // , expr subst
r_cnjg(&q__4, &bcoeff);
q__3.r = q__4.r * sumb.r - q__4.i * sumb.i;
q__3.i = q__4.r * sumb.i + q__4.i * sumb.r; // , expr subst
q__1.r = q__2.r - q__3.r;
q__1.i = q__2.i - q__3.i; // , expr subst
sum.r = q__1.r;
sum.i = q__1.i; // , expr subst
/* Form x(j) = - SUM / conjg( a*S(j,j) - b*P(j,j) ) */
/* with scaling and perturbation of the denominator */
i__3 = j + j * s_dim1;
q__3.r = acoeff * s[i__3].r;
q__3.i = acoeff * s[i__3].i; // , expr subst
i__4 = j + j * p_dim1;
q__4.r = bcoeff.r * p[i__4].r - bcoeff.i * p[i__4].i;
q__4.i = bcoeff.r * p[i__4].i + bcoeff.i * p[i__4] .r; // , expr subst
q__2.r = q__3.r - q__4.r;
q__2.i = q__3.i - q__4.i; // , expr subst
r_cnjg(&q__1, &q__2);
d__.r = q__1.r;
d__.i = q__1.i; // , expr subst
if ((r__1 = d__.r, f2c_abs(r__1)) + (r__2 = r_imag(&d__), f2c_abs( r__2)) <= dmin__)
{
q__1.r = dmin__;
q__1.i = 0.f; // , expr subst
d__.r = q__1.r;
d__.i = q__1.i; // , expr subst
}
if ((r__1 = d__.r, f2c_abs(r__1)) + (r__2 = r_imag(&d__), f2c_abs( r__2)) < 1.f)
{
if ((r__1 = sum.r, f2c_abs(r__1)) + (r__2 = r_imag(&sum), f2c_abs(r__2)) >= bignum * ((r__3 = d__.r, f2c_abs( r__3)) + (r__4 = r_imag(&d__), f2c_abs(r__4))))
{
temp = 1.f / ((r__1 = sum.r, f2c_abs(r__1)) + (r__2 = r_imag(&sum), f2c_abs(r__2)));
i__3 = j - 1;
for (jr = je;
jr <= i__3;
++jr)
{
i__4 = jr;
i__5 = jr;
q__1.r = temp * work[i__5].r;
q__1.i = temp * work[i__5].i; // , expr subst
work[i__4].r = q__1.r;
work[i__4].i = q__1.i; // , expr subst
/* L90: */
}
xmax = temp * xmax;
q__1.r = temp * sum.r;
q__1.i = temp * sum.i; // , expr subst
sum.r = q__1.r;
sum.i = q__1.i; // , expr subst
}
}
i__3 = j;
q__2.r = -sum.r;
q__2.i = -sum.i; // , expr subst
cladiv_(&q__1, &q__2, &d__);
work[i__3].r = q__1.r;
work[i__3].i = q__1.i; // , expr subst
/* Computing MAX */
i__3 = j;
r__3 = xmax;
r__4 = (r__1 = work[i__3].r, f2c_abs(r__1)) + ( r__2 = r_imag(&work[j]), f2c_abs(r__2)); // , expr subst
xmax = max(r__3,r__4);
/* L100: */
}
/* Back transform eigenvector if HOWMNY='B'. */
if (ilback)
{
i__2 = *n + 1 - je;
cgemv_("N", n, &i__2, &c_b2, &vl[je * vl_dim1 + 1], ldvl, &work[je], &c__1, &c_b1, &work[*n + 1], &c__1);
isrc = 2;
ibeg = 1;
}
else
{
isrc = 1;
ibeg = je;
}
/* Copy and scale eigenvector into column of VL */
xmax = 0.f;
i__2 = *n;
for (jr = ibeg;
jr <= i__2;
++jr)
{
/* Computing MAX */
i__3 = (isrc - 1) * *n + jr;
r__3 = xmax;
r__4 = (r__1 = work[i__3].r, f2c_abs(r__1)) + ( r__2 = r_imag(&work[(isrc - 1) * *n + jr]), f2c_abs( r__2)); // , expr subst
xmax = max(r__3,r__4);
/* L110: */
}
if (xmax > safmin)
{
temp = 1.f / xmax;
i__2 = *n;
for (jr = ibeg;
jr <= i__2;
++jr)
{
i__3 = jr + ieig * vl_dim1;
i__4 = (isrc - 1) * *n + jr;
q__1.r = temp * work[i__4].r;
q__1.i = temp * work[ i__4].i; // , expr subst
vl[i__3].r = q__1.r;
vl[i__3].i = q__1.i; // , expr subst
/* L120: */
}
}
else
{
ibeg = *n + 1;
}
i__2 = ibeg - 1;
for (jr = 1;
jr <= i__2;
++jr)
{
i__3 = jr + ieig * vl_dim1;
vl[i__3].r = 0.f;
vl[i__3].i = 0.f; // , expr subst
/* L130: */
}
}
L140:
;
}
}
/* Right eigenvectors */
if (compr)
{
ieig = im + 1;
/* Main loop over eigenvalues */
for (je = *n;
je >= 1;
--je)
{
if (ilall)
{
ilcomp = TRUE_;
}
else
{
ilcomp = select[je];
}
if (ilcomp)
{
--ieig;
i__1 = je + je * s_dim1;
i__2 = je + je * p_dim1;
if ((r__2 = s[i__1].r, f2c_abs(r__2)) + (r__3 = r_imag(&s[je + je * s_dim1]), f2c_abs(r__3)) <= safmin && (r__1 = p[i__2].r, f2c_abs(r__1)) <= safmin)
{
/* Singular matrix pencil -- return unit eigenvector */
i__1 = *n;
for (jr = 1;
jr <= i__1;
++jr)
{
i__2 = jr + ieig * vr_dim1;
vr[i__2].r = 0.f;
vr[i__2].i = 0.f; // , expr subst
/* L150: */
}
i__1 = ieig + ieig * vr_dim1;
vr[i__1].r = 1.f;
vr[i__1].i = 0.f; // , expr subst
goto L250;
}
/* Non-singular eigenvalue: */
/* Compute coefficients a and b in */
/* ( a A - b B ) x = 0 */
/* Computing MAX */
i__1 = je + je * s_dim1;
i__2 = je + je * p_dim1;
r__4 = ((r__2 = s[i__1].r, f2c_abs(r__2)) + (r__3 = r_imag(&s[je + je * s_dim1]), f2c_abs(r__3))) * ascale;
r__5 = (r__1 = p[i__2].r, f2c_abs(r__1)) * bscale;
r__4 = max(r__4,r__5); // ; expr subst
temp = 1.f / max(r__4,safmin);
i__1 = je + je * s_dim1;
q__2.r = temp * s[i__1].r;
q__2.i = temp * s[i__1].i; // , expr subst
q__1.r = ascale * q__2.r;
q__1.i = ascale * q__2.i; // , expr subst
salpha.r = q__1.r;
salpha.i = q__1.i; // , expr subst
i__1 = je + je * p_dim1;
sbeta = temp * p[i__1].r * bscale;
acoeff = sbeta * ascale;
q__1.r = bscale * salpha.r;
q__1.i = bscale * salpha.i; // , expr subst
bcoeff.r = q__1.r;
bcoeff.i = q__1.i; // , expr subst
/* Scale to avoid underflow */
lsa = f2c_abs(sbeta) >= safmin && f2c_abs(acoeff) < small;
lsb = (r__1 = salpha.r, f2c_abs(r__1)) + (r__2 = r_imag(&salpha), f2c_abs(r__2)) >= safmin && (r__3 = bcoeff.r, f2c_abs(r__3)) + (r__4 = r_imag(&bcoeff), f2c_abs(r__4)) < small;
scale = 1.f;
if (lsa)
{
scale = small / f2c_abs(sbeta) * min(anorm,big);
}
if (lsb)
{
/* Computing MAX */
r__3 = scale;
r__4 = small / ((r__1 = salpha.r, f2c_abs(r__1)) + (r__2 = r_imag(&salpha), f2c_abs(r__2))) * min( bnorm,big); // , expr subst
scale = max(r__3,r__4);
}
if (lsa || lsb)
{
/* Computing MIN */
/* Computing MAX */
r__5 = 1.f, r__6 = f2c_abs(acoeff);
r__5 = max(r__5,r__6);
r__6 = (r__1 = bcoeff.r, f2c_abs(r__1)) + (r__2 = r_imag(&bcoeff), f2c_abs(r__2)); // ; expr subst
r__3 = scale;
r__4 = 1.f / (safmin * max(r__5,r__6)); // , expr subst
scale = min(r__3,r__4);
if (lsa)
{
acoeff = ascale * (scale * sbeta);
}
else
{
acoeff = scale * acoeff;
}
if (lsb)
{
q__2.r = scale * salpha.r;
q__2.i = scale * salpha.i; // , expr subst
q__1.r = bscale * q__2.r;
q__1.i = bscale * q__2.i; // , expr subst
bcoeff.r = q__1.r;
bcoeff.i = q__1.i; // , expr subst
}
else
{
q__1.r = scale * bcoeff.r;
q__1.i = scale * bcoeff.i; // , expr subst
bcoeff.r = q__1.r;
bcoeff.i = q__1.i; // , expr subst
}
}
acoefa = f2c_abs(acoeff);
bcoefa = (r__1 = bcoeff.r, f2c_abs(r__1)) + (r__2 = r_imag(& bcoeff), f2c_abs(r__2));
xmax = 1.f;
i__1 = *n;
for (jr = 1;
jr <= i__1;
++jr)
{
i__2 = jr;
work[i__2].r = 0.f;
work[i__2].i = 0.f; // , expr subst
/* L160: */
}
i__1 = je;
work[i__1].r = 1.f;
work[i__1].i = 0.f; // , expr subst
/* Computing MAX */
r__1 = ulp * acoefa * anorm;
r__2 = ulp * bcoefa * bnorm;
r__1 = max(r__1,r__2); // ; expr subst
dmin__ = max(r__1,safmin);
/* Triangular solve of (a A - b B) x = 0 (columnwise) */
/* WORK(1:j-1) contains sums w, */
/* WORK(j+1:JE) contains x */
i__1 = je - 1;
for (jr = 1;
jr <= i__1;
++jr)
{
i__2 = jr;
i__3 = jr + je * s_dim1;
q__2.r = acoeff * s[i__3].r;
q__2.i = acoeff * s[i__3].i; // , expr subst
i__4 = jr + je * p_dim1;
q__3.r = bcoeff.r * p[i__4].r - bcoeff.i * p[i__4].i;
q__3.i = bcoeff.r * p[i__4].i + bcoeff.i * p[i__4] .r; // , expr subst
q__1.r = q__2.r - q__3.r;
q__1.i = q__2.i - q__3.i; // , expr subst
work[i__2].r = q__1.r;
work[i__2].i = q__1.i; // , expr subst
/* L170: */
}
i__1 = je;
work[i__1].r = 1.f;
work[i__1].i = 0.f; // , expr subst
for (j = je - 1;
j >= 1;
--j)
{
/* Form x(j) := - w(j) / d */
/* with scaling and perturbation of the denominator */
i__1 = j + j * s_dim1;
q__2.r = acoeff * s[i__1].r;
q__2.i = acoeff * s[i__1].i; // , expr subst
i__2 = j + j * p_dim1;
q__3.r = bcoeff.r * p[i__2].r - bcoeff.i * p[i__2].i;
q__3.i = bcoeff.r * p[i__2].i + bcoeff.i * p[i__2] .r; // , expr subst
q__1.r = q__2.r - q__3.r;
q__1.i = q__2.i - q__3.i; // , expr subst
d__.r = q__1.r;
d__.i = q__1.i; // , expr subst
if ((r__1 = d__.r, f2c_abs(r__1)) + (r__2 = r_imag(&d__), f2c_abs( r__2)) <= dmin__)
{
q__1.r = dmin__;
q__1.i = 0.f; // , expr subst
d__.r = q__1.r;
d__.i = q__1.i; // , expr subst
}
if ((r__1 = d__.r, f2c_abs(r__1)) + (r__2 = r_imag(&d__), f2c_abs( r__2)) < 1.f)
{
i__1 = j;
if ((r__1 = work[i__1].r, f2c_abs(r__1)) + (r__2 = r_imag( &work[j]), f2c_abs(r__2)) >= bignum * ((r__3 = d__.r, f2c_abs(r__3)) + (r__4 = r_imag(&d__), f2c_abs( r__4))))
{
i__1 = j;
temp = 1.f / ((r__1 = work[i__1].r, f2c_abs(r__1)) + ( r__2 = r_imag(&work[j]), f2c_abs(r__2)));
i__1 = je;
for (jr = 1;
jr <= i__1;
++jr)
{
i__2 = jr;
i__3 = jr;
q__1.r = temp * work[i__3].r;
q__1.i = temp * work[i__3].i; // , expr subst
work[i__2].r = q__1.r;
work[i__2].i = q__1.i; // , expr subst
/* L180: */
}
}
}
i__1 = j;
i__2 = j;
q__2.r = -work[i__2].r;
q__2.i = -work[i__2].i; // , expr subst
cladiv_(&q__1, &q__2, &d__);
work[i__1].r = q__1.r;
work[i__1].i = q__1.i; // , expr subst
if (j > 1)
{
/* w = w + x(j)*(a S(*,j) - b P(*,j) ) with scaling */
i__1 = j;
if ((r__1 = work[i__1].r, f2c_abs(r__1)) + (r__2 = r_imag( &work[j]), f2c_abs(r__2)) > 1.f)
{
i__1 = j;
temp = 1.f / ((r__1 = work[i__1].r, f2c_abs(r__1)) + ( r__2 = r_imag(&work[j]), f2c_abs(r__2)));
if (acoefa * rwork[j] + bcoefa * rwork[*n + j] >= bignum * temp)
{
i__1 = je;
for (jr = 1;
jr <= i__1;
++jr)
{
i__2 = jr;
i__3 = jr;
q__1.r = temp * work[i__3].r;
q__1.i = temp * work[i__3].i; // , expr subst
work[i__2].r = q__1.r;
work[i__2].i = q__1.i; // , expr subst
/* L190: */
}
}
}
i__1 = j;
q__1.r = acoeff * work[i__1].r;
q__1.i = acoeff * work[i__1].i; // , expr subst
ca.r = q__1.r;
ca.i = q__1.i; // , expr subst
i__1 = j;
q__1.r = bcoeff.r * work[i__1].r - bcoeff.i * work[ i__1].i;
q__1.i = bcoeff.r * work[i__1].i + bcoeff.i * work[i__1].r; // , expr subst
cb.r = q__1.r;
cb.i = q__1.i; // , expr subst
i__1 = j - 1;
for (jr = 1;
jr <= i__1;
++jr)
{
i__2 = jr;
i__3 = jr;
i__4 = jr + j * s_dim1;
q__3.r = ca.r * s[i__4].r - ca.i * s[i__4].i;
q__3.i = ca.r * s[i__4].i + ca.i * s[i__4] .r; // , expr subst
q__2.r = work[i__3].r + q__3.r;
q__2.i = work[ i__3].i + q__3.i; // , expr subst
i__5 = jr + j * p_dim1;
q__4.r = cb.r * p[i__5].r - cb.i * p[i__5].i;
q__4.i = cb.r * p[i__5].i + cb.i * p[i__5] .r; // , expr subst
q__1.r = q__2.r - q__4.r;
q__1.i = q__2.i - q__4.i; // , expr subst
work[i__2].r = q__1.r;
work[i__2].i = q__1.i; // , expr subst
/* L200: */
}
}
/* L210: */
}
/* Back transform eigenvector if HOWMNY='B'. */
if (ilback)
{
cgemv_("N", n, &je, &c_b2, &vr[vr_offset], ldvr, &work[1], &c__1, &c_b1, &work[*n + 1], &c__1);
isrc = 2;
iend = *n;
}
else
{
isrc = 1;
iend = je;
}
/* Copy and scale eigenvector into column of VR */
xmax = 0.f;
i__1 = iend;
for (jr = 1;
jr <= i__1;
++jr)
{
/* Computing MAX */
i__2 = (isrc - 1) * *n + jr;
r__3 = xmax;
r__4 = (r__1 = work[i__2].r, f2c_abs(r__1)) + ( r__2 = r_imag(&work[(isrc - 1) * *n + jr]), f2c_abs( r__2)); // , expr subst
xmax = max(r__3,r__4);
/* L220: */
}
if (xmax > safmin)
{
temp = 1.f / xmax;
i__1 = iend;
for (jr = 1;
jr <= i__1;
++jr)
{
i__2 = jr + ieig * vr_dim1;
i__3 = (isrc - 1) * *n + jr;
q__1.r = temp * work[i__3].r;
q__1.i = temp * work[ i__3].i; // , expr subst
vr[i__2].r = q__1.r;
vr[i__2].i = q__1.i; // , expr subst
/* L230: */
}
}
else
{
iend = 0;
}
i__1 = *n;
for (jr = iend + 1;
jr <= i__1;
++jr)
{
i__2 = jr + ieig * vr_dim1;
vr[i__2].r = 0.f;
vr[i__2].i = 0.f; // , expr subst
/* L240: */
}
}
L250:
;
}
}
return 0;
/* End of CTGEVC */
}
/* ctgevc_ */
| {
"pile_set_name": "Github"
} |
(define var "goose")
;; Any reference to var here will be bound to "goose"
(let* ((var1 10)
(var2 (+ var1 12)))
;; But the definition of var1 could not refer to var2
) | {
"pile_set_name": "Github"
} |
/*
* /MathJax/jax/output/HTML-CSS/fonts/TeX/WinIE6/Regular/Bold.js
*
* Copyright (c) 2009-2017 The MathJax Consortium
*
* 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.
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.MathJax_WinIE6,{57920:[518,17,1150,64,1084],57921:[694,193,575,14,561],57922:[518,17,1150,65,1085],57923:[694,194,575,14,561],57924:[518,17,1150,64,1085],57925:[767,267,575,14,561],57926:[724,194,1150,64,1084],57927:[724,193,1150,64,1085],57928:[694,224,1150,65,1085],57929:[694,224,1150,64,1085],57930:[547,46,1150,64,1084],57931:[547,46,1150,47,1102],57932:[694,16,639,1,640],57933:[710,17,628,60,657],57934:[694,-1,639,64,574],57935:[686,24,958,56,901],57936:[587,86,767,97,670],57937:[587,86,767,96,670],57938:[750,250,575,63,511],57939:[820,180,958,78,988],57940:[451,8,894,65,830],57941:[452,8,1150,65,1084],57942:[714,0,722,55,676],57943:[750,249,319,129,190],57944:[750,248,575,145,430],57945:[604,17,767,64,702],57946:[604,16,767,64,702],57947:[603,16,767,64,702],57948:[604,16,767,64,702],57949:[711,211,569,64,632],57950:[391,-109,894,64,828],57951:[524,-32,894,64,829],57952:[711,210,894,64,829],57953:[505,3,894,64,829],57954:[697,199,894,96,797],57955:[697,199,894,96,797],57956:[617,116,1150,64,1085],57957:[618,116,1150,64,1085],57958:[587,85,894,96,797],57959:[587,86,894,96,796],57960:[697,199,894,96,797],57961:[697,199,894,96,796],57962:[632,132,894,64,828],57963:[632,132,894,64,828],57964:[693,-1,894,65,829],57965:[711,-1,1022,69,953],57966:[500,210,1022,68,953],57967:[711,211,1150,65,1084],57968:[719,129,894,64,829],57969:[711,24,894,65,828],57970:[719,154,894,64,828],57971:[719,129,894,32,861],57972:[750,17,447,64,381],57973:[741,223,447,57,389],57974:[724,224,447,63,382]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/WinIE6/Regular/Bold.js");
| {
"pile_set_name": "Github"
} |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.clustering.infinispan.subsystem;
import org.infinispan.Cache;
import org.infinispan.interceptors.AsyncInterceptor;
import org.jboss.as.clustering.controller.FunctionExecutorRegistry;
/**
* Executor for metrics based on a cache interceptor.
* @author Paul Ferraro
*/
public class CacheInterceptorOperationExecutor<I extends AsyncInterceptor> extends CacheOperationExecutor<I> {
private final Class<I> interceptorClass;
public CacheInterceptorOperationExecutor(FunctionExecutorRegistry<Cache<?, ?>> executors, Class<I> interceptorClass) {
super(executors);
this.interceptorClass = interceptorClass;
}
@Override
public I apply(Cache<?, ?> cache) {
return cache.getAdvancedCache().getAsyncInterceptorChain().findInterceptorExtending(this.interceptorClass);
}
}
| {
"pile_set_name": "Github"
} |
//
// CKFetchShareMetadataOperation.h
// CloudKit
//
// Copyright © 2016 Apple Inc. All rights reserved.
//
#import <CloudKit/CKOperation.h>
/* Since you can't know what container this share is in before you fetch its metadata, you may run this operation in any container you have access to */
@class CKShareMetadata, CKFetchShareMetadataOptions;
NS_ASSUME_NONNULL_BEGIN
API_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0))
@interface CKFetchShareMetadataOperation : CKOperation
- (instancetype)init NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithShareURLs:(NSArray<NSURL *> *)shareURLs;
@property (nonatomic, copy, nullable) NSArray<NSURL *> *shareURLs;
/* If set to YES, the resulting CKShareMetadata will have a rootRecord object filled out. Defaults to NO.
The resulting CKShareMetadata will have a rootRecordID property regardless of the value of this property. */
@property (nonatomic, assign) BOOL shouldFetchRootRecord;
/* Declares which user-defined keys should be fetched and added to the resulting rootRecord. Only consulted if shouldFetchRootRecord is YES.
If nil, declares the entire root record should be downloaded. If set to an empty array, declares that no user fields should be downloaded. Defaults to nil. */
@property (nonatomic, copy, nullable) NSArray<NSString *> *rootRecordDesiredKeys;
@property (nonatomic, copy, nullable) void (^perShareMetadataBlock)(NSURL *shareURL, CKShareMetadata * _Nullable shareMetadata, NSError * _Nullable error);
@property (nonatomic, copy, nullable) void (^fetchShareMetadataCompletionBlock)(NSError * _Nullable operationError);
@end
NS_ASSUME_NONNULL_END
| {
"pile_set_name": "Github"
} |
/*
* arLabelingSub*.c
* ARToolKit5
*
* This file is part of ARToolKit.
*
* ARToolKit is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARToolKit 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 ARToolKit. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules, and to
* copy and distribute the resulting executable under terms of your choice,
* provided that you also meet, for each linked independent module, the terms and
* conditions of the license of that module. An independent module is a module
* which is neither derived from nor based on this library. If you modify this
* library, you may extend this exception to your version of the library, but you
* are not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version.
*
* Copyright 2015 Daqri, LLC.
* Copyright 2003-2015 ARToolworks, Inc.
*
* Author(s): Hirokazu Kato, Philip Lamb
*
*/
#undef AR_PIXEL_FORMAT_CCC
#undef AR_PIXEL_FORMAT_CCCA
#undef AR_PIXEL_FORMAT_ACCC
#define AR_PIXEL_FORMAT_C
#undef AR_PIXEL_FORMAT_CY
#undef AR_PIXEL_FORMAT_YC
#undef AR_PIXEL_FORMAT_CCC_565
#undef AR_PIXEL_FORMAT_CCCA_5551
#undef AR_PIXEL_FORMAT_CCCA_4444
#undef AR_LABELING_DEBUG_ENABLE_F
#undef AR_LABELING_WHITE_REGION_F
#undef AR_LABELING_FRAME_IMAGE_F
#undef AR_LABELING_ADAPTIVE
#include "arLabelingSub.h"
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<script type="text/javascript" src="//use.typekit.net/jbn8qxr.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<link rel="stylesheet" href="../../css/drop.css" />
<link rel="stylesheet" href="../../css/drop-tooltip-theme-arrows.css" />
<style>
body {
font-family: "proxima-nova", "Helvetica Neue", sans-serif;
color: #444;
}
.scroll-parent {
margin: 200px;
height: 300px;
width: 300px;
display: inline-block;
overflow: auto;
border: 2px solid #eee;
padding: 40px;
}
</style>
</head>
<body>
<div class="scroll-parent">
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="top center">Tooltip on Top</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="bottom center">Tooltip on Bottom</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="left middle">Tooltip on Left</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="right middle">Tooltip on Right</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="bottom left">Tooltip on Bottom Left</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="bottom right">Tooltip on Bottom Right</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="top left">Tooltip on Top Left</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="top right">Tooltip on Top Right</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="left bottom">Tooltip on Left Bottom</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="left top">Tooltip on Left Top</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="right bottom">Tooltip on Right Bottom</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
<p><a href="javascript:;" class="drop-tooltip" data-tooltip-content="Whoa, I'm a tooltip" data-attach="right top">Tooltip on Right Top</a></p>
<p>This is a paragraph of text</p>
<p>This is a paragraph of text</p>
</div>
<script src="../resources/js/log.js"></script>
<script src="../resources/js/jquery.js"></script>
<script src="../../utils.js"></script>
<script src="../../tether.js"></script>
<script src="/drop/drop.min.js"></script>
<script src="../../tooltip.js"></script>
<script src="../../constraint.js"></script>
<script>
$('.drop-tooltip').each(function(){
new Tooltip({
el: this,
attach: $(this).data('attach')
});
});
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
CHRUBY_VERSION="0.3.9"
RUBIES=()
for dir in "$PREFIX/opt/rubies" "$HOME/.rubies"; do
[[ -d "$dir" && -n "$(ls -A "$dir")" ]] && RUBIES+=("$dir"/*)
done
unset dir
function chruby_reset()
{
[[ -z "$RUBY_ROOT" ]] && return
PATH=":$PATH:"; PATH="${PATH//:$RUBY_ROOT\/bin:/:}"
[[ -n "$GEM_ROOT" ]] && PATH="${PATH//:$GEM_ROOT\/bin:/:}"
if (( UID != 0 )); then
[[ -n "$GEM_HOME" ]] && PATH="${PATH//:$GEM_HOME\/bin:/:}"
GEM_PATH=":$GEM_PATH:"
[[ -n "$GEM_HOME" ]] && GEM_PATH="${GEM_PATH//:$GEM_HOME:/:}"
[[ -n "$GEM_ROOT" ]] && GEM_PATH="${GEM_PATH//:$GEM_ROOT:/:}"
GEM_PATH="${GEM_PATH#:}"; GEM_PATH="${GEM_PATH%:}"
unset GEM_HOME
[[ -z "$GEM_PATH" ]] && unset GEM_PATH
fi
PATH="${PATH#:}"; PATH="${PATH%:}"
unset RUBY_ROOT RUBY_ENGINE RUBY_VERSION RUBYOPT GEM_ROOT
hash -r
}
function chruby_use()
{
if [[ ! -x "$1/bin/ruby" ]]; then
echo "chruby: $1/bin/ruby not executable" >&2
return 1
fi
[[ -n "$RUBY_ROOT" ]] && chruby_reset
export RUBY_ROOT="$1"
export RUBYOPT="$2"
export PATH="$RUBY_ROOT/bin:$PATH"
eval "$(RUBYGEMS_GEMDEPS="" "$RUBY_ROOT/bin/ruby" - <<EOF
puts "export RUBY_ENGINE=#{Object.const_defined?(:RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'};"
puts "export RUBY_VERSION=#{RUBY_VERSION};"
begin; require 'rubygems'; puts "export GEM_ROOT=#{Gem.default_dir.inspect};"; rescue LoadError; end
EOF
)"
export PATH="${GEM_ROOT:+$GEM_ROOT/bin:}$PATH"
if (( UID != 0 )); then
export GEM_HOME="$HOME/.gem/$RUBY_ENGINE/$RUBY_VERSION"
export GEM_PATH="$GEM_HOME${GEM_ROOT:+:$GEM_ROOT}${GEM_PATH:+:$GEM_PATH}"
export PATH="$GEM_HOME/bin:$PATH"
fi
hash -r
}
function chruby()
{
case "$1" in
-h|--help)
echo "usage: chruby [RUBY|VERSION|system] [RUBYOPT...]"
;;
-V|--version)
echo "chruby: $CHRUBY_VERSION"
;;
"")
local dir ruby
for dir in "${RUBIES[@]}"; do
dir="${dir%%/}"; ruby="${dir##*/}"
if [[ "$dir" == "$RUBY_ROOT" ]]; then
echo " * ${ruby} ${RUBYOPT}"
else
echo " ${ruby}"
fi
done
;;
system) chruby_reset ;;
*)
local dir ruby match
for dir in "${RUBIES[@]}"; do
dir="${dir%%/}"; ruby="${dir##*/}"
case "$ruby" in
"$1") match="$dir" && break ;;
*"$1"*) match="$dir" ;;
esac
done
if [[ -z "$match" ]]; then
echo "chruby: unknown Ruby: $1" >&2
return 1
fi
shift
chruby_use "$match" "$*"
;;
esac
}
| {
"pile_set_name": "Github"
} |
obj-y += prom.o setup.o irq.o
| {
"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>
#import <FBSDKCoreKit/FBSDKGraphRequestConnection.h>
#import "FBSDKMacros.h"
@class FBSDKAccessToken;
@class FBSDKGraphRequest;
/** NSNotificationCenter name indicating a result of a failed log flush attempt. The posted object will be an NSError instance. */
FBSDK_EXTERN NSString *const FBSDKAppEventsLoggingResultNotification;
/** optional plist key ("FacebookLoggingOverrideAppID") for setting `loggingOverrideAppID` */
FBSDK_EXTERN NSString *const FBSDKAppEventsOverrideAppIDBundleKey;
/**
NS_ENUM (NSUInteger, FBSDKAppEventsFlushBehavior)
Specifies when `FBSDKAppEvents` sends log events to the server.
*/
typedef NS_ENUM(NSUInteger, FBSDKAppEventsFlushBehavior)
{
/** Flush automatically: periodically (once a minute or every 100 logged events) and always at app reactivation. */
FBSDKAppEventsFlushBehaviorAuto = 0,
/** Only flush when the `flush` method is called. When an app is moved to background/terminated, the
events are persisted and re-established at activation, but they will only be written with an
explicit call to `flush`. */
FBSDKAppEventsFlushBehaviorExplicitOnly,
};
/**
@methodgroup Predefined event names for logging events common to many apps. Logging occurs through the `logEvent` family of methods on `FBSDKAppEvents`.
Common event parameters are provided in the `FBSDKAppEventsParameterNames*` constants.
*/
/** Log this event when the user has achieved a level in the app. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameAchievedLevel;
/** Log this event when the user has entered their payment info. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameAddedPaymentInfo;
/** Log this event when the user has added an item to their cart. The valueToSum passed to logEvent should be the item's price. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameAddedToCart;
/** Log this event when the user has added an item to their wishlist. The valueToSum passed to logEvent should be the item's price. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameAddedToWishlist;
/** Log this event when a user has completed registration with the app. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameCompletedRegistration;
/** Log this event when the user has completed a tutorial in the app. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameCompletedTutorial;
/** Log this event when the user has entered the checkout process. The valueToSum passed to logEvent should be the total price in the cart. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameInitiatedCheckout;
/** Log this event when the user has rated an item in the app. The valueToSum passed to logEvent should be the numeric rating. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameRated;
/** Log this event when a user has performed a search within the app. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameSearched;
/** Log this event when the user has spent app credits. The valueToSum passed to logEvent should be the number of credits spent. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameSpentCredits;
/** Log this event when the user has unlocked an achievement in the app. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameUnlockedAchievement;
/** Log this event when a user has viewed a form of content in the app. */
FBSDK_EXTERN NSString *const FBSDKAppEventNameViewedContent;
/**
@methodgroup Predefined event name parameters for common additional information to accompany events logged through the `logEvent` family
of methods on `FBSDKAppEvents`. Common event names are provided in the `FBAppEventName*` constants.
*/
/**
* Parameter key used to specify data for the one or more pieces of content being logged about.
* Data should be a JSON encoded string.
* Example:
* "[{\"id\": \"1234\", \"quantity\": 2, \"item_price\": 5.99}, {\"id\": \"5678\", \"quantity\": 1, \"item_price\": 9.99}]"
*/
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNameContent;
/** Parameter key used to specify an ID for the specific piece of content being logged about. Could be an EAN, article identifier, etc., depending on the nature of the app. */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNameContentID;
/** Parameter key used to specify a generic content type/family for the logged event, e.g. "music", "photo", "video". Options to use will vary based upon what the app is all about. */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNameContentType;
/** Parameter key used to specify currency used with logged event. E.g. "USD", "EUR", "GBP". See ISO-4217 for specific values. One reference for these is <http://en.wikipedia.org/wiki/ISO_4217>. */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNameCurrency;
/** Parameter key used to specify a description appropriate to the event being logged. E.g., the name of the achievement unlocked in the `FBAppEventNameAchievementUnlocked` event. */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNameDescription;
/** Parameter key used to specify the level achieved in a `FBAppEventNameAchieved` event. */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNameLevel;
/** Parameter key used to specify the maximum rating available for the `FBAppEventNameRate` event. E.g., "5" or "10". */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNameMaxRatingValue;
/** Parameter key used to specify how many items are being processed for an `FBAppEventNameInitiatedCheckout` or `FBAppEventNamePurchased` event. */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNameNumItems;
/** Parameter key used to specify whether payment info is available for the `FBAppEventNameInitiatedCheckout` event. `FBSDKAppEventParameterValueYes` and `FBSDKAppEventParameterValueNo` are good canonical values to use for this parameter. */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNamePaymentInfoAvailable;
/** Parameter key used to specify method user has used to register for the app, e.g., "Facebook", "email", "Twitter", etc */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNameRegistrationMethod;
/** Parameter key used to specify the string provided by the user for a search operation. */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNameSearchString;
/** Parameter key used to specify whether the activity being logged about was successful or not. `FBSDKAppEventParameterValueYes` and `FBSDKAppEventParameterValueNo` are good canonical values to use for this parameter. */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterNameSuccess;
/*
@methodgroup Predefined values to assign to event parameters that accompany events logged through the `logEvent` family
of methods on `FBSDKAppEvents`. Common event parameters are provided in the `FBSDKAppEventParameterName*` constants.
*/
/** Yes-valued parameter value to be used with parameter keys that need a Yes/No value */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterValueYes;
/** No-valued parameter value to be used with parameter keys that need a Yes/No value */
FBSDK_EXTERN NSString *const FBSDKAppEventParameterValueNo;
/**
Client-side event logging for specialized application analytics available through Facebook App Insights
and for use with Facebook Ads conversion tracking and optimization.
The `FBSDKAppEvents` static class has a few related roles:
+ Logging predefined and application-defined events to Facebook App Insights with a
numeric value to sum across a large number of events, and an optional set of key/value
parameters that define "segments" for this event (e.g., 'purchaserStatus' : 'frequent', or
'gamerLevel' : 'intermediate')
+ Logging events to later be used for ads optimization around lifetime value.
+ Methods that control the way in which events are flushed out to the Facebook servers.
Here are some important characteristics of the logging mechanism provided by `FBSDKAppEvents`:
+ Events are not sent immediately when logged. They're cached and flushed out to the Facebook servers
in a number of situations:
- when an event count threshold is passed (currently 100 logged events).
- when a time threshold is passed (currently 15 seconds).
- when an app has gone to background and is then brought back to the foreground.
+ Events will be accumulated when the app is in a disconnected state, and sent when the connection is
restored and one of the above 'flush' conditions are met.
+ The `FBSDKAppEvents` class is thread-safe in that events may be logged from any of the app's threads.
+ The developer can set the `flushBehavior` on `FBSDKAppEvents` to force the flushing of events to only
occur on an explicit call to the `flush` method.
+ The developer can turn on console debug output for event logging and flushing to the server by using
the `FBSDKLoggingBehaviorAppEvents` value in `[FBSettings setLoggingBehavior:]`.
Some things to note when logging events:
+ There is a limit on the number of unique event names an app can use, on the order of 1000.
+ There is a limit to the number of unique parameter names in the provided parameters that can
be used per event, on the order of 25. This is not just for an individual call, but for all
invocations for that eventName.
+ Event names and parameter names (the keys in the NSDictionary) must be between 2 and 40 characters, and
must consist of alphanumeric characters, _, -, or spaces.
+ The length of each parameter value can be no more than on the order of 100 characters.
*/
@interface FBSDKAppEvents : NSObject
/*
* Basic event logging
*/
/**
Log an event with just an eventName.
- Parameter eventName: The name of the event to record. Limitations on number of events and name length
are given in the `FBSDKAppEvents` documentation.
*/
+ (void)logEvent:(NSString *)eventName;
/**
Log an event with an eventName and a numeric value to be aggregated with other events of this name.
- Parameter eventName: The name of the event to record. Limitations on number of events and name length
are given in the `FBSDKAppEvents` documentation. Common event names are provided in `FBAppEventName*` constants.
- Parameter valueToSum: Amount to be aggregated into all events of this eventName, and App Insights will report
the cumulative and average value of this amount.
*/
+ (void)logEvent:(NSString *)eventName
valueToSum:(double)valueToSum;
/**
Log an event with an eventName and a set of key/value pairs in the parameters dictionary.
Parameter limitations are described above.
- Parameter eventName: The name of the event to record. Limitations on number of events and name construction
are given in the `FBSDKAppEvents` documentation. Common event names are provided in `FBAppEventName*` constants.
- Parameter parameters: Arbitrary parameter dictionary of characteristics. The keys to this dictionary must
be NSString's, and the values are expected to be NSString or NSNumber. Limitations on the number of
parameters and name construction are given in the `FBSDKAppEvents` documentation. Commonly used parameter names
are provided in `FBSDKAppEventParameterName*` constants.
*/
+ (void)logEvent:(NSString *)eventName
parameters:(NSDictionary *)parameters;
/**
Log an event with an eventName, a numeric value to be aggregated with other events of this name,
and a set of key/value pairs in the parameters dictionary.
- Parameter eventName: The name of the event to record. Limitations on number of events and name construction
are given in the `FBSDKAppEvents` documentation. Common event names are provided in `FBAppEventName*` constants.
- Parameter valueToSum: Amount to be aggregated into all events of this eventName, and App Insights will report
the cumulative and average value of this amount.
- Parameter parameters: Arbitrary parameter dictionary of characteristics. The keys to this dictionary must
be NSString's, and the values are expected to be NSString or NSNumber. Limitations on the number of
parameters and name construction are given in the `FBSDKAppEvents` documentation. Commonly used parameter names
are provided in `FBSDKAppEventParameterName*` constants.
*/
+ (void)logEvent:(NSString *)eventName
valueToSum:(double)valueToSum
parameters:(NSDictionary *)parameters;
/**
Log an event with an eventName, a numeric value to be aggregated with other events of this name,
and a set of key/value pairs in the parameters dictionary. Providing session lets the developer
target a particular <FBSession>. If nil is provided, then `[FBSession activeSession]` will be used.
- Parameter eventName: The name of the event to record. Limitations on number of events and name construction
are given in the `FBSDKAppEvents` documentation. Common event names are provided in `FBAppEventName*` constants.
- Parameter valueToSum: Amount to be aggregated into all events of this eventName, and App Insights will report
the cumulative and average value of this amount. Note that this is an NSNumber, and a value of `nil` denotes
that this event doesn't have a value associated with it for summation.
- Parameter parameters: Arbitrary parameter dictionary of characteristics. The keys to this dictionary must
be NSString's, and the values are expected to be NSString or NSNumber. Limitations on the number of
parameters and name construction are given in the `FBSDKAppEvents` documentation. Commonly used parameter names
are provided in `FBSDKAppEventParameterName*` constants.
- Parameter accessToken: The optional access token to log the event as.
*/
+ (void)logEvent:(NSString *)eventName
valueToSum:(NSNumber *)valueToSum
parameters:(NSDictionary *)parameters
accessToken:(FBSDKAccessToken *)accessToken;
/*
* Purchase logging
*/
/**
Log a purchase of the specified amount, in the specified currency.
- Parameter purchaseAmount: Purchase amount to be logged, as expressed in the specified currency. This value
will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346).
- Parameter currency: Currency, is denoted as, e.g. "USD", "EUR", "GBP". See ISO-4217 for
specific values. One reference for these is <http://en.wikipedia.org/wiki/ISO_4217>.
This event immediately triggers a flush of the `FBSDKAppEvents` event queue, unless the `flushBehavior` is set
to `FBSDKAppEventsFlushBehaviorExplicitOnly`.
*/
+ (void)logPurchase:(double)purchaseAmount
currency:(NSString *)currency;
/**
Log a purchase of the specified amount, in the specified currency, also providing a set of
additional characteristics describing the purchase.
- Parameter purchaseAmount: Purchase amount to be logged, as expressed in the specified currency.This value
will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346).
- Parameter currency: Currency, is denoted as, e.g. "USD", "EUR", "GBP". See ISO-4217 for
specific values. One reference for these is <http://en.wikipedia.org/wiki/ISO_4217>.
- Parameter parameters: Arbitrary parameter dictionary of characteristics. The keys to this dictionary must
be NSString's, and the values are expected to be NSString or NSNumber. Limitations on the number of
parameters and name construction are given in the `FBSDKAppEvents` documentation. Commonly used parameter names
are provided in `FBSDKAppEventParameterName*` constants.
This event immediately triggers a flush of the `FBSDKAppEvents` event queue, unless the `flushBehavior` is set
to `FBSDKAppEventsFlushBehaviorExplicitOnly`.
*/
+ (void)logPurchase:(double)purchaseAmount
currency:(NSString *)currency
parameters:(NSDictionary *)parameters;
/**
Log a purchase of the specified amount, in the specified currency, also providing a set of
additional characteristics describing the purchase, as well as an <FBSession> to log to.
- Parameter purchaseAmount: Purchase amount to be logged, as expressed in the specified currency.This value
will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346).
- Parameter currency: Currency, is denoted as, e.g. "USD", "EUR", "GBP". See ISO-4217 for
specific values. One reference for these is <http://en.wikipedia.org/wiki/ISO_4217>.
- Parameter parameters: Arbitrary parameter dictionary of characteristics. The keys to this dictionary must
be NSString's, and the values are expected to be NSString or NSNumber. Limitations on the number of
parameters and name construction are given in the `FBSDKAppEvents` documentation. Commonly used parameter names
are provided in `FBSDKAppEventParameterName*` constants.
- Parameter accessToken: The optional access token to log the event as.
This event immediately triggers a flush of the `FBSDKAppEvents` event queue, unless the `flushBehavior` is set
to `FBSDKAppEventsFlushBehaviorExplicitOnly`.
*/
+ (void)logPurchase:(double)purchaseAmount
currency:(NSString *)currency
parameters:(NSDictionary *)parameters
accessToken:(FBSDKAccessToken *)accessToken;
/*
* Push Notifications Logging
*/
/**
Log an app event that tracks that the application was open via Push Notification.
- Parameter payload: Notification payload received via `UIApplicationDelegate`.
*/
+ (void)logPushNotificationOpen:(NSDictionary *)payload;
/**
Log an app event that tracks that a custom action was taken from a push notification.
- Parameter payload: Notification payload received via `UIApplicationDelegate`.
- Parameter action: Name of the action that was taken.
*/
+ (void)logPushNotificationOpen:(NSDictionary *)payload action:(NSString *)action;
/**
Notifies the events system that the app has launched and, when appropriate, logs an "activated app" event.
This function is called automatically from FBSDKApplicationDelegate applicationDidBecomeActive, unless
one overrides 'FacebookAutoLogAppEventsEnabled' key to false in the project info plist file.
In case 'FacebookAutoLogAppEventsEnabled' is set to false, then it should typically be placed in the
app delegates' `applicationDidBecomeActive:` method.
This method also takes care of logging the event indicating the first time this app has been launched, which, among other things, is used to
track user acquisition and app install ads conversions.
`activateApp` will not log an event on every app launch, since launches happen every time the app is backgrounded and then foregrounded.
"activated app" events will be logged when the app has not been active for more than 60 seconds. This method also causes a "deactivated app"
event to be logged when sessions are "completed", and these events are logged with the session length, with an indication of how much
time has elapsed between sessions, and with the number of background/foreground interruptions that session had. This data
is all visible in your app's App Events Insights.
*/
+ (void)activateApp;
/*
* Push Notifications Registration
*/
/**
Sets and sends device token to register the current application for push notifications.
Sets and sends a device token from `NSData` representation that you get from `UIApplicationDelegate.-application:didRegisterForRemoteNotificationsWithDeviceToken:`.
- Parameter deviceToken: Device token data.
*/
+ (void)setPushNotificationsDeviceToken:(NSData *)deviceToken;
/*
* Control over event batching/flushing
*/
/**
Get the current event flushing behavior specifying when events are sent back to Facebook servers.
*/
+ (FBSDKAppEventsFlushBehavior)flushBehavior;
/**
Set the current event flushing behavior specifying when events are sent back to Facebook servers.
- Parameter flushBehavior: The desired `FBSDKAppEventsFlushBehavior` to be used.
*/
+ (void)setFlushBehavior:(FBSDKAppEventsFlushBehavior)flushBehavior;
/**
Set the 'override' App ID for App Event logging.
In some cases, apps want to use one Facebook App ID for login and social presence and another
for App Event logging. (An example is if multiple apps from the same company share an app ID for login, but
want distinct logging.) By default, this value is `nil`, and defers to the `FBSDKAppEventsOverrideAppIDBundleKey`
plist value. If that's not set, it defaults to `[FBSDKSettings appID]`.
This should be set before any other calls are made to `FBSDKAppEvents`. Thus, you should set it in your application
delegate's `application:didFinishLaunchingWithOptions:` delegate.
- Parameter appID: The Facebook App ID to be used for App Event logging.
*/
+ (void)setLoggingOverrideAppID:(NSString *)appID;
/**
Get the 'override' App ID for App Event logging.
- See:setLoggingOverrideAppID:
*/
+ (NSString *)loggingOverrideAppID;
/**
Explicitly kick off flushing of events to Facebook. This is an asynchronous method, but it does initiate an immediate
kick off. Server failures will be reported through the NotificationCenter with notification ID `FBSDKAppEventsLoggingResultNotification`.
*/
+ (void)flush;
/**
Creates a request representing the Graph API call to retrieve a Custom Audience "third party ID" for the app's Facebook user.
Callers will send this ID back to their own servers, collect up a set to create a Facebook Custom Audience with,
and then use the resultant Custom Audience to target ads.
- Parameter accessToken: The access token to use to establish the user's identity for users logged into Facebook through this app.
If `nil`, then the `[FBSDKAccessToken currentAccessToken]` is used.
The JSON in the request's response will include an "custom_audience_third_party_id" key/value pair, with the value being the ID retrieved.
This ID is an encrypted encoding of the Facebook user's ID and the invoking Facebook app ID.
Multiple calls with the same user will return different IDs, thus these IDs cannot be used to correlate behavior
across devices or applications, and are only meaningful when sent back to Facebook for creating Custom Audiences.
The ID retrieved represents the Facebook user identified in the following way: if the specified access token is valid,
the ID will represent the user associated with that token; otherwise the ID will represent the user logged into the
native Facebook app on the device. If there is no native Facebook app, no one is logged into it, or the user has opted out
at the iOS level from ad tracking, then a `nil` ID will be returned.
This method returns `nil` if either the user has opted-out (via iOS) from Ad Tracking, the app itself has limited event usage
via the `[FBSDKSettings limitEventAndDataUsage]` flag, or a specific Facebook user cannot be identified.
*/
+ (FBSDKGraphRequest *)requestForCustomAudienceThirdPartyIDWithAccessToken:(FBSDKAccessToken *)accessToken;
/*
Sets a custom user ID to associate with all app events.
The userID is persisted until it is cleared by passing nil.
*/
+ (void)setUserID:(NSString *)userID;
/*
Returns the set custom user ID.
*/
+ (NSString *)userID;
/*
Sends a request to update the properties for the current user, set by `setUserID:`
You must call `FBSDKAppEvents setUserID:` before making this call.
- Parameter properties: the custom user properties
- Parameter handler: the optional completion handler
*/
+ (void)updateUserProperties:(NSDictionary *)properties handler:(FBSDKGraphRequestHandler)handler;
@end
| {
"pile_set_name": "Github"
} |
/*
*
* Copyright 2015 gRPC 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.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h"
#include <string.h>
#include "src/core/lib/security/util/json_util.h"
#include "src/core/lib/surface/api_trace.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
//
// Auth Refresh Token.
//
int grpc_auth_refresh_token_is_valid(
const grpc_auth_refresh_token* refresh_token) {
return (refresh_token != nullptr) &&
strcmp(refresh_token->type, GRPC_AUTH_JSON_TYPE_INVALID);
}
grpc_auth_refresh_token grpc_auth_refresh_token_create_from_json(
const grpc_json* json) {
grpc_auth_refresh_token result;
const char* prop_value;
int success = 0;
memset(&result, 0, sizeof(grpc_auth_refresh_token));
result.type = GRPC_AUTH_JSON_TYPE_INVALID;
if (json == nullptr) {
gpr_log(GPR_ERROR, "Invalid json.");
goto end;
}
prop_value = grpc_json_get_string_property(json, "type");
if (prop_value == nullptr ||
strcmp(prop_value, GRPC_AUTH_JSON_TYPE_AUTHORIZED_USER)) {
goto end;
}
result.type = GRPC_AUTH_JSON_TYPE_AUTHORIZED_USER;
if (!grpc_copy_json_string_property(json, "client_secret",
&result.client_secret) ||
!grpc_copy_json_string_property(json, "client_id", &result.client_id) ||
!grpc_copy_json_string_property(json, "refresh_token",
&result.refresh_token)) {
goto end;
}
success = 1;
end:
if (!success) grpc_auth_refresh_token_destruct(&result);
return result;
}
grpc_auth_refresh_token grpc_auth_refresh_token_create_from_string(
const char* json_string) {
char* scratchpad = gpr_strdup(json_string);
grpc_json* json = grpc_json_parse_string(scratchpad);
grpc_auth_refresh_token result =
grpc_auth_refresh_token_create_from_json(json);
if (json != nullptr) grpc_json_destroy(json);
gpr_free(scratchpad);
return result;
}
void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token* refresh_token) {
if (refresh_token == nullptr) return;
refresh_token->type = GRPC_AUTH_JSON_TYPE_INVALID;
if (refresh_token->client_id != nullptr) {
gpr_free(refresh_token->client_id);
refresh_token->client_id = nullptr;
}
if (refresh_token->client_secret != nullptr) {
gpr_free(refresh_token->client_secret);
refresh_token->client_secret = nullptr;
}
if (refresh_token->refresh_token != nullptr) {
gpr_free(refresh_token->refresh_token);
refresh_token->refresh_token = nullptr;
}
}
//
// Oauth2 Token Fetcher credentials.
//
static void oauth2_token_fetcher_destruct(grpc_call_credentials* creds) {
grpc_oauth2_token_fetcher_credentials* c =
reinterpret_cast<grpc_oauth2_token_fetcher_credentials*>(creds);
GRPC_MDELEM_UNREF(c->access_token_md);
gpr_mu_destroy(&c->mu);
grpc_pollset_set_destroy(grpc_polling_entity_pollset_set(&c->pollent));
grpc_httpcli_context_destroy(&c->httpcli_context);
}
grpc_credentials_status
grpc_oauth2_token_fetcher_credentials_parse_server_response(
const grpc_http_response* response, grpc_mdelem* token_md,
grpc_millis* token_lifetime) {
char* null_terminated_body = nullptr;
char* new_access_token = nullptr;
grpc_credentials_status status = GRPC_CREDENTIALS_OK;
grpc_json* json = nullptr;
if (response == nullptr) {
gpr_log(GPR_ERROR, "Received NULL response.");
status = GRPC_CREDENTIALS_ERROR;
goto end;
}
if (response->body_length > 0) {
null_terminated_body =
static_cast<char*>(gpr_malloc(response->body_length + 1));
null_terminated_body[response->body_length] = '\0';
memcpy(null_terminated_body, response->body, response->body_length);
}
if (response->status != 200) {
gpr_log(GPR_ERROR, "Call to http server ended with error %d [%s].",
response->status,
null_terminated_body != nullptr ? null_terminated_body : "");
status = GRPC_CREDENTIALS_ERROR;
goto end;
} else {
grpc_json* access_token = nullptr;
grpc_json* token_type = nullptr;
grpc_json* expires_in = nullptr;
grpc_json* ptr;
json = grpc_json_parse_string(null_terminated_body);
if (json == nullptr) {
gpr_log(GPR_ERROR, "Could not parse JSON from %s", null_terminated_body);
status = GRPC_CREDENTIALS_ERROR;
goto end;
}
if (json->type != GRPC_JSON_OBJECT) {
gpr_log(GPR_ERROR, "Response should be a JSON object");
status = GRPC_CREDENTIALS_ERROR;
goto end;
}
for (ptr = json->child; ptr; ptr = ptr->next) {
if (strcmp(ptr->key, "access_token") == 0) {
access_token = ptr;
} else if (strcmp(ptr->key, "token_type") == 0) {
token_type = ptr;
} else if (strcmp(ptr->key, "expires_in") == 0) {
expires_in = ptr;
}
}
if (access_token == nullptr || access_token->type != GRPC_JSON_STRING) {
gpr_log(GPR_ERROR, "Missing or invalid access_token in JSON.");
status = GRPC_CREDENTIALS_ERROR;
goto end;
}
if (token_type == nullptr || token_type->type != GRPC_JSON_STRING) {
gpr_log(GPR_ERROR, "Missing or invalid token_type in JSON.");
status = GRPC_CREDENTIALS_ERROR;
goto end;
}
if (expires_in == nullptr || expires_in->type != GRPC_JSON_NUMBER) {
gpr_log(GPR_ERROR, "Missing or invalid expires_in in JSON.");
status = GRPC_CREDENTIALS_ERROR;
goto end;
}
gpr_asprintf(&new_access_token, "%s %s", token_type->value,
access_token->value);
*token_lifetime = strtol(expires_in->value, nullptr, 10) * GPR_MS_PER_SEC;
if (!GRPC_MDISNULL(*token_md)) GRPC_MDELEM_UNREF(*token_md);
*token_md = grpc_mdelem_from_slices(
grpc_slice_from_static_string(GRPC_AUTHORIZATION_METADATA_KEY),
grpc_slice_from_copied_string(new_access_token));
status = GRPC_CREDENTIALS_OK;
}
end:
if (status != GRPC_CREDENTIALS_OK && !GRPC_MDISNULL(*token_md)) {
GRPC_MDELEM_UNREF(*token_md);
*token_md = GRPC_MDNULL;
}
if (null_terminated_body != nullptr) gpr_free(null_terminated_body);
if (new_access_token != nullptr) gpr_free(new_access_token);
if (json != nullptr) grpc_json_destroy(json);
return status;
}
static void on_oauth2_token_fetcher_http_response(void* user_data,
grpc_error* error) {
GRPC_LOG_IF_ERROR("oauth_fetch", GRPC_ERROR_REF(error));
grpc_credentials_metadata_request* r =
static_cast<grpc_credentials_metadata_request*>(user_data);
grpc_oauth2_token_fetcher_credentials* c =
reinterpret_cast<grpc_oauth2_token_fetcher_credentials*>(r->creds);
grpc_mdelem access_token_md = GRPC_MDNULL;
grpc_millis token_lifetime;
grpc_credentials_status status =
grpc_oauth2_token_fetcher_credentials_parse_server_response(
&r->response, &access_token_md, &token_lifetime);
// Update cache and grab list of pending requests.
gpr_mu_lock(&c->mu);
c->token_fetch_pending = false;
c->access_token_md = GRPC_MDELEM_REF(access_token_md);
c->token_expiration = status == GRPC_CREDENTIALS_OK
? grpc_core::ExecCtx::Get()->Now() + token_lifetime
: 0;
grpc_oauth2_pending_get_request_metadata* pending_request =
c->pending_requests;
c->pending_requests = nullptr;
gpr_mu_unlock(&c->mu);
// Invoke callbacks for all pending requests.
while (pending_request != nullptr) {
if (status == GRPC_CREDENTIALS_OK) {
grpc_credentials_mdelem_array_add(pending_request->md_array,
access_token_md);
} else {
error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Error occured when fetching oauth2 token.", &error, 1);
}
GRPC_CLOSURE_SCHED(pending_request->on_request_metadata, error);
grpc_polling_entity_del_from_pollset_set(
pending_request->pollent, grpc_polling_entity_pollset_set(&c->pollent));
grpc_oauth2_pending_get_request_metadata* prev = pending_request;
pending_request = pending_request->next;
gpr_free(prev);
}
GRPC_MDELEM_UNREF(access_token_md);
grpc_call_credentials_unref(r->creds);
grpc_credentials_metadata_request_destroy(r);
}
static bool oauth2_token_fetcher_get_request_metadata(
grpc_call_credentials* creds, grpc_polling_entity* pollent,
grpc_auth_metadata_context context, grpc_credentials_mdelem_array* md_array,
grpc_closure* on_request_metadata, grpc_error** error) {
grpc_oauth2_token_fetcher_credentials* c =
reinterpret_cast<grpc_oauth2_token_fetcher_credentials*>(creds);
// Check if we can use the cached token.
grpc_millis refresh_threshold =
GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS * GPR_MS_PER_SEC;
grpc_mdelem cached_access_token_md = GRPC_MDNULL;
gpr_mu_lock(&c->mu);
if (!GRPC_MDISNULL(c->access_token_md) &&
(c->token_expiration - grpc_core::ExecCtx::Get()->Now() >
refresh_threshold)) {
cached_access_token_md = GRPC_MDELEM_REF(c->access_token_md);
}
if (!GRPC_MDISNULL(cached_access_token_md)) {
gpr_mu_unlock(&c->mu);
grpc_credentials_mdelem_array_add(md_array, cached_access_token_md);
GRPC_MDELEM_UNREF(cached_access_token_md);
return true;
}
// Couldn't get the token from the cache.
// Add request to c->pending_requests and start a new fetch if needed.
grpc_oauth2_pending_get_request_metadata* pending_request =
static_cast<grpc_oauth2_pending_get_request_metadata*>(
gpr_malloc(sizeof(*pending_request)));
pending_request->md_array = md_array;
pending_request->on_request_metadata = on_request_metadata;
pending_request->pollent = pollent;
grpc_polling_entity_add_to_pollset_set(
pollent, grpc_polling_entity_pollset_set(&c->pollent));
pending_request->next = c->pending_requests;
c->pending_requests = pending_request;
bool start_fetch = false;
if (!c->token_fetch_pending) {
c->token_fetch_pending = true;
start_fetch = true;
}
gpr_mu_unlock(&c->mu);
if (start_fetch) {
grpc_call_credentials_ref(creds);
c->fetch_func(grpc_credentials_metadata_request_create(creds),
&c->httpcli_context, &c->pollent,
on_oauth2_token_fetcher_http_response,
grpc_core::ExecCtx::Get()->Now() + refresh_threshold);
}
return false;
}
static void oauth2_token_fetcher_cancel_get_request_metadata(
grpc_call_credentials* creds, grpc_credentials_mdelem_array* md_array,
grpc_error* error) {
grpc_oauth2_token_fetcher_credentials* c =
reinterpret_cast<grpc_oauth2_token_fetcher_credentials*>(creds);
gpr_mu_lock(&c->mu);
grpc_oauth2_pending_get_request_metadata* prev = nullptr;
grpc_oauth2_pending_get_request_metadata* pending_request =
c->pending_requests;
while (pending_request != nullptr) {
if (pending_request->md_array == md_array) {
// Remove matching pending request from the list.
if (prev != nullptr) {
prev->next = pending_request->next;
} else {
c->pending_requests = pending_request->next;
}
// Invoke the callback immediately with an error.
GRPC_CLOSURE_SCHED(pending_request->on_request_metadata,
GRPC_ERROR_REF(error));
gpr_free(pending_request);
break;
}
prev = pending_request;
pending_request = pending_request->next;
}
gpr_mu_unlock(&c->mu);
GRPC_ERROR_UNREF(error);
}
static void init_oauth2_token_fetcher(grpc_oauth2_token_fetcher_credentials* c,
grpc_fetch_oauth2_func fetch_func) {
memset(c, 0, sizeof(grpc_oauth2_token_fetcher_credentials));
c->base.type = GRPC_CALL_CREDENTIALS_TYPE_OAUTH2;
gpr_ref_init(&c->base.refcount, 1);
gpr_mu_init(&c->mu);
c->token_expiration = 0;
c->fetch_func = fetch_func;
c->pollent =
grpc_polling_entity_create_from_pollset_set(grpc_pollset_set_create());
grpc_httpcli_context_init(&c->httpcli_context);
}
//
// Google Compute Engine credentials.
//
static grpc_call_credentials_vtable compute_engine_vtable = {
oauth2_token_fetcher_destruct, oauth2_token_fetcher_get_request_metadata,
oauth2_token_fetcher_cancel_get_request_metadata};
static void compute_engine_fetch_oauth2(
grpc_credentials_metadata_request* metadata_req,
grpc_httpcli_context* httpcli_context, grpc_polling_entity* pollent,
grpc_iomgr_cb_func response_cb, grpc_millis deadline) {
grpc_http_header header = {(char*)"Metadata-Flavor", (char*)"Google"};
grpc_httpcli_request request;
memset(&request, 0, sizeof(grpc_httpcli_request));
request.host = (char*)GRPC_COMPUTE_ENGINE_METADATA_HOST;
request.http.path = (char*)GRPC_COMPUTE_ENGINE_METADATA_TOKEN_PATH;
request.http.hdr_count = 1;
request.http.hdrs = &header;
/* TODO(ctiller): Carry the resource_quota in ctx and share it with the host
channel. This would allow us to cancel an authentication query when under
extreme memory pressure. */
grpc_resource_quota* resource_quota =
grpc_resource_quota_create("oauth2_credentials");
grpc_httpcli_get(
httpcli_context, pollent, resource_quota, &request, deadline,
GRPC_CLOSURE_CREATE(response_cb, metadata_req, grpc_schedule_on_exec_ctx),
&metadata_req->response);
grpc_resource_quota_unref_internal(resource_quota);
}
grpc_call_credentials* grpc_google_compute_engine_credentials_create(
void* reserved) {
grpc_oauth2_token_fetcher_credentials* c =
static_cast<grpc_oauth2_token_fetcher_credentials*>(
gpr_malloc(sizeof(grpc_oauth2_token_fetcher_credentials)));
GRPC_API_TRACE("grpc_compute_engine_credentials_create(reserved=%p)", 1,
(reserved));
GPR_ASSERT(reserved == nullptr);
init_oauth2_token_fetcher(c, compute_engine_fetch_oauth2);
c->base.vtable = &compute_engine_vtable;
return &c->base;
}
//
// Google Refresh Token credentials.
//
static void refresh_token_destruct(grpc_call_credentials* creds) {
grpc_google_refresh_token_credentials* c =
reinterpret_cast<grpc_google_refresh_token_credentials*>(creds);
grpc_auth_refresh_token_destruct(&c->refresh_token);
oauth2_token_fetcher_destruct(&c->base.base);
}
static grpc_call_credentials_vtable refresh_token_vtable = {
refresh_token_destruct, oauth2_token_fetcher_get_request_metadata,
oauth2_token_fetcher_cancel_get_request_metadata};
static void refresh_token_fetch_oauth2(
grpc_credentials_metadata_request* metadata_req,
grpc_httpcli_context* httpcli_context, grpc_polling_entity* pollent,
grpc_iomgr_cb_func response_cb, grpc_millis deadline) {
grpc_google_refresh_token_credentials* c =
reinterpret_cast<grpc_google_refresh_token_credentials*>(
metadata_req->creds);
grpc_http_header header = {(char*)"Content-Type",
(char*)"application/x-www-form-urlencoded"};
grpc_httpcli_request request;
char* body = nullptr;
gpr_asprintf(&body, GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING,
c->refresh_token.client_id, c->refresh_token.client_secret,
c->refresh_token.refresh_token);
memset(&request, 0, sizeof(grpc_httpcli_request));
request.host = (char*)GRPC_GOOGLE_OAUTH2_SERVICE_HOST;
request.http.path = (char*)GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH;
request.http.hdr_count = 1;
request.http.hdrs = &header;
request.handshaker = &grpc_httpcli_ssl;
/* TODO(ctiller): Carry the resource_quota in ctx and share it with the host
channel. This would allow us to cancel an authentication query when under
extreme memory pressure. */
grpc_resource_quota* resource_quota =
grpc_resource_quota_create("oauth2_credentials_refresh");
grpc_httpcli_post(
httpcli_context, pollent, resource_quota, &request, body, strlen(body),
deadline,
GRPC_CLOSURE_CREATE(response_cb, metadata_req, grpc_schedule_on_exec_ctx),
&metadata_req->response);
grpc_resource_quota_unref_internal(resource_quota);
gpr_free(body);
}
grpc_call_credentials*
grpc_refresh_token_credentials_create_from_auth_refresh_token(
grpc_auth_refresh_token refresh_token) {
grpc_google_refresh_token_credentials* c;
if (!grpc_auth_refresh_token_is_valid(&refresh_token)) {
gpr_log(GPR_ERROR, "Invalid input for refresh token credentials creation");
return nullptr;
}
c = static_cast<grpc_google_refresh_token_credentials*>(
gpr_zalloc(sizeof(grpc_google_refresh_token_credentials)));
init_oauth2_token_fetcher(&c->base, refresh_token_fetch_oauth2);
c->base.base.vtable = &refresh_token_vtable;
c->refresh_token = refresh_token;
return &c->base.base;
}
static char* create_loggable_refresh_token(grpc_auth_refresh_token* token) {
if (strcmp(token->type, GRPC_AUTH_JSON_TYPE_INVALID) == 0) {
return gpr_strdup("<Invalid json token>");
}
char* loggable_token = nullptr;
gpr_asprintf(&loggable_token,
"{\n type: %s\n client_id: %s\n client_secret: "
"<redacted>\n refresh_token: <redacted>\n}",
token->type, token->client_id);
return loggable_token;
}
grpc_call_credentials* grpc_google_refresh_token_credentials_create(
const char* json_refresh_token, void* reserved) {
grpc_auth_refresh_token token =
grpc_auth_refresh_token_create_from_string(json_refresh_token);
if (grpc_api_trace.enabled()) {
char* loggable_token = create_loggable_refresh_token(&token);
gpr_log(GPR_INFO,
"grpc_refresh_token_credentials_create(json_refresh_token=%s, "
"reserved=%p)",
loggable_token, reserved);
gpr_free(loggable_token);
}
GPR_ASSERT(reserved == nullptr);
return grpc_refresh_token_credentials_create_from_auth_refresh_token(token);
}
//
// Oauth2 Access Token credentials.
//
static void access_token_destruct(grpc_call_credentials* creds) {
grpc_access_token_credentials* c =
reinterpret_cast<grpc_access_token_credentials*>(creds);
GRPC_MDELEM_UNREF(c->access_token_md);
}
static bool access_token_get_request_metadata(
grpc_call_credentials* creds, grpc_polling_entity* pollent,
grpc_auth_metadata_context context, grpc_credentials_mdelem_array* md_array,
grpc_closure* on_request_metadata, grpc_error** error) {
grpc_access_token_credentials* c =
reinterpret_cast<grpc_access_token_credentials*>(creds);
grpc_credentials_mdelem_array_add(md_array, c->access_token_md);
return true;
}
static void access_token_cancel_get_request_metadata(
grpc_call_credentials* c, grpc_credentials_mdelem_array* md_array,
grpc_error* error) {
GRPC_ERROR_UNREF(error);
}
static grpc_call_credentials_vtable access_token_vtable = {
access_token_destruct, access_token_get_request_metadata,
access_token_cancel_get_request_metadata};
grpc_call_credentials* grpc_access_token_credentials_create(
const char* access_token, void* reserved) {
grpc_access_token_credentials* c =
static_cast<grpc_access_token_credentials*>(
gpr_zalloc(sizeof(grpc_access_token_credentials)));
GRPC_API_TRACE(
"grpc_access_token_credentials_create(access_token=<redacted>, "
"reserved=%p)",
1, (reserved));
GPR_ASSERT(reserved == nullptr);
c->base.type = GRPC_CALL_CREDENTIALS_TYPE_OAUTH2;
c->base.vtable = &access_token_vtable;
gpr_ref_init(&c->base.refcount, 1);
char* token_md_value;
gpr_asprintf(&token_md_value, "Bearer %s", access_token);
grpc_core::ExecCtx exec_ctx;
c->access_token_md = grpc_mdelem_from_slices(
grpc_slice_from_static_string(GRPC_AUTHORIZATION_METADATA_KEY),
grpc_slice_from_copied_string(token_md_value));
gpr_free(token_md_value);
return &c->base;
}
| {
"pile_set_name": "Github"
} |
-- Created on: 2000-05-10
-- Created by: Andrey BETENEV
-- Copyright (c) 2000-2014 OPEN CASCADE SAS
--
-- This file is part of Open CASCADE Technology software library.
--
-- This library is free software; you can redistribute it and/or modify it under
-- the terms of the GNU Lesser General Public License version 2.1 as published
-- by the Free Software Foundation, with special exception defined in the file
-- OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
-- distribution for complete text of the license and disclaimer of any warranty.
--
-- Alternatively, this file may be used under the terms of Open CASCADE
-- commercial license or contractual agreement.
-- Generator: ExpToCas (EXPRESS -> CASCADE/XSTEP Translator) V1.1
class RWRepItemGroup from RWStepAP214
---Purpose: Read & Write tool for RepItemGroup
uses
Check from Interface,
StepWriter from StepData,
StepReaderData from StepData,
EntityIterator from Interface,
RepItemGroup from StepAP214
is
Create returns RWRepItemGroup from RWStepAP214;
---Purpose: Empty constructor
ReadStep (me; data: StepReaderData from StepData; num: Integer;
ach : in out Check from Interface;
ent : RepItemGroup from StepAP214);
---Purpose: Reads RepItemGroup
WriteStep (me; SW: in out StepWriter from StepData;
ent: RepItemGroup from StepAP214);
---Purpose: Writes RepItemGroup
Share (me; ent : RepItemGroup from StepAP214;
iter: in out EntityIterator from Interface);
---Purpose: Fills data for graph (shared items)
end RWRepItemGroup;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2016 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 <libgen.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ext2fs/ext2fs.h>
#include <et/com_err.h>
#include <sparse/sparse.h>
struct {
int crc;
int sparse;
int gzip;
char *in_file;
char *out_file;
bool overwrite_input;
} params = {
.crc = 0,
.sparse = 1,
.gzip = 0,
};
#define ext2fs_fatal(Retval, Format, ...) \
do { \
com_err("error", Retval, Format, __VA_ARGS__); \
exit(EXIT_FAILURE); \
} while(0)
#define sparse_fatal(Format) \
do { \
fprintf(stderr, "sparse: "Format); \
exit(EXIT_FAILURE); \
} while(0)
static void usage(char *path)
{
char *progname = basename(path);
fprintf(stderr, "%s [ options ] <image or block device> <output image>\n"
" -c include CRC block\n"
" -z gzip output\n"
" -S don't use sparse output format\n", progname);
}
static struct buf_item {
struct buf_item *next;
void *buf[0];
} *buf_list;
static void add_chunk(ext2_filsys fs, struct sparse_file *s, blk_t chunk_start, blk_t chunk_end)
{
int retval;
unsigned int nb_blk = chunk_end - chunk_start;
size_t len = nb_blk * fs->blocksize;
int64_t offset = (int64_t)chunk_start * (int64_t)fs->blocksize;
if (params.overwrite_input == false) {
if (sparse_file_add_file(s, params.in_file, offset, len, chunk_start) < 0)
sparse_fatal("adding data to the sparse file");
} else {
/*
* The input file will be overwritten, make a copy of
* the blocks
*/
struct buf_item *bi = calloc(1, sizeof(struct buf_item) + len);
if (buf_list == NULL)
buf_list = bi;
else {
bi->next = buf_list;
buf_list = bi;
}
retval = io_channel_read_blk64(fs->io, chunk_start, nb_blk, bi->buf);
if (retval < 0)
ext2fs_fatal(retval, "reading block %u - %u", chunk_start, chunk_end);
if (sparse_file_add_data(s, bi->buf, len, chunk_start) < 0)
sparse_fatal("adding data to the sparse file");
}
}
static void free_chunks(void)
{
struct buf_item *bi;
while (buf_list) {
bi = buf_list->next;
free(buf_list);
buf_list = bi;
}
}
static struct sparse_file *ext_to_sparse(const char *in_file)
{
errcode_t retval;
ext2_filsys fs;
struct sparse_file *s;
int64_t chunk_start = -1;
blk_t first_blk, last_blk, nb_blk, cur_blk;
retval = ext2fs_open(in_file, 0, 0, 0, unix_io_manager, &fs);
if (retval)
ext2fs_fatal(retval, "while reading %s", in_file);
retval = ext2fs_read_block_bitmap(fs);
if (retval)
ext2fs_fatal(retval, "while reading block bitmap of %s", in_file);
first_blk = ext2fs_get_block_bitmap_start2(fs->block_map);
last_blk = ext2fs_get_block_bitmap_end2(fs->block_map);
nb_blk = last_blk - first_blk + 1;
s = sparse_file_new(fs->blocksize, (uint64_t)fs->blocksize * (uint64_t)nb_blk);
if (!s)
sparse_fatal("creating sparse file");
/*
* The sparse format encodes the size of a chunk (and its header) in a
* 32-bit unsigned integer (UINT32_MAX)
* When writing the chunk, the library uses a single call to write().
* Linux's implementation of the 'write' syscall does not allow transfers
* larger than INT32_MAX (32-bit _and_ 64-bit systems).
* Make sure we do not create chunks larger than this limit.
*/
int64_t max_blk_per_chunk = (INT32_MAX - 12) / fs->blocksize;
/* Iter on the blocks to merge contiguous chunk */
for (cur_blk = first_blk; cur_blk <= last_blk; ++cur_blk) {
if (ext2fs_test_block_bitmap2(fs->block_map, cur_blk)) {
if (chunk_start == -1) {
chunk_start = cur_blk;
} else if (cur_blk - chunk_start + 1 == max_blk_per_chunk) {
add_chunk(fs, s, chunk_start, cur_blk);
chunk_start = -1;
}
} else if (chunk_start != -1) {
add_chunk(fs, s, chunk_start, cur_blk);
chunk_start = -1;
}
}
if (chunk_start != -1)
add_chunk(fs, s, chunk_start, cur_blk - 1);
ext2fs_free(fs);
return s;
}
static bool same_file(const char *in, const char *out)
{
struct stat st1, st2;
if (access(out, F_OK) == -1)
return false;
if (lstat(in, &st1) == -1)
ext2fs_fatal(errno, "stat %s\n", in);
if (lstat(out, &st2) == -1)
ext2fs_fatal(errno, "stat %s\n", out);
return st1.st_ino == st2.st_ino;
}
int main(int argc, char *argv[])
{
int opt;
int out_fd;
struct sparse_file *s;
while ((opt = getopt(argc, argv, "czS")) != -1) {
switch(opt) {
case 'c':
params.crc = 1;
break;
case 'z':
params.gzip = 1;
break;
case 'S':
params.sparse = 0;
break;
default:
usage(argv[0]);
exit(EXIT_FAILURE);
}
}
if (optind + 1 >= argc) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
params.in_file = strdup(argv[optind++]);
params.out_file = strdup(argv[optind]);
params.overwrite_input = same_file(params.in_file, params.out_file);
s = ext_to_sparse(params.in_file);
out_fd = open(params.out_file, O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (out_fd == -1)
ext2fs_fatal(errno, "opening %s\n", params.out_file);
if (sparse_file_write(s, out_fd, params.gzip, params.sparse, params.crc) < 0)
sparse_fatal("writing sparse file");
sparse_file_destroy(s);
free(params.in_file);
free(params.out_file);
free_chunks();
close(out_fd);
return 0;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<!-- these should make the input non-native -->
<input type="text" value="Text Input" style="border-width: 0">
<input type="text" value="Text Input" style="border-width: 1px">
<input type="text" value="Text Input" style="border-width: 2px">
<input type="text" value="Text Input" style="border-width: 3px">
<input type="text" value="Text Input" style="border-width: 4px">
<input type="text" value="Text Input" style="border-width: 5px">
<input type="text" value="Text Input" style="border-width: 6px">
<input type="text" value="Text Input" style="border-style: dotted">
<input type="text" value="Text Input" style="border-color: green">
<input type="text" value="Text Input" style="background-color: transparent">
<input type="text" value="Text Input" style="background-color: white">
<input type="text" value="Text Input" style="border-top-left-radius: 0px">
<input type="text" value="Text Input" style="border-top-right-radius: 1px">
<input type="text" value="Text Input" style="border-bottom-right-radius: 2px">
<input type="text" value="Text Input" style="border-bottom-left-radius: 3px">
<input type="text" value="Text Input" style="border-inline-start-width: 3px">
<input type="text" value="Text Input" style="border-inline-end-width: 3px">
<!-- these should let it stay native -->
<input type="text" value="" style="color: black">
<input type="text" value="" style="font-weight: normal">
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2016 The Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
"""PEP 376 implementation."""
from __future__ import unicode_literals
import base64
import codecs
import contextlib
import hashlib
import logging
import os
import posixpath
import sys
import zipimport
from . import DistlibException, resources
from .compat import StringIO
from .version import get_scheme, UnsupportedVersionError
from .metadata import Metadata, METADATA_FILENAME, WHEEL_METADATA_FILENAME
from .util import (parse_requirement, cached_property, parse_name_and_version,
read_exports, write_exports, CSVReader, CSVWriter)
__all__ = ['Distribution', 'BaseInstalledDistribution',
'InstalledDistribution', 'EggInfoDistribution',
'DistributionPath']
logger = logging.getLogger(__name__)
EXPORTS_FILENAME = 'pydist-exports.json'
COMMANDS_FILENAME = 'pydist-commands.json'
DIST_FILES = ('INSTALLER', METADATA_FILENAME, 'RECORD', 'REQUESTED',
'RESOURCES', EXPORTS_FILENAME, 'SHARED')
DISTINFO_EXT = '.dist-info'
class _Cache(object):
"""
A simple cache mapping names and .dist-info paths to distributions
"""
def __init__(self):
"""
Initialise an instance. There is normally one for each DistributionPath.
"""
self.name = {}
self.path = {}
self.generated = False
def clear(self):
"""
Clear the cache, setting it to its initial state.
"""
self.name.clear()
self.path.clear()
self.generated = False
def add(self, dist):
"""
Add a distribution to the cache.
:param dist: The distribution to add.
"""
if dist.path not in self.path:
self.path[dist.path] = dist
self.name.setdefault(dist.key, []).append(dist)
class DistributionPath(object):
"""
Represents a set of distributions installed on a path (typically sys.path).
"""
def __init__(self, path=None, include_egg=False):
"""
Create an instance from a path, optionally including legacy (distutils/
setuptools/distribute) distributions.
:param path: The path to use, as a list of directories. If not specified,
sys.path is used.
:param include_egg: If True, this instance will look for and return legacy
distributions as well as those based on PEP 376.
"""
if path is None:
path = sys.path
self.path = path
self._include_dist = True
self._include_egg = include_egg
self._cache = _Cache()
self._cache_egg = _Cache()
self._cache_enabled = True
self._scheme = get_scheme('default')
def _get_cache_enabled(self):
return self._cache_enabled
def _set_cache_enabled(self, value):
self._cache_enabled = value
cache_enabled = property(_get_cache_enabled, _set_cache_enabled)
def clear_cache(self):
"""
Clears the internal cache.
"""
self._cache.clear()
self._cache_egg.clear()
def _yield_distributions(self):
"""
Yield .dist-info and/or .egg(-info) distributions.
"""
# We need to check if we've seen some resources already, because on
# some Linux systems (e.g. some Debian/Ubuntu variants) there are
# symlinks which alias other files in the environment.
seen = set()
for path in self.path:
finder = resources.finder_for_path(path)
if finder is None:
continue
r = finder.find('')
if not r or not r.is_container:
continue
rset = sorted(r.resources)
for entry in rset:
r = finder.find(entry)
if not r or r.path in seen:
continue
if self._include_dist and entry.endswith(DISTINFO_EXT):
possible_filenames = [METADATA_FILENAME, WHEEL_METADATA_FILENAME]
for metadata_filename in possible_filenames:
metadata_path = posixpath.join(entry, metadata_filename)
pydist = finder.find(metadata_path)
if pydist:
break
else:
continue
with contextlib.closing(pydist.as_stream()) as stream:
metadata = Metadata(fileobj=stream, scheme='legacy')
logger.debug('Found %s', r.path)
seen.add(r.path)
yield new_dist_class(r.path, metadata=metadata,
env=self)
elif self._include_egg and entry.endswith(('.egg-info',
'.egg')):
logger.debug('Found %s', r.path)
seen.add(r.path)
yield old_dist_class(r.path, self)
def _generate_cache(self):
"""
Scan the path for distributions and populate the cache with
those that are found.
"""
gen_dist = not self._cache.generated
gen_egg = self._include_egg and not self._cache_egg.generated
if gen_dist or gen_egg:
for dist in self._yield_distributions():
if isinstance(dist, InstalledDistribution):
self._cache.add(dist)
else:
self._cache_egg.add(dist)
if gen_dist:
self._cache.generated = True
if gen_egg:
self._cache_egg.generated = True
@classmethod
def distinfo_dirname(cls, name, version):
"""
The *name* and *version* parameters are converted into their
filename-escaped form, i.e. any ``'-'`` characters are replaced
with ``'_'`` other than the one in ``'dist-info'`` and the one
separating the name from the version number.
:parameter name: is converted to a standard distribution name by replacing
any runs of non- alphanumeric characters with a single
``'-'``.
:type name: string
:parameter version: is converted to a standard version string. Spaces
become dots, and all other non-alphanumeric characters
(except dots) become dashes, with runs of multiple
dashes condensed to a single dash.
:type version: string
:returns: directory name
:rtype: string"""
name = name.replace('-', '_')
return '-'.join([name, version]) + DISTINFO_EXT
def get_distributions(self):
"""
Provides an iterator that looks for distributions and returns
:class:`InstalledDistribution` or
:class:`EggInfoDistribution` instances for each one of them.
:rtype: iterator of :class:`InstalledDistribution` and
:class:`EggInfoDistribution` instances
"""
if not self._cache_enabled:
for dist in self._yield_distributions():
yield dist
else:
self._generate_cache()
for dist in self._cache.path.values():
yield dist
if self._include_egg:
for dist in self._cache_egg.path.values():
yield dist
def get_distribution(self, name):
"""
Looks for a named distribution on the path.
This function only returns the first result found, as no more than one
value is expected. If nothing is found, ``None`` is returned.
:rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution`
or ``None``
"""
result = None
name = name.lower()
if not self._cache_enabled:
for dist in self._yield_distributions():
if dist.key == name:
result = dist
break
else:
self._generate_cache()
if name in self._cache.name:
result = self._cache.name[name][0]
elif self._include_egg and name in self._cache_egg.name:
result = self._cache_egg.name[name][0]
return result
def provides_distribution(self, name, version=None):
"""
Iterates over all distributions to find which distributions provide *name*.
If a *version* is provided, it will be used to filter the results.
This function only returns the first result found, since no more than
one values are expected. If the directory is not found, returns ``None``.
:parameter version: a version specifier that indicates the version
required, conforming to the format in ``PEP-345``
:type name: string
:type version: string
"""
matcher = None
if not version is None:
try:
matcher = self._scheme.matcher('%s (%s)' % (name, version))
except ValueError:
raise DistlibException('invalid name or version: %r, %r' %
(name, version))
for dist in self.get_distributions():
provided = dist.provides
for p in provided:
p_name, p_ver = parse_name_and_version(p)
if matcher is None:
if p_name == name:
yield dist
break
else:
if p_name == name and matcher.match(p_ver):
yield dist
break
def get_file_path(self, name, relative_path):
"""
Return the path to a resource file.
"""
dist = self.get_distribution(name)
if dist is None:
raise LookupError('no distribution named %r found' % name)
return dist.get_resource_path(relative_path)
def get_exported_entries(self, category, name=None):
"""
Return all of the exported entries in a particular category.
:param category: The category to search for entries.
:param name: If specified, only entries with that name are returned.
"""
for dist in self.get_distributions():
r = dist.exports
if category in r:
d = r[category]
if name is not None:
if name in d:
yield d[name]
else:
for v in d.values():
yield v
class Distribution(object):
"""
A base class for distributions, whether installed or from indexes.
Either way, it must have some metadata, so that's all that's needed
for construction.
"""
build_time_dependency = False
"""
Set to True if it's known to be only a build-time dependency (i.e.
not needed after installation).
"""
requested = False
"""A boolean that indicates whether the ``REQUESTED`` metadata file is
present (in other words, whether the package was installed by user
request or it was installed as a dependency)."""
def __init__(self, metadata):
"""
Initialise an instance.
:param metadata: The instance of :class:`Metadata` describing this
distribution.
"""
self.metadata = metadata
self.name = metadata.name
self.key = self.name.lower() # for case-insensitive comparisons
self.version = metadata.version
self.locator = None
self.digest = None
self.extras = None # additional features requested
self.context = None # environment marker overrides
self.download_urls = set()
self.digests = {}
@property
def source_url(self):
"""
The source archive download URL for this distribution.
"""
return self.metadata.source_url
download_url = source_url # Backward compatibility
@property
def name_and_version(self):
"""
A utility property which displays the name and version in parentheses.
"""
return '%s (%s)' % (self.name, self.version)
@property
def provides(self):
"""
A set of distribution names and versions provided by this distribution.
:return: A set of "name (version)" strings.
"""
plist = self.metadata.provides
s = '%s (%s)' % (self.name, self.version)
if s not in plist:
plist.append(s)
return plist
def _get_requirements(self, req_attr):
md = self.metadata
logger.debug('Getting requirements from metadata %r', md.todict())
reqts = getattr(md, req_attr)
return set(md.get_requirements(reqts, extras=self.extras,
env=self.context))
@property
def run_requires(self):
return self._get_requirements('run_requires')
@property
def meta_requires(self):
return self._get_requirements('meta_requires')
@property
def build_requires(self):
return self._get_requirements('build_requires')
@property
def test_requires(self):
return self._get_requirements('test_requires')
@property
def dev_requires(self):
return self._get_requirements('dev_requires')
def matches_requirement(self, req):
"""
Say if this instance matches (fulfills) a requirement.
:param req: The requirement to match.
:rtype req: str
:return: True if it matches, else False.
"""
# Requirement may contain extras - parse to lose those
# from what's passed to the matcher
r = parse_requirement(req)
scheme = get_scheme(self.metadata.scheme)
try:
matcher = scheme.matcher(r.requirement)
except UnsupportedVersionError:
# XXX compat-mode if cannot read the version
logger.warning('could not read version %r - using name only',
req)
name = req.split()[0]
matcher = scheme.matcher(name)
name = matcher.key # case-insensitive
result = False
for p in self.provides:
p_name, p_ver = parse_name_and_version(p)
if p_name != name:
continue
try:
result = matcher.match(p_ver)
break
except UnsupportedVersionError:
pass
return result
def __repr__(self):
"""
Return a textual representation of this instance,
"""
if self.source_url:
suffix = ' [%s]' % self.source_url
else:
suffix = ''
return '<Distribution %s (%s)%s>' % (self.name, self.version, suffix)
def __eq__(self, other):
"""
See if this distribution is the same as another.
:param other: The distribution to compare with. To be equal to one
another. distributions must have the same type, name,
version and source_url.
:return: True if it is the same, else False.
"""
if type(other) is not type(self):
result = False
else:
result = (self.name == other.name and
self.version == other.version and
self.source_url == other.source_url)
return result
def __hash__(self):
"""
Compute hash in a way which matches the equality test.
"""
return hash(self.name) + hash(self.version) + hash(self.source_url)
class BaseInstalledDistribution(Distribution):
"""
This is the base class for installed distributions (whether PEP 376 or
legacy).
"""
hasher = None
def __init__(self, metadata, path, env=None):
"""
Initialise an instance.
:param metadata: An instance of :class:`Metadata` which describes the
distribution. This will normally have been initialised
from a metadata file in the ``path``.
:param path: The path of the ``.dist-info`` or ``.egg-info``
directory for the distribution.
:param env: This is normally the :class:`DistributionPath`
instance where this distribution was found.
"""
super(BaseInstalledDistribution, self).__init__(metadata)
self.path = path
self.dist_path = env
def get_hash(self, data, hasher=None):
"""
Get the hash of some data, using a particular hash algorithm, if
specified.
:param data: The data to be hashed.
:type data: bytes
:param hasher: The name of a hash implementation, supported by hashlib,
or ``None``. Examples of valid values are ``'sha1'``,
``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and
``'sha512'``. If no hasher is specified, the ``hasher``
attribute of the :class:`InstalledDistribution` instance
is used. If the hasher is determined to be ``None``, MD5
is used as the hashing algorithm.
:returns: The hash of the data. If a hasher was explicitly specified,
the returned hash will be prefixed with the specified hasher
followed by '='.
:rtype: str
"""
if hasher is None:
hasher = self.hasher
if hasher is None:
hasher = hashlib.md5
prefix = ''
else:
hasher = getattr(hashlib, hasher)
prefix = '%s=' % self.hasher
digest = hasher(data).digest()
digest = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')
return '%s%s' % (prefix, digest)
class InstalledDistribution(BaseInstalledDistribution):
"""
Created with the *path* of the ``.dist-info`` directory provided to the
constructor. It reads the metadata contained in ``pydist.json`` when it is
instantiated., or uses a passed in Metadata instance (useful for when
dry-run mode is being used).
"""
hasher = 'sha256'
def __init__(self, path, metadata=None, env=None):
self.finder = finder = resources.finder_for_path(path)
if finder is None:
import pdb; pdb.set_trace ()
if env and env._cache_enabled and path in env._cache.path:
metadata = env._cache.path[path].metadata
elif metadata is None:
r = finder.find(METADATA_FILENAME)
# Temporary - for Wheel 0.23 support
if r is None:
r = finder.find(WHEEL_METADATA_FILENAME)
# Temporary - for legacy support
if r is None:
r = finder.find('METADATA')
if r is None:
raise ValueError('no %s found in %s' % (METADATA_FILENAME,
path))
with contextlib.closing(r.as_stream()) as stream:
metadata = Metadata(fileobj=stream, scheme='legacy')
super(InstalledDistribution, self).__init__(metadata, path, env)
if env and env._cache_enabled:
env._cache.add(self)
try:
r = finder.find('REQUESTED')
except AttributeError:
import pdb; pdb.set_trace ()
self.requested = r is not None
def __repr__(self):
return '<InstalledDistribution %r %s at %r>' % (
self.name, self.version, self.path)
def __str__(self):
return "%s %s" % (self.name, self.version)
def _get_records(self):
"""
Get the list of installed files for the distribution
:return: A list of tuples of path, hash and size. Note that hash and
size might be ``None`` for some entries. The path is exactly
as stored in the file (which is as in PEP 376).
"""
results = []
r = self.get_distinfo_resource('RECORD')
with contextlib.closing(r.as_stream()) as stream:
with CSVReader(stream=stream) as record_reader:
# Base location is parent dir of .dist-info dir
#base_location = os.path.dirname(self.path)
#base_location = os.path.abspath(base_location)
for row in record_reader:
missing = [None for i in range(len(row), 3)]
path, checksum, size = row + missing
#if not os.path.isabs(path):
# path = path.replace('/', os.sep)
# path = os.path.join(base_location, path)
results.append((path, checksum, size))
return results
@cached_property
def exports(self):
"""
Return the information exported by this distribution.
:return: A dictionary of exports, mapping an export category to a dict
of :class:`ExportEntry` instances describing the individual
export entries, and keyed by name.
"""
result = {}
r = self.get_distinfo_resource(EXPORTS_FILENAME)
if r:
result = self.read_exports()
return result
def read_exports(self):
"""
Read exports data from a file in .ini format.
:return: A dictionary of exports, mapping an export category to a list
of :class:`ExportEntry` instances describing the individual
export entries.
"""
result = {}
r = self.get_distinfo_resource(EXPORTS_FILENAME)
if r:
with contextlib.closing(r.as_stream()) as stream:
result = read_exports(stream)
return result
def write_exports(self, exports):
"""
Write a dictionary of exports to a file in .ini format.
:param exports: A dictionary of exports, mapping an export category to
a list of :class:`ExportEntry` instances describing the
individual export entries.
"""
rf = self.get_distinfo_file(EXPORTS_FILENAME)
with open(rf, 'w') as f:
write_exports(exports, f)
def get_resource_path(self, relative_path):
"""
NOTE: This API may change in the future.
Return the absolute path to a resource file with the given relative
path.
:param relative_path: The path, relative to .dist-info, of the resource
of interest.
:return: The absolute path where the resource is to be found.
"""
r = self.get_distinfo_resource('RESOURCES')
with contextlib.closing(r.as_stream()) as stream:
with CSVReader(stream=stream) as resources_reader:
for relative, destination in resources_reader:
if relative == relative_path:
return destination
raise KeyError('no resource file with relative path %r '
'is installed' % relative_path)
def list_installed_files(self):
"""
Iterates over the ``RECORD`` entries and returns a tuple
``(path, hash, size)`` for each line.
:returns: iterator of (path, hash, size)
"""
for result in self._get_records():
yield result
def write_installed_files(self, paths, prefix, dry_run=False):
"""
Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any
existing ``RECORD`` file is silently overwritten.
prefix is used to determine when to write absolute paths.
"""
prefix = os.path.join(prefix, '')
base = os.path.dirname(self.path)
base_under_prefix = base.startswith(prefix)
base = os.path.join(base, '')
record_path = self.get_distinfo_file('RECORD')
logger.info('creating %s', record_path)
if dry_run:
return None
with CSVWriter(record_path) as writer:
for path in paths:
if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')):
# do not put size and hash, as in PEP-376
hash_value = size = ''
else:
size = '%d' % os.path.getsize(path)
with open(path, 'rb') as fp:
hash_value = self.get_hash(fp.read())
if path.startswith(base) or (base_under_prefix and
path.startswith(prefix)):
path = os.path.relpath(path, base)
writer.writerow((path, hash_value, size))
# add the RECORD file itself
if record_path.startswith(base):
record_path = os.path.relpath(record_path, base)
writer.writerow((record_path, '', ''))
return record_path
def check_installed_files(self):
"""
Checks that the hashes and sizes of the files in ``RECORD`` are
matched by the files themselves. Returns a (possibly empty) list of
mismatches. Each entry in the mismatch list will be a tuple consisting
of the path, 'exists', 'size' or 'hash' according to what didn't match
(existence is checked first, then size, then hash), the expected
value and the actual value.
"""
mismatches = []
base = os.path.dirname(self.path)
record_path = self.get_distinfo_file('RECORD')
for path, hash_value, size in self.list_installed_files():
if not os.path.isabs(path):
path = os.path.join(base, path)
if path == record_path:
continue
if not os.path.exists(path):
mismatches.append((path, 'exists', True, False))
elif os.path.isfile(path):
actual_size = str(os.path.getsize(path))
if size and actual_size != size:
mismatches.append((path, 'size', size, actual_size))
elif hash_value:
if '=' in hash_value:
hasher = hash_value.split('=', 1)[0]
else:
hasher = None
with open(path, 'rb') as f:
actual_hash = self.get_hash(f.read(), hasher)
if actual_hash != hash_value:
mismatches.append((path, 'hash', hash_value, actual_hash))
return mismatches
@cached_property
def shared_locations(self):
"""
A dictionary of shared locations whose keys are in the set 'prefix',
'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'.
The corresponding value is the absolute path of that category for
this distribution, and takes into account any paths selected by the
user at installation time (e.g. via command-line arguments). In the
case of the 'namespace' key, this would be a list of absolute paths
for the roots of namespace packages in this distribution.
The first time this property is accessed, the relevant information is
read from the SHARED file in the .dist-info directory.
"""
result = {}
shared_path = os.path.join(self.path, 'SHARED')
if os.path.isfile(shared_path):
with codecs.open(shared_path, 'r', encoding='utf-8') as f:
lines = f.read().splitlines()
for line in lines:
key, value = line.split('=', 1)
if key == 'namespace':
result.setdefault(key, []).append(value)
else:
result[key] = value
return result
def write_shared_locations(self, paths, dry_run=False):
"""
Write shared location information to the SHARED file in .dist-info.
:param paths: A dictionary as described in the documentation for
:meth:`shared_locations`.
:param dry_run: If True, the action is logged but no file is actually
written.
:return: The path of the file written to.
"""
shared_path = os.path.join(self.path, 'SHARED')
logger.info('creating %s', shared_path)
if dry_run:
return None
lines = []
for key in ('prefix', 'lib', 'headers', 'scripts', 'data'):
path = paths[key]
if os.path.isdir(paths[key]):
lines.append('%s=%s' % (key, path))
for ns in paths.get('namespace', ()):
lines.append('namespace=%s' % ns)
with codecs.open(shared_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines))
return shared_path
def get_distinfo_resource(self, path):
if path not in DIST_FILES:
raise DistlibException('invalid path for a dist-info file: '
'%r at %r' % (path, self.path))
finder = resources.finder_for_path(self.path)
if finder is None:
raise DistlibException('Unable to get a finder for %s' % self.path)
return finder.find(path)
def get_distinfo_file(self, path):
"""
Returns a path located under the ``.dist-info`` directory. Returns a
string representing the path.
:parameter path: a ``'/'``-separated path relative to the
``.dist-info`` directory or an absolute path;
If *path* is an absolute path and doesn't start
with the ``.dist-info`` directory path,
a :class:`DistlibException` is raised
:type path: str
:rtype: str
"""
# Check if it is an absolute path # XXX use relpath, add tests
if path.find(os.sep) >= 0:
# it's an absolute path?
distinfo_dirname, path = path.split(os.sep)[-2:]
if distinfo_dirname != self.path.split(os.sep)[-1]:
raise DistlibException(
'dist-info file %r does not belong to the %r %s '
'distribution' % (path, self.name, self.version))
# The file must be relative
if path not in DIST_FILES:
raise DistlibException('invalid path for a dist-info file: '
'%r at %r' % (path, self.path))
return os.path.join(self.path, path)
def list_distinfo_files(self):
"""
Iterates over the ``RECORD`` entries and returns paths for each line if
the path is pointing to a file located in the ``.dist-info`` directory
or one of its subdirectories.
:returns: iterator of paths
"""
base = os.path.dirname(self.path)
for path, checksum, size in self._get_records():
# XXX add separator or use real relpath algo
if not os.path.isabs(path):
path = os.path.join(base, path)
if path.startswith(self.path):
yield path
def __eq__(self, other):
return (isinstance(other, InstalledDistribution) and
self.path == other.path)
# See http://docs.python.org/reference/datamodel#object.__hash__
__hash__ = object.__hash__
class EggInfoDistribution(BaseInstalledDistribution):
"""Created with the *path* of the ``.egg-info`` directory or file provided
to the constructor. It reads the metadata contained in the file itself, or
if the given path happens to be a directory, the metadata is read from the
file ``PKG-INFO`` under that directory."""
requested = True # as we have no way of knowing, assume it was
shared_locations = {}
def __init__(self, path, env=None):
def set_name_and_version(s, n, v):
s.name = n
s.key = n.lower() # for case-insensitive comparisons
s.version = v
self.path = path
self.dist_path = env
if env and env._cache_enabled and path in env._cache_egg.path:
metadata = env._cache_egg.path[path].metadata
set_name_and_version(self, metadata.name, metadata.version)
else:
metadata = self._get_metadata(path)
# Need to be set before caching
set_name_and_version(self, metadata.name, metadata.version)
if env and env._cache_enabled:
env._cache_egg.add(self)
super(EggInfoDistribution, self).__init__(metadata, path, env)
def _get_metadata(self, path):
requires = None
def parse_requires_data(data):
"""Create a list of dependencies from a requires.txt file.
*data*: the contents of a setuptools-produced requires.txt file.
"""
reqs = []
lines = data.splitlines()
for line in lines:
line = line.strip()
if line.startswith('['):
logger.warning('Unexpected line: quitting requirement scan: %r',
line)
break
r = parse_requirement(line)
if not r:
logger.warning('Not recognised as a requirement: %r', line)
continue
if r.extras:
logger.warning('extra requirements in requires.txt are '
'not supported')
if not r.constraints:
reqs.append(r.name)
else:
cons = ', '.join('%s%s' % c for c in r.constraints)
reqs.append('%s (%s)' % (r.name, cons))
return reqs
def parse_requires_path(req_path):
"""Create a list of dependencies from a requires.txt file.
*req_path*: the path to a setuptools-produced requires.txt file.
"""
reqs = []
try:
with codecs.open(req_path, 'r', 'utf-8') as fp:
reqs = parse_requires_data(fp.read())
except IOError:
pass
return reqs
if path.endswith('.egg'):
if os.path.isdir(path):
meta_path = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
metadata = Metadata(path=meta_path, scheme='legacy')
req_path = os.path.join(path, 'EGG-INFO', 'requires.txt')
requires = parse_requires_path(req_path)
else:
# FIXME handle the case where zipfile is not available
zipf = zipimport.zipimporter(path)
fileobj = StringIO(
zipf.get_data('EGG-INFO/PKG-INFO').decode('utf8'))
metadata = Metadata(fileobj=fileobj, scheme='legacy')
try:
data = zipf.get_data('EGG-INFO/requires.txt')
requires = parse_requires_data(data.decode('utf-8'))
except IOError:
requires = None
elif path.endswith('.egg-info'):
if os.path.isdir(path):
req_path = os.path.join(path, 'requires.txt')
requires = parse_requires_path(req_path)
path = os.path.join(path, 'PKG-INFO')
metadata = Metadata(path=path, scheme='legacy')
else:
raise DistlibException('path must end with .egg-info or .egg, '
'got %r' % path)
if requires:
metadata.add_requirements(requires)
return metadata
def __repr__(self):
return '<EggInfoDistribution %r %s at %r>' % (
self.name, self.version, self.path)
def __str__(self):
return "%s %s" % (self.name, self.version)
def check_installed_files(self):
"""
Checks that the hashes and sizes of the files in ``RECORD`` are
matched by the files themselves. Returns a (possibly empty) list of
mismatches. Each entry in the mismatch list will be a tuple consisting
of the path, 'exists', 'size' or 'hash' according to what didn't match
(existence is checked first, then size, then hash), the expected
value and the actual value.
"""
mismatches = []
record_path = os.path.join(self.path, 'installed-files.txt')
if os.path.exists(record_path):
for path, _, _ in self.list_installed_files():
if path == record_path:
continue
if not os.path.exists(path):
mismatches.append((path, 'exists', True, False))
return mismatches
def list_installed_files(self):
"""
Iterates over the ``installed-files.txt`` entries and returns a tuple
``(path, hash, size)`` for each line.
:returns: a list of (path, hash, size)
"""
def _md5(path):
f = open(path, 'rb')
try:
content = f.read()
finally:
f.close()
return hashlib.md5(content).hexdigest()
def _size(path):
return os.stat(path).st_size
record_path = os.path.join(self.path, 'installed-files.txt')
result = []
if os.path.exists(record_path):
with codecs.open(record_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
p = os.path.normpath(os.path.join(self.path, line))
# "./" is present as a marker between installed files
# and installation metadata files
if not os.path.exists(p):
logger.warning('Non-existent file: %s', p)
if p.endswith(('.pyc', '.pyo')):
continue
#otherwise fall through and fail
if not os.path.isdir(p):
result.append((p, _md5(p), _size(p)))
result.append((record_path, None, None))
return result
def list_distinfo_files(self, absolute=False):
"""
Iterates over the ``installed-files.txt`` entries and returns paths for
each line if the path is pointing to a file located in the
``.egg-info`` directory or one of its subdirectories.
:parameter absolute: If *absolute* is ``True``, each returned path is
transformed into a local absolute path. Otherwise the
raw value from ``installed-files.txt`` is returned.
:type absolute: boolean
:returns: iterator of paths
"""
record_path = os.path.join(self.path, 'installed-files.txt')
skip = True
with codecs.open(record_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line == './':
skip = False
continue
if not skip:
p = os.path.normpath(os.path.join(self.path, line))
if p.startswith(self.path):
if absolute:
yield p
else:
yield line
def __eq__(self, other):
return (isinstance(other, EggInfoDistribution) and
self.path == other.path)
# See http://docs.python.org/reference/datamodel#object.__hash__
__hash__ = object.__hash__
new_dist_class = InstalledDistribution
old_dist_class = EggInfoDistribution
class DependencyGraph(object):
"""
Represents a dependency graph between distributions.
The dependency relationships are stored in an ``adjacency_list`` that maps
distributions to a list of ``(other, label)`` tuples where ``other``
is a distribution and the edge is labeled with ``label`` (i.e. the version
specifier, if such was provided). Also, for more efficient traversal, for
every distribution ``x``, a list of predecessors is kept in
``reverse_list[x]``. An edge from distribution ``a`` to
distribution ``b`` means that ``a`` depends on ``b``. If any missing
dependencies are found, they are stored in ``missing``, which is a
dictionary that maps distributions to a list of requirements that were not
provided by any other distributions.
"""
def __init__(self):
self.adjacency_list = {}
self.reverse_list = {}
self.missing = {}
def add_distribution(self, distribution):
"""Add the *distribution* to the graph.
:type distribution: :class:`distutils2.database.InstalledDistribution`
or :class:`distutils2.database.EggInfoDistribution`
"""
self.adjacency_list[distribution] = []
self.reverse_list[distribution] = []
#self.missing[distribution] = []
def add_edge(self, x, y, label=None):
"""Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type label: ``str`` or ``None``
"""
self.adjacency_list[x].append((y, label))
# multiple edges are allowed, so be careful
if x not in self.reverse_list[y]:
self.reverse_list[y].append(x)
def add_missing(self, distribution, requirement):
"""
Add a missing *requirement* for the given *distribution*.
:type distribution: :class:`distutils2.database.InstalledDistribution`
or :class:`distutils2.database.EggInfoDistribution`
:type requirement: ``str``
"""
logger.debug('%s missing %r', distribution, requirement)
self.missing.setdefault(distribution, []).append(requirement)
def _repr_dist(self, dist):
return '%s %s' % (dist.name, dist.version)
def repr_node(self, dist, level=1):
"""Prints only a subgraph"""
output = [self._repr_dist(dist)]
for other, label in self.adjacency_list[dist]:
dist = self._repr_dist(other)
if label is not None:
dist = '%s [%s]' % (dist, label)
output.append(' ' * level + str(dist))
suboutput = self.repr_node(other, level + 1)
subs = suboutput.split('\n')
output.extend(subs[1:])
return '\n'.join(output)
def to_dot(self, f, skip_disconnected=True):
"""Writes a DOT output for the graph to the provided file *f*.
If *skip_disconnected* is set to ``True``, then all distributions
that are not dependent on any other distribution are skipped.
:type f: has to support ``file``-like operations
:type skip_disconnected: ``bool``
"""
disconnected = []
f.write("digraph dependencies {\n")
for dist, adjs in self.adjacency_list.items():
if len(adjs) == 0 and not skip_disconnected:
disconnected.append(dist)
for other, label in adjs:
if not label is None:
f.write('"%s" -> "%s" [label="%s"]\n' %
(dist.name, other.name, label))
else:
f.write('"%s" -> "%s"\n' % (dist.name, other.name))
if not skip_disconnected and len(disconnected) > 0:
f.write('subgraph disconnected {\n')
f.write('label = "Disconnected"\n')
f.write('bgcolor = red\n')
for dist in disconnected:
f.write('"%s"' % dist.name)
f.write('\n')
f.write('}\n')
f.write('}\n')
def topological_sort(self):
"""
Perform a topological sort of the graph.
:return: A tuple, the first element of which is a topologically sorted
list of distributions, and the second element of which is a
list of distributions that cannot be sorted because they have
circular dependencies and so form a cycle.
"""
result = []
# Make a shallow copy of the adjacency list
alist = {}
for k, v in self.adjacency_list.items():
alist[k] = v[:]
while True:
# See what we can remove in this run
to_remove = []
for k, v in list(alist.items())[:]:
if not v:
to_remove.append(k)
del alist[k]
if not to_remove:
# What's left in alist (if anything) is a cycle.
break
# Remove from the adjacency list of others
for k, v in alist.items():
alist[k] = [(d, r) for d, r in v if d not in to_remove]
logger.debug('Moving to result: %s',
['%s (%s)' % (d.name, d.version) for d in to_remove])
result.extend(to_remove)
return result, list(alist.keys())
def __repr__(self):
"""Representation of the graph"""
output = []
for dist, adjs in self.adjacency_list.items():
output.append(self.repr_node(dist))
return '\n'.join(output)
def make_graph(dists, scheme='default'):
"""Makes a dependency graph from the given distributions.
:parameter dists: a list of distributions
:type dists: list of :class:`distutils2.database.InstalledDistribution` and
:class:`distutils2.database.EggInfoDistribution` instances
:rtype: a :class:`DependencyGraph` instance
"""
scheme = get_scheme(scheme)
graph = DependencyGraph()
provided = {} # maps names to lists of (version, dist) tuples
# first, build the graph and find out what's provided
for dist in dists:
graph.add_distribution(dist)
for p in dist.provides:
name, version = parse_name_and_version(p)
logger.debug('Add to provided: %s, %s, %s', name, version, dist)
provided.setdefault(name, []).append((version, dist))
# now make the edges
for dist in dists:
requires = (dist.run_requires | dist.meta_requires |
dist.build_requires | dist.dev_requires)
for req in requires:
try:
matcher = scheme.matcher(req)
except UnsupportedVersionError:
# XXX compat-mode if cannot read the version
logger.warning('could not read version %r - using name only',
req)
name = req.split()[0]
matcher = scheme.matcher(name)
name = matcher.key # case-insensitive
matched = False
if name in provided:
for version, provider in provided[name]:
try:
match = matcher.match(version)
except UnsupportedVersionError:
match = False
if match:
graph.add_edge(dist, provider, req)
matched = True
break
if not matched:
graph.add_missing(dist, req)
return graph
def get_dependent_dists(dists, dist):
"""Recursively generate a list of distributions from *dists* that are
dependent on *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested
"""
if dist not in dists:
raise DistlibException('given distribution %r is not a member '
'of the list' % dist.name)
graph = make_graph(dists)
dep = [dist] # dependent distributions
todo = graph.reverse_list[dist] # list of nodes we should inspect
while todo:
d = todo.pop()
dep.append(d)
for succ in graph.reverse_list[d]:
if succ not in dep:
todo.append(succ)
dep.pop(0) # remove dist from dep, was there to prevent infinite loops
return dep
def get_required_dists(dists, dist):
"""Recursively generate a list of distributions from *dists* that are
required by *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested
"""
if dist not in dists:
raise DistlibException('given distribution %r is not a member '
'of the list' % dist.name)
graph = make_graph(dists)
req = [] # required distributions
todo = graph.adjacency_list[dist] # list of nodes we should inspect
while todo:
d = todo.pop()[0]
req.append(d)
for pred in graph.adjacency_list[d]:
if pred not in req:
todo.append(pred)
return req
def make_dist(name, version, **kwargs):
"""
A convenience method for making a dist given just a name and version.
"""
summary = kwargs.pop('summary', 'Placeholder for summary')
md = Metadata(**kwargs)
md.name = name
md.version = version
md.summary = summary or 'Placeholder for summary'
return Distribution(md)
| {
"pile_set_name": "Github"
} |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2011 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google Inc. 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
// OWNER 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.
// Protocol buffer deep copy and merge.
// TODO: RawMessage.
package proto
import (
"fmt"
"log"
"reflect"
"strings"
)
// Clone returns a deep copy of a protocol buffer.
func Clone(src Message) Message {
in := reflect.ValueOf(src)
if in.IsNil() {
return src
}
out := reflect.New(in.Type().Elem())
dst := out.Interface().(Message)
Merge(dst, src)
return dst
}
// Merger is the interface representing objects that can merge messages of the same type.
type Merger interface {
// Merge merges src into this message.
// Required and optional fields that are set in src will be set to that value in dst.
// Elements of repeated fields will be appended.
//
// Merge may panic if called with a different argument type than the receiver.
Merge(src Message)
}
// generatedMerger is the custom merge method that generated protos will have.
// We must add this method since a generate Merge method will conflict with
// many existing protos that have a Merge data field already defined.
type generatedMerger interface {
XXX_Merge(src Message)
}
// Merge merges src into dst.
// Required and optional fields that are set in src will be set to that value in dst.
// Elements of repeated fields will be appended.
// Merge panics if src and dst are not the same type, or if dst is nil.
func Merge(dst, src Message) {
if m, ok := dst.(Merger); ok {
m.Merge(src)
return
}
in := reflect.ValueOf(src)
out := reflect.ValueOf(dst)
if out.IsNil() {
panic("proto: nil destination")
}
if in.Type() != out.Type() {
panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src))
}
if in.IsNil() {
return // Merge from nil src is a noop
}
if m, ok := dst.(generatedMerger); ok {
m.XXX_Merge(src)
return
}
mergeStruct(out.Elem(), in.Elem())
}
func mergeStruct(out, in reflect.Value) {
sprop := GetProperties(in.Type())
for i := 0; i < in.NumField(); i++ {
f := in.Type().Field(i)
if strings.HasPrefix(f.Name, "XXX_") {
continue
}
mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
}
if emIn, err := extendable(in.Addr().Interface()); err == nil {
emOut, _ := extendable(out.Addr().Interface())
mIn, muIn := emIn.extensionsRead()
if mIn != nil {
mOut := emOut.extensionsWrite()
muIn.Lock()
mergeExtension(mOut, mIn)
muIn.Unlock()
}
}
uf := in.FieldByName("XXX_unrecognized")
if !uf.IsValid() {
return
}
uin := uf.Bytes()
if len(uin) > 0 {
out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
}
}
// mergeAny performs a merge between two values of the same type.
// viaPtr indicates whether the values were indirected through a pointer (implying proto2).
// prop is set if this is a struct field (it may be nil).
func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
if in.Type() == protoMessageType {
if !in.IsNil() {
if out.IsNil() {
out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
} else {
Merge(out.Interface().(Message), in.Interface().(Message))
}
}
return
}
switch in.Kind() {
case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
reflect.String, reflect.Uint32, reflect.Uint64:
if !viaPtr && isProto3Zero(in) {
return
}
out.Set(in)
case reflect.Interface:
// Probably a oneof field; copy non-nil values.
if in.IsNil() {
return
}
// Allocate destination if it is not set, or set to a different type.
// Otherwise we will merge as normal.
if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
}
mergeAny(out.Elem(), in.Elem(), false, nil)
case reflect.Map:
if in.Len() == 0 {
return
}
if out.IsNil() {
out.Set(reflect.MakeMap(in.Type()))
}
// For maps with value types of *T or []byte we need to deep copy each value.
elemKind := in.Type().Elem().Kind()
for _, key := range in.MapKeys() {
var val reflect.Value
switch elemKind {
case reflect.Ptr:
val = reflect.New(in.Type().Elem().Elem())
mergeAny(val, in.MapIndex(key), false, nil)
case reflect.Slice:
val = in.MapIndex(key)
val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
default:
val = in.MapIndex(key)
}
out.SetMapIndex(key, val)
}
case reflect.Ptr:
if in.IsNil() {
return
}
if out.IsNil() {
out.Set(reflect.New(in.Elem().Type()))
}
mergeAny(out.Elem(), in.Elem(), true, nil)
case reflect.Slice:
if in.IsNil() {
return
}
if in.Type().Elem().Kind() == reflect.Uint8 {
// []byte is a scalar bytes field, not a repeated field.
// Edge case: if this is in a proto3 message, a zero length
// bytes field is considered the zero value, and should not
// be merged.
if prop != nil && prop.proto3 && in.Len() == 0 {
return
}
// Make a deep copy.
// Append to []byte{} instead of []byte(nil) so that we never end up
// with a nil result.
out.SetBytes(append([]byte{}, in.Bytes()...))
return
}
n := in.Len()
if out.IsNil() {
out.Set(reflect.MakeSlice(in.Type(), 0, n))
}
switch in.Type().Elem().Kind() {
case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
reflect.String, reflect.Uint32, reflect.Uint64:
out.Set(reflect.AppendSlice(out, in))
default:
for i := 0; i < n; i++ {
x := reflect.Indirect(reflect.New(in.Type().Elem()))
mergeAny(x, in.Index(i), false, nil)
out.Set(reflect.Append(out, x))
}
}
case reflect.Struct:
mergeStruct(out, in)
default:
// unknown type, so not a protocol buffer
log.Printf("proto: don't know how to copy %v", in)
}
}
func mergeExtension(out, in map[int32]Extension) {
for extNum, eIn := range in {
eOut := Extension{desc: eIn.desc}
if eIn.value != nil {
v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
eOut.value = v.Interface()
}
if eIn.enc != nil {
eOut.enc = make([]byte, len(eIn.enc))
copy(eOut.enc, eIn.enc)
}
out[extNum] = eOut
}
}
| {
"pile_set_name": "Github"
} |
package client // import "github.com/docker/docker/client"
import (
"context"
"encoding/json"
"net/url"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
)
// NetworkList returns the list of networks configured in the docker host.
func (cli *Client) NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) {
query := url.Values{}
if options.Filters.Len() > 0 {
//lint:ignore SA1019 for old code
filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters)
if err != nil {
return nil, err
}
query.Set("filters", filterJSON)
}
var networkResources []types.NetworkResource
resp, err := cli.get(ctx, "/networks", query, nil)
defer ensureReaderClosed(resp)
if err != nil {
return networkResources, err
}
err = json.NewDecoder(resp.body).Decode(&networkResources)
return networkResources, err
}
| {
"pile_set_name": "Github"
} |
/*
* 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 org.silkframework.plugins.temporal.relation
import org.scalatest.{FlatSpec, Matchers}
/**
* Tests the After Metric.
* @author Panayiotis Smeros <[email protected]> (National and Kapodistrian University of Athens)
*/
class AfterMetricTest extends FlatSpec with Matchers {
val metric = new AfterMetric()
"AfterMetric" should "compare date time intervals" in {
metric.evaluate("[2000-01-01T00:00:02, 2000-01-01T00:00:03)", "[2000-01-01T00:00:00, 2000-01-01T00:00:01)") should equal(0.0)
}
"AfterMetric" should "compare date times" in {
metric.evaluate("2000-01-05T00:00:00", "2000-01-01T00:00:00") should equal(0.0)
metric.evaluate("2000-01-01T00:00:00", "2000-01-02T00:00:00") should equal(1.0)
metric.evaluate("2000-01-01T00:00:01", "2000-01-01T00:00:00") should equal(0.0)
metric.evaluate("2000-01-01T00:00:00", "2000-01-01T00:00:01") should equal(1.0)
}
"AfterMetric" should "compare dates" in {
metric.evaluate("2000-01-05", "2000-01-01") should equal(0.0)
metric.evaluate("2000-01-00", "2000-01-02") should equal(1.0)
}
}
| {
"pile_set_name": "Github"
} |
# SPDX-License-Identifier: AGPL-3.0-or-later
@apps @minidlna
Feature: minidlna Simple Media Server
Run miniDLNA media server
Background:
Given I'm a logged in user
And the minidlna application is installed
Scenario: Enable minidlna application
Given the minidlna application is disabled
When I enable the minidlna application
Then the minidlna service should be running
Scenario: Disable minidlna application
Given the minidlna application is enabled
When I disable the minidlna application
Then the minidlna service should not be running
| {
"pile_set_name": "Github"
} |
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Examples:
[2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
For example:
add(1)
add(2)
findMedian() -> 1.5
add(3)
findMedian() -> 2
Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.
Hide Company Tags Google
Show Tags
| {
"pile_set_name": "Github"
} |
package com.google.sitebricks;
import java.io.File;
public class FileTemplateSource implements TemplateSource {
private File templateFile;
public FileTemplateSource(File templateFile) {
this.templateFile = templateFile;
}
@Override
public String getLocation() {
return templateFile.getAbsolutePath();
}
}
| {
"pile_set_name": "Github"
} |
# ADVSDK
ADVSDK是一款针对PaddlePaddle框架定制的轻量级SDK。目前支持学术届和工业界公认的基线测试算法,并且支持输出$L_0$、$L_2$和$L_(inf)$并可视化。
## 支持算法
- PGD
- FGSM
## 使用教程
全部教程使用jupter编写,方便使用和阅读。
- [攻击AlexNet](sdk_demo_alexnet.ipynb)
- [攻击ResNet](sdk_demo.ipynb)
## 模型文件地址
https://github.com/PaddlePaddle/models/tree/develop/PaddleCV/image_classification
wget http://paddle-imagenet-models-name.bj.bcebos.com/ResNet50_pretrained.tar
tar -xvf ResNet50_pretrained.tar
[更多模型](https://github.com/PaddlePaddle/models/tree/develop/PaddleCV)
## 初始化环境
pip install opencv-python
pip install paddlepaddle==1.5
| {
"pile_set_name": "Github"
} |
/*
MIT License (MIT)
Copyright (c) 2015 Clement CN Tsang
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.
*/
#import "CTAssetsPickerDefines.h"
#import "CTAssetsPickerController.h"
#import "CTAssetsPickerController+Internal.h"
#import "CTAssetCollectionViewController.h"
#import "CTAssetCollectionViewCell.h"
#import "CTAssetsGridViewController.h"
#import "PHAssetCollection+CTAssetsPickerController.h"
#import "PHAsset+CTAssetsPickerController.h"
#import "PHImageManager+CTAssetsPickerController.h"
#import "NSBundle+CTAssetsPickerController.h"
@interface CTAssetCollectionViewController()
<PHPhotoLibraryChangeObserver, CTAssetsGridViewControllerDelegate>
@property (nonatomic, weak) CTAssetsPickerController *picker;
@property (nonatomic, strong) UIBarButtonItem *cancelButton;
@property (nonatomic, strong) UIBarButtonItem *doneButton;
@property (nonatomic, copy) NSArray *fetchResults;
@property (nonatomic, copy) NSArray *assetCollections;
@property (nonatomic, strong) PHCachingImageManager *imageManager;
@property (nonatomic, strong) PHAssetCollection *defaultAssetCollection;
@property (nonatomic, assign) BOOL didShowDefaultAssetCollection;
@property (nonatomic, assign) BOOL didSelectDefaultAssetCollection;
@end
@implementation CTAssetCollectionViewController
- (instancetype)init
{
if (self = [super initWithStyle:UITableViewStylePlain])
{
_imageManager = [PHCachingImageManager new];
[self addNotificationObserver];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupViews];
[self localize];
[self setupDefaultAssetCollection];
[self setupFetchResults];
[self registerChangeObserver];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self setupButtons];
[self updateTitle:self.picker.selectedAssets];
[self updateButton:self.picker.selectedAssets];
[self selectDefaultAssetCollection];
}
- (void)dealloc
{
[self unregisterChangeObserver];
[self removeNotificationObserver];
}
#pragma mark - Reload user interface
- (void)reloadUserInterface
{
[self setupViews];
[self setupButtons];
[self localize];
[self setupDefaultAssetCollection];
[self setupFetchResults];
}
#pragma mark - Accessors
- (CTAssetsPickerController *)picker
{
return (CTAssetsPickerController *)self.splitViewController.parentViewController;
}
- (NSIndexPath *)indexPathForAssetCollection:(PHAssetCollection *)assetCollection
{
NSInteger row = [self.assetCollections indexOfObject:assetCollection];
if (row != NSNotFound)
return [NSIndexPath indexPathForRow:row inSection:0];
else
return nil;
}
#pragma mark - Setup
- (void)setupViews
{
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight =
self.picker.assetCollectionThumbnailSize.height +
self.tableView.layoutMargins.top +
self.tableView.layoutMargins.bottom;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
- (void)setupButtons
{
if (self.doneButton == nil)
{
NSString *title = (self.picker.doneButtonTitle) ?
self.picker.doneButtonTitle : CTAssetsPickerLocalizedString(@"Done", nil);
self.doneButton =
[[UIBarButtonItem alloc] initWithTitle:title
style:UIBarButtonItemStyleDone
target:self.picker
action:@selector(finishPickingAssets:)];
}
if (self.cancelButton == nil)
{
self.cancelButton =
[[UIBarButtonItem alloc] initWithTitle:CTAssetsPickerLocalizedString(@"Cancel", nil)
style:UIBarButtonItemStylePlain
target:self.picker
action:@selector(dismiss:)];
}
}
- (void)localize
{
[self resetTitle];
}
- (void)setupFetchResults
{
NSMutableArray *fetchResults = [NSMutableArray new];
for (NSNumber *subtypeNumber in self.picker.assetCollectionSubtypes)
{
PHAssetCollectionType type = [PHAssetCollection ctassetPickerAssetCollectionTypeOfSubtype:subtypeNumber.integerValue];
PHAssetCollectionSubtype subtype = subtypeNumber.integerValue;
PHFetchResult *fetchResult =
[PHAssetCollection fetchAssetCollectionsWithType:type
subtype:subtype
options:self.picker.assetCollectionFetchOptions];
[fetchResults addObject:fetchResult];
}
self.fetchResults = [NSMutableArray arrayWithArray:fetchResults];
[self updateAssetCollections];
[self reloadData];
[self showDefaultAssetCollection];
}
- (void)updateAssetCollections
{
NSMutableArray *assetCollections = [NSMutableArray new];
for (PHFetchResult *fetchResult in self.fetchResults)
{
for (PHAssetCollection *assetCollection in fetchResult)
{
BOOL showsAssetCollection = YES;
if (!self.picker.showsEmptyAlbums)
{
PHFetchOptions *options = [PHFetchOptions new];
options.predicate = self.picker.assetsFetchOptions.predicate;
if ([options respondsToSelector:@selector(setFetchLimit:)])
options.fetchLimit = 1;
NSInteger count = [assetCollection ctassetPikcerCountOfAssetsFetchedWithOptions:options];
showsAssetCollection = (count > 0);
}
if (showsAssetCollection)
[assetCollections addObject:assetCollection];
}
}
self.assetCollections = [NSMutableArray arrayWithArray:assetCollections];
}
- (void)setupDefaultAssetCollection
{
if (!self.picker || self.picker.defaultAssetCollection == PHAssetCollectionSubtypeAny) {
self.defaultAssetCollection = nil;
return;
}
PHAssetCollectionType type = [PHAssetCollection ctassetPickerAssetCollectionTypeOfSubtype:self.picker.defaultAssetCollection];
PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:type subtype:self.picker.defaultAssetCollection options:self.picker.assetCollectionFetchOptions];
self.defaultAssetCollection = fetchResult.firstObject;
}
#pragma mark - Rotation
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
[self updateTitle:self.picker.selectedAssets];
[self updateButton:self.picker.selectedAssets];
} completion:nil];
}
#pragma mark - Notifications
- (void)addNotificationObserver
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(selectedAssetsChanged:)
name:CTAssetsPickerSelectedAssetsDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(contentSizeCategoryChanged:)
name:UIContentSizeCategoryDidChangeNotification
object:nil];
}
- (void)removeNotificationObserver
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:CTAssetsPickerSelectedAssetsDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIContentSizeCategoryDidChangeNotification object:nil];
}
#pragma mark - Photo library change observer
- (void)registerChangeObserver
{
[[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
}
- (void)unregisterChangeObserver
{
[[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
}
#pragma mark - Photo library changed
- (void)photoLibraryDidChange:(PHChange *)changeInstance
{
// Call might come on any background queue. Re-dispatch to the main queue to handle it.
dispatch_async(dispatch_get_main_queue(), ^{
NSMutableArray *updatedFetchResults = nil;
for (PHFetchResult *fetchResult in self.fetchResults)
{
PHFetchResultChangeDetails *changeDetails = [changeInstance changeDetailsForFetchResult:fetchResult];
if (changeDetails)
{
if (!updatedFetchResults)
updatedFetchResults = [self.fetchResults mutableCopy];
updatedFetchResults[[self.fetchResults indexOfObject:fetchResult]] = changeDetails.fetchResultAfterChanges;
}
}
if (updatedFetchResults)
{
self.fetchResults = updatedFetchResults;
[self updateAssetCollections];
[self reloadData];
}
});
}
#pragma mark - Selected assets changed
- (void)selectedAssetsChanged:(NSNotification *)notification
{
NSArray *selectedAssets = (NSArray *)notification.object;
[self updateTitle:selectedAssets];
[self updateButton:selectedAssets];
}
- (void)updateTitle:(NSArray *)selectedAssets
{
if ([self isTopViewController] && selectedAssets.count > 0)
self.title = self.picker.selectedAssetsString;
else
[self resetTitle];
}
- (void)updateButton:(NSArray *)selectedAssets
{
self.navigationItem.leftBarButtonItem = (self.picker.showsCancelButton) ? self.cancelButton : nil;
self.navigationItem.rightBarButtonItem = [self isTopViewController] ? self.doneButton : nil;
if (self.picker.alwaysEnableDoneButton)
self.navigationItem.rightBarButtonItem.enabled = YES;
else
self.navigationItem.rightBarButtonItem.enabled = (self.picker.selectedAssets.count > 0);
}
- (BOOL)isTopViewController
{
UIViewController *vc = self.splitViewController.viewControllers.lastObject;
if ([vc isMemberOfClass:[UINavigationController class]])
return (self == ((UINavigationController *)vc).topViewController);
else
return NO;
}
- (void)resetTitle
{
if (!self.picker.title)
self.title = CTAssetsPickerLocalizedString(@"Photos", nil);
else
self.title = self.picker.title;
}
#pragma mark - Content size category changed
- (void)contentSizeCategoryChanged:(NSNotification *)notification
{
[self reloadData];
}
#pragma mark - Reload data
- (void)reloadData
{
if (self.assetCollections.count > 0)
[self.tableView reloadData];
else
[self.picker showNoAssets];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.assetCollections.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
PHAssetCollection *collection = self.assetCollections[indexPath.row];
NSUInteger count;
if (self.picker.showsNumberOfAssets)
count = [collection ctassetPikcerCountOfAssetsFetchedWithOptions:self.picker.assetsFetchOptions];
else
count = NSNotFound;
static NSString *cellIdentifier = @"CellIdentifier";
CTAssetCollectionViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
cell = [[CTAssetCollectionViewCell alloc] initWithThumbnailSize:self.picker.assetCollectionThumbnailSize
reuseIdentifier:cellIdentifier];
[cell bind:collection count:count];
[self requestThumbnailsForCell:cell assetCollection:collection];
return cell;
}
- (void)requestThumbnailsForCell:(CTAssetCollectionViewCell *)cell assetCollection:(PHAssetCollection *)collection
{
NSUInteger count = cell.thumbnailStacks.thumbnailViews.count;
NSArray *assets = [self posterAssetsFromAssetCollection:collection count:count];
CGSize targetSize = [self.picker imageSizeForContainerSize:self.picker.assetCollectionThumbnailSize];
for (NSUInteger index = 0; index < count; index++)
{
CTAssetThumbnailView *thumbnailView = [cell.thumbnailStacks thumbnailAtIndex:index];
thumbnailView.hidden = (assets.count > 0) ? YES : NO;
if (index < assets.count)
{
PHAsset *asset = assets[index];
[self.imageManager ctassetsPickerRequestImageForAsset:asset
targetSize:targetSize
contentMode:PHImageContentModeAspectFill
options:self.picker.thumbnailRequestOptions
resultHandler:^(UIImage *image, NSDictionary *info){
[thumbnailView setHidden:NO];
[thumbnailView bind:image assetCollection:collection];
}];
}
}
}
- (NSArray *)posterAssetsFromAssetCollection:(PHAssetCollection *)collection count:(NSUInteger)count;
{
PHFetchOptions *options = [PHFetchOptions new];
options.predicate = self.picker.assetsFetchOptions.predicate; // aligned specified predicate
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult *result = [PHAsset fetchKeyAssetsInAssetCollection:collection options:options];
NSUInteger location = 0;
NSUInteger length = (result.count < count) ? result.count : count;
NSArray *assets = [self itemsFromFetchResult:result range:NSMakeRange(location, length)];
return assets;
}
- (NSArray *)itemsFromFetchResult:(PHFetchResult *)result range:(NSRange)range
{
if (result.count == 0)
return nil;
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
NSArray *array = [result objectsAtIndexes:indexSet];
return array;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
PHAssetCollection *collection = self.assetCollections[indexPath.row];
CTAssetsGridViewController *vc = [CTAssetsGridViewController new];
vc.title = self.picker.selectedAssetsString ? : collection.localizedTitle;
vc.assetCollection = collection;
vc.delegate = self;
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
nav.delegate = (id<UINavigationControllerDelegate>)self.picker;
[self.picker setShouldCollapseDetailViewController:NO];
[self.splitViewController showDetailViewController:nav sender:nil];
}
#pragma mark - Show / select default asset collection
- (void)showDefaultAssetCollection
{
if (self.defaultAssetCollection && !self.didShowDefaultAssetCollection)
{
CTAssetsGridViewController *vc = [CTAssetsGridViewController new];
vc.title = self.picker.selectedAssetsString ? : self.defaultAssetCollection.localizedTitle;
vc.assetCollection = self.defaultAssetCollection;
vc.delegate = self;
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
nav.delegate = (id<UINavigationControllerDelegate>)self.picker;
[self.picker setShouldCollapseDetailViewController:(self.picker.modalPresentationStyle == UIModalPresentationFormSheet)];
[self.splitViewController showDetailViewController:nav sender:nil];
NSIndexPath *indexPath = [self indexPathForAssetCollection:self.defaultAssetCollection];
[self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
self.didShowDefaultAssetCollection = YES;
}
}
- (void)selectDefaultAssetCollection
{
if (self.defaultAssetCollection && !self.didSelectDefaultAssetCollection)
{
NSIndexPath *indexPath = [self indexPathForAssetCollection:self.defaultAssetCollection];
if (indexPath)
{
[UIView animateWithDuration:0.0f
animations:^{
[self.tableView selectRowAtIndexPath:indexPath
animated:(!self.splitViewController.collapsed)
scrollPosition:UITableViewScrollPositionTop];
}
completion:^(BOOL finished){
// mimic clearsSelectionOnViewWillAppear
if (finished && self.splitViewController.collapsed)
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}];
}
self.didSelectDefaultAssetCollection = YES;
}
}
#pragma mark - Grid view controller delegate
- (void)assetsGridViewController:(CTAssetsGridViewController *)picker photoLibraryDidChangeForAssetCollection:(PHAssetCollection *)assetCollection
{
NSIndexPath *indexPath = [self indexPathForAssetCollection:assetCollection];
if (indexPath)
{
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}
}
@end | {
"pile_set_name": "Github"
} |
class AddBudgetTranslations < ActiveRecord::Migration[4.2]
def change
create_table :budget_translations do |t|
t.integer :budget_id, null: false
t.string :locale, null: false
t.timestamps null: false
t.string :name
t.index :budget_id
t.index :locale
end
end
end
| {
"pile_set_name": "Github"
} |
msgid ""
msgstr ""
"Project-Id-Version: QueryPHP Page\n"
"POT-Creation-Date: 2017-11-06 13:46+0800\n"
"PO-Revision-Date: 2018-05-04 08:00+0800\n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: zh_TW\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.7\n"
"X-Poedit-Basepath: ../../vendor/hunzhiwange/framework/src/Leevel/Page\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __\n"
"X-Poedit-SearchPath-0: .\n"
#: bootstrap_simple.php:65 bootstrap_simple.php:67
msgid "上一页"
msgstr "上一頁"
#: bootstrap_simple.php:78 bootstrap_simple.php:80
msgid "下一页"
msgstr "下一頁"
#: defaults.php:112
#, php-format
msgid "共 %d 条"
msgstr "共 %d 條"
#: defaults.php:201
msgid "前往"
msgstr "前往"
#: defaults.php:201
msgid "页"
msgstr "頁"
| {
"pile_set_name": "Github"
} |
<html>
<head>
<meta charset="utf-8" />
<title>Test #1 for bug #1043537</title>
<style>
div {
width: 200px;
height: 200px;
background: yellow;
}
div:before {
content: '';
background: hotpink;
display: block;
width: 40px;
height: 40px;
overflow: hidden;
resize: both;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.vfs;
import java.net.URI;
import java.nio.file.Path;
import org.xwiki.component.annotation.Role;
/**
* Helper to create a {@link Path} instance from an XWiki VFS URI
* (e.g. {@code attach:[email protected]/some/path}).
*
* @version $Id: 3d7d7f2f6e2dae579cfca2d26e4203b21178c243 $
* @since 8.4RC1
*/
@Role
public interface VfsPathFactory
{
/**
* @param uri the XWiki VFS URI (e.g. {@code attach:[email protected]/some/path})
* @return the corresponding NIO2 {@link Path} instance
* @throws VfsException if the URI is not valid or the user doesn't have permissions to access it
*/
Path create(URI uri) throws VfsException;
}
| {
"pile_set_name": "Github"
} |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./app.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./app.ts":
/*!****************!*\
!*** ./app.ts ***!
\****************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\nexports.__esModule = true;\nvar foo;\nfoo.bar = 'foobar';\n\n\n//# sourceURL=webpack:///./app.ts?");
/***/ })
/******/ }); | {
"pile_set_name": "Github"
} |
#-*- coding: ISO-8859-1 -*-
# pysqlite2/test/factory.py: tests for the various factories in pysqlite
#
# Copyright (C) 2005-2007 Gerhard Häring <[email protected]>
#
# This file is part of pysqlite.
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
import unittest
import sqlite3 as sqlite
class MyConnection(sqlite.Connection):
def __init__(self, *args, **kwargs):
sqlite.Connection.__init__(self, *args, **kwargs)
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
class MyCursor(sqlite.Cursor):
def __init__(self, *args, **kwargs):
sqlite.Cursor.__init__(self, *args, **kwargs)
self.row_factory = dict_factory
class ConnectionFactoryTests(unittest.TestCase):
def setUp(self):
self.con = sqlite.connect(":memory:", factory=MyConnection)
def tearDown(self):
self.con.close()
def CheckIsInstance(self):
self.assertTrue(isinstance(self.con,
MyConnection),
"connection is not instance of MyConnection")
class CursorFactoryTests(unittest.TestCase):
def setUp(self):
self.con = sqlite.connect(":memory:")
def tearDown(self):
self.con.close()
def CheckIsInstance(self):
cur = self.con.cursor(factory=MyCursor)
self.assertTrue(isinstance(cur,
MyCursor),
"cursor is not instance of MyCursor")
class RowFactoryTestsBackwardsCompat(unittest.TestCase):
def setUp(self):
self.con = sqlite.connect(":memory:")
def CheckIsProducedByFactory(self):
cur = self.con.cursor(factory=MyCursor)
cur.execute("select 4+5 as foo")
row = cur.fetchone()
self.assertTrue(isinstance(row,
dict),
"row is not instance of dict")
cur.close()
def tearDown(self):
self.con.close()
class RowFactoryTests(unittest.TestCase):
def setUp(self):
self.con = sqlite.connect(":memory:")
def CheckCustomFactory(self):
self.con.row_factory = lambda cur, row: list(row)
row = self.con.execute("select 1, 2").fetchone()
self.assertTrue(isinstance(row,
list),
"row is not instance of list")
def CheckSqliteRowIndex(self):
self.con.row_factory = sqlite.Row
row = self.con.execute("select 1 as a, 2 as b").fetchone()
self.assertTrue(isinstance(row,
sqlite.Row),
"row is not instance of sqlite.Row")
col1, col2 = row["a"], row["b"]
self.assertTrue(col1 == 1, "by name: wrong result for column 'a'")
self.assertTrue(col2 == 2, "by name: wrong result for column 'a'")
col1, col2 = row["A"], row["B"]
self.assertTrue(col1 == 1, "by name: wrong result for column 'A'")
self.assertTrue(col2 == 2, "by name: wrong result for column 'B'")
col1, col2 = row[0], row[1]
self.assertTrue(col1 == 1, "by index: wrong result for column 0")
self.assertTrue(col2 == 2, "by index: wrong result for column 1")
def CheckSqliteRowIter(self):
"""Checks if the row object is iterable"""
self.con.row_factory = sqlite.Row
row = self.con.execute("select 1 as a, 2 as b").fetchone()
for col in row:
pass
def CheckSqliteRowAsTuple(self):
"""Checks if the row object can be converted to a tuple"""
self.con.row_factory = sqlite.Row
row = self.con.execute("select 1 as a, 2 as b").fetchone()
t = tuple(row)
def CheckSqliteRowAsDict(self):
"""Checks if the row object can be correctly converted to a dictionary"""
self.con.row_factory = sqlite.Row
row = self.con.execute("select 1 as a, 2 as b").fetchone()
d = dict(row)
self.assertEqual(d["a"], row["a"])
self.assertEqual(d["b"], row["b"])
def CheckSqliteRowHashCmp(self):
"""Checks if the row object compares and hashes correctly"""
self.con.row_factory = sqlite.Row
row_1 = self.con.execute("select 1 as a, 2 as b").fetchone()
row_2 = self.con.execute("select 1 as a, 2 as b").fetchone()
row_3 = self.con.execute("select 1 as a, 3 as b").fetchone()
self.assertTrue(row_1 == row_1)
self.assertTrue(row_1 == row_2)
self.assertTrue(row_2 != row_3)
self.assertFalse(row_1 != row_1)
self.assertFalse(row_1 != row_2)
self.assertFalse(row_2 == row_3)
self.assertEqual(row_1, row_2)
self.assertEqual(hash(row_1), hash(row_2))
self.assertNotEqual(row_1, row_3)
self.assertNotEqual(hash(row_1), hash(row_3))
def tearDown(self):
self.con.close()
class TextFactoryTests(unittest.TestCase):
def setUp(self):
self.con = sqlite.connect(":memory:")
def CheckUnicode(self):
austria = unicode("Österreich", "latin1")
row = self.con.execute("select ?", (austria,)).fetchone()
self.assertTrue(type(row[0]) == unicode, "type of row[0] must be unicode")
def CheckString(self):
self.con.text_factory = str
austria = unicode("Österreich", "latin1")
row = self.con.execute("select ?", (austria,)).fetchone()
self.assertTrue(type(row[0]) == str, "type of row[0] must be str")
self.assertTrue(row[0] == austria.encode("utf-8"), "column must equal original data in UTF-8")
def CheckCustom(self):
self.con.text_factory = lambda x: unicode(x, "utf-8", "ignore")
austria = unicode("Österreich", "latin1")
row = self.con.execute("select ?", (austria.encode("latin1"),)).fetchone()
self.assertTrue(type(row[0]) == unicode, "type of row[0] must be unicode")
self.assertTrue(row[0].endswith(u"reich"), "column must contain original data")
def CheckOptimizedUnicode(self):
self.con.text_factory = sqlite.OptimizedUnicode
austria = unicode("Österreich", "latin1")
germany = unicode("Deutchland")
a_row = self.con.execute("select ?", (austria,)).fetchone()
d_row = self.con.execute("select ?", (germany,)).fetchone()
self.assertTrue(type(a_row[0]) == unicode, "type of non-ASCII row must be unicode")
self.assertTrue(type(d_row[0]) == str, "type of ASCII-only row must be str")
def tearDown(self):
self.con.close()
class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase):
def setUp(self):
self.con = sqlite.connect(":memory:")
self.con.execute("create table test (value text)")
self.con.execute("insert into test (value) values (?)", ("a\x00b",))
def CheckString(self):
# text_factory defaults to unicode
row = self.con.execute("select value from test").fetchone()
self.assertIs(type(row[0]), unicode)
self.assertEqual(row[0], "a\x00b")
def CheckCustom(self):
# A custom factory should receive an str argument
self.con.text_factory = lambda x: x
row = self.con.execute("select value from test").fetchone()
self.assertIs(type(row[0]), str)
self.assertEqual(row[0], "a\x00b")
def CheckOptimizedUnicodeAsString(self):
# ASCII -> str argument
self.con.text_factory = sqlite.OptimizedUnicode
row = self.con.execute("select value from test").fetchone()
self.assertIs(type(row[0]), str)
self.assertEqual(row[0], "a\x00b")
def CheckOptimizedUnicodeAsUnicode(self):
# Non-ASCII -> unicode argument
self.con.text_factory = sqlite.OptimizedUnicode
self.con.execute("delete from test")
self.con.execute("insert into test (value) values (?)", (u'ä\0ö',))
row = self.con.execute("select value from test").fetchone()
self.assertIs(type(row[0]), unicode)
self.assertEqual(row[0], u"ä\x00ö")
def tearDown(self):
self.con.close()
def suite():
connection_suite = unittest.makeSuite(ConnectionFactoryTests, "Check")
cursor_suite = unittest.makeSuite(CursorFactoryTests, "Check")
row_suite_compat = unittest.makeSuite(RowFactoryTestsBackwardsCompat, "Check")
row_suite = unittest.makeSuite(RowFactoryTests, "Check")
text_suite = unittest.makeSuite(TextFactoryTests, "Check")
text_zero_bytes_suite = unittest.makeSuite(TextFactoryTestsWithEmbeddedZeroBytes, "Check")
return unittest.TestSuite((connection_suite, cursor_suite, row_suite_compat, row_suite, text_suite, text_zero_bytes_suite))
def test():
runner = unittest.TextTestRunner()
runner.run(suite())
if __name__ == "__main__":
test()
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='utf-8'?>
<section xmlns="https://code.dccouncil.us/schemas/dc-library" xmlns:codified="https://code.dccouncil.us/schemas/codified" xmlns:codify="https://code.dccouncil.us/schemas/codify" xmlns:xi="http://www.w3.org/2001/XInclude" containing-doc="D.C. Code">
<num>50-1703</num>
<heading>Requirements.</heading>
<para>
<num>(a)</num>
<text>The operator of a motor vehicle may not transport any child of less than 3 years of age unless the child is properly restrained in a child restraint seat.</text>
</para>
<para>
<num>(b)</num>
<text>The operator of a motor vehicle shall not transport any child under 16 years of age unless the child is properly restrained in an approved child safety restraint system or restrained in a seat belt. Children under 8 years of age shall be properly seated in an installed infant, convertible (toddler) or booster child safety seat, according to the manufacturer’s instructions. A booster seat shall only be used with both a lap and shoulder belt.</text>
</para>
<para>
<num>(c)</num>
<text>A parent or legal guardian may transport his or her own child without restraint herein if that person is transporting a number of his or her own children of less than 16 years of age which exceeds the number of passenger positions equipped with safety belts in the motor vehicle. However, an unrestrained child may not be transported in the front seat of a motor vehicle.</text>
</para>
<para>
<num>(d)</num>
<text>Automobile rental companies shall be required to inform each customer of the provisions of this chapter and provide educational materials to the customer. The educational materials shall be provided by the Department of Transportation.</text>
</para>
<annotations>
<annotation doc="D.C. Law 4-194" type="History" path="§4">Mar. 10, 1983, D.C. Law 4-194, § 4, 30 DCR 49</annotation>
<annotation doc="D.C. Law 9-57" type="History">Mar. 7, 1992, D.C. Law 9-57, § 2(b), 38 DCR 7283</annotation>
<annotation doc="D.C. Law 14-212" type="History">Oct. 19, 2002, D.C. Law 14-212, § 2(a), 49 DCR 8137</annotation>
<annotation type="Effect of Amendments"><cite doc="D.C. Law 14-212">D.C. Law 14-212</cite> rewrote subsec. (b) and added subsec. (d). Prior to amendment, subsec. (b) read as follows: “(b) The operator of a motor vehicle may not transport any child between 3 years of age and 16 years of age unless the child is properly restrained in an approved child restraint seat or safety belt.”</annotation>
<annotation type="Prior Codifications">1981 Ed., § 40-1203.</annotation>
<annotation type="Section References">This section is referenced in <cite path="§50-1706">§ 50-1706</cite>.</annotation>
</annotations>
</section>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 1999-2000 Harri Porten ([email protected])
* Copyright (C) 2008-2018 Apple Inc. All rights reserved.
*
* 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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#pragma once
#include "JSObject.h"
namespace JSC {
class DateInstance final : public JSNonFinalObject {
public:
using Base = JSNonFinalObject;
static constexpr bool needsDestruction = true;
static void destroy(JSCell* cell)
{
static_cast<DateInstance*>(cell)->DateInstance::~DateInstance();
}
template<typename CellType, SubspaceAccess mode>
static IsoSubspace* subspaceFor(VM& vm)
{
return &vm.dateInstanceSpace;
}
static DateInstance* create(VM& vm, Structure* structure, double date)
{
DateInstance* instance = new (NotNull, allocateCell<DateInstance>(vm.heap)) DateInstance(vm, structure);
instance->finishCreation(vm, date);
return instance;
}
static DateInstance* create(VM& vm, Structure* structure)
{
DateInstance* instance = new (NotNull, allocateCell<DateInstance>(vm.heap)) DateInstance(vm, structure);
instance->finishCreation(vm);
return instance;
}
double internalNumber() const { return m_internalNumber; }
void setInternalNumber(double value) { m_internalNumber = value; }
DECLARE_EXPORT_INFO;
const GregorianDateTime* gregorianDateTime(VM& vm) const
{
if (m_data && m_data->m_gregorianDateTimeCachedForMS == internalNumber())
return &m_data->m_cachedGregorianDateTime;
return calculateGregorianDateTime(vm);
}
const GregorianDateTime* gregorianDateTimeUTC(VM& vm) const
{
if (m_data && m_data->m_gregorianDateTimeUTCCachedForMS == internalNumber())
return &m_data->m_cachedGregorianDateTimeUTC;
return calculateGregorianDateTimeUTC(vm);
}
static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
{
return Structure::create(vm, globalObject, prototype, TypeInfo(JSDateType, StructureFlags), info());
}
static ptrdiff_t offsetOfInternalNumber() { return OBJECT_OFFSETOF(DateInstance, m_internalNumber); }
static ptrdiff_t offsetOfData() { return OBJECT_OFFSETOF(DateInstance, m_data); }
private:
JS_EXPORT_PRIVATE DateInstance(VM&, Structure*);
void finishCreation(VM&);
JS_EXPORT_PRIVATE void finishCreation(VM&, double);
JS_EXPORT_PRIVATE const GregorianDateTime* calculateGregorianDateTime(VM&) const;
JS_EXPORT_PRIVATE const GregorianDateTime* calculateGregorianDateTimeUTC(VM&) const;
double m_internalNumber { PNaN };
mutable RefPtr<DateInstanceData> m_data;
};
} // namespace JSC
| {
"pile_set_name": "Github"
} |
import { Injectable } from "@angular/core";
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { Observable, throwError } from "rxjs";
import { catchError, tap, map } from "rxjs/operators";
import { IFile } from "./file";
import { environment } from "src/environments/environment";
import { IAuditLogEntry } from "../auditlogs/audit-log";
@Injectable({
providedIn: "root",
})
export class FileService {
private fileUrl = environment.ResourceServer.Endpoint + "files";
constructor(private http: HttpClient) {}
getFiles(): Observable<IFile[]> {
return this.http
.get<IFile[]>(this.fileUrl)
.pipe(catchError(this.handleError));
}
getFile(id: string): Observable<IFile | undefined> {
return this.http
.get<IFile>(this.fileUrl + "/" + id)
.pipe(catchError(this.handleError));
}
uploadFile(file: IFile): Observable<IFile | undefined> {
const formData: FormData = new FormData();
formData.append("formFile", file.formFile);
formData.append("name", file.name);
formData.append("description", file.description);
return this.http
.post<IFile>(this.fileUrl, formData)
.pipe(catchError(this.handleError));
}
updateFile(file: IFile): Observable<IFile | undefined> {
return this.http
.put<IFile>(this.fileUrl + "/" + file.id, file)
.pipe(catchError(this.handleError));
}
downloadFile(file: IFile): Observable<Blob> {
return this.http
.get(this.fileUrl + "/" + file.id + "/download", { responseType: "blob" })
.pipe(catchError(this.handleError));
}
deleteFile(file: IFile): Observable<IFile | undefined> {
return this.http
.delete<IFile>(this.fileUrl + "/" + file.id)
.pipe(catchError(this.handleError));
}
getAuditLogs(id: string): Observable<IAuditLogEntry[] | undefined> {
return this.http
.get<IAuditLogEntry[]>(this.fileUrl + "/" + id + "/auditLogs")
.pipe(catchError(this.handleError));
}
private handleError(err: HttpErrorResponse) {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
let errorMessage = "";
if (err.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
errorMessage = `An error occurred: ${err.error.message}`;
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
}
console.error(errorMessage);
return throwError(errorMessage);
}
}
| {
"pile_set_name": "Github"
} |
# SPDX-License-Identifier: CC-BY-SA-2.0
# SPDX-FileCopyrightText: 2013-2020 Normation SAS
post:
summary: Trigger update of policies
description: Update configuration policies if needed
operationId: updatePolicies
responses:
"200":
description: Success
content:
application/json:
schema:
type: object
required:
- result
- action
- data
properties:
result:
type: string
description: Result of the request
enum:
- success
- error
action:
type: string
description: The id of the action
enum:
- updatePolicies
data:
type: object
required:
- policies
properties:
policies:
type: string
enum:
- Started
tags:
- System
x-code-samples:
- lang: curl
source:
$ref: ../../code_samples/curl/system/update-policies.sh
| {
"pile_set_name": "Github"
} |
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
438CAE5F1B50060D00EA8B00 /* ActionKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 438CAE531B50060D00EA8B00 /* ActionKit.framework */; };
438CAE661B50060D00EA8B00 /* ActionKitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 438CAE651B50060D00EA8B00 /* ActionKitTests.swift */; };
438CAE721B5006EA00EA8B00 /* ActionKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 438CAE6F1B5006EA00EA8B00 /* ActionKit.swift */; };
438CAE731B5006EA00EA8B00 /* UIControl+ActionKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 438CAE701B5006EA00EA8B00 /* UIControl+ActionKit.swift */; };
438CAE741B5006EA00EA8B00 /* UIGestureRecognizer+ActionKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 438CAE711B5006EA00EA8B00 /* UIGestureRecognizer+ActionKit.swift */; };
72AB3FCE1D256D68009A6411 /* UIBarButtonItem+ActionKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72AB3FCD1D256D68009A6411 /* UIBarButtonItem+ActionKit.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
438CAE601B50060D00EA8B00 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 438CAE4A1B50060D00EA8B00 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 438CAE521B50060D00EA8B00;
remoteInfo = ActionKit;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
438CAE531B50060D00EA8B00 /* ActionKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = ActionKit.framework; sourceTree = BUILT_PRODUCTS_DIR; };
438CAE571B50060D00EA8B00 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
438CAE5E1B50060D00EA8B00 /* ActionKitTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = ActionKitTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
438CAE641B50060D00EA8B00 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
438CAE651B50060D00EA8B00 /* ActionKitTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ActionKitTests.swift; sourceTree = "<group>"; };
438CAE6F1B5006EA00EA8B00 /* ActionKit.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ActionKit.swift; sourceTree = "<group>"; };
438CAE701B5006EA00EA8B00 /* UIControl+ActionKit.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIControl+ActionKit.swift"; sourceTree = "<group>"; };
438CAE711B5006EA00EA8B00 /* UIGestureRecognizer+ActionKit.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIGestureRecognizer+ActionKit.swift"; sourceTree = "<group>"; };
72AB3FCD1D256D68009A6411 /* UIBarButtonItem+ActionKit.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIBarButtonItem+ActionKit.swift"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
438CAE4F1B50060D00EA8B00 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
438CAE5B1B50060D00EA8B00 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
438CAE5F1B50060D00EA8B00 /* ActionKit.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
438CAE491B50060D00EA8B00 = {
isa = PBXGroup;
children = (
438CAE551B50060D00EA8B00 /* ActionKit */,
438CAE621B50060D00EA8B00 /* ActionKitTests */,
438CAE541B50060D00EA8B00 /* Products */,
);
sourceTree = "<group>";
};
438CAE541B50060D00EA8B00 /* Products */ = {
isa = PBXGroup;
children = (
438CAE531B50060D00EA8B00 /* ActionKit.framework */,
438CAE5E1B50060D00EA8B00 /* ActionKitTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
438CAE551B50060D00EA8B00 /* ActionKit */ = {
isa = PBXGroup;
children = (
438CAE6F1B5006EA00EA8B00 /* ActionKit.swift */,
438CAE701B5006EA00EA8B00 /* UIControl+ActionKit.swift */,
438CAE711B5006EA00EA8B00 /* UIGestureRecognizer+ActionKit.swift */,
72AB3FCD1D256D68009A6411 /* UIBarButtonItem+ActionKit.swift */,
438CAE561B50060D00EA8B00 /* Supporting Files */,
);
path = ActionKit;
sourceTree = "<group>";
};
438CAE561B50060D00EA8B00 /* Supporting Files */ = {
isa = PBXGroup;
children = (
438CAE571B50060D00EA8B00 /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
438CAE621B50060D00EA8B00 /* ActionKitTests */ = {
isa = PBXGroup;
children = (
438CAE651B50060D00EA8B00 /* ActionKitTests.swift */,
438CAE631B50060D00EA8B00 /* Supporting Files */,
);
path = ActionKitTests;
sourceTree = "<group>";
};
438CAE631B50060D00EA8B00 /* Supporting Files */ = {
isa = PBXGroup;
children = (
438CAE641B50060D00EA8B00 /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
438CAE501B50060D00EA8B00 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXHeadersBuildPhase section */
/* Begin PBXNativeTarget section */
438CAE521B50060D00EA8B00 /* ActionKit */ = {
isa = PBXNativeTarget;
buildConfigurationList = 438CAE691B50060D00EA8B00 /* Build configuration list for PBXNativeTarget "ActionKit" */;
buildPhases = (
438CAE4E1B50060D00EA8B00 /* Sources */,
438CAE4F1B50060D00EA8B00 /* Frameworks */,
438CAE501B50060D00EA8B00 /* Headers */,
438CAE511B50060D00EA8B00 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = ActionKit;
productName = ActionKit;
productReference = 438CAE531B50060D00EA8B00 /* ActionKit.framework */;
productType = "com.apple.product-type.framework";
};
438CAE5D1B50060D00EA8B00 /* ActionKitTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 438CAE6C1B50060D00EA8B00 /* Build configuration list for PBXNativeTarget "ActionKitTests" */;
buildPhases = (
438CAE5A1B50060D00EA8B00 /* Sources */,
438CAE5B1B50060D00EA8B00 /* Frameworks */,
438CAE5C1B50060D00EA8B00 /* Resources */,
);
buildRules = (
);
dependencies = (
438CAE611B50060D00EA8B00 /* PBXTargetDependency */,
);
name = ActionKitTests;
productName = ActionKitTests;
productReference = 438CAE5E1B50060D00EA8B00 /* ActionKitTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
438CAE4A1B50060D00EA8B00 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftMigration = 0700;
LastSwiftUpdateCheck = 0700;
LastUpgradeCheck = 1030;
ORGANIZATIONNAME = ActionKit;
TargetAttributes = {
438CAE521B50060D00EA8B00 = {
CreatedOnToolsVersion = 6.4;
LastSwiftMigration = 0900;
};
438CAE5D1B50060D00EA8B00 = {
CreatedOnToolsVersion = 6.4;
LastSwiftMigration = 0900;
LastSwiftMigration = 1110;
};
};
};
buildConfigurationList = 438CAE4D1B50060D00EA8B00 /* Build configuration list for PBXProject "ActionKit" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 438CAE491B50060D00EA8B00;
productRefGroup = 438CAE541B50060D00EA8B00 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
438CAE521B50060D00EA8B00 /* ActionKit */,
438CAE5D1B50060D00EA8B00 /* ActionKitTests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
438CAE511B50060D00EA8B00 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
438CAE5C1B50060D00EA8B00 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
438CAE4E1B50060D00EA8B00 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
438CAE731B5006EA00EA8B00 /* UIControl+ActionKit.swift in Sources */,
72AB3FCE1D256D68009A6411 /* UIBarButtonItem+ActionKit.swift in Sources */,
438CAE741B5006EA00EA8B00 /* UIGestureRecognizer+ActionKit.swift in Sources */,
438CAE721B5006EA00EA8B00 /* ActionKit.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
438CAE5A1B50060D00EA8B00 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
438CAE661B50060D00EA8B00 /* ActionKitTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
438CAE611B50060D00EA8B00 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 438CAE521B50060D00EA8B00 /* ActionKit */;
targetProxy = 438CAE601B50060D00EA8B00 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
438CAE671B50060D00EA8B00 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
438CAE681B50060D00EA8B00 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
438CAE6A1B50060D00EA8B00 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = ActionKit/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "ActionKit.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
438CAE6B1B50060D00EA8B00 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = ActionKit/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "ActionKit.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 5.0;
};
name = Release;
};
438CAE6D1B50060D00EA8B00 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
FRAMEWORK_SEARCH_PATHS = "$(inherited)";
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
INFOPLIST_FILE = ActionKitTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "ActionKit.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 4.0;
};
name = Debug;
};
438CAE6E1B50060D00EA8B00 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
FRAMEWORK_SEARCH_PATHS = "$(inherited)";
INFOPLIST_FILE = ActionKitTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "ActionKit.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 4.0;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
438CAE4D1B50060D00EA8B00 /* Build configuration list for PBXProject "ActionKit" */ = {
isa = XCConfigurationList;
buildConfigurations = (
438CAE671B50060D00EA8B00 /* Debug */,
438CAE681B50060D00EA8B00 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
438CAE691B50060D00EA8B00 /* Build configuration list for PBXNativeTarget "ActionKit" */ = {
isa = XCConfigurationList;
buildConfigurations = (
438CAE6A1B50060D00EA8B00 /* Debug */,
438CAE6B1B50060D00EA8B00 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
438CAE6C1B50060D00EA8B00 /* Build configuration list for PBXNativeTarget "ActionKitTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
438CAE6D1B50060D00EA8B00 /* Debug */,
438CAE6E1B50060D00EA8B00 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 438CAE4A1B50060D00EA8B00 /* Project object */;
}
| {
"pile_set_name": "Github"
} |
/* Generated from:
* ap-northeast-1 (https://d33vqc0rt9ld30.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* eu-west-1 (https://d3teyb21fexa9r.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* us-east-1 (https://d1uauaxba7bl26.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* us-west-1 (https://d68hl49wbnanq.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0,
* us-west-2 (https://d201a2mn26r7lk.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json), version 16.2.0
*/
import {ResourceBase} from '../resource'
import {Value, List} from '../dataTypes'
export interface SubnetGroupProperties {
Description?: Value<string>
SubnetGroupName?: Value<string>
SubnetIds: List<Value<string>>
}
export default class SubnetGroup extends ResourceBase<SubnetGroupProperties> {
constructor(properties: SubnetGroupProperties) {
super('AWS::DAX::SubnetGroup', properties)
}
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
| {
"pile_set_name": "Github"
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
echo "\nDatabase error: ",
$heading,
"\n\n",
$message,
"\n\n"; | {
"pile_set_name": "Github"
} |