text
stringlengths 2
99.9k
| meta
dict |
---|---|
/*
* Copyright (C) 2013 Synopsys, Inc. (www.synopsys.com)
*
* Licensed under the LGPL v2.1 or later, see the file COPYING.LIB in this tarball.
*/
#define __JMP_BUF_SP (13+1)
| {
"pile_set_name": "Github"
} |
line0=BIND пътища,11
chroot=Коренова директория в която да се стартира BIND ,3,По подразбиране
no_chroot=В chroot директорията ли е named.conf?,1,0-Да,1-Не
auto_chroot=Команда за откриване на chroot директория,3,Използвай указаната по-горе директория
named_user=Юзер от чието име да се стартира BIND ,3,По подразбиране
named_group=Група от чието име да се стартира BIND,3,По подразбиране
zones_file=Добавяй новите зони във файл,3,named.conf
relative_paths=Използване на относителни пътища към зоновите файлове в <tt>named.conf</tt>?,1,1-Да,0-Не
keys_dir=Директория за DNSSEC ключове,3,Същата като за файловете за зони
line1=Настройки на дисплея,11
show_list=Показвай имената като,1,0-Икони,1-Списък
by_view=Категоризиране на зоните по изглед?,1,1-Да,0-Не
records_order=Ред за показване на записите по,1,1-Име,2-Стойност,3-IP адрес,0-Ред на добавяне
max_zones=Максимален брой зони за показване,0
rev_def=Обновяването на обратните адреси е,1,0-Включено по подразбиране,1-Изключено по подразбиране,2-Overwrite by default
rev_must=Обратнита зони трябва да съществуват?,1,1-Да,0-Не
support_aaaa=Поддръжка на DNS за IPv6 адреси,1,1-Да,0-Не
allow_comments=Позволи коментари към записите,1,1-Да,0-Не
allow_wild=Позволи wildcards,1,1-Да,0-Не
allow_underscore=Позволи underscores in record names?,1,1-Да,0-Не
short_names=Конвертирай записните имена в канонична форма?,1,0-Да,1-Не
extra_forward=Допълнителни типове записи за правите зони,0
extra_reverse=Допълнителни типове записи за обратните зони,0
largezones=Показване на записи в зоните?,1,0-Да,1-Не (за големи зони)
default_view=Подразбиращ се изглед за нови зони,3,Първият в списъка
line2=Настройки на зоналните файлове,11
soa_style=Стил на серийния номер,1,0-Running number,1-Date based (YYYYMMDDnn)
soa_start=Начално число в базираните на дата SOA,0,3
master_ttl=Добавяй $ttl в началото на новите зонални файлове,1,1-Да,0-Не
master_dir=Директория за главните зонални файлове,3,По подразбиране
slave_dir=Директория за подчинените/stub зонални файлове,3,По подразбиране
forwardzonefilename_format=Формат за имената на препращащите зонални файлове,0
reversezonefilename_format=Формат на имената на обръщащите зонални файлове,0
file_owner=Собственик на зоналните файлове (юзер:група),3,По подразбиране
file_perms=Права за зоналните файлове (in octal),3,По подразбиране
slave_file_perms=Права за файлове за подчинени зони (in octal),3,Същите като по-горе
default_prins=Подразбиращ се главен сървър за главни зони,3,Име на хоста на системата
default_master=Главен сървър по подразбиране(s) за подчинените зони,0
updserial_on=Атоматично обновяване на серийните номера,1,1-Да,0-Не
ipv6_mode=Домейн за обърнати IPv6 адреси,1,1-ip6.arpa,0-ip6.int
confirm_zone=Потвърждаване преди изтриване на зони?,1,1-Да,0-Не
confirm_rec=Потвърждаване преди изтриване на записи?,1,1-Да,0-Не
free_nets=IP мрежи за свободни адреси,3,Автоматично
force_random=Източник на ентропия за DNSSEC ключовете,1,1-/dev/random (Сигурно, но бавно),0-/dev/urandom (Потенциално несигурно, но бързо)
spf_record=Тип на реалния запис за Sender Permitted From,1,1-SPF,0-TXT
line2.5=Групови подчинени сървъри,11
this_ip=Подразбиращ се IP адрес за главния сървър за отдалечените подчинени зони,3,IP адресът на името на хоста
other_slaves=Добавяне на други подчинени IP адреси в списъка на главните за подчинените?,1,1-Да,0-Не
extra_slaves=Допълнителни главни IP адреси за подчинените зони,3,Няма
line3=Системна конфигурация,11
named_conf=Пълен път към файла named.conf,0
named_path=Пълен път към изпълнимия файл named,0
whois_cmd=Пълен път към командата whois,0
ndc_cmd=Команда за презареждане на zone,0
rndc_cmd=Пълен път към командата rdnc,0
rndcconf_cmd=Пълен път към командата rdnc-confgen,0
rndc_conf=Пълен път към файла rdnc.conf,0
checkzone=Пълен път към командата named-checkzone,0
checkconf=Пълен път към командата named-checkconf,0
keygen=Пълен път към командата dnssec-keygen,0
signzone=Пълен път към командата dnssec-signzone,0
pid_file=Местонахождение на PID по подразбиране,3,/var/run/named.pid
no_pid_chroot=В chroot директорията ли е PID файла?,1,0-Да,1-Не
start_cmd=Команда за стартиране на BIND,3,По подразбиране
stop_cmd=Команда за спиране на BIND,3,Просто убий процеса
restart_cmd=Команда за прилагане на конфигурацията на BIND,10,-Просто изпрати HUP сигнал,restart-Спри и стартирай,Друга команда
dnssectools_conf=Пълен път към файла dnssec-tools.conf,0
dnssectools_rollmgr_pidfile=Пълен път към rollmgr pid файла на dnssec-tools,0
dnssectools_rollrec=Пълен път към rollrec файла на dnssec-tools,0
dnssectools_keydir=Пълен път към директорията за ключове на dnssec-tools,0
| {
"pile_set_name": "Github"
} |
// (c) Copyright 2015-2017 JONNALAGADDA Srinivas
//
// 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 flow
import (
"database/sql"
"errors"
"fmt"
"math"
"strings"
)
// GroupID is the type of unique group identifiers.
type GroupID int64
// Group represents a specified collection of users. A user belongs
// to zero or more groups.
type Group struct {
ID GroupID `json:"ID"` // Globally-unique ID
Name string `json:"Name"` // Globally-unique name
GroupType string `json:"GroupType"` // Is this a user-specific group? Etc.
}
// Unexported type, only for convenience methods.
type _Groups struct{}
// Groups provides a resource-like interface to groups in the system.
var Groups _Groups
// NewSingleton creates a singleton group associated with the given
// user. The e-mail address of the user is used as the name of the
// group. This serves as the linking identifier.
func (_Groups) NewSingleton(otx *sql.Tx, uid UserID) (GroupID, error) {
var tx *sql.Tx
var err error
if otx == nil {
tx, err = db.Begin()
if err != nil {
return 0, err
}
defer tx.Rollback()
} else {
tx = otx
}
q := `
INSERT INTO wf_groups_master(name, group_type)
SELECT u.email, 'S'
FROM wf_users_master u
WHERE u.id = ?
`
res, err := tx.Exec(q, uid)
if err != nil {
return 0, err
}
var gid int64
gid, err = res.LastInsertId()
if err != nil {
return 0, err
}
res, err = tx.Exec("INSERT INTO wf_group_users(group_id, user_id) VALUES(?, ?)", gid, uid)
if err != nil {
return 0, err
}
_, err = res.LastInsertId()
if err != nil {
return 0, err
}
if otx == nil {
err = tx.Commit()
if err != nil {
return 0, err
}
}
return GroupID(gid), nil
}
// New creates a new group that can be populated with users later.
func (_Groups) New(otx *sql.Tx, name string, gtype string) (GroupID, error) {
name = strings.TrimSpace(name)
gtype = strings.TrimSpace(gtype)
if name == "" || gtype == "" {
return 0, errors.New("group name and type must not be empty")
}
switch gtype {
case "G": // General
// Nothing to do
default:
return 0, errors.New("unknown group type")
}
var tx *sql.Tx
var err error
if otx == nil {
tx, err = db.Begin()
if err != nil {
return 0, err
}
defer tx.Rollback()
} else {
tx = otx
}
res, err := tx.Exec("INSERT INTO wf_groups_master(name, group_type) VALUES(?, ?)", name, gtype)
if err != nil {
return 0, err
}
var id int64
id, err = res.LastInsertId()
if err != nil {
return 0, err
}
if otx == nil {
err = tx.Commit()
if err != nil {
return 0, err
}
}
return GroupID(id), nil
}
// List answers a subset of the groups, based on the input
// specification.
//
// Result set begins with ID >= `offset`, and has not more than
// `limit` elements. A value of `0` for `offset` fetches from the
// beginning, while a value of `0` for `limit` fetches until the end.
func (_Groups) List(offset, limit int64) ([]*Group, error) {
if offset < 0 || limit < 0 {
return nil, errors.New("offset and limit must be non-negative integers")
}
if limit == 0 {
limit = math.MaxInt64
}
q := `
SELECT id, name, group_type
FROM wf_groups_master
ORDER BY id
LIMIT ? OFFSET ?
`
rows, err := db.Query(q, limit, offset)
if err != nil {
return nil, err
}
defer rows.Close()
ary := make([]*Group, 0, 10)
for rows.Next() {
var g Group
err = rows.Scan(&g.ID, &g.Name, &g.GroupType)
if err != nil {
return nil, err
}
ary = append(ary, &g)
}
if err = rows.Err(); err != nil {
return nil, err
}
return ary, nil
}
// Get initialises the group by reading from database.
func (_Groups) Get(id GroupID) (*Group, error) {
if id <= 0 {
return nil, errors.New("group ID should be a positive integer")
}
var elem Group
row := db.QueryRow("SELECT id, name, group_type FROM wf_groups_master WHERE id = ?", id)
err := row.Scan(&elem.ID, &elem.Name, &elem.GroupType)
if err != nil {
return nil, err
}
return &elem, nil
}
// Rename renames the given group.
func (_Groups) Rename(otx *sql.Tx, id GroupID, name string) error {
name = strings.TrimSpace(name)
if name == "" {
return errors.New("name cannot be empty")
}
var elem Group
row := db.QueryRow("SELECT id, name, group_type FROM wf_groups_master WHERE id = ?", id)
err := row.Scan(&elem.ID, &elem.Name, &elem.GroupType)
if err != nil {
return err
}
if elem.GroupType == "S" {
return errors.New("cannot rename a singleton group")
}
var tx *sql.Tx
if otx == nil {
tx, err = db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
} else {
tx = otx
}
_, err = tx.Exec("UPDATE wf_groups_master SET name = ? WHERE id = ?", name, id)
if err != nil {
return err
}
if otx == nil {
err = tx.Commit()
if err != nil {
return err
}
}
return nil
}
// Delete deletes the given group from the system, if no access
// context is actively using it.
func (_Groups) Delete(otx *sql.Tx, id GroupID) error {
if id <= 0 {
return errors.New("group ID must be a positive integer")
}
row := db.QueryRow("SELECT group_type FROM wf_groups_master WHERE id = ?", id)
var gtype string
err := row.Scan(>ype)
if err != nil {
return err
}
if gtype == "S" {
return errors.New("singleton groups cannot be deleted")
}
row = db.QueryRow("SELECT COUNT(*) FROM wf_ac_group_roles WHERE group_id = ?", id)
var n int64
err = row.Scan(&n)
if n > 0 {
return errors.New("group is being used in at least one access context; cannot delete")
}
var tx *sql.Tx
if otx == nil {
tx, err = db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
} else {
tx = otx
}
_, err = tx.Exec("DELETE FROM wf_group_users WHERE group_id = ?", id)
if err != nil {
return err
}
res, err := tx.Exec("DELETE FROM wf_groups_master WHERE id = ?", id)
if err != nil {
return err
}
n, err = res.RowsAffected()
if n != 1 {
return fmt.Errorf("expected number of affected rows : 1; actual affected : %d", n)
}
if otx == nil {
err = tx.Commit()
if err != nil {
return err
}
}
return nil
}
// Users answers a list of the given group's users.
func (_Groups) Users(gid GroupID) ([]*User, error) {
q := `
SELECT um.id, um.first_name, um.last_name, um.email, um.active
FROM wf_users_master um
JOIN wf_group_users gu ON gu.user_id = um.id
WHERE gu.group_id = ?
`
rows, err := db.Query(q, gid)
if err != nil {
return nil, err
}
defer rows.Close()
ary := make([]*User, 0, 2)
for rows.Next() {
var elem User
err = rows.Scan(&elem.ID, &elem.FirstName, &elem.LastName, &elem.Email, &elem.Active)
if err != nil {
return nil, err
}
ary = append(ary, &elem)
}
if rows.Err() != nil {
return nil, err
}
return ary, nil
}
// HasUser answers `true` if this group includes the given user;
// `false` otherwise.
func (_Groups) HasUser(gid GroupID, uid UserID) (bool, error) {
q := `
SELECT id FROM wf_group_users
WHERE group_id = ?
AND user_id = ?
ORDER BY id
LIMIT 1
`
var id int64
row := db.QueryRow(q, gid, uid)
err := row.Scan(&id)
switch {
case err == sql.ErrNoRows:
return false, errors.New("given user is not part of the specified group")
case err != nil:
return false, err
default:
return true, nil
}
}
// SingletonUser answer the user ID of the corresponding user, if this
// group is a singleton group.
func (_Groups) SingletonUser(gid GroupID) (*User, error) {
q := `
SELECT um.id, um.first_name, um.last_name, um.email, um.active
FROM wf_users_master um
JOIN wf_group_users gus ON gus.user_id = um.id
JOIN wf_groups_master gm ON gus.group_id = gm.id
WHERE gm.id = ?
AND gm.group_type = 'S'
ORDER BY um.id
LIMIT 1
`
var elem User
row := db.QueryRow(q, gid)
err := row.Scan(&elem.ID, &elem.FirstName, &elem.LastName, &elem.Email, &elem.Active)
switch {
case err != nil:
return nil, err
default:
return &elem, nil
}
}
// AddUser adds the given user as a member of this group.
func (_Groups) AddUser(otx *sql.Tx, gid GroupID, uid UserID) error {
if gid <= 0 || uid <= 0 {
return errors.New("group ID and user ID must be positive integers")
}
var tx *sql.Tx
var err error
if otx == nil {
tx, err = db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
} else {
tx = otx
}
var gtype string
row := tx.QueryRow("SELECT group_type FROM wf_groups_master WHERE id = ?", gid)
err = row.Scan(>ype)
if err != nil {
return err
}
if gtype == "S" {
return errors.New("cannot add users to singleton groups")
}
_, err = tx.Exec("INSERT INTO wf_group_users(group_id, user_id) VALUES(?, ?)", gid, uid)
if err != nil {
return err
}
if otx == nil {
err = tx.Commit()
if err != nil {
return err
}
}
return nil
}
// RemoveUser removes the given user from this group, if the user is a
// member of the group. This operation is idempotent.
func (_Groups) RemoveUser(otx *sql.Tx, gid GroupID, uid UserID) error {
if gid <= 0 || uid <= 0 {
return errors.New("group ID and user ID must be positive integers")
}
var tx *sql.Tx
var err error
if otx == nil {
tx, err = db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
} else {
tx = otx
}
var gtype string
row := tx.QueryRow("SELECT group_type FROM wf_groups_master WHERE id = ?", gid)
err = row.Scan(>ype)
if err != nil {
return err
}
if gtype == "S" {
return errors.New("cannot remove users from singleton groups")
}
res, err := tx.Exec("DELETE FROM wf_group_users WHERE group_id = ? AND user_id = ?", gid, uid)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("expected number of affected rows : 1; actual affected : %d", n)
}
if otx == nil {
err = tx.Commit()
if err != nil {
return err
}
}
return nil
}
| {
"pile_set_name": "Github"
} |
// (C) Copyright Gennadiy Rozental 2001-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
// Boost.Test
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/test/parameterized_test.hpp>
using namespace boost::unit_test;
// BOOST
#include <boost/functional.hpp>
#include <boost/static_assert.hpp>
#include <boost/mem_fn.hpp>
#include <boost/bind.hpp>
// STL
#include <string>
#include <stdexcept>
#include <algorithm>
#include <functional>
#include <iostream>
#include <memory>
#include <list>
//____________________________________________________________________________//
template<int n>
struct power_of_10 {
BOOST_STATIC_CONSTANT( unsigned long, value = 10*power_of_10<n-1>::value );
};
template<>
struct power_of_10<0> {
BOOST_STATIC_CONSTANT( unsigned long, value = 1 );
};
//____________________________________________________________________________//
template<int AlphabetSize>
class hash_function {
public:
BOOST_STATIC_ASSERT( AlphabetSize <= 5 );
explicit hash_function( std::string const& alphabet )
: m_alphabet( alphabet )
{
if( m_alphabet.size() != AlphabetSize )
throw std::runtime_error( "Wrong alphabet size" );
std::sort( m_alphabet.begin(), m_alphabet.end() );
if( std::adjacent_find( m_alphabet.begin(), m_alphabet.end() ) != m_alphabet.end() )
throw std::logic_error( "Duplicate characters in alphabet" );
}
unsigned long operator()( std::string const& arg )
{
m_result = 0;
if( arg.length() > 8 )
throw std::runtime_error( "Wrong argument size" );
std::string::const_iterator it = std::find_if( arg.begin(), arg.end(),
std::bind1st( boost::mem_fun( &hash_function::helper_ ), this ) );
if( it != arg.end() )
throw std::out_of_range( std::string( "Invalid character " ) + *it );
return m_result;
}
private:
bool helper_( char c )
{
std::string::const_iterator it = std::find( m_alphabet.begin(), m_alphabet.end(), c );
if( it == m_alphabet.end() )
return true;
m_result += power_of_10_( it - m_alphabet.begin() );
return false;
}
unsigned long power_of_10_( int i ) {
switch( i ) {
case 0: return power_of_10<0>::value;
case 1: return power_of_10<1>::value;
case 2: return power_of_10<2>::value;
case 3: return power_of_10<3>::value;
case 4: return power_of_10<4>::value;
default: return 0;
}
}
// Data members
std::string m_alphabet;
unsigned long m_result;
};
//____________________________________________________________________________//
struct hash_function_test_data {
std::string orig_string;
unsigned long exp_value;
friend std::istream& operator>>( std::istream& istr, hash_function_test_data& test_data )
{
std::istream& tmp = istr >> test_data.orig_string;
return !tmp ? tmp : istr >> test_data.exp_value;
}
};
//____________________________________________________________________________//
class hash_function_tester {
public:
explicit hash_function_tester( std::string const& alphabet )
: m_function_under_test( alphabet ) {}
void test( hash_function_test_data const& test_data )
{
if( test_data.exp_value == (unsigned long)-1 )
BOOST_CHECK_THROW( m_function_under_test( test_data.orig_string ), std::runtime_error );
else if( test_data.exp_value == (unsigned long)-2 )
BOOST_CHECK_THROW( m_function_under_test( test_data.orig_string ), std::out_of_range );
else {
BOOST_TEST_MESSAGE( "Testing: " << test_data.orig_string );
BOOST_CHECK_EQUAL( m_function_under_test( test_data.orig_string ), test_data.exp_value );
}
}
private:
hash_function<4> m_function_under_test;
};
//____________________________________________________________________________//
struct massive_hash_function_test : test_suite {
massive_hash_function_test() : test_suite( "massive_hash_function_test" ) {
std::string alphabet;
std::cout << "Enter alphabet (4 characters without delimeters)\n";
std::cin >> alphabet;
boost::shared_ptr<hash_function_tester> instance( new hash_function_tester( alphabet ) );
std::cout << "\nEnter test data in a format [string] [value] to check correct calculation\n";
std::cout << "Enter test data in a format [string] -1 to check long string validation\n";
std::cout << "Enter test data in a format [string] -2 to check invalid argument string validation\n";
std::list<hash_function_test_data> test_data_store;
while( !std::cin.eof() ) {
hash_function_test_data test_data;
if( !(std::cin >> test_data) )
break;
test_data_store.push_back( test_data );
}
add( make_test_case( &hash_function_tester::test,
"hash_function_tester",
__FILE__,
__LINE__,
instance,
test_data_store.begin(),
test_data_store.end() ) );
}
};
//____________________________________________________________________________//
test_suite*
init_unit_test_suite( int, char* [] ) {
framework::master_test_suite().p_name.value = "Unit test example 12";
framework::master_test_suite().add( new massive_hash_function_test );
return 0;
}
//____________________________________________________________________________//
// EOF
| {
"pile_set_name": "Github"
} |
NAME
install - installs files from a source filesystem to a target filesystem
SYNOPSIS
install [name] [OPTIONS]...
DESCRIPTION
install builds a list of candidate source and target mounted filesystems. If there are multiple candidates, the user is prompted for selections. By default, install copies all files from the source filesystem's root to the target filesystem's root path. The source filesystem can define label, boot, and reboot behavior via .prop and a fully custom install experience via .install which supercedes install running cp from source to target filesystems. Developers creating their own .install files for devices should respect environment variables set by install as per options it is given, such as the root path. This manual page details those environment variables.
OPTIONS
--from=ADDR
Specifies the source filesystem or its root path. ADDR can be the device uuid or a directory path. If this is a directory path, it represents a root path to install from. This option can also be used to specify source paths that would otherwise be ignored, those being devfs, tmpfs, and the rootfs. e.g. --from=/tmp . Note that if both --from and --label are used, install expects the source path to have a .prop defining the same label. See .prop for more details.
--to=ADDR
Same as --from but specifies the target filesystem by uuid or its root path. This option can also be used to specify filesystems that are otherwise ignored including tmpfs. i.e. --to=ADDR where ADDR matches the tmpfs device address or its mount point path. e.g. --to=/tmp
--fromDir=PATH
Install PATH from source. PATH is relative to the root of the source filesystem or path given by --from. The default is .
--root=PATH
Same as --fromDir but for the target filesystem.
--toDir=PATH
Same as --root. Either can be used. It is meaningless to specify both and is not documented which takes precedence in such a case.
-u, --update
Indicates that install should prompt the user before modifying files. This invokes -i and -u for /bin/cp.
The following can override settings defined in .prop in the source filesystem.
--label=LABEL
use LABEL for label instead of any value specified by .prop
--nosetlabel
do not set target label. --nolabelset is deprecated
--nosetboot
do not set target as default boot device when rebooting. --noboot is deprecated
--noreboot
do not reboot after install
.prop
.prop should have valid lua syntax for a table of keys and their values: e.g. "{label='OpenOS'}"
All fields are optional, as is the .prop file
label:string
Declares an identifying name of the installation. This is displayed by install during source selection and also can be used on the commandline: e.g. (where {label="tape"} is given) `install tape`. If setlabel is true, this value is used for the target filesystem label. --label overrides this value. Note that install uses a case insensitive search: e.g. install TAPE works the same as install tape.
setlabel:boolean
Determines whether the install should set the target filesystem's label. If .prop does not define a label and the user does not define a command line --label=LABEL, setlabel has no action. --nosetlabel overrides this value
setboot:boolean
Determines if the target filesystem should be set as the machine's default boot device. Default is false, overriden by --nosetboot
reboot:boolean
Determines if the machine should reboot after the install completes. Overriden by --noreboot
ignore:boolean
If true, the installer will skip the source filesystem and not include it for selection
EXAMPLE:
{label='OpenOS', setlabel=true, setboot=true, reboot=true}
.install ENVIRONMENT
A loot disc can optionally provide a custom installation script at the root of the source filesytem selected for installation. The script must be named ".install"
When provided, the default install action is replaced by executation of this script. The default action is to copy all source files to the destination
A table of configuration options, named `install`, is provided in _ENV
These are the keys and their descriptions of that table
_ENV.install.from:
This is the path of the selected source filesystem to install from. It should be the path to the executing .install
example: /mnt/ABC/.install is executing, thus _ENV.install.from is "/mnt/ABC/"
_ENV.install.to:
This is the path of the selected target filesystem to install to.
example: "/"
_ENV.install.fromDir
This is the relative path to use in the source filesystem as passed by command line to install. If unspecified to install it defaults to "."
example: Perhaps the user executed `install --fromDir="bin"` with the intention that only files under /mnt/ABC/bin would be copied to their rootfs
_ENV.install.root
This is the relative path to use in the target filesystem as passed by command line to install. If unspecified to install it defaults to "."
example: The user prefers to install to usr/ and uses `install --root=usr` and here _ENV.install.root would be "usr"
_ENV.install.update
Assigned value of --update, see OPTIONS
_ENV.install.label
Assigned value of --label or .prop's label, see OPTIONS
_ENV.install.setlabel
Assigned value of .prop's setlabel unless --nosetlabel, see OPTIONS
_ENV.install.setboot
Assigned value of .prop's boot unless --nosetboot, see OPTIONS
_ENV.install.reboot
Assigned value of .prop's reboot unless --noreboot, see OPTIONS
EXAMPLES
install
Searches all non rootfs filesystems to install from, and all non tmpfs filesystems to install to. Prompts the user for a selection, and copies. If .prop is defined in source, sets label and will prompt for reboot when completed.
install openos
Searches candidates source filesystems that have .prop's that define label="OpenOS" and prompts the user to confirm install to candidate target filesystems.
| {
"pile_set_name": "Github"
} |
/**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic 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.
*
* FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.ui.struts.action.mobility.outbound;
import com.google.common.io.ByteStreams;
import org.fenixedu.academic.domain.ExecutionDegree;
import org.fenixedu.academic.domain.ExecutionYear;
import org.fenixedu.academic.domain.Person;
import org.fenixedu.academic.domain.accessControl.academicAdministration.AcademicOperationType;
import org.fenixedu.academic.domain.candidacyProcess.mobility.MobilityProgram;
import org.fenixedu.academic.domain.exceptions.DomainException;
import org.fenixedu.academic.domain.mobility.outbound.OutboundMobilityCandidacyContest;
import org.fenixedu.academic.domain.mobility.outbound.OutboundMobilityCandidacyContestGroup;
import org.fenixedu.academic.domain.mobility.outbound.OutboundMobilityCandidacyPeriod;
import org.fenixedu.academic.domain.organizationalStructure.UniversityUnit;
import org.fenixedu.academic.domain.period.CandidacyPeriod;
import org.fenixedu.academic.domain.period.CandidacyPeriod_Base;
import org.fenixedu.academic.util.Bundle;
import org.fenixedu.bennu.core.i18n.BundleUtil;
import org.joda.time.DateTime;
import pt.ist.fenixframework.Atomic;
import pt.ist.fenixframework.FenixFramework;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
public class OutboundMobilityContextBean implements Serializable {
private ExecutionYear executionYear;
private SortedSet<OutboundMobilityCandidacyPeriod> candidacyPeriods = new TreeSet<OutboundMobilityCandidacyPeriod>();
private SortedSet<MobilityProgram> mobilityPrograms = new TreeSet<MobilityProgram>();
private SortedSet<OutboundMobilityCandidacyContestGroup> mobilityGroups =
new TreeSet<OutboundMobilityCandidacyContestGroup>();
private DateTime startDateTime;
private DateTime endDateTime;
private MobilityProgram mobilityProgram;
private ExecutionDegree executionDegree;
private UniversityUnit unit;
private Integer vacancies;
private Person person;
private transient InputStream stream;
private long fileSize;
private String fileName;
private String optionIntroductoryDestription;
private String optionValue;
private Boolean availableForCandidates;
public OutboundMobilityContextBean() {
setExecutionYear(ExecutionYear.readCurrentExecutionYear());
}
public OutboundMobilityContextBean(OutboundMobilityContextBean bean) {
setExecutionYear(bean.getExecutionYear());
this.candidacyPeriods = new TreeSet<>(bean.getCandidacyPeriods());
this.executionYear = bean.getExecutionYear();
this.mobilityPrograms = bean.getMobilityPrograms().stream().filter(FenixFramework::isDomainObjectValid)
.collect(Collectors.toCollection(TreeSet::new));
this.mobilityGroups = bean.getMobilityGroups().stream().filter(FenixFramework::isDomainObjectValid)
.collect(Collectors.toCollection(TreeSet::new));
}
public ExecutionYear getExecutionYear() {
return executionYear;
}
public void setExecutionYear(final ExecutionYear executionYear) {
this.executionYear = executionYear;
selectLastOpenedCandidacyPeriod();
}
public void selectLastOpenedCandidacyPeriod() {
this.candidacyPeriods.clear();
this.executionYear.getCandidacyPeriodsSet().stream()
.filter(p -> p instanceof OutboundMobilityCandidacyPeriod && p.getStart().isBefore(DateTime.now().plusDays(1)))
.max(Comparator.comparing(CandidacyPeriod_Base::getStart))
.ifPresent(p -> this.candidacyPeriods.add((OutboundMobilityCandidacyPeriod) p));
}
public void getPossibleCandidacyPeriods(final SortedSet<OutboundMobilityCandidacyPeriod> candidacyPeriods) {
if (executionYear != null) {
for (final CandidacyPeriod candidacyPeriod : executionYear.getCandidacyPeriodsSet()) {
if (candidacyPeriod instanceof OutboundMobilityCandidacyPeriod) {
final OutboundMobilityCandidacyPeriod outboundMobilityCandidacyPeriod =
(OutboundMobilityCandidacyPeriod) candidacyPeriod;
candidacyPeriods.add(outboundMobilityCandidacyPeriod);
}
}
}
}
public SortedSet<OutboundMobilityCandidacyPeriod> getCandidacyPeriods() {
return candidacyPeriods;
}
public List<OutboundMobilityCandidacyPeriod> getCandidacyPeriodsAsList() {
return new ArrayList<OutboundMobilityCandidacyPeriod>(candidacyPeriods);
}
public void setCandidacyPeriodsAsList(List<OutboundMobilityCandidacyPeriod> candidacyPeriodsAsList) {
this.candidacyPeriods.retainAll(candidacyPeriodsAsList);
this.candidacyPeriods.addAll(candidacyPeriodsAsList);
}
public SortedSet<OutboundMobilityCandidacyContestGroup> getMobilityGroups() {
return mobilityGroups;
}
public List<OutboundMobilityCandidacyContestGroup> getMobilityGroupsAsList() {
return new ArrayList<OutboundMobilityCandidacyContestGroup>(mobilityGroups);
}
public void setMobilityGroupsAsList(List<OutboundMobilityCandidacyContestGroup> mobilityGroupsAsList) {
this.mobilityGroups.retainAll(mobilityGroupsAsList);
this.mobilityGroups.addAll(mobilityGroupsAsList);
}
public SortedSet<MobilityProgram> getMobilityPrograms() {
return mobilityPrograms;
}
public List<MobilityProgram> getMobilityProgramsAsList() {
return new ArrayList<MobilityProgram>(mobilityPrograms);
}
public void setMobilityProgramsAsList(List<MobilityProgram> mobilityProgramsAsList) {
this.mobilityPrograms.retainAll(mobilityProgramsAsList);
this.mobilityPrograms.addAll(mobilityProgramsAsList);
}
public DateTime getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(DateTime startDateTime) {
this.startDateTime = startDateTime;
}
public DateTime getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(DateTime endDateTime) {
this.endDateTime = endDateTime;
}
public void createNewOutboundMobilityCandidacyPeriod() {
final OutboundMobilityCandidacyPeriod candidacyPeriod =
OutboundMobilityCandidacyPeriod.create(getExecutionYear(), getStartDateTime(), getEndDateTime());
candidacyPeriods.add(candidacyPeriod);
}
public void createNewOutboundMobilityCandidacyContest() {
for (final OutboundMobilityCandidacyPeriod candidacyPeriod : candidacyPeriods) {
if (executionDegree == null) {
for (final OutboundMobilityCandidacyContestGroup mobilityGroup : mobilityGroups) {
candidacyPeriod.createOutboundMobilityCandidacyContest(mobilityGroup, mobilityProgram, unit, vacancies);
}
} else {
candidacyPeriod.createOutboundMobilityCandidacyContest(executionDegree, mobilityProgram, unit, vacancies);
}
}
executionDegree = null;
unit = null;
vacancies = null;
}
public ExecutionDegree getExecutionDegree() {
return executionDegree;
}
public void setExecutionDegree(ExecutionDegree executionDegree) {
this.executionDegree = executionDegree;
}
public UniversityUnit getUnit() {
return unit;
}
public void setUnit(UniversityUnit unit) {
this.unit = unit;
}
public Integer getVacancies() {
return vacancies;
}
public void setVacancies(Integer vacancies) {
this.vacancies = vacancies;
}
public MobilityProgram getMobilityProgram() {
return mobilityProgram;
}
public void setMobilityProgram(MobilityProgram mobilityProgram) {
this.mobilityProgram = mobilityProgram;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public SortedSet<OutboundMobilityCandidacyContest> getOutboundMobilityCandidacyContest() {
final SortedSet<OutboundMobilityCandidacyContest> result = new TreeSet<OutboundMobilityCandidacyContest>();
for (final OutboundMobilityCandidacyPeriod candidacyPeriod : candidacyPeriods) {
for (final OutboundMobilityCandidacyContest contest : candidacyPeriod.getOutboundMobilityCandidacyContestSet()) {
if (mobilityPrograms.contains(contest.getMobilityAgreement().getMobilityProgram())) {
final OutboundMobilityCandidacyContestGroup mobilityGroup =
contest.getOutboundMobilityCandidacyContestGroup();
if (mobilityGroups.contains(mobilityGroup)) {
result.add(contest);
}
}
}
}
return result;
}
public void addDegreeToGroup() {
for (final OutboundMobilityCandidacyContestGroup mobilityGroup : mobilityGroups) {
mobilityGroup.addExecutionDegreeService(executionDegree);
}
}
public void removeDegreeFromGroup() {
for (final OutboundMobilityCandidacyContestGroup mobilityGroup : mobilityGroups) {
mobilityGroup.removeExecutionDegreeService(executionDegree);
}
}
@Atomic
public void addMobilityCoordinator() {
if (person != null) {
for (final OutboundMobilityCandidacyContestGroup mobilityGroup : mobilityGroups) {
mobilityGroup.addMobilityCoordinatorService(person);
}
addOperationPermissions(person);
}
}
private void addOperationPermissions(Person person) {
AcademicOperationType.VALIDATE_MOBILITY_OUTBOUND_CANDIDACIES.grant(person.getUser());
}
public InputStream getStream() {
return stream;
}
public void setStream(InputStream stream) {
this.stream = stream;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getOptionIntroductoryDestription() {
return optionIntroductoryDestription;
}
public void setOptionIntroductoryDestription(String optionIntroductoryDestription) {
this.optionIntroductoryDestription = optionIntroductoryDestription;
}
public String getOptionValue() {
return optionValue;
}
public void setOptionValue(String optionValue) {
this.optionValue = optionValue;
}
public Boolean getAvailableForCandidates() {
return availableForCandidates;
}
public void setAvailableForCandidates(Boolean availableForCandidates) {
this.availableForCandidates = availableForCandidates;
}
protected String readStreamContents() throws IOException {
try (final InputStream stream = this.getStream()) {
if (stream == null || getFileSize() == 0) {
return null;
}
return new String(ByteStreams.toByteArray(stream), StandardCharsets.UTF_8);
}
}
public void uploadClassifications() throws IOException {
final String contents = readStreamContents();
if (contents != null) {
for (final OutboundMobilityCandidacyContestGroup group : mobilityGroups) {
for (final OutboundMobilityCandidacyPeriod candidacyPeriod : candidacyPeriods) {
group.setGrades(candidacyPeriod, contents);
}
}
} else {
throw new DomainException("error.mobility.outbound.unable.to.set.grades", BundleUtil.getString(Bundle.ACADEMIC,
"error.mobility.outbound.null.file"));
}
}
public void addCandidateOption() {
for (final OutboundMobilityCandidacyPeriod period : candidacyPeriods) {
if (optionIntroductoryDestription != null && !optionIntroductoryDestription.isEmpty()) {
period.setOptionIntroductoryDestriptionService(optionIntroductoryDestription);
}
if (optionValue != null && !optionValue.isEmpty()) {
period.addOption(optionValue, availableForCandidates);
}
}
}
}
| {
"pile_set_name": "Github"
} |
{
"x" : 40,
"y" : 40,
"z" : 0
} | {
"pile_set_name": "Github"
} |
;;; lsp-clients-test.el --- unit tests for lsp-clients.el -*- lexical-binding: t -*-
;; Copyright (C) 2019 Daniel Martín <[email protected]>.
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Code:
(require 'ert)
(require 'lsp-javascript)
(require 'js) ;; Standard mode in Emacs for JS.
(defconst test-location (file-name-directory (or load-file-name buffer-file-name)))
;; Some of the different flavors of the @flow tag we may
;; encounter, and things we don't want to match.
(defconst lsp-flow-regular-tag "// @flow")
(defconst lsp-flow-c-style-tag "/* @flow */")
(defconst lsp-flow-simple-multiline-tag
"/**
* @flow
*/")
(defconst lsp-flow-multiline-with-comments-before-tag
"/**
* This is a wonderful Flow file.
*
* Author: Awesome programmer.
*
* @flow
*/")
(defconst lsp-flow-wrong-tag
"/**
* @notflow
*/")
(defconst lsp-flow-but-not-in-comment-tag "@flow")
(ert-deftest lsp-flow-regular-tag-detection ()
(should (with-temp-buffer
(insert lsp-flow-regular-tag)
(lsp-clients-flow-tag-string-present-p))))
(ert-deftest lsp-flow-c-style-tag-detection ()
(should (with-temp-buffer
(insert lsp-flow-c-style-tag)
(lsp-clients-flow-tag-string-present-p))))
(ert-deftest lsp-flow-simple-multiline-tag-detection ()
(should (with-temp-buffer
(insert lsp-flow-simple-multiline-tag)
(lsp-clients-flow-tag-string-present-p))))
(ert-deftest lsp-flow-simple-multiline-with-comments-before-tag-detection ()
(should (with-temp-buffer
(insert lsp-flow-multiline-with-comments-before-tag)
(lsp-clients-flow-tag-string-present-p))))
(ert-deftest lsp-flow-wrong-tag-detection ()
(should (not (with-temp-buffer
(insert lsp-flow-wrong-tag)
(lsp-clients-flow-tag-string-present-p)))))
(ert-deftest lsp-flow-but-not-in-comment-tag-detection ()
(should (not (with-temp-buffer
(insert lsp-flow-but-not-in-comment-tag)
(lsp-clients-flow-tag-string-present-p)))))
(ert-deftest lsp-flow-should-activate-on-flow-project ()
;; Set `js-mode' ON and check that a Flow project activates the Flow
;; LSP client.
(let ((major-mode 'js-mode))
(should (lsp-clients-flow-activate-p (concat test-location "fixtures/SampleFlowProject/src/sample.js") nil))))
(ert-deftest lsp-flow-should-activate-on-flow-project-without-flow-file-comment ()
(let ((major-mode 'js-mode))
(should (lsp-clients-flow-activate-p (concat test-location "fixtures/SampleFlowProject/src/sample-without-flow-comment.js") nil))))
(ert-deftest lsp-flow-should-not-activate-if-not-flow-project-or-no-tag ()
(let ((major-mode 'js-mode))
(should (not (lsp-clients-flow-activate-p (concat test-location "fixtures/SampleJsProject/src/sample.js") nil)))))
(ert-deftest lsp-flow-should-not-activate-on-typescript-project ()
;; Set `js-mode' ON and check that a TypeScript project does not
;; activate the Flow LSP client.
(let ((major-mode 'js-mode))
(should (not (lsp-clients-flow-activate-p (concat test-location "fixtures/SampleTypeScriptProject/src/sample.ts") nil)))))
(ert-deftest lsp-typescript-javascript-activates-based-on-file-extension ()
(should (lsp-typescript-javascript-tsx-jsx-activate-p "abc.js"))
(should (lsp-typescript-javascript-tsx-jsx-activate-p "abc.jsx"))
(should (lsp-typescript-javascript-tsx-jsx-activate-p "abc.ts"))
(should (lsp-typescript-javascript-tsx-jsx-activate-p "abc.tsx"))
(should (lsp-typescript-javascript-tsx-jsx-activate-p "a1.ts"))
(should (lsp-typescript-javascript-tsx-jsx-activate-p "a1.d.ts"))
(should (not (lsp-typescript-javascript-tsx-jsx-activate-p "abc.tsxx")))
(should (not (lsp-typescript-javascript-tsx-jsx-activate-p "abc.jss"))))
;;; lsp-clients-test.el ends here
| {
"pile_set_name": "Github"
} |
// Created by cgo -godefs - DO NOT EDIT
// cgo -godefs types_linux.go
// +build 386,linux
package unix
const (
sizeofPtr = 0x4
sizeofShort = 0x2
sizeofInt = 0x4
sizeofLong = 0x4
sizeofLongLong = 0x8
PathMax = 0x1000
)
type (
_C_short int16
_C_int int32
_C_long int32
_C_long_long int64
)
type Timespec struct {
Sec int32
Nsec int32
}
type Timeval struct {
Sec int32
Usec int32
}
type Timex struct {
Modes uint32
Offset int32
Freq int32
Maxerror int32
Esterror int32
Status int32
Constant int32
Precision int32
Tolerance int32
Time Timeval
Tick int32
Ppsfreq int32
Jitter int32
Shift int32
Stabil int32
Jitcnt int32
Calcnt int32
Errcnt int32
Stbcnt int32
Tai int32
Pad_cgo_0 [44]byte
}
type Time_t int32
type Tms struct {
Utime int32
Stime int32
Cutime int32
Cstime int32
}
type Utimbuf struct {
Actime int32
Modtime int32
}
type Rusage struct {
Utime Timeval
Stime Timeval
Maxrss int32
Ixrss int32
Idrss int32
Isrss int32
Minflt int32
Majflt int32
Nswap int32
Inblock int32
Oublock int32
Msgsnd int32
Msgrcv int32
Nsignals int32
Nvcsw int32
Nivcsw int32
}
type Rlimit struct {
Cur uint64
Max uint64
}
type _Gid_t uint32
type Stat_t struct {
Dev uint64
X__pad1 uint16
Pad_cgo_0 [2]byte
X__st_ino uint32
Mode uint32
Nlink uint32
Uid uint32
Gid uint32
Rdev uint64
X__pad2 uint16
Pad_cgo_1 [2]byte
Size int64
Blksize int32
Blocks int64
Atim Timespec
Mtim Timespec
Ctim Timespec
Ino uint64
}
type Statfs_t struct {
Type int32
Bsize int32
Blocks uint64
Bfree uint64
Bavail uint64
Files uint64
Ffree uint64
Fsid Fsid
Namelen int32
Frsize int32
Flags int32
Spare [4]int32
}
type Dirent struct {
Ino uint64
Off int64
Reclen uint16
Type uint8
Name [256]int8
Pad_cgo_0 [1]byte
}
type Fsid struct {
X__val [2]int32
}
type Flock_t struct {
Type int16
Whence int16
Start int64
Len int64
Pid int32
}
type RawSockaddrInet4 struct {
Family uint16
Port uint16
Addr [4]byte /* in_addr */
Zero [8]uint8
}
type RawSockaddrInet6 struct {
Family uint16
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
type RawSockaddrUnix struct {
Family uint16
Path [108]int8
}
type RawSockaddrLinklayer struct {
Family uint16
Protocol uint16
Ifindex int32
Hatype uint16
Pkttype uint8
Halen uint8
Addr [8]uint8
}
type RawSockaddrNetlink struct {
Family uint16
Pad uint16
Pid uint32
Groups uint32
}
type RawSockaddr struct {
Family uint16
Data [14]int8
}
type RawSockaddrAny struct {
Addr RawSockaddr
Pad [96]int8
}
type _Socklen uint32
type Linger struct {
Onoff int32
Linger int32
}
type Iovec struct {
Base *byte
Len uint32
}
type IPMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type IPMreqn struct {
Multiaddr [4]byte /* in_addr */
Address [4]byte /* in_addr */
Ifindex int32
}
type IPv6Mreq struct {
Multiaddr [16]byte /* in6_addr */
Interface uint32
}
type Msghdr struct {
Name *byte
Namelen uint32
Iov *Iovec
Iovlen uint32
Control *byte
Controllen uint32
Flags int32
}
type Cmsghdr struct {
Len uint32
Level int32
Type int32
X__cmsg_data [0]uint8
}
type Inet4Pktinfo struct {
Ifindex int32
Spec_dst [4]byte /* in_addr */
Addr [4]byte /* in_addr */
}
type Inet6Pktinfo struct {
Addr [16]byte /* in6_addr */
Ifindex uint32
}
type IPv6MTUInfo struct {
Addr RawSockaddrInet6
Mtu uint32
}
type ICMPv6Filter struct {
Data [8]uint32
}
type Ucred struct {
Pid int32
Uid uint32
Gid uint32
}
type TCPInfo struct {
State uint8
Ca_state uint8
Retransmits uint8
Probes uint8
Backoff uint8
Options uint8
Pad_cgo_0 [2]byte
Rto uint32
Ato uint32
Snd_mss uint32
Rcv_mss uint32
Unacked uint32
Sacked uint32
Lost uint32
Retrans uint32
Fackets uint32
Last_data_sent uint32
Last_ack_sent uint32
Last_data_recv uint32
Last_ack_recv uint32
Pmtu uint32
Rcv_ssthresh uint32
Rtt uint32
Rttvar uint32
Snd_ssthresh uint32
Snd_cwnd uint32
Advmss uint32
Reordering uint32
Rcv_rtt uint32
Rcv_space uint32
Total_retrans uint32
}
const (
SizeofSockaddrInet4 = 0x10
SizeofSockaddrInet6 = 0x1c
SizeofSockaddrAny = 0x70
SizeofSockaddrUnix = 0x6e
SizeofSockaddrLinklayer = 0x14
SizeofSockaddrNetlink = 0xc
SizeofLinger = 0x8
SizeofIPMreq = 0x8
SizeofIPMreqn = 0xc
SizeofIPv6Mreq = 0x14
SizeofMsghdr = 0x1c
SizeofCmsghdr = 0xc
SizeofInet4Pktinfo = 0xc
SizeofInet6Pktinfo = 0x14
SizeofIPv6MTUInfo = 0x20
SizeofICMPv6Filter = 0x20
SizeofUcred = 0xc
SizeofTCPInfo = 0x68
)
const (
IFA_UNSPEC = 0x0
IFA_ADDRESS = 0x1
IFA_LOCAL = 0x2
IFA_LABEL = 0x3
IFA_BROADCAST = 0x4
IFA_ANYCAST = 0x5
IFA_CACHEINFO = 0x6
IFA_MULTICAST = 0x7
IFLA_UNSPEC = 0x0
IFLA_ADDRESS = 0x1
IFLA_BROADCAST = 0x2
IFLA_IFNAME = 0x3
IFLA_MTU = 0x4
IFLA_LINK = 0x5
IFLA_QDISC = 0x6
IFLA_STATS = 0x7
IFLA_COST = 0x8
IFLA_PRIORITY = 0x9
IFLA_MASTER = 0xa
IFLA_WIRELESS = 0xb
IFLA_PROTINFO = 0xc
IFLA_TXQLEN = 0xd
IFLA_MAP = 0xe
IFLA_WEIGHT = 0xf
IFLA_OPERSTATE = 0x10
IFLA_LINKMODE = 0x11
IFLA_LINKINFO = 0x12
IFLA_NET_NS_PID = 0x13
IFLA_IFALIAS = 0x14
IFLA_MAX = 0x1d
RT_SCOPE_UNIVERSE = 0x0
RT_SCOPE_SITE = 0xc8
RT_SCOPE_LINK = 0xfd
RT_SCOPE_HOST = 0xfe
RT_SCOPE_NOWHERE = 0xff
RT_TABLE_UNSPEC = 0x0
RT_TABLE_COMPAT = 0xfc
RT_TABLE_DEFAULT = 0xfd
RT_TABLE_MAIN = 0xfe
RT_TABLE_LOCAL = 0xff
RT_TABLE_MAX = 0xffffffff
RTA_UNSPEC = 0x0
RTA_DST = 0x1
RTA_SRC = 0x2
RTA_IIF = 0x3
RTA_OIF = 0x4
RTA_GATEWAY = 0x5
RTA_PRIORITY = 0x6
RTA_PREFSRC = 0x7
RTA_METRICS = 0x8
RTA_MULTIPATH = 0x9
RTA_FLOW = 0xb
RTA_CACHEINFO = 0xc
RTA_TABLE = 0xf
RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1
RTN_LOCAL = 0x2
RTN_BROADCAST = 0x3
RTN_ANYCAST = 0x4
RTN_MULTICAST = 0x5
RTN_BLACKHOLE = 0x6
RTN_UNREACHABLE = 0x7
RTN_PROHIBIT = 0x8
RTN_THROW = 0x9
RTN_NAT = 0xa
RTN_XRESOLVE = 0xb
RTNLGRP_NONE = 0x0
RTNLGRP_LINK = 0x1
RTNLGRP_NOTIFY = 0x2
RTNLGRP_NEIGH = 0x3
RTNLGRP_TC = 0x4
RTNLGRP_IPV4_IFADDR = 0x5
RTNLGRP_IPV4_MROUTE = 0x6
RTNLGRP_IPV4_ROUTE = 0x7
RTNLGRP_IPV4_RULE = 0x8
RTNLGRP_IPV6_IFADDR = 0x9
RTNLGRP_IPV6_MROUTE = 0xa
RTNLGRP_IPV6_ROUTE = 0xb
RTNLGRP_IPV6_IFINFO = 0xc
RTNLGRP_IPV6_PREFIX = 0x12
RTNLGRP_IPV6_RULE = 0x13
RTNLGRP_ND_USEROPT = 0x14
SizeofNlMsghdr = 0x10
SizeofNlMsgerr = 0x14
SizeofRtGenmsg = 0x1
SizeofNlAttr = 0x4
SizeofRtAttr = 0x4
SizeofIfInfomsg = 0x10
SizeofIfAddrmsg = 0x8
SizeofRtMsg = 0xc
SizeofRtNexthop = 0x8
)
type NlMsghdr struct {
Len uint32
Type uint16
Flags uint16
Seq uint32
Pid uint32
}
type NlMsgerr struct {
Error int32
Msg NlMsghdr
}
type RtGenmsg struct {
Family uint8
}
type NlAttr struct {
Len uint16
Type uint16
}
type RtAttr struct {
Len uint16
Type uint16
}
type IfInfomsg struct {
Family uint8
X__ifi_pad uint8
Type uint16
Index int32
Flags uint32
Change uint32
}
type IfAddrmsg struct {
Family uint8
Prefixlen uint8
Flags uint8
Scope uint8
Index uint32
}
type RtMsg struct {
Family uint8
Dst_len uint8
Src_len uint8
Tos uint8
Table uint8
Protocol uint8
Scope uint8
Type uint8
Flags uint32
}
type RtNexthop struct {
Len uint16
Flags uint8
Hops uint8
Ifindex int32
}
const (
SizeofSockFilter = 0x8
SizeofSockFprog = 0x8
)
type SockFilter struct {
Code uint16
Jt uint8
Jf uint8
K uint32
}
type SockFprog struct {
Len uint16
Pad_cgo_0 [2]byte
Filter *SockFilter
}
type InotifyEvent struct {
Wd int32
Mask uint32
Cookie uint32
Len uint32
Name [0]int8
}
const SizeofInotifyEvent = 0x10
type PtraceRegs struct {
Ebx int32
Ecx int32
Edx int32
Esi int32
Edi int32
Ebp int32
Eax int32
Xds int32
Xes int32
Xfs int32
Xgs int32
Orig_eax int32
Eip int32
Xcs int32
Eflags int32
Esp int32
Xss int32
}
type FdSet struct {
Bits [32]int32
}
type Sysinfo_t struct {
Uptime int32
Loads [3]uint32
Totalram uint32
Freeram uint32
Sharedram uint32
Bufferram uint32
Totalswap uint32
Freeswap uint32
Procs uint16
Pad uint16
Totalhigh uint32
Freehigh uint32
Unit uint32
X_f [8]int8
}
type Utsname struct {
Sysname [65]int8
Nodename [65]int8
Release [65]int8
Version [65]int8
Machine [65]int8
Domainname [65]int8
}
type Ustat_t struct {
Tfree int32
Tinode uint32
Fname [6]int8
Fpack [6]int8
}
type EpollEvent struct {
Events uint32
Fd int32
Pad int32
}
const (
AT_FDCWD = -0x64
AT_SYMLINK_NOFOLLOW = 0x100
AT_REMOVEDIR = 0x200
)
type Termios struct {
Iflag uint32
Oflag uint32
Cflag uint32
Lflag uint32
Line uint8
Cc [32]uint8
Pad_cgo_0 [3]byte
Ispeed uint32
Ospeed uint32
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<plurals name="hs__csat_rating_value">
<item quantity="other">ਤੁਸੀਂ ਸੇਵਾ ਨੂੰ %d ਸਟਾਰ ਦਿੱਤੇ।</item>
<item quantity="one">ਤੁਸੀਂ ਸੇਵਾ ਨੂੰ 1 ਸਟਾਰ ਦਿੱਤਾ।</item>
</plurals>
<plurals name="hs__notification_content_title">
<item quantity="other">%d ਸਹਾਇਤਾ ਵਲੋਂ ਨਵਾਂ ਸੁਨੇਹਾ</item>
<item quantity="one">ਸਹਾਇਤਾ ਵਲੋਂ ਨਵਾਂ ਸੁਨੇਹਾ</item>
</plurals>
</resources>
| {
"pile_set_name": "Github"
} |
var locale = {
locale: 'kn_IN',
today: 'ಇಂದು',
now: 'ಈಗ',
backToToday: 'ಇಂದು ಹಿಂದಿರುಗಿ',
ok: 'ಸರಿ',
clear: 'ಸ್ಪಷ್ಟ',
month: 'ತಿಂಗಳು',
year: 'ವರ್ಷ',
timeSelect: 'ಸಮಯ ಆಯ್ಕೆಮಾಡಿ',
dateSelect: 'ದಿನಾಂಕವನ್ನು ಆಯ್ಕೆ ಮಾಡಿ',
weekSelect: 'ಒಂದು ವಾರದ ಆರಿಸಿ',
monthSelect: 'ಒಂದು ತಿಂಗಳು ಆಯ್ಕೆಮಾಡಿ',
yearSelect: 'ಒಂದು ವರ್ಷ ಆರಿಸಿ',
decadeSelect: 'ಒಂದು ದಶಕದ ಆಯ್ಕೆಮಾಡಿ',
yearFormat: 'YYYY',
dateFormat: 'M/D/YYYY',
dayFormat: 'D',
dateTimeFormat: 'M/D/YYYY HH:mm:ss',
monthBeforeYear: true,
previousMonth: 'ಹಿಂದಿನ ತಿಂಗಳು (ಪೇಜ್ಅಪ್)',
nextMonth: 'ಮುಂದಿನ ತಿಂಗಳು (ಪೇಜ್ಡೌನ್)',
previousYear: 'ಕಳೆದ ವರ್ಷ (Ctrl + ಎಡ)',
nextYear: 'ಮುಂದಿನ ವರ್ಷ (Ctrl + ಬಲ)',
previousDecade: 'ಕಳೆದ ದಶಕ',
nextDecade: 'ಮುಂದಿನ ದಶಕ',
previousCentury: 'ಕಳೆದ ಶತಮಾನ',
nextCentury: 'ಮುಂದಿನ ಶತಮಾನ'
};
export default locale; | {
"pile_set_name": "Github"
} |
; RUN: opt < %s -lowerswitch
define void @test() {
switch i32 0, label %Next [
]
Next: ; preds = %0
ret void
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the PHP_CodeCoverage package.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Generates an HTML report from an PHP_CodeCoverage object.
*
* @since Class available since Release 1.0.0
*/
class PHP_CodeCoverage_Report_HTML
{
/**
* @var string
*/
private $templatePath;
/**
* @var string
*/
private $generator;
/**
* @var int
*/
private $lowUpperBound;
/**
* @var int
*/
private $highLowerBound;
/**
* Constructor.
*
* @param int $lowUpperBound
* @param int $highLowerBound
* @param string $generator
*/
public function __construct($lowUpperBound = 50, $highLowerBound = 90, $generator = '')
{
$this->generator = $generator;
$this->highLowerBound = $highLowerBound;
$this->lowUpperBound = $lowUpperBound;
$this->templatePath = sprintf(
'%s%sHTML%sRenderer%sTemplate%s',
dirname(__FILE__),
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR
);
}
/**
* @param PHP_CodeCoverage $coverage
* @param string $target
*/
public function process(PHP_CodeCoverage $coverage, $target)
{
$target = $this->getDirectory($target);
$report = $coverage->getReport();
unset($coverage);
if (!isset($_SERVER['REQUEST_TIME'])) {
$_SERVER['REQUEST_TIME'] = time();
}
$date = date('D M j G:i:s T Y', $_SERVER['REQUEST_TIME']);
$dashboard = new PHP_CodeCoverage_Report_HTML_Renderer_Dashboard(
$this->templatePath,
$this->generator,
$date,
$this->lowUpperBound,
$this->highLowerBound
);
$directory = new PHP_CodeCoverage_Report_HTML_Renderer_Directory(
$this->templatePath,
$this->generator,
$date,
$this->lowUpperBound,
$this->highLowerBound
);
$file = new PHP_CodeCoverage_Report_HTML_Renderer_File(
$this->templatePath,
$this->generator,
$date,
$this->lowUpperBound,
$this->highLowerBound
);
$directory->render($report, $target . 'index.html');
$dashboard->render($report, $target . 'dashboard.html');
foreach ($report as $node) {
$id = $node->getId();
if ($node instanceof PHP_CodeCoverage_Report_Node_Directory) {
if (!file_exists($target . $id)) {
mkdir($target . $id, 0777, true);
}
$directory->render($node, $target . $id . '/index.html');
$dashboard->render($node, $target . $id . '/dashboard.html');
} else {
$dir = dirname($target . $id);
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
$file->render($node, $target . $id . '.html');
}
}
$this->copyFiles($target);
}
/**
* @param string $target
*/
private function copyFiles($target)
{
$dir = $this->getDirectory($target . 'css');
copy($this->templatePath . 'css/bootstrap.min.css', $dir . 'bootstrap.min.css');
copy($this->templatePath . 'css/nv.d3.min.css', $dir . 'nv.d3.min.css');
copy($this->templatePath . 'css/style.css', $dir . 'style.css');
$dir = $this->getDirectory($target . 'fonts');
copy($this->templatePath . 'fonts/glyphicons-halflings-regular.eot', $dir . 'glyphicons-halflings-regular.eot');
copy($this->templatePath . 'fonts/glyphicons-halflings-regular.svg', $dir . 'glyphicons-halflings-regular.svg');
copy($this->templatePath . 'fonts/glyphicons-halflings-regular.ttf', $dir . 'glyphicons-halflings-regular.ttf');
copy($this->templatePath . 'fonts/glyphicons-halflings-regular.woff', $dir . 'glyphicons-halflings-regular.woff');
copy($this->templatePath . 'fonts/glyphicons-halflings-regular.woff2', $dir . 'glyphicons-halflings-regular.woff2');
$dir = $this->getDirectory($target . 'js');
copy($this->templatePath . 'js/bootstrap.min.js', $dir . 'bootstrap.min.js');
copy($this->templatePath . 'js/d3.min.js', $dir . 'd3.min.js');
copy($this->templatePath . 'js/holder.min.js', $dir . 'holder.min.js');
copy($this->templatePath . 'js/html5shiv.min.js', $dir . 'html5shiv.min.js');
copy($this->templatePath . 'js/jquery.min.js', $dir . 'jquery.min.js');
copy($this->templatePath . 'js/nv.d3.min.js', $dir . 'nv.d3.min.js');
copy($this->templatePath . 'js/respond.min.js', $dir . 'respond.min.js');
}
/**
* @param string $directory
* @return string
* @throws PHP_CodeCoverage_Exception
* @since Method available since Release 1.2.0
*/
private function getDirectory($directory)
{
if (substr($directory, -1, 1) != DIRECTORY_SEPARATOR) {
$directory .= DIRECTORY_SEPARATOR;
}
if (is_dir($directory)) {
return $directory;
}
if (@mkdir($directory, 0777, true)) {
return $directory;
}
throw new PHP_CodeCoverage_Exception(
sprintf(
'Directory "%s" does not exist.',
$directory
)
);
}
}
| {
"pile_set_name": "Github"
} |
package com.hankkin.mycartdemo.chatview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.hankkin.mycartdemo.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Hankkin on 16/12/11.
* 注释:参考MyChartView原理相
*/
public class SingleView extends View {
private Paint mPaint, mChartPaint;
private Rect mBound;
private int mStartWidth, mHeight, mWidth, mChartWidth, mSize;
private int lineColor, leftColor, lefrColorBottom,selectLeftColor;
private List<Float> list = new ArrayList<>();
private getNumberListener listener;
private int number = 1000;
private int selectIndex = -1;
private List<Integer> selectIndexRoles = new ArrayList<>();
public void setList(List<Float> list) {
this.list = list;
mSize = getWidth() / 25;
mStartWidth = getWidth() / 13;
mChartWidth = getWidth() / 13 - mSize / 2;
invalidate();
}
public SingleView(Context context) {
this(context, null);
}
public SingleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SingleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyChartView, defStyleAttr, 0);
int n = array.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = array.getIndex(i);
switch (attr) {
case R.styleable.MyChartView_xyColor:
lineColor = array.getColor(attr, Color.BLACK);
break;
case R.styleable.MyChartView_leftColor:
// 默认颜色设置为黑色
leftColor = array.getColor(attr, Color.BLACK);
break;
case R.styleable.MyChartView_leftColorBottom:
lefrColorBottom = array.getColor(attr, Color.BLACK);
break;
case R.styleable.MyChartView_selectLeftColor:
// 默认颜色设置为黑色
selectLeftColor = array.getColor(attr, Color.BLACK);
break;
default:
bringToFront();
}
}
array.recycle();
init();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width;
int height;
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
width = widthSize * 1 / 2;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
height = heightSize * 1 / 2;
}
setMeasuredDimension(width, height);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
mWidth = getWidth();
mHeight = getHeight();
mStartWidth = getWidth() / 13;
mSize = mWidth / 25;
mChartWidth = getWidth() / 13 - mSize / 2;
}
private void init() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mBound = new Rect();
mChartPaint = new Paint();
mChartPaint.setAntiAlias(true);
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
if (hasWindowFocus) {
}
}
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
if (visibility == VISIBLE) {
mSize = getWidth() / 25;
mStartWidth = getWidth() / 13;
mChartWidth = getWidth() / 13 - mSize / 2;
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setColor(lineColor);
for (int i = 0; i < 12; i++) {
//画数字
mPaint.setTextSize(35);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.getTextBounds(String.valueOf(i + 1) + "", 0, String.valueOf(i).length(), mBound);
canvas.drawText(String.valueOf(i + 1) + "月", mStartWidth - mBound.width() * 1 / 2,
mHeight - 60 + mBound.height() * 1 / 2, mPaint);
mStartWidth += getWidth() / 13;
}
for (int i = 0; i < 12; i++) {
int size = mHeight / 120;
mChartPaint.setStyle(Paint.Style.FILL);
if (list.size() > 0) {
if (selectIndexRoles.contains(i)){
mChartPaint.setShader(null);
mChartPaint.setColor(selectLeftColor);
}
else {
LinearGradient lg = new LinearGradient(mChartWidth, mChartWidth + mSize, mHeight - 100,
(float) (mHeight - 100 - list.get(i) * size), lefrColorBottom, leftColor, Shader.TileMode.MIRROR);
mChartPaint.setShader(lg);
}
//画柱状图
RectF rectF = new RectF();
rectF.left = mChartWidth;
rectF.right = mChartWidth + mSize;
rectF.bottom = mHeight - 100;
rectF.top = mHeight - 100 - list.get(i) * size;
canvas.drawRoundRect(rectF, 20, 20, mChartPaint);
mChartWidth += getWidth() / 13;
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
int x = (int) ev.getX();
int y = (int) ev.getY();
int left = 0;
int top = 0;
int right = mWidth / 12;
int bottom = mHeight - 100;
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
for (int i = 0; i < 12; i++) {
Rect rect = new Rect(left, top, right, bottom);
left += mWidth / 12;
right += mWidth / 12;
if (rect.contains(x, y)) {
if (listener != null){
listener.getNumber(i, x, y);
number = i;
selectIndex = i;
selectIndexRoles.clear();
selectIndexRoles.add(selectIndex);
invalidate();
}
}
}
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
public void setListener(getNumberListener listener) {
this.listener = listener;
}
public interface getNumberListener {
void getNumber(int number, int x, int y);
}
}
| {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "avmplus.h"
#ifdef VMCFG_EVAL
#include "eval.h"
namespace avmplus
{
namespace RTC
{
// Syntax error strings. When these include formats they are to be interpreted as printf style
// formats for now, notably %s means utf8 or latin1 string. Note that a string may be used
// more than one place, so if you add or remove or change a format be sure to look for all
// occurrences of the string. Note also that order matters crucially, see the enum in eval.h.
static const char* const syntax_errors[] = {
/* SYNTAXERR_EOT_IN_REGEXP */ "Unexpected end of program in regexp literal",
/* SYNTAXERR_NEWLINE_IN_REGEXP */ "Illegal newline in regexp literal",
/* SYNTAXERR_XML_UNEXPECTED_TOKEN */ "Unexpected token in XML parsing",
/* SYNTAXERR_NATIVE_NOT_SUPPORTED */ "'native' functions are not supported",
/* SYNTAXERR_DEFAULT_NOT_EXPECTED */ "'default' not expected here",
/* SYNTAXERR_ILLEGAL_QNAME */ "Illegal qualified name",
/* SYNTAXERR_IMPOSSIBLE_DEFAULT */ "Unsupported default value (ABC restriction)",
/* SYNTAXERR_ILLEGAL_TYPENAME */ "Illegal type name",
/* SYNTAXERR_ILLEGAL_FIELDNAME */ "Illegal field name: String, number, or identifier is required",
/* SYNTAXERR_ILLEGAL_PROPNAME */ "Illegal property identifier",
/* SYNTAXERR_QUALIFIER_NOT_ALLOWED */"Qualifier not allowed here",
/* SYNTAXERR_ILLEGAL_INCLUDE */ "Illegal 'include' directive",
/* SYNTAXERR_ILLEGAL_NAMESPACE */ "Illegal 'namespace' directive",
/* SYNTAXERR_ILLEGAL_IN_INTERFACE */ "Variable or constant definition not allowed in interface",
/* SYNTAXERR_ONE_ARGUMENT_REQUIRED */"Exactly one argument required",
/* SYNTAXERR_NO_FUNCTIONS_IN_BLOCKS*/"Function definitions cannot be block-local",
/* SYNTAXERR_SEMICOLON_OR_NEWLINE */ "Expecting semicolon or newline",
/* SYNTAXERR_CONST_INIT_REQD */ "'const' bindings must be initialized",
/* SYNTAXERR_ILLEGAL_USE */ "Illegal 'use' directive",
/* SYNTAXERR_RETURN_OUTSIDE_FN */ "'return' statement only allowed inside a function",
/* SYNTAXERR_VOIDFN_RETURNS_VALUE */ "'void' function cannot return a value",
/* SYNTAXERR_EXPECT_DXNS */ "Expected 'default xml namespace'",
/* SYNTAXERR_FOR_IN_ONEBINDING */ "Only one variable binding allowed in for-in",
/* SYNTAXERR_FOR_EACH_REQS_IN */ "'for each' requires use of the 'in' form",
/* SYNTAXERR_DUPLICATE_DEFAULT */ "Duplicate 'default' clause",
/* SYNTAXERR_EXPECT_CASE_OR_DEFAULT*/"Expecting 'case' or 'default'",
/* SYNTAXERR_CLASS_NOT_ALLOWED */ "Class not allowed here",
/* SYNTAXERR_PROPERTY_OPERATOR_REQUIRED */ "Property operator required",
/* SYNTAXERR_INTERFACE_NOT_ALLOWED */"Interface not allowed here",
/* SYNTAXERR_XML_ILLEGAL_CHARS */ "Illegal embedded characters in XML literal",
/* SYNTAXERR_STMT_IN_INTERFACE */ "Statements not allowed in interface",
/* SYNTAXERR_ILLEGAL_STMT */ "Illegal statement",
/* SYNTAXERR_KWD_NOT_ALLOWED */ "'%s' not allowed here",
/* SYNTAXERR_INCLUDE_ORIGIN */ "The 'include' directive is only allowed in programs whose origin is a file",
/* SYNTAXERR_INCLUDE_INACCESSIBLE */ "An include file could not be opened or read",
/* SYNTAXERR_REDEFINITION */ "Conflicting binding of name",
/* SYNTAXERR_REDEFINITION_TYPE */ "Conflicting binding of names: mismatching types",
/* SYNTAXERR_REDUNDANT_CONST */ "Redundant constant binding",
/* SYNTAXERR_REDUNDANT_METHOD */ "Redundant method binding",
/* SYNTAXERR_REDUNDANT_NAMESPACE */ "Redundant namespace binding",
/* SYNTAXERR_DEFAULT_VALUE_REQD */ "Default value required",
#ifdef DEBUG
/* SYNTAXERR_WRONG_TOKEN */ "Wrong token - expected %d got %d",
#else
/* SYNTAXERR_WRONG_TOKEN */ "Wrong token",
#endif
/* SYNTAXERR_EXPECTED_IDENT */ "Expected identifier",
/* SYNTAXERR_ILLEGALCHAR_NUL */ "Illegal character in input: NUL",
/* SYNTAXERR_ILLEGAL_NUMBER */ "Illegal numeric literal: no digits",
/* SYNTAXERR_ILLEGALCHAR_POSTNUMBER*/"Illegal character following numeric literal: %c",
/* SYNTAXERR_EOI_IN_COMMENT */ "End of input in block comment",
/* SYNTAXERR_ILLEGALCHAR */ "Illegal character in input: %c",
/* SYNTAXERR_UNTERMINATED_STRING */ "Unterminated string literal (newline or end of input)",
/* SYNTAXERR_EOI_IN_ESC */ "End of input in escape sequence",
/* SYNTAXERR_XML_UNTERMINATED */ "Unterminated XML token",
/* SYNTAXERR_XML_INVALID_SLASH */ "Invalid sequence starting with '/'",
/* SYNTAXERR_XML_INVALID_LEFTBANG */ "Invalid sequence starting with '<!'",
/* SYNTAXERR_IDENT_IS_KWD */ "Illegal identifier: escape sequence makes it look like a keyword",
/* SYNTAXERR_EOL_IN_ESC */ "Illegal line terminator in escape sequence",
/* SYNTAXERR_INVALID_VAR_ESC */ "Invalid variable-length unicode escape",
/* SYNTAXERR_ILLEGAL_BREAK */ "No 'break' allowed here",
/* SYNTAXERR_BREAK_LABEL_UNDEF */ "'break' to undefined label",
/* SYNTAXERR_ILLEGAL_CONTINUE */ "No 'continue' allowed here",
/* SYNTAXERR_CONTINUE_LABEL_UNDEF */ "'continue' to undefined label",
/* SYNTAXERR_XML_EOI_IN_MARKUP */ "End of input in XML markup",
/* SYNTAXERR_UNBOUND_CONST_NAME */ "Unbound name in constant expression",
/* SYNTAXERR_ILLEGAL_OP_IN_CONSTEXPR */ "Illegal operator in constant expression",
/* SYNTAXERR_CONFIG_NAMESPACE_SHADOWING */ "Definition shadows a configuration namespace",
/* SYNTAXERR_ILLEGAL_METADATA */ "Bad or redundant metadata",
/* SYNTAXERR_KWD_NAMESPACE_REQUIRED */ "'namespace' is required here",
/* SYNTAXERR_CONFIG_NAMESPACE_NOT_ALLOWED */ "A 'config' namespace may not be defined here",
/* SYNTAXERR_CONFIG_NAMESPACE_MUST_BE_UNQUALIFIED */ "'config namespace' must not have a qualifier",
/* SYNTAXERR_DUPLICATE_CONFIG */ "Redundant program configuration expression",
/* SYNTAXERR_DIRECTIVE_REQUIRED */ "Directive required",
/* SYNTAXERR_METADATA_NOT_ALLOWED */ "Metadata not allowed",
/* SYNTAXERR_NEWLINE_NOT_ALLOWED */ "Newline not allowed",
/* SYNTAXERR_DUPLICATE_QUALIFIER */ "Duplicated qualifier",
/* SYNTAXERR_CONFIG_REQUIRED */ "Configuration name reference required",
/* SYNTAXERR_CONFIG_PROHIBITED */ "Configuration name reference prohibited",
/* SYNTAXERR_GOTO_LABEL_UNDEFINED */ "Undefined label in 'goto' statement",
/* SYNTAXERR_GOTO_LABEL_AMBIGUOUS */ "Ambiguous label in 'goto' statement",
/* SYNTAXERR_MISSING_BASE_CLASS */ "Base class not found",
/* SYNTAXERR_CIRCULAR_TYPE_HIERARCHY */ "Cycle in the inheritance hierarchy",
};
// Assume that the number of unique identifiers in a program is roughly the square root
// of the raw length of the program. Needs experimental verification. May only be
// true for programs above a certain size; may want a lower limit on the table size.
//
// Using this "arbitrary" value for k we have to use mod when computing the hash bucket
// when interning. Faster would be to round k up to a power of 2, then use k-1 as a
// mask in intern().
static Str** makeStrTable(Allocator* allocator, uint32_t tableSize)
{
Str** strTable = (Str**)allocator->alloc(sizeof(Str*) * tableSize);
for ( uint32_t i=0 ; i < tableSize ; i++ )
strTable[i] = NULL;
return strTable;
}
static const wchar default_filename[] = { '(', 'e', 'v', 'a', 'l', ' ', 's', 't', 'r', 'i', 'n', 'g', ')', 0 };
Compiler::Compiler(HostContext* context, const wchar* filename, const wchar* src, uint32_t srclen, bool public_by_default)
: context(context)
, allocator(new Allocator(this))
, filename(filename != NULL ? filename : default_filename)
, tableSize(uint32_t(sqrt((double)srclen)))
, es3_keywords(false) // ActionScript 3: false
, standard_regex(false) // ActionScript 3: false
, liberal_idents(true) // ActionScript 3: true
, local_functions(true) // ActionScript 3: true
, octal_literals(false) // ActionScript 3: false
, origin_is_file(filename != NULL)
, debugging(true)
, namespace_counter(1)
, strTable(makeStrTable(allocator, tableSize))
, lexer(this, src, srclen)
, parser(this, &lexer, public_by_default)
, abc(this)
, SYM_(intern(""))
, SYM_AS3(intern("AS3"))
, SYM_AS3_vec(intern("__AS3__.vec"))
, SYM_Array(intern("Array"))
, SYM_CONFIG(intern("CONFIG"))
, SYM_Namespace(intern("Namespace"))
, SYM_Number(intern("Number"))
, SYM_Object(intern("Object"))
, SYM_RegExp(intern("RegExp"))
, SYM_Vector(intern("Vector"))
, SYM_XML(intern("XML"))
, SYM_XMLList(intern("XMLList"))
, SYM_anonymous(intern("anonymous"))
, SYM_arguments(intern("arguments"))
, SYM_children(intern("children"))
, SYM_config(intern("config"))
, SYM_each(intern("each"))
, SYM_extends(intern("extends"))
, SYM_get(intern("get"))
, SYM_implements(intern("implements"))
, SYM_int(intern("int"))
, SYM_length(intern("length"))
, SYM_namespace(intern("namespace"))
#ifdef DEBUG
, SYM_print(intern("print"))
#endif
, SYM_set(intern("set"))
, SYM_use(intern("use"))
, SYM_xml(intern("xml"))
, str_filename(intern(this->filename, 0))
, NS_public(abc.addNamespace(CONSTANT_Namespace, abc.addString(SYM_)))
, NS_private(abc.addNamespace(CONSTANT_PrivateNs, abc.addString(SYM_)))
, NS_internal(NS_private)
, NS_AS3_vec(abc.addNamespace(CONSTANT_Namespace, abc.addString(SYM_AS3_vec)))
, ID_Array(abc.addQName(NS_public, abc.addString(SYM_Array)))
, ID_Namespace(abc.addQName(NS_public, abc.addString(SYM_Namespace)))
, ID_Number(abc.addQName(NS_public, abc.addString(SYM_Number)))
, ID_Object(abc.addQName(NS_public, abc.addString(SYM_Object)))
, ID_RegExp(abc.addQName(NS_public, abc.addString(SYM_RegExp)))
, ID_Vector(abc.addQName(NS_AS3_vec, abc.addString(SYM_Vector)))
, ID_XML(abc.addQName(NS_public, abc.addString(SYM_XML)))
, ID_XMLList(abc.addQName(NS_public, abc.addString(SYM_XMLList)))
, ID_children(abc.addQName(NS_public, abc.addString(SYM_children)))
, ID_int(abc.addQName(NS_public, abc.addString(SYM_int)))
, ID_length(abc.addQName(NS_public, abc.addString(SYM_length)))
#ifdef DEBUG
, ID_print(abc.addQName(NS_public, abc.addString(SYM_print)))
#endif
, NSS_public(abc.addNsset(ALLOC(Seq<uint32_t>, (NS_public, ALLOC(Seq<uint32_t>, (NS_internal))))))
, MNL_public(abc.addMultinameL(NSS_public, false))
, MNL_public_attr(abc.addMultinameL(NSS_public, true))
{
}
void Compiler::destroy()
{
delete allocator;
}
void Compiler::compile()
{
#if 0 && defined DEBUG
lexer.trace();
#endif
Program* program = parser.parse();
if (context->stopAfterParse)
return;
ABCTraitsTable* global_traits = ALLOC(ABCTraitsTable, (this));
ABCMethodInfo* global_info = ALLOC(ABCMethodInfo, (this, abc.addString("script$init"), 0, NULL, 0, NULL, 0));
ABCMethodBodyInfo* global_body = ALLOC(ABCMethodBodyInfo, (this, global_info, global_traits, 1, false));
uint32_t nsset = 0;
nsset = global_body->cogen.buildNssetWithPublic(program->openNamespaces);
ProgramCtx ctx(global_body->cogen.allocator, nsset, program->openNamespaces, global_body->cogen.getTemp());
program->cogenTypes(&global_body->cogen, &ctx, global_traits, program->classes);
program->cogen(&global_body->cogen, &ctx);
global_info->setFlags(global_body->getFlags() | abcMethod_SETS_DXNS);
ALLOC(ABCScriptInfo, (this, global_info, global_traits));
global_body->clearTraits(); // the traits belong to the script, so don't emit them with the body too
abc.serialize(context->obtainStorageForResult(abc.size()));
}
void Compiler::internalError(uint32_t lineno, const char* fmt, ...)
{
va_list args;
va_start(args,fmt);
internalWarningOrError(true, lineno, fmt, args);
va_end(args);
}
void Compiler::internalWarning(uint32_t lineno, const char* fmt, ...)
{
va_list args;
va_start(args,fmt);
internalWarningOrError(false, lineno, fmt, args);
va_end(args);
}
void Compiler::internalWarningOrError(bool error, uint32_t lineno, const char* fmt, va_list args)
{
char buf[500];
char lbuf[12];
if (lineno != 0)
VMPI_sprintf(lbuf, "%d", lineno);
else
VMPI_strcpy(lbuf, "Unknown");
{
char fbuf[500];
formatUtf8(fbuf, sizeof(fbuf), filename);
VMPI_snprintf(buf, sizeof(buf), "%s:%s: Internal %s: ", fbuf, lbuf, (error ? "error" : "warning"));
buf[sizeof(buf)-1] = 0;
}
int k = int(VMPI_strlen(buf));
VMPI_vsnprintf(buf+k, sizeof(buf)-k, fmt, args);
if (error)
context->throwInternalError(buf);
}
void Compiler::syntaxError(uint32_t lineno, SyntaxError fmt, ...)
{
const char* fmtstring = syntax_errors[(int)fmt];
char buf[500];
char lbuf[12];
if (lineno != 0)
VMPI_sprintf(lbuf, "%d", lineno);
else
VMPI_strcpy(lbuf, "Unknown");
{
char fbuf[500];
formatUtf8(fbuf, sizeof(fbuf), filename);
VMPI_snprintf(buf, sizeof(buf), "%s:%s: Syntax error: ", fbuf, lbuf);
buf[sizeof(buf)-1] = 0;
}
int k = int(VMPI_strlen(buf));
va_list args;
va_start(args,fmt);
VMPI_vsnprintf(buf+k, sizeof(buf)-k, fmtstring, args);
va_end(args);
context->throwSyntaxError(buf);
}
Str* Compiler::intern(const char* s)
{
StringBuilder b(this);
b.append(s);
return b.str();
}
Str* Compiler::intern(uint32_t u)
{
wchar buf[12];
uint32_t i = 0;
if (u == 0)
buf[i++] = '0';
else {
while (u != 0) {
buf[i++] = '0' + (u % 10);
u /= 10;
}
for ( uint32_t j=0, k=i-1 ; j < k ; j++, k-- ) {
wchar c = buf[j];
buf[j] = buf[k];
buf[k] = c;
}
}
return intern(buf, i);
}
Str* Compiler::intern(const wchar* chars, uint32_t nchars)
{
// '%' may not be the best here, see comment above about how to speed it up
// if it turns out to be a bottleneck.
uint32_t h = hashString(chars, nchars) % tableSize;
for ( Str* p = strTable[h] ; p != NULL ; p = p->next ) {
if (p->hash == h)
if (p->length == nchars)
if (VMPI_memcmp(p->s, chars, sizeof(wchar)*nchars) == 0)
return p;
}
// The string is not known yet
Str* str = (Str*)allocator->alloc(sizeof(Str) + sizeof(wchar)*(nchars - 1 + 1)); // -1 for the elt in Str, +1 for the NUL
VMPI_memcpy(str->s, chars, sizeof(wchar)*nchars);
str->s[nchars] = 0;
str->hash = h;
str->ident = ~0U;
str->next = strTable[h];
str->length = nchars;
strTable[h] = str;
#if 0 && defined DEBUG
char buf[200];
printf(">>> Interning: %s\n", getn(buf, str, sizeof(buf)));
#endif
return str;
}
}
}
#endif // VMCFG_EVAL
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <map>
#include <memory>
#include <string>
#include "db/dbformat.h"
#include "db/db_impl.h"
#include "db/table_properties_collector.h"
#include "rocksdb/table_properties.h"
#include "rocksdb/table.h"
#include "table/block_based_table_factory.h"
#include "util/coding.h"
#include "util/testharness.h"
#include "util/testutil.h"
namespace rocksdb {
class TablePropertiesTest {
private:
unique_ptr<TableReader> table_reader_;
};
// TODO(kailiu) the following classes should be moved to some more general
// places, so that other tests can also make use of them.
// `FakeWritableFile` and `FakeRandomeAccessFile` bypass the real file system
// and therefore enable us to quickly setup the tests.
class FakeWritableFile : public WritableFile {
public:
~FakeWritableFile() { }
const std::string& contents() const { return contents_; }
virtual Status Close() { return Status::OK(); }
virtual Status Flush() { return Status::OK(); }
virtual Status Sync() { return Status::OK(); }
virtual Status Append(const Slice& data) {
contents_.append(data.data(), data.size());
return Status::OK();
}
private:
std::string contents_;
};
class FakeRandomeAccessFile : public RandomAccessFile {
public:
explicit FakeRandomeAccessFile(const Slice& contents)
: contents_(contents.data(), contents.size()) {
}
virtual ~FakeRandomeAccessFile() { }
uint64_t Size() const { return contents_.size(); }
virtual Status Read(uint64_t offset, size_t n, Slice* result,
char* scratch) const {
if (offset > contents_.size()) {
return Status::InvalidArgument("invalid Read offset");
}
if (offset + n > contents_.size()) {
n = contents_.size() - offset;
}
memcpy(scratch, &contents_[offset], n);
*result = Slice(scratch, n);
return Status::OK();
}
private:
std::string contents_;
};
class DumbLogger : public Logger {
public:
virtual void Logv(const char* format, va_list ap) { }
virtual size_t GetLogFileSize() const { return 0; }
};
// Utilities test functions
void MakeBuilder(
const Options& options,
std::unique_ptr<FakeWritableFile>* writable,
std::unique_ptr<TableBuilder>* builder) {
writable->reset(new FakeWritableFile);
builder->reset(
options.table_factory->GetTableBuilder(options, writable->get(),
options.compression));
}
void OpenTable(
const Options& options,
const std::string& contents,
std::unique_ptr<TableReader>* table_reader) {
std::unique_ptr<RandomAccessFile> file(new FakeRandomeAccessFile(contents));
auto s = options.table_factory->GetTableReader(
options,
EnvOptions(),
std::move(file),
contents.size(),
table_reader
);
ASSERT_OK(s);
}
// Collects keys that starts with "A" in a table.
class RegularKeysStartWithA: public TablePropertiesCollector {
public:
const char* Name() const { return "RegularKeysStartWithA"; }
Status Finish(TableProperties::UserCollectedProperties* properties) {
std::string encoded;
PutVarint32(&encoded, count_);
*properties = TableProperties::UserCollectedProperties {
{ "TablePropertiesTest", "Rocksdb" },
{ "Count", encoded }
};
return Status::OK();
}
Status Add(const Slice& user_key, const Slice& value) {
// simply asssume all user keys are not empty.
if (user_key.data()[0] == 'A') {
++count_;
}
return Status::OK();
}
virtual TableProperties::UserCollectedProperties
GetReadableProperties() const {
return {};
}
private:
uint32_t count_ = 0;
};
TEST(TablePropertiesTest, CustomizedTablePropertiesCollector) {
Options options;
// make sure the entries will be inserted with order.
std::map<std::string, std::string> kvs = {
{"About", "val5"}, // starts with 'A'
{"Abstract", "val2"}, // starts with 'A'
{"Around", "val7"}, // starts with 'A'
{"Beyond", "val3"},
{"Builder", "val1"},
{"Cancel", "val4"},
{"Find", "val6"},
};
// Test properties collectors with internal keys or regular keys
for (bool encode_as_internal : { true, false }) {
// -- Step 1: build table
auto collector = new RegularKeysStartWithA();
if (encode_as_internal) {
options.table_properties_collectors = {
std::make_shared<UserKeyTablePropertiesCollector>(collector)
};
} else {
options.table_properties_collectors.resize(1);
options.table_properties_collectors[0].reset(collector);
}
std::unique_ptr<TableBuilder> builder;
std::unique_ptr<FakeWritableFile> writable;
MakeBuilder(options, &writable, &builder);
for (const auto& kv : kvs) {
if (encode_as_internal) {
InternalKey ikey(kv.first, 0, ValueType::kTypeValue);
builder->Add(ikey.Encode(), kv.second);
} else {
builder->Add(kv.first, kv.second);
}
}
ASSERT_OK(builder->Finish());
// -- Step 2: Open table
std::unique_ptr<TableReader> table_reader;
OpenTable(options, writable->contents(), &table_reader);
const auto& properties =
table_reader->GetTableProperties().user_collected_properties;
ASSERT_EQ("Rocksdb", properties.at("TablePropertiesTest"));
uint32_t starts_with_A = 0;
Slice key(properties.at("Count"));
ASSERT_TRUE(GetVarint32(&key, &starts_with_A));
ASSERT_EQ(3u, starts_with_A);
}
}
TEST(TablePropertiesTest, InternalKeyPropertiesCollector) {
InternalKey keys[] = {
InternalKey("A", 0, ValueType::kTypeValue),
InternalKey("B", 0, ValueType::kTypeValue),
InternalKey("C", 0, ValueType::kTypeValue),
InternalKey("W", 0, ValueType::kTypeDeletion),
InternalKey("X", 0, ValueType::kTypeDeletion),
InternalKey("Y", 0, ValueType::kTypeDeletion),
InternalKey("Z", 0, ValueType::kTypeDeletion),
};
for (bool sanitized : { false, true }) {
std::unique_ptr<TableBuilder> builder;
std::unique_ptr<FakeWritableFile> writable;
Options options;
if (sanitized) {
options.table_properties_collectors = {
std::make_shared<RegularKeysStartWithA>()
};
// with sanitization, even regular properties collector will be able to
// handle internal keys.
auto comparator = options.comparator;
// HACK: Set options.info_log to avoid writing log in
// SanitizeOptions().
options.info_log = std::make_shared<DumbLogger>();
options = SanitizeOptions(
"db", // just a place holder
nullptr, // with skip internal key comparator
nullptr, // don't care filter policy
options
);
options.comparator = comparator;
} else {
options.table_properties_collectors = {
std::make_shared<InternalKeyPropertiesCollector>()
};
}
MakeBuilder(options, &writable, &builder);
for (const auto& k : keys) {
builder->Add(k.Encode(), "val");
}
ASSERT_OK(builder->Finish());
std::unique_ptr<TableReader> table_reader;
OpenTable(options, writable->contents(), &table_reader);
const auto& properties =
table_reader->GetTableProperties().user_collected_properties;
uint64_t deleted = GetDeletedKeys(properties);
ASSERT_EQ(4u, deleted);
if (sanitized) {
uint32_t starts_with_A = 0;
Slice key(properties.at("Count"));
ASSERT_TRUE(GetVarint32(&key, &starts_with_A));
ASSERT_EQ(1u, starts_with_A);
}
}
}
} // namespace rocksdb
int main(int argc, char** argv) {
return rocksdb::test::RunAllTests();
}
| {
"pile_set_name": "Github"
} |
layui.define(['jquery'],function(exports){
var $ = layui.jquery;
var self = {
elem:null,
barTimer:0,
barWidth:0,
config:{
color:'#5a8bff',
errorColor:'#FF5722',
height:2,
}
}
function randomNum(minNum,maxNum){
switch(arguments.length){
case 1:
return parseInt(Math.random()*minNum+1,10);
break;
case 2:
return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10);
break;
default:
return 0;
break;
}
}
function setBarWidth(num){
self.barWidth = num;
self.elem.css('width',self.barWidth + '%');
}
function addBarWidth(num){
self.barWidth += num;
if(self.barWidth >= 100) self.barWidth = 100;
setBarWidth(self.barWidth);
return self.barWidth;
}
function hideBar(barColor){
clearInterval(self.barTimer);
addBarWidth(100);
self.elem.css({ 'backgroundColor':barColor });
setTimeout(function(){
self.elem.css({
'opacity':0
});
setBarWidth(0);
},250);
}
self.start = function (config) {
this.config = $.extend(this.config,config || {});
if(this.barTimer){
clearInterval(this.barTimer);
setBarWidth(0);
}
if(this.elem == null){
this.elem = $('<div id="nepadmin-loadbar"></div>');
$('body').prepend(this.elem);
}
this.elem.css({
'height':this.config.height,
'backgroundColor':this.config.color,
'position': 'fixed',
'top':0,
'left':0,
'width': 0,
'width':0,
'opacity':1,
'zIndex':2000,
'transition': 'all .2s linear'
});
addBarWidth(randomNum(1,10));
this.barTimer = setInterval(function(){
addBarWidth(randomNum(1,10));
if(self.barWidth >= 75) self.barWidth = 75
},160);
}
self.finish = function () {
hideBar(this.config.color);
}
self.error = function(){
hideBar(this.config.errorColor);
}
exports('loadBar',self);
}) | {
"pile_set_name": "Github"
} |
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
# Add Yarn node_modules folder to the asset load path.
# Rails.application.config.assets.paths << Rails.root.join('node_modules')
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in the app/assets
# folder are already added.
Rails.application.config.assets.precompile += %w[*.png *.jpg *.jpeg *.gif *.svg]
| {
"pile_set_name": "Github"
} |
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
/*
* Copyright 2008-2011 ZXing 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 <zxing/common/CharacterSetECI.h>
#include <zxing/common/IllegalArgumentException.h>
#include <zxing/FormatException.h>
using std::string;
using zxing::common::CharacterSetECI;
using zxing::IllegalArgumentException;
std::map<int, CharacterSetECI*> CharacterSetECI::VALUE_TO_ECI;
std::map<std::string, CharacterSetECI*> CharacterSetECI::NAME_TO_ECI;
const bool CharacterSetECI::inited = CharacterSetECI::init_tables();
#define ADD_CHARACTER_SET(VALUES, STRINGS) \
{ static int values[] = {VALUES, -1}; \
static char const* strings[] = {STRINGS, 0}; \
addCharacterSet(values, strings); }
#define XC ,
bool CharacterSetECI::init_tables() {
ADD_CHARACTER_SET(0 XC 2, "Cp437");
ADD_CHARACTER_SET(1 XC 3, "ISO8859_1" XC "ISO-8859-1");
ADD_CHARACTER_SET(4, "ISO8859_2" XC "ISO-8859-2");
ADD_CHARACTER_SET(5, "ISO8859_3" XC "ISO-8859-3");
ADD_CHARACTER_SET(6, "ISO8859_4" XC "ISO-8859-4");
ADD_CHARACTER_SET(7, "ISO8859_5" XC "ISO-8859-5");
ADD_CHARACTER_SET(8, "ISO8859_6" XC "ISO-8859-6");
ADD_CHARACTER_SET(9, "ISO8859_7" XC "ISO-8859-7");
ADD_CHARACTER_SET(10, "ISO8859_8" XC "ISO-8859-8");
ADD_CHARACTER_SET(11, "ISO8859_9" XC "ISO-8859-9");
ADD_CHARACTER_SET(12, "ISO8859_10" XC "ISO-8859-10");
ADD_CHARACTER_SET(13, "ISO8859_11" XC "ISO-8859-11");
ADD_CHARACTER_SET(15, "ISO8859_13" XC "ISO-8859-13");
ADD_CHARACTER_SET(16, "ISO8859_14" XC "ISO-8859-14");
ADD_CHARACTER_SET(17, "ISO8859_15" XC "ISO-8859-15");
ADD_CHARACTER_SET(18, "ISO8859_16" XC "ISO-8859-16");
ADD_CHARACTER_SET(20, "SJIS" XC "Shift_JIS");
ADD_CHARACTER_SET(21, "Cp1250" XC "windows-1250");
ADD_CHARACTER_SET(22, "Cp1251" XC "windows-1251");
ADD_CHARACTER_SET(23, "Cp1252" XC "windows-1252");
ADD_CHARACTER_SET(24, "Cp1256" XC "windows-1256");
ADD_CHARACTER_SET(25, "UnicodeBigUnmarked" XC "UTF-16BE" XC "UnicodeBig");
ADD_CHARACTER_SET(26, "UTF8" XC "UTF-8");
ADD_CHARACTER_SET(27 XC 170, "ASCII" XC "US-ASCII");
ADD_CHARACTER_SET(28, "Big5");
ADD_CHARACTER_SET(29, "GB18030" XC "GB2312" XC "EUC_CN" XC "GBK");
ADD_CHARACTER_SET(30, "EUC_KR" XC "EUC-KR");
return true;
}
#undef XC
CharacterSetECI::CharacterSetECI(int const* values,
char const* const* names)
: values_(values), names_(names) {
for(int const* values = values_; *values != -1; values++) {
VALUE_TO_ECI[*values] = this;
}
for(char const* const* names = names_; *names; names++) {
NAME_TO_ECI[string(*names)] = this;
}
}
char const* CharacterSetECI::name() const {
return names_[0];
}
int CharacterSetECI::getValue() const {
return values_[0];
}
void CharacterSetECI::addCharacterSet(int const* values, char const* const* names) {
new CharacterSetECI(values, names);
}
CharacterSetECI* CharacterSetECI::getCharacterSetECIByValue(int value) {
if (value < 0 || value >= 900) {
throw FormatException();
}
return VALUE_TO_ECI[value];
}
CharacterSetECI* CharacterSetECI::getCharacterSetECIByName(string const& name) {
return NAME_TO_ECI[name];
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2019 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using Alachisoft.NCache.Caching.Messaging;
using Alachisoft.NCache.Common.Caching;
using Alachisoft.NCache.Common.DataStructures.Clustered;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Common.Pooling;
using Alachisoft.NCache.Util;
using System;
using System.Collections;
using System.IO;
namespace Alachisoft.NCache.Caching.Topologies.Clustered
{
/// <summary>
/// State Txfr corresponder for Mirror and Replicated topology.
/// Gets the data from cache and sends the data to the joining node in the form of ReplicaStateTxfrInfo.
/// </summary>
class ReplicaStateTxfrCorresponder : IDisposable
{
/// <summary>
/// 200K is the threshold data size.
/// Above this threshold value, data will be
/// transfered in chunks.
/// </summary>
protected long _threshold = 20 * 1024;//200 * 1000;
protected int _keyCount = 0;
protected int _collKeyCount = 0;
internal ClusterCacheBase _parent;
protected object[] _keyList = null;
protected object[] _collectionsList = null;
protected bool _collectionStateTransferStarted = false;
private Stream stream = null;
private Address _clientNode;
// <summary> The default operation timeout, to be specified in the configuration. </summary>
private int _defOpTimeout = 60000;
public int Timeout
{
get { return _defOpTimeout; }
set { _defOpTimeout = value; }
}
internal ReplicaStateTxfrCorresponder(ClusterCacheBase parent, Address requestingNode)
{
_parent = parent;
_clientNode = requestingNode;
stream = new MemoryStream((int)_threshold);
_keyCount = 0;
_collKeyCount = 0;
}
internal ReplicaStateTxfrInfo GetData()
{
if (_keyList == null)
_keyList = MiscUtil.GetKeys(_parent.InternalCache, _defOpTimeout);
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "state txfr request for cache entry");
if (_keyList != null && _keyList.Length > 0)
{
return GetCacheItems();
}
return new ReplicaStateTxfrInfo(true);
}
private ReplicaStateTxfrInfo GetCacheItems()
{
long sizeToSend = 0;
CacheEntry entry = null;
try
{
ReplicaStateTxfrInfo info = null;
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "bucket size :" + _keyList.Length);
if (_keyList.Length == _keyCount && _collectionsList != null && _collectionsList.Length > 0)
{
_keyList = _collectionsList;
_collectionStateTransferStarted = true;
_collectionsList = null;
_keyCount = 0;
}
else
{
while (_keyCount < _keyList.Length)
{
string key = _keyList[_keyCount] as string;
OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
operationContext.Add(OperationContextFieldName.GenerateQueryInfo, true);
operationContext.UseObjectPool = false;
entry = _parent.InternalCache.InternalCache.Get(key, false, operationContext);
_keyCount++;
if (entry != null)
{
info = new ReplicaStateTxfrInfo(key, entry, false, sizeToSend, this.stream, DataType.CacheItems);
break;
}
}
}
if (_parent.Context.NCacheLog.IsInfoEnabled) _parent.Context.NCacheLog.Info("StateTxfrCorresponder.GetData(2)", "items sent :" + _keyCount);
_parent.Context.PerfStatsColl.ResetStateTransferPerfmonCounter();
_parent.Context.PerfStatsColl.IncrementStateTxfrPerSecStatsBy(_keyCount);
if (_collectionStateTransferStarted || (info == null && _collKeyCount > 0))
return new ReplicaStateTxfrInfo(false);
return info != null ? info : new ReplicaStateTxfrInfo(true);
}
finally
{
if (entry != null)
entry.MarkFree(NCModulesConstants.Global);
}
}
private void TransferMessages()
{
OrderedDictionary topicWiseMessagees = _parent.GetMessageList(0,true);
if (_parent.NCacheLog.IsInfoEnabled)
_parent.NCacheLog.Info("StateTransferTask.TransferMessages", " message transfer started");
if (topicWiseMessagees != null)
{
foreach (DictionaryEntry topicWiseMessage in topicWiseMessagees)
{
ClusteredArrayList messageList = topicWiseMessage.Value as ClusteredArrayList;
if (_parent.NCacheLog.IsInfoEnabled)
_parent.NCacheLog.Info("StateTransferTask.TransferMessages", " topic : " + topicWiseMessage.Key + " messaeg count : " + messageList.Count);
foreach (string messageId in messageList)
{
try
{
TransferrableMessage message = _parent.GetTransferrableMessage(topicWiseMessage.Key as string, messageId);
if (message != null)
{
_parent.InternalCache.StoreTransferrableMessage(topicWiseMessage.Key as string, message);
}
}
catch (Exception e)
{
_parent.NCacheLog.Error("StateTransferTask.TransferMessages", e.ToString());
}
}
}
}
if (_parent.NCacheLog.IsInfoEnabled)
_parent.NCacheLog.Info("StateTransferTask.TransferMessages", " message transfer ended");
}
public void Dispose()
{
_collKeyCount = 0;
_parent = null;
_keyList = null;
_collectionsList = null;
_collectionStateTransferStarted = false;
stream = null;
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* desktop.c
* Copyright (C) 2017 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#include "data-types.h"
#include <dlfcn.h>
#define FUNC(name, restype, ...) typedef restype (*name##_func)(__VA_ARGS__); static name##_func name = NULL
#define LOAD_FUNC(handle, name) {\
*(void **) (&name) = dlsym(handle, #name); \
const char* error = dlerror(); \
if (error != NULL) { \
PyErr_Format(PyExc_OSError, "Failed to load the function %s with error: %s", #name, error); dlclose(handle); handle = NULL; return NULL; \
} \
}
FUNC(sn_display_new, void*, void*, void*, void*);
FUNC(sn_launchee_context_new_from_environment, void*, void*, int);
FUNC(sn_launchee_context_new, void*, void*, int, const char*);
FUNC(sn_display_unref, void, void*);
FUNC(sn_launchee_context_setup_window, void, void*, int32_t);
FUNC(sn_launchee_context_complete, void, void*);
FUNC(sn_launchee_context_unref, void, void*);
static void* libsn_handle = NULL;
static PyObject*
init_x11_startup_notification(PyObject UNUSED *self, PyObject *args) {
static bool done = false;
if (!done) {
done = true;
const char* libnames[] = {
#if defined(_KITTY_STARTUP_NOTIFICATION_LIBRARY)
_KITTY_STARTUP_NOTIFICATION_LIBRARY,
#else
"libstartup-notification-1.so",
// some installs are missing the .so symlink, so try the full name
"libstartup-notification-1.so.0",
"libstartup-notification-1.so.0.0.0",
#endif
NULL
};
for (int i = 0; libnames[i]; i++) {
libsn_handle = dlopen(libnames[i], RTLD_LAZY);
if (libsn_handle) break;
}
if (libsn_handle == NULL) {
PyErr_Format(PyExc_OSError, "Failed to load %s with error: %s", libnames[0], dlerror());
return NULL;
}
dlerror(); /* Clear any existing error */
#define F(name) LOAD_FUNC(libsn_handle, name)
F(sn_display_new);
F(sn_launchee_context_new_from_environment);
F(sn_launchee_context_new);
F(sn_display_unref);
F(sn_launchee_context_setup_window);
F(sn_launchee_context_complete);
F(sn_launchee_context_unref);
#undef F
}
int window_id;
PyObject *dp;
char *startup_id = NULL;
if (!PyArg_ParseTuple(args, "O!i|z", &PyLong_Type, &dp, &window_id, &startup_id)) return NULL;
void* display = PyLong_AsVoidPtr(dp);
void* sn_display = sn_display_new(display, NULL, NULL);
if (!sn_display) { PyErr_SetString(PyExc_OSError, "Failed to create SnDisplay"); return NULL; }
void *ctx = startup_id ? sn_launchee_context_new(sn_display, 0, startup_id) : sn_launchee_context_new_from_environment(sn_display, 0);
sn_display_unref(sn_display);
if (!ctx) { PyErr_SetString(PyExc_OSError, "Failed to create startup-notification context"); return NULL; }
sn_launchee_context_setup_window(ctx, window_id);
return PyLong_FromVoidPtr(ctx);
}
static PyObject*
end_x11_startup_notification(PyObject UNUSED *self, PyObject *args) {
if (!libsn_handle) Py_RETURN_NONE;
PyObject *dp;
if (!PyArg_ParseTuple(args, "O!", &PyLong_Type, &dp)) return NULL;
void *ctx = PyLong_AsVoidPtr(dp);
sn_launchee_context_complete(ctx);
sn_launchee_context_unref(ctx);
Py_RETURN_NONE;
}
static PyMethodDef module_methods[] = {
METHODB(init_x11_startup_notification, METH_VARARGS),
METHODB(end_x11_startup_notification, METH_VARARGS),
{NULL, NULL, 0, NULL} /* Sentinel */
};
static void* libcanberra_handle = NULL;
static void *canberra_ctx = NULL;
FUNC(ca_context_create, int, void**);
FUNC(ca_context_destroy, int, void*);
typedef int (*ca_context_play_func)(void*, uint32_t, ...); static ca_context_play_func ca_context_play = NULL;
static PyObject*
load_libcanberra_functions(void) {
LOAD_FUNC(libcanberra_handle, ca_context_create);
LOAD_FUNC(libcanberra_handle, ca_context_play);
LOAD_FUNC(libcanberra_handle, ca_context_destroy);
return NULL;
}
static void
load_libcanberra(void) {
static bool done = false;
if (done) return;
done = true;
const char* libnames[] = {
#if defined(_KITTY_CANBERRA_LIBRARY)
_KITTY_CANBERRA_LIBRARY,
#else
"libcanberra.so",
// some installs are missing the .so symlink, so try the full name
"libcanberra.so.0",
"libcanberra.so.0.2.5",
#endif
NULL
};
for (int i = 0; libnames[i]; i++) {
libcanberra_handle = dlopen(libnames[i], RTLD_LAZY);
if (libcanberra_handle) break;
}
if (libcanberra_handle == NULL) {
fprintf(stderr, "Failed to load %s, cannot play beep sound, with error: %s\n", libnames[0], dlerror());
return;
}
load_libcanberra_functions();
if (PyErr_Occurred()) {
PyErr_Print();
dlclose(libcanberra_handle); libcanberra_handle = NULL;
}
if (ca_context_create(&canberra_ctx) != 0) {
fprintf(stderr, "Failed to create libcanberra context, cannot play beep sound\n");
ca_context_destroy(canberra_ctx); canberra_ctx = NULL;
dlclose(libcanberra_handle); libcanberra_handle = NULL;
}
}
void
play_canberra_sound(const char *which_sound, const char *event_id) {
load_libcanberra();
if (libcanberra_handle == NULL || canberra_ctx == NULL) return;
ca_context_play(
canberra_ctx, 0,
"event.id", which_sound,
"event.description", event_id,
NULL
);
}
static void
finalize(void) {
if (libsn_handle) dlclose(libsn_handle);
libsn_handle = NULL;
if (canberra_ctx) ca_context_destroy(canberra_ctx);
canberra_ctx = NULL;
if (libcanberra_handle) dlclose(libcanberra_handle);
}
bool
init_desktop(PyObject *m) {
if (PyModule_AddFunctions(m, module_methods) != 0) return false;
if (Py_AtExit(finalize) != 0) {
PyErr_SetString(PyExc_RuntimeError, "Failed to register the desktop.c at exit handler");
return false;
}
return true;
}
| {
"pile_set_name": "Github"
} |
/*
Copyright (C) 2010-2017 Kristian Duske
This file is part of TrenchBroom.
TrenchBroom is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TrenchBroom is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with TrenchBroom. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GroupRenderer.h"
#include "PreferenceManager.h"
#include "Preferences.h"
#include "Model/EditorContext.h"
#include "Model/GroupNode.h"
#include "Renderer/GLVertexType.h"
#include "Renderer/PrimType.h"
#include "Renderer/RenderBatch.h"
#include "Renderer/RenderContext.h"
#include "Renderer/RenderService.h"
#include "Renderer/TextAnchor.h"
#include <vector>
#include <vector>
namespace TrenchBroom {
namespace Renderer {
class GroupRenderer::GroupNameAnchor : public TextAnchor3D {
private:
const Model::GroupNode* m_group;
public:
GroupNameAnchor(const Model::GroupNode* group) :
m_group(group) {}
private:
vm::vec3f basePosition() const override {
auto position = vm::vec3f(m_group->logicalBounds().center());
position[2] = float(m_group->logicalBounds().max.z());
position[2] += 2.0f;
return position;
}
TextAlignment::Type alignment() const override {
return TextAlignment::Bottom;
}
};
GroupRenderer::GroupRenderer(const Model::EditorContext& editorContext) :
m_editorContext(editorContext),
m_boundsValid(false),
m_showOverlays(true),
m_showOccludedOverlays(false),
m_overrideBoundsColor(false),
m_showOccludedBounds(false) {}
void GroupRenderer::setGroups(const std::vector<Model::GroupNode*>& groups) {
m_groups = groups;
invalidate();
}
void GroupRenderer::invalidate() {
invalidateBounds();
}
void GroupRenderer::clear() {
m_groups.clear();
m_boundsRenderer = DirectEdgeRenderer();
}
void GroupRenderer::setShowOverlays(const bool showOverlays) {
m_showOverlays = showOverlays;
}
void GroupRenderer::setOverlayTextColor(const Color& overlayTextColor) {
m_overlayTextColor = overlayTextColor;
}
void GroupRenderer::setOverlayBackgroundColor(const Color& overlayBackgroundColor) {
m_overlayBackgroundColor = overlayBackgroundColor;
}
void GroupRenderer::setShowOccludedOverlays(const bool showOccludedOverlays) {
m_showOccludedOverlays = showOccludedOverlays;
}
void GroupRenderer::setOverrideBoundsColor(const bool overrideBoundsColor) {
m_overrideBoundsColor = overrideBoundsColor;
}
void GroupRenderer::setBoundsColor(const Color& boundsColor) {
m_boundsColor = boundsColor;
}
void GroupRenderer::setShowOccludedBounds(const bool showOccludedBounds) {
m_showOccludedBounds = showOccludedBounds;
}
void GroupRenderer::setOccludedBoundsColor(const Color& occludedBoundsColor) {
m_occludedBoundsColor = occludedBoundsColor;
}
void GroupRenderer::render(RenderContext& renderContext, RenderBatch& renderBatch) {
if (!m_groups.empty()) {
if (renderContext.showGroupBounds()) {
renderBounds(renderContext, renderBatch);
renderNames(renderContext, renderBatch);
}
}
}
void GroupRenderer::renderBounds(RenderContext&, RenderBatch& renderBatch) {
if (!m_boundsValid) {
validateBounds();
}
if (m_showOccludedBounds) {
m_boundsRenderer.renderOnTop(renderBatch, m_overrideBoundsColor, m_occludedBoundsColor);
}
m_boundsRenderer.render(renderBatch, m_overrideBoundsColor, m_boundsColor);
}
void GroupRenderer::renderNames(RenderContext& renderContext, RenderBatch& renderBatch) {
if (m_showOverlays) {
Renderer::RenderService renderService(renderContext, renderBatch);
renderService.setForegroundColor(m_overlayTextColor);
renderService.setBackgroundColor(m_overlayBackgroundColor);
for (const auto* group : m_groups) {
if (shouldRenderGroup(group)) {
const GroupNameAnchor anchor(group);
if (m_showOccludedOverlays) {
renderService.setShowOccludedObjects();
} else {
renderService.setHideOccludedObjects();
}
renderService.renderString(groupString(group), anchor);
}
}
}
}
void GroupRenderer::invalidateBounds() {
m_boundsValid = false;
}
struct GroupRenderer::BuildColoredBoundsVertices {
using Vertex = GLVertexTypes::P3C4::Vertex;
std::vector<Vertex>& vertices;
Color color;
BuildColoredBoundsVertices(std::vector<Vertex>& i_vertices, const Color& i_color) :
vertices(i_vertices),
color(i_color) {}
void operator()(const vm::vec3& v1, const vm::vec3& v2) {
vertices.emplace_back(vm::vec3f(v1), color);
vertices.emplace_back(vm::vec3f(v2), color);
}
};
struct GroupRenderer::BuildBoundsVertices {
std::vector<GLVertexTypes::P3::Vertex>& vertices;
BuildBoundsVertices(std::vector<GLVertexTypes::P3::Vertex>& i_vertices) :
vertices(i_vertices) {}
void operator()(const vm::vec3& v1, const vm::vec3& v2) {
vertices.emplace_back(vm::vec3f(v1));
vertices.emplace_back(vm::vec3f(v2));
}
};
void GroupRenderer::validateBounds() {
if (m_overrideBoundsColor) {
std::vector<GLVertexTypes::P3::Vertex> vertices;
vertices.reserve(24 * m_groups.size());
BuildBoundsVertices boundsBuilder(vertices);
for (const Model::GroupNode* group : m_groups) {
if (shouldRenderGroup(group)) {
group->logicalBounds().for_each_edge(boundsBuilder);
}
}
m_boundsRenderer = DirectEdgeRenderer(VertexArray::move(std::move(vertices)), PrimType::Lines);
} else {
std::vector<GLVertexTypes::P3C4::Vertex> vertices;
vertices.reserve(24 * m_groups.size());
for (const Model::GroupNode* group : m_groups) {
if (shouldRenderGroup(group)) {
BuildColoredBoundsVertices boundsBuilder(vertices, boundsColor(group));
group->logicalBounds().for_each_edge(boundsBuilder);
}
}
m_boundsRenderer = DirectEdgeRenderer(VertexArray::move(std::move(vertices)), PrimType::Lines);
}
m_boundsValid = true;
}
bool GroupRenderer::shouldRenderGroup(const Model::GroupNode* group) const {
const auto& currentGroup = m_editorContext.currentGroup();
const auto* parentGroup = group->group();
return parentGroup == currentGroup && m_editorContext.visible(group);
}
AttrString GroupRenderer::groupString(const Model::GroupNode* group) const {
return group->name();
}
const Color& GroupRenderer::boundsColor(const Model::GroupNode* /* group */) const {
return pref(Preferences::DefaultGroupColor);
}
}
}
| {
"pile_set_name": "Github"
} |
@node ftrylockfile
@section @code{ftrylockfile}
@findex ftrylockfile
POSIX specification:@* @url{https://pubs.opengroup.org/onlinepubs/9699919799/functions/ftrylockfile.html}
Gnulib module: ---
Portability problems fixed by Gnulib:
@itemize
@end itemize
Portability problems not fixed by Gnulib:
@itemize
@item
This function is missing on some platforms:
Minix 3.1.8, mingw, MSVC 14.
@end itemize
| {
"pile_set_name": "Github"
} |
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using NUnit.Framework;
namespace MongoDB.UnitTests
{
[TestFixture]
public class TestMongoRegex
{
[Test]
public void CanBeCunstructedFromNullExpressionAndOptions()
{
var regex = new MongoRegex(null, null);
Assert.IsNull(regex.Expression);
Assert.IsNull(regex.RawOptions);
}
[Test]
public void CanBeConstructed()
{
var regex = new MongoRegex("expression");
Assert.AreEqual("expression", regex.Expression);
Assert.AreEqual(string.Empty, regex.RawOptions);
}
[Test]
public void CanBeConstructedWithOption()
{
var regex = new MongoRegex("expression", "options");
Assert.AreEqual("expression",regex.Expression);
Assert.AreEqual("options",regex.RawOptions);
}
[Test]
public void CanBeConstructedFromRegex()
{
const RegexOptions options = RegexOptions.IgnoreCase |
RegexOptions.IgnorePatternWhitespace |
RegexOptions.Multiline;
var regex = new MongoRegex(new Regex("expression", options));
Assert.AreEqual("expression", regex.Expression);
Assert.AreEqual("img", regex.RawOptions);
}
[Test]
public void MongoRegexOptionFlagsAreIndependent()
{
var regex = new MongoRegex("expression", MongoRegexOption.IgnoreCase);
Assert.AreEqual("expression", regex.Expression);
Assert.AreEqual("i", regex.RawOptions);
}
[Test]
public void CanBeConstructedWithMongoRegexOption()
{
var regex = new MongoRegex("expression", MongoRegexOption.IgnoreCase | MongoRegexOption.IgnorePatternWhitespace | MongoRegexOption.Multiline);
Assert.AreEqual("expression", regex.Expression);
Assert.AreEqual("img", regex.RawOptions);
}
[Test]
public void CanBeConstructedWithRegexOptions()
{
var regex = new MongoRegex("expression", RegexOptions.IgnoreCase | RegexOptions.Multiline);
Assert.AreEqual("expression", regex.Expression);
Assert.AreEqual("im", regex.RawOptions);
}
[Test]
public void CanReadOptions()
{
var regex = new MongoRegex("expression", "img");
Assert.AreEqual(MongoRegexOption.IgnoreCase | MongoRegexOption.IgnorePatternWhitespace | MongoRegexOption.Multiline, regex.Options);
}
[Test]
public void CanSetOptions()
{
var regex = new MongoRegex("expression", null)
{
Options = MongoRegexOption.IgnoreCase | MongoRegexOption.IgnorePatternWhitespace
};
Assert.AreEqual("ig",regex.RawOptions);
}
[Test]
public void CanBeBinarySerialized()
{
var source = new MongoRegex("exp", "opt");
var formatter = new BinaryFormatter();
var mem = new MemoryStream();
formatter.Serialize(mem, source);
mem.Position = 0;
var dest = (MongoRegex)formatter.Deserialize(mem);
Assert.AreEqual(source, dest);
}
[Test]
public void CanBeXmlSerialized()
{
var source = new MongoRegex("exp", "opt");
var serializer = new XmlSerializer(typeof(MongoRegex));
var writer = new StringWriter();
serializer.Serialize(writer, source);
var dest = (MongoRegex)serializer.Deserialize(new StringReader(writer.ToString()));
Assert.AreEqual(source, dest);
}
[Test]
public void CanBeXmlSerializedWhenNullPropertys()
{
var source = new MongoRegex(null, null);
var serializer = new XmlSerializer(typeof(MongoRegex));
var writer = new StringWriter();
serializer.Serialize(writer, source);
var dest = (MongoRegex)serializer.Deserialize(new StringReader(writer.ToString()));
Assert.AreEqual(source, dest);
}
[Test]
public void CanBuildNetRegex()
{
var regex = new MongoRegex("expression", MongoRegexOption.IgnoreCase|MongoRegexOption.IgnorePatternWhitespace|MongoRegexOption.Multiline);
var netRegex = regex.BuildRegex();
Assert.IsNotNull(netRegex);
Assert.AreEqual("expression",netRegex.ToString());
Assert.AreEqual(RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline, netRegex.Options);
}
}
} | {
"pile_set_name": "Github"
} |
var spawn = require('child_process').spawn;
module.exports = function (file, opts, cb) {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
if (!opts) opts = {};
var ed = /^win/.test(process.platform) ? 'notepad' : 'vim';
var editor = opts.editor || process.env.VISUAL || process.env.EDITOR || ed;
var args = editor.split(/\s+/);
var bin = args.shift();
var ps = spawn(bin, args.concat([ file ]), { stdio: 'inherit' });
ps.on('exit', function (code, sig) {
if (typeof cb === 'function') cb(code, sig)
});
};
| {
"pile_set_name": "Github"
} |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ElectronNET.API
{
/// <summary>
/// Communicate asynchronously from the main process to renderer processes.
/// </summary>
public sealed class IpcMain
{
private static IpcMain _ipcMain;
private static object _syncRoot = new object();
internal IpcMain() { }
internal static IpcMain Instance
{
get
{
if(_ipcMain == null)
{
lock (_syncRoot)
{
if(_ipcMain == null)
{
_ipcMain = new IpcMain();
}
}
}
return _ipcMain;
}
}
/// <summary>
/// Listens to channel, when a new message arrives listener would be called with
/// listener(event, args...).
/// </summary>
/// <param name="channel">Channelname.</param>
/// <param name="listener">Callback Method.</param>
public void On(string channel, Action<object> listener)
{
BridgeConnector.Socket.Emit("registerIpcMainChannel", channel);
BridgeConnector.Socket.Off(channel);
BridgeConnector.Socket.On(channel, (args) =>
{
List<object> objectArray = FormatArguments(args);
if(objectArray.Count == 1)
{
listener(objectArray.First());
}
else
{
listener(objectArray);
}
});
}
private List<object> FormatArguments(object args)
{
List<object> objectArray = ((JArray)args).ToObject<object[]>().ToList();
for (int index = 0; index < objectArray.Count; index++)
{
var item = objectArray[index];
if (item == null)
{
objectArray.Remove(item);
}
}
return objectArray;
}
/// <summary>
/// Send a message to the renderer process synchronously via channel,
/// you can also send arbitrary arguments.
///
/// Note: Sending a synchronous message will block the whole renderer process,
/// unless you know what you are doing you should never use it.
/// </summary>
/// <param name="channel"></param>
/// <param name="listener"></param>
public void OnSync(string channel, Func<object, object> listener)
{
BridgeConnector.Socket.Emit("registerSyncIpcMainChannel", channel);
BridgeConnector.Socket.On(channel, (args) => {
List<object> objectArray = FormatArguments(args);
object parameter;
if (objectArray.Count == 1)
{
parameter = objectArray.First();
}
else
{
parameter = objectArray;
}
var result = listener(parameter);
BridgeConnector.Socket.Emit(channel + "Sync", result);
});
}
/// <summary>
/// Adds a one time listener method for the event. This listener is invoked only
/// the next time a message is sent to channel, after which it is removed.
/// </summary>
/// <param name="channel">Channelname.</param>
/// <param name="listener">Callback Method.</param>
public void Once(string channel, Action<object> listener)
{
BridgeConnector.Socket.Emit("registerOnceIpcMainChannel", channel);
BridgeConnector.Socket.On(channel, (args) =>
{
List<object> objectArray = FormatArguments(args);
if (objectArray.Count == 1)
{
listener(objectArray.First());
}
else
{
listener(objectArray);
}
});
}
/// <summary>
/// Removes listeners of the specified channel.
/// </summary>
/// <param name="channel">Channelname.</param>
public void RemoveAllListeners(string channel)
{
BridgeConnector.Socket.Emit("removeAllListenersIpcMainChannel", channel);
}
/// <summary>
/// Send a message to the renderer process asynchronously via channel, you can also send
/// arbitrary arguments. Arguments will be serialized in JSON internally and hence
/// no functions or prototype chain will be included. The renderer process handles it by
/// listening for channel with ipcRenderer module.
/// </summary>
/// <param name="browserWindow">BrowserWindow with channel.</param>
/// <param name="channel">Channelname.</param>
/// <param name="data">Arguments data.</param>
public void Send(BrowserWindow browserWindow, string channel, params object[] data)
{
List<JObject> jobjects = new List<JObject>();
List<JArray> jarrays = new List<JArray>();
List<object> objects = new List<object>();
foreach (var parameterObject in data)
{
if(parameterObject.GetType().IsArray || parameterObject.GetType().IsGenericType && parameterObject is IEnumerable)
{
jarrays.Add(JArray.FromObject(parameterObject, _jsonSerializer));
} else if(parameterObject.GetType().IsClass && !parameterObject.GetType().IsPrimitive && !(parameterObject is string))
{
jobjects.Add(JObject.FromObject(parameterObject, _jsonSerializer));
} else if(parameterObject.GetType().IsPrimitive || (parameterObject is string))
{
objects.Add(parameterObject);
}
}
if(jobjects.Count > 0 || jarrays.Count > 0)
{
BridgeConnector.Socket.Emit("sendToIpcRenderer", JObject.FromObject(browserWindow, _jsonSerializer), channel, jarrays.ToArray(), jobjects.ToArray(), objects.ToArray());
}
else
{
BridgeConnector.Socket.Emit("sendToIpcRenderer", JObject.FromObject(browserWindow, _jsonSerializer), channel, data);
}
}
private JsonSerializer _jsonSerializer = new JsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
}
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{4C491ADD-C086-4641-92E5-0EA368C939EF}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SmokeScenario</RootNamespace>
<AssemblyName>SmokeScenario</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Azure.Services.AppAuthentication, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Azure.Services.AppAuthentication.1.0.3\lib\net452\Microsoft.Azure.Services.AppAuthentication.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Clients.ActiveDirectory, Version=3.19.8.16603, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.IdentityModel.Clients.ActiveDirectory.3.19.8\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Clients.ActiveDirectory.Platform, Version=3.19.8.16603, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.IdentityModel.Clients.ActiveDirectory.3.19.8\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll</HintPath>
</Reference>
<Reference Include="Microsoft.ServiceBus, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\WindowsAzure.ServiceBus.5.2.0\lib\net45\Microsoft.ServiceBus.dll</HintPath>
</Reference>
<Reference Include="Microsoft.WindowsAzure.Configuration, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.WindowsAzure.ConfigurationManager.3.2.3\lib\net40\Microsoft.WindowsAzure.Configuration.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.IdentityModel" />
<Reference Include="System.IdentityModel.Tokens.Jwt, Version=4.0.40306.1554, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\System.IdentityModel.Tokens.Jwt.4.0.4.403061554\lib\net45\System.IdentityModel.Tokens.Jwt.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SenderClient.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.0">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.4.5">
<Visible>False</Visible>
<ProductName>Windows Installer 4.5</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="packages\Microsoft.Azure.Services.AppAuthentication.1.0.3\build\Microsoft.Azure.Services.AppAuthentication.targets" Condition="Exists('packages\Microsoft.Azure.Services.AppAuthentication.1.0.3\build\Microsoft.Azure.Services.AppAuthentication.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\Microsoft.Azure.Services.AppAuthentication.1.0.3\build\Microsoft.Azure.Services.AppAuthentication.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.Azure.Services.AppAuthentication.1.0.3\build\Microsoft.Azure.Services.AppAuthentication.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | {
"pile_set_name": "Github"
} |
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="?attr/colorControlNormal"
android:pathData="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z" />
</vector>
| {
"pile_set_name": "Github"
} |
/*
* This file is part of the phpv8/php-v8 PHP extension.
*
* Copyright (c) 2015-2018 Bogdan Padalko <[email protected]>
*
* Licensed under the MIT license: http://opensource.org/licenses/MIT
*
* For the full copyright and license information, please view the
* LICENSE file that was distributed with this source or visit
* http://opensource.org/licenses/MIT
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_v8_primitive.h"
#include "php_v8_value.h"
#include "php_v8.h"
zend_class_entry* php_v8_primitive_class_entry;
#define this_ce php_v8_primitive_class_entry
PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_VOID_INFO_EX(arginfo_value, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry php_v8_primitive_methods[] = {
PHP_V8_ABSTRACT_ME(PrimitiveValue, value)
PHP_FE_END
};
PHP_MINIT_FUNCTION(php_v8_primitive)
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, PHP_V8_NS, "PrimitiveValue", php_v8_primitive_methods);
this_ce = zend_register_internal_class_ex(&ce, php_v8_value_class_entry);
this_ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS;
return SUCCESS;
}
| {
"pile_set_name": "Github"
} |
package nisrulz.github.sample.usingandroidarchcomponents;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | {
"pile_set_name": "Github"
} |
concrete VerbPor of Verb = CatPor ** VerbRomance with
(ResRomance = ResPor) ;
| {
"pile_set_name": "Github"
} |
/* scheme.h for Chez Scheme Version 9.5.5 (ta6nt) */
/* Do not edit this file. It is automatically generated and */
/* specifically tailored to the version of Chez Scheme named */
/* above. Always be certain that you have the correct scheme.h */
/* for the version of Chez Scheme you are using. */
/* Warning: Some macros may evaluate arguments more than once. */
/* Enable function prototypes by default. */
#ifndef PROTO
#define PROTO(x) x
#endif
/* Specify declaration of exports. */
#ifdef _WIN32
# if __cplusplus
# ifdef SCHEME_IMPORT
# define EXPORT extern "C" __declspec (dllimport)
# elif SCHEME_STATIC
# define EXPORT extern "C"
# else
# define EXPORT extern "C" __declspec (dllexport)
# endif
# else
# ifdef SCHEME_IMPORT
# define EXPORT extern __declspec (dllimport)
# elif SCHEME_STATIC
# define EXPORT extern
# else
# define EXPORT extern __declspec (dllexport)
# endif
# endif
#else
# if __cplusplus
# define EXPORT extern "C"
# else
# define EXPORT extern
# endif
#endif
/* Chez Scheme Version and machine type */
#define VERSION "9.5.5"
#define MACHINE_TYPE "ta6nt"
/* All Scheme objects are of type ptr. Type iptr and */
/* uptr are signed and unsigned ints of the same size */
/* as a ptr */
typedef void * ptr;
typedef long long int iptr;
typedef unsigned long long int uptr;
/* String elements are 32-bit tagged char objects */
typedef unsigned int string_char;
/* Bytevector elements are 8-bit unsigned "octets" */
typedef unsigned char octet;
/* Type predicates */
#define Sfixnump(x) (((uptr)(x)&0x7)==0x0)
#define Scharp(x) (((uptr)(x)&0xFF)==0x16)
#define Snullp(x) ((uptr)(x)==0x26)
#define Seof_objectp(x) ((uptr)(x)==0x36)
#define Sbwp_objectp(x) ((uptr)(x)==0x4E)
#define Sbooleanp(x) (((uptr)(x)&0xF7)==0x6)
#define Spairp(x) (((uptr)(x)&0x7)==0x1)
#define Ssymbolp(x) (((uptr)(x)&0x7)==0x3)
#define Sprocedurep(x) (((uptr)(x)&0x7)==0x5)
#define Sflonump(x) (((uptr)(x)&0x7)==0x2)
#define Svectorp(x) ((((uptr)(x)&0x7)==0x7) &&\
(((uptr)((*((ptr *)((uptr)(x)+1))))&0x7)==0x0))
#define Sfxvectorp(x) ((((uptr)(x)&0x7)==0x7) &&\
(((uptr)((*((ptr *)((uptr)(x)+1))))&0x7)==0x3))
#define Sbytevectorp(x) ((((uptr)(x)&0x7)==0x7) &&\
(((uptr)((*((ptr *)((uptr)(x)+1))))&0x3)==0x1))
#define Sstringp(x) ((((uptr)(x)&0x7)==0x7) &&\
(((uptr)((*((ptr *)((uptr)(x)+1))))&0x7)==0x2))
#define Sbignump(x) ((((uptr)(x)&0x7)==0x7) &&\
(((uptr)((*((ptr *)((uptr)(x)+1))))&0x1F)==0x6))
#define Sboxp(x) ((((uptr)(x)&0x7)==0x7) &&\
(((uptr)((*((ptr *)((uptr)(x)+1))))&0x7F)==0xE))
#define Sinexactnump(x) ((((uptr)(x)&0x7)==0x7) &&\
((uptr)((*((ptr *)((uptr)(x)+1))))==0x36))
#define Sexactnump(x) ((((uptr)(x)&0x7)==0x7) &&\
((uptr)((*((ptr *)((uptr)(x)+1))))==0x56))
#define Sratnump(x) ((((uptr)(x)&0x7)==0x7) &&\
((uptr)((*((ptr *)((uptr)(x)+1))))==0x16))
#define Sinputportp(x) ((((uptr)(x)&0x7)==0x7) &&\
(((uptr)((*((ptr *)((uptr)(x)+1))))&0x1FF)==0x11E))
#define Soutputportp(x) ((((uptr)(x)&0x7)==0x7) &&\
(((uptr)((*((ptr *)((uptr)(x)+1))))&0x2FF)==0x21E))
#define Srecordp(x) ((((uptr)(x)&0x7)==0x7) &&\
(((uptr)((*((ptr *)((uptr)(x)+1))))&0x7)==0x7))
/* Accessors */
#define Sfixnum_value(x) ((iptr)(x)/8)
#define Schar_value(x) ((string_char)((uptr)(x)>>8))
#define Sboolean_value(x) ((x) != Sfalse)
#define Scar(x) (*((ptr *)((uptr)(x)+7)))
#define Scdr(x) (*((ptr *)((uptr)(x)+15)))
#define Sflonum_value(x) (*((double *)((uptr)(x)+6)))
#define Svector_length(x) ((iptr)((uptr)(*((iptr *)((uptr)(x)+1)))>>4))
#define Svector_ref(x,i) (((ptr *)((uptr)(x)+9))[i])
#define Sfxvector_length(x) ((iptr)((uptr)(*((iptr *)((uptr)(x)+1)))>>4))
#define Sfxvector_ref(x,i) (((ptr *)((uptr)(x)+9))[i])
#define Sbytevector_length(x) ((iptr)((uptr)(*((iptr *)((uptr)(x)+1)))>>3))
#define Sbytevector_u8_ref(x,i) (((octet *)((uptr)(x)+9))[i])
/* Warning: Sbytevector_data(x) returns a pointer into x. */
#define Sbytevector_data(x) &Sbytevector_u8_ref(x,0)
#define Sstring_length(x) ((iptr)((uptr)(*((iptr *)((uptr)(x)+1)))>>4))
#define Sstring_ref(x,i) Schar_value(((string_char *)((uptr)(x)+9))[i])
#define Sunbox(x) (*((ptr *)((uptr)(x)+9)))
EXPORT iptr Sinteger_value PROTO((ptr));
#define Sunsigned_value(x) (uptr)Sinteger_value(x)
EXPORT int Sinteger32_value PROTO((ptr));
#define Sunsigned32_value(x) (unsigned int)Sinteger32_value(x)
EXPORT long long Sinteger64_value PROTO((ptr));
#define Sunsigned64_value(x) (unsigned long long)Sinteger64_value(x)
/* Mutators */
EXPORT void Sset_box PROTO((ptr, ptr));
EXPORT void Sset_car PROTO((ptr, ptr));
EXPORT void Sset_cdr PROTO((ptr, ptr));
#define Sstring_set(x,i,c) ((void)((((string_char *)((uptr)(x)+9))[i]) = (string_char)(uptr)Schar(c)))
#define Sfxvector_set(x,i,n) ((void)(Sfxvector_ref(x,i) = (n)))
#define Sbytevector_u8_set(x,i,n) ((void)(Sbytevector_u8_ref(x,i) = (n)))
EXPORT void Svector_set PROTO((ptr, iptr, ptr));
/* Constructors */
#define Sfixnum(x) ((ptr)(uptr)((x)*8))
#define Schar(x) ((ptr)(uptr)((x)<<8|0x16))
#define Snil ((ptr)0x26)
#define Strue ((ptr)0xE)
#define Sfalse ((ptr)0x6)
#define Sboolean(x) ((x)?Strue:Sfalse)
#define Sbwp_object ((ptr)0x4E)
#define Seof_object ((ptr)0x36)
#define Svoid ((ptr)0x3E)
EXPORT ptr Scons PROTO((ptr, ptr));
EXPORT ptr Sstring_to_symbol PROTO((const char *));
EXPORT ptr Ssymbol_to_string PROTO((ptr));
EXPORT ptr Sflonum PROTO((double));
EXPORT ptr Smake_vector PROTO((iptr, ptr));
EXPORT ptr Smake_fxvector PROTO((iptr, ptr));
EXPORT ptr Smake_bytevector PROTO((iptr, int));
EXPORT ptr Smake_string PROTO((iptr, int));
EXPORT ptr Smake_uninitialized_string PROTO((iptr));
EXPORT ptr Sstring PROTO((const char *));
EXPORT ptr Sstring_of_length PROTO((const char *, iptr));
EXPORT ptr Sstring_utf8 PROTO((const char*, iptr));
EXPORT ptr Sbox PROTO((ptr));
EXPORT ptr Sinteger PROTO((iptr));
EXPORT ptr Sunsigned PROTO((uptr));
EXPORT ptr Sinteger32 PROTO((int));
EXPORT ptr Sunsigned32 PROTO((unsigned int));
EXPORT ptr Sinteger64 PROTO((long long));
EXPORT ptr Sunsigned64 PROTO((unsigned long long));
/* Miscellaneous */
EXPORT ptr Stop_level_value PROTO((ptr));
EXPORT void Sset_top_level_value PROTO((ptr, ptr));
EXPORT void Slock_object PROTO((ptr));
EXPORT void Sunlock_object PROTO((ptr));
EXPORT int Slocked_objectp PROTO((ptr));
EXPORT void Sforeign_symbol PROTO((const char *, void *));
EXPORT void Sregister_symbol PROTO((const char *, void *));
/* Support for calls into Scheme */
EXPORT ptr Scall0 PROTO((ptr));
EXPORT ptr Scall1 PROTO((ptr, ptr));
EXPORT ptr Scall2 PROTO((ptr, ptr, ptr));
EXPORT ptr Scall3 PROTO((ptr, ptr, ptr, ptr));
EXPORT void Sinitframe PROTO((iptr));
EXPORT void Sput_arg PROTO((iptr, ptr));
EXPORT ptr Scall PROTO((ptr, iptr));
/* Warning: Sforeign_callable_entry_point(x) returns a pointer into x. */
#define Sforeign_callable_entry_point(x) ((void (*) PROTO((void)))((uptr)(x)+65))
#define Sforeign_callable_code_object(x) ((ptr)((uptr)(x)-65))
/* Customization support. */
EXPORT const char * Skernel_version PROTO((void));
EXPORT void Sretain_static_relocation PROTO((void));
EXPORT void Sset_verbose PROTO((int));
EXPORT void Sscheme_init PROTO((void (*)(void)));
EXPORT void Sregister_boot_file PROTO((const char *));
EXPORT void Sregister_boot_file_fd PROTO((const char *, int fd));
EXPORT void Sregister_heap_file PROTO((const char *));
EXPORT void Scompact_heap PROTO((void));
EXPORT void Ssave_heap PROTO((const char *, int));
EXPORT void Sbuild_heap PROTO((const char *, void (*)(void)));
EXPORT void Senable_expeditor PROTO((const char *));
EXPORT int Sscheme_start PROTO((int, const char *[]));
EXPORT int Sscheme_script PROTO((const char *, int, const char *[]));
EXPORT int Sscheme_program PROTO((const char *, int, const char *[]));
EXPORT void Sscheme_deinit PROTO((void));
/* Thread support. */
EXPORT int Sactivate_thread PROTO((void));
EXPORT void Sdeactivate_thread PROTO((void));
EXPORT int Sdestroy_thread PROTO((void));
/* Windows support. */
#include <wchar.h>
EXPORT char * Sgetenv PROTO((const char *));
EXPORT wchar_t * Sutf8_to_wide PROTO((const char *));
EXPORT char * Swide_to_utf8 PROTO((const wchar_t *));
/* Features. */
#define FEATURE_ICONV
#define FEATURE_EXPEDITOR
#define FEATURE_PTHREADS
#define FEATURE_WINDOWS
/* Locking macros. */
#define INITLOCK(addr) (*((long long *) addr) = 0)
#define SPINLOCK(addr) \
{ \
while (_InterlockedExchange64(addr, 1) != 0) { \
while(*((long long *) addr) != 0); \
} \
} while(0)
#define UNLOCK(addr) (*((long long *) addr) = 0)
#define LOCKED_INCR(addr, res) (res = (-1 == _InterlockedExchangeAdd64(addr, 1)))
#define LOCKED_DECR(addr, res) (res = (1 == _InterlockedExchangeAdd64(addr, -1)))
| {
"pile_set_name": "Github"
} |
[
// *********************************************************************************
{ "name" : "OMA",
"type" : "Service" },
// *********************************************************************************
{ "name" : "QMI Client OMA",
"type" : "Client" },
// *********************************************************************************
{ "name" : "QMI Message OMA",
"type" : "Message-ID-Enum" },
// *********************************************************************************
{ "name" : "QMI Indication OMA",
"type" : "Indication-ID-Enum" },
// *********************************************************************************
{ "name" : "Reset",
"type" : "Message",
"service" : "OMA",
"id" : "0x0000",
"version" : "1.0",
"output" : [ { "common-ref" : "Operation Result" } ] },
// *********************************************************************************
{ "name" : "Set Event Report",
"type" : "Message",
"service" : "OMA",
"id" : "0x0001",
"version" : "1.0",
"input" : [ { "name" : "Network Initiated Alert Reporting",
"id" : "0x10",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "gboolean" },
{ "name" : "Session State Reporting",
"id" : "0x11",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "gboolean" } ],
"output" : [ { "common-ref" : "Operation Result" } ] },
{ "name" : "Event Report",
"type" : "Indication",
"service" : "OMA",
"id" : "0x0001",
"output" : [ { "name" : "Network Initiated Alert",
"id" : "0x10",
"mandatory" : "no",
"type" : "TLV",
"format" : "sequence",
"contents" : [ { "name" : "Session Type",
"format" : "guint8",
"public-format" : "QmiOmaSessionType" },
{ "name" : "Session ID",
"format" : "guint16" } ] },
{ "name" : "Session State",
"id" : "0x11",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "QmiOmaSessionState" },
{ "name" : "Session Fail Reason",
"id" : "0x12",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "QmiOmaSessionFailedReason" } ] },
// *********************************************************************************
{ "name" : "Start Session",
"type" : "Message",
"service" : "OMA",
"id" : "0x0020",
"version" : "1.0",
"input" : [ { "name" : "Session Type",
"id" : "0x10",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "QmiOmaSessionType" } ],
"output" : [ { "common-ref" : "Operation Result" } ] },
// *********************************************************************************
{ "name" : "Cancel Session",
"type" : "Message",
"service" : "OMA",
"id" : "0x0021",
"version" : "1.0",
"output" : [ { "common-ref" : "Operation Result" } ] },
// *********************************************************************************
{ "name" : "Get Session Info",
"type" : "Message",
"service" : "OMA",
"id" : "0x0022",
"output" : [ { "name" : "Session Info",
"id" : "0x10",
"mandatory" : "no",
"type" : "TLV",
"format" : "sequence",
"contents" : [ { "name" : "Session State",
"format" : "guint8",
"public-format" : "QmiOmaSessionState" },
{ "name" : "Session Type",
"format" : "guint8",
"public-format" : "QmiOmaSessionType" } ],
"prerequisites": [ { "common-ref" : "Success" } ] },
{ "name" : "Session Failed Reason",
"id" : "0x11",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "QmiOmaSessionFailedReason",
"prerequisites" : [ { "field" : "Session Info Session State",
"operation" : "==",
"value" : "QMI_OMA_SESSION_STATE_FAILED" } ] },
{ "name" : "Retry Info",
"id" : "0x12",
"mandatory" : "no",
"type" : "TLV",
"format" : "sequence",
"contents" : [ { "name" : "Retry Count",
"format" : "guint8" },
{ "name" : "Retry Pause Timer",
"format" : "guint16" },
{ "name" : "Retry Pause Timer Remaining",
"format" : "guint16" } ],
"prerequisites": [ { "common-ref" : "Success" } ] },
{ "name" : "Network Initiated Alert",
"id" : "0x13",
"mandatory" : "no",
"type" : "TLV",
"format" : "sequence",
"contents" : [ { "name" : "Session Type",
"format" : "guint8",
"public-format" : "QmiOmaSessionType" },
{ "name" : "Session ID",
"format" : "guint16" } ],
"prerequisites": [ { "common-ref" : "Success" } ] },
{ "common-ref" : "Operation Result" } ] },
// *********************************************************************************
{ "name" : "Send Selection",
"type" : "Message",
"service" : "OMA",
"id" : "0x0023",
"input" : [ { "name" : "Network Initiated Alert Selection",
"id" : "0x10",
"mandatory" : "no",
"type" : "TLV",
"format" : "sequence",
"contents" : [ { "name" : "Control Point Selection Accept",
"format" : "guint8",
"public-format" : "gboolean" },
{ "name" : "Session ID",
"format" : "guint16" } ] } ],
"output" : [ { "common-ref" : "Operation Result" } ] },
// *********************************************************************************
{ "name" : "Get Feature Setting",
"type" : "Message",
"service" : "OMA",
"id" : "0x0024",
"output" : [ { "name" : "Device Provisioning Service Update Config",
"id" : "0x10",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "gboolean",
"prerequisites" : [ { "common-ref" : "Success" } ] },
{ "name" : "PRL Update Service Config",
"id" : "0x11",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "gboolean",
"prerequisites" : [ { "common-ref" : "Success" } ] },
{ "name" : "HFA Feature Config",
"id" : "0x12",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "gboolean",
"prerequisites" : [ { "common-ref" : "Success" } ] },
{ "name" : "HFA Feature Done State",
"id" : "0x13",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "QmiOmaHfaFeatureDoneState",
"prerequisites" : [ { "common-ref" : "Success" } ] },
{ "common-ref" : "Operation Result" } ] },
// *********************************************************************************
{ "name" : "Set Feature Setting",
"type" : "Message",
"service" : "OMA",
"id" : "0x0025",
"input" : [ { "name" : "Device Provisioning Service Update Config",
"id" : "0x10",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "gboolean" },
{ "name" : "PRL Update Service Config",
"id" : "0x11",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "gboolean" },
{ "name" : "HFA Feature Config",
"id" : "0x12",
"mandatory" : "no",
"type" : "TLV",
"format" : "guint8",
"public-format" : "gboolean" } ],
"output" : [ { "common-ref" : "Operation Result" } ] }
]
| {
"pile_set_name": "Github"
} |
平川ありさ最新番号
【C-849】罪と罰 万引き女 #07 人妻編・2</a>2008-03-09ゴーゴーズ$$$GoGo’s Core120分钟 | {
"pile_set_name": "Github"
} |
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//
package IceDiscovery;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;
class LookupI extends _LookupDisp
{
abstract private class Request<T, AmdCB> implements Runnable
{
Request(T id, int retryCount)
{
_id = id;
_requestId = java.util.UUID.randomUUID().toString();
_retryCount = retryCount;
}
T
getId()
{
return _id;
}
boolean
addCallback(AmdCB cb)
{
_callbacks.add(cb);
return _callbacks.size() == 1;
}
boolean
retry()
{
return --_retryCount >= 0;
}
void
invoke(String domainId, Map<LookupPrx, LookupReplyPrx> lookups)
{
_lookupCount = lookups.size();
_failureCount = 0;
final Ice.Identity id = new Ice.Identity(_requestId, "");
for(Map.Entry<LookupPrx, LookupReplyPrx> entry : lookups.entrySet())
{
invokeWithLookup(domainId,
entry.getKey(),
LookupReplyPrxHelper.uncheckedCast(entry.getValue().ice_identity(id)));
}
}
boolean
exception()
{
if(++_failureCount == _lookupCount)
{
finished(null);
return true;
}
return false;
}
String
getRequestId()
{
return _requestId;
}
void
scheduleTimer(long timeout)
{
_future = _timer.schedule(this, timeout, java.util.concurrent.TimeUnit.MILLISECONDS);
}
void
cancelTimer()
{
assert _future != null;
_future.cancel(false);
_future = null;
}
abstract void finished(Ice.ObjectPrx proxy);
abstract protected void invokeWithLookup(String domainId, LookupPrx lookup, LookupReplyPrx lookupReply);
private final String _requestId;
protected int _retryCount;
protected int _lookupCount;
protected int _failureCount;
protected List<AmdCB> _callbacks = new ArrayList<AmdCB>();
protected T _id;
protected java.util.concurrent.Future<?> _future;
};
private class AdapterRequest extends Request<String, Ice.AMD_Locator_findAdapterById>
{
AdapterRequest(String id, int retryCount)
{
super(id, retryCount);
_start = System.nanoTime();
_latency = 0;
}
@Override
boolean
retry()
{
return _proxies.size() == 0 && --_retryCount >= 0;
}
boolean
response(Ice.ObjectPrx proxy, boolean isReplicaGroup)
{
if(isReplicaGroup)
{
_proxies.add(proxy);
if(_latency == 0)
{
_latency = (long)((System.nanoTime() - _start) * _latencyMultiplier / 100000.0);
if(_latency == 0)
{
_latency = 1; // 1ms
}
cancelTimer();
scheduleTimer(_latency);
}
return false;
}
finished(proxy);
return true;
}
@Override
void
finished(Ice.ObjectPrx proxy)
{
if(proxy != null || _proxies.isEmpty())
{
sendResponse(proxy);
}
else if(_proxies.size() == 1)
{
sendResponse(_proxies.toArray(new Ice.ObjectPrx[1])[0]);
}
else
{
List<Ice.Endpoint> endpoints = new ArrayList<Ice.Endpoint>();
Ice.ObjectPrx result = null;
for(Ice.ObjectPrx prx : _proxies)
{
if(result == null)
{
result = prx;
}
endpoints.addAll(java.util.Arrays.asList(prx.ice_getEndpoints()));
}
sendResponse(result.ice_endpoints(endpoints.toArray(new Ice.Endpoint[endpoints.size()])));
}
}
@Override
public void
run()
{
adapterRequestTimedOut(this);
}
@Override
protected void
invokeWithLookup(String domainId, LookupPrx lookup, LookupReplyPrx lookupReply)
{
lookup.begin_findAdapterById(domainId, _id, lookupReply, new Ice.Callback()
{
@Override
public void
completed(Ice.AsyncResult r)
{
try
{
r.throwLocalException();
}
catch(Ice.LocalException ex)
{
adapterRequestException(AdapterRequest.this, ex);
}
}
});
}
private void
sendResponse(Ice.ObjectPrx proxy)
{
for(Ice.AMD_Locator_findAdapterById cb : _callbacks)
{
cb.ice_response(proxy);
}
_callbacks.clear();
}
//
// We use a set because the same IceDiscovery plugin might return multiple times
// the same proxy if it's accessible through multiple network interfaces and if we
// also sent the request to multiple interfaces.
//
private Set<Ice.ObjectPrx> _proxies = new HashSet<Ice.ObjectPrx>();
private long _start;
private long _latency;
};
private class ObjectRequest extends Request<Ice.Identity, Ice.AMD_Locator_findObjectById>
{
ObjectRequest(Ice.Identity id, int retryCount)
{
super(id, retryCount);
}
void
response(Ice.ObjectPrx proxy)
{
finished(proxy);
}
@Override
void
finished(Ice.ObjectPrx proxy)
{
for(Ice.AMD_Locator_findObjectById cb : _callbacks)
{
cb.ice_response(proxy);
}
_callbacks.clear();
}
@Override
public void
run()
{
objectRequestTimedOut(this);
}
@Override
protected void
invokeWithLookup(String domainId, LookupPrx lookup, LookupReplyPrx lookupReply)
{
lookup.begin_findObjectById(domainId, _id, lookupReply, new Ice.Callback()
{
@Override
public void
completed(Ice.AsyncResult r)
{
try
{
r.throwLocalException();
}
catch(Ice.LocalException ex)
{
objectRequestException(ObjectRequest.this, ex);
}
}
});
}
};
public LookupI(LocatorRegistryI registry, LookupPrx lookup, Ice.Properties properties)
{
_registry = registry;
_lookup = lookup;
_timeout = properties.getPropertyAsIntWithDefault("IceDiscovery.Timeout", 300);
_retryCount = properties.getPropertyAsIntWithDefault("IceDiscovery.RetryCount", 3);
_latencyMultiplier = properties.getPropertyAsIntWithDefault("IceDiscovery.LatencyMultiplier", 1);
_domainId = properties.getProperty("IceDiscovery.DomainId");
_timer = IceInternal.Util.getInstance(lookup.ice_getCommunicator()).timer();
//
// Create one lookup proxy per endpoint from the given proxy. We want to send a multicast
// datagram on each endpoint.
//
Ice.Endpoint[] single = new Ice.Endpoint[1];
for(Ice.Endpoint endpt : lookup.ice_getEndpoints())
{
single[0] = endpt;
_lookups.put((LookupPrx)lookup.ice_endpoints(single), null);
}
assert(!_lookups.isEmpty());
}
void
setLookupReply(LookupReplyPrx lookupReply)
{
//
// Use a lookup reply proxy whose adress matches the interface used to send multicast datagrams.
//
Ice.Endpoint[] single = new Ice.Endpoint[1];
for(Map.Entry<LookupPrx, LookupReplyPrx> entry : _lookups.entrySet())
{
Ice.UDPEndpointInfo info = (Ice.UDPEndpointInfo)entry.getKey().ice_getEndpoints()[0].getInfo();
if(!info.mcastInterface.isEmpty())
{
for(Ice.Endpoint q : lookupReply.ice_getEndpoints())
{
Ice.EndpointInfo r = q.getInfo();
if(r instanceof Ice.IPEndpointInfo && ((Ice.IPEndpointInfo)r).host.equals(info.mcastInterface))
{
single[0] = q;
entry.setValue((LookupReplyPrx)lookupReply.ice_endpoints(single));
}
}
}
if(entry.getValue() == null)
{
// Fallback: just use the given lookup reply proxy if no matching endpoint found.
entry.setValue(lookupReply);
}
}
}
@Override
public void
findObjectById(String domainId, Ice.Identity id, IceDiscovery.LookupReplyPrx reply, Ice.Current c)
{
if(!domainId.equals(_domainId))
{
return; // Ignore.
}
Ice.ObjectPrx proxy = _registry.findObject(id);
if(proxy != null)
{
//
// Reply to the mulicast request using the given proxy.
//
try
{
reply.begin_foundObjectById(id, proxy);
}
catch(Ice.LocalException ex)
{
// Ignore
}
}
}
@Override
public void
findAdapterById(String domainId, String adapterId, IceDiscovery.LookupReplyPrx reply, Ice.Current c)
{
if(!domainId.equals(_domainId))
{
return; // Ignore.
}
Ice.Holder<Boolean> isReplicaGroup = new Ice.Holder<Boolean>();
Ice.ObjectPrx proxy = _registry.findAdapter(adapterId, isReplicaGroup);
if(proxy != null)
{
//
// Reply to the multicast request using the given proxy.
//
try
{
reply.begin_foundAdapterById(adapterId, proxy, isReplicaGroup.value);
}
catch(Ice.LocalException ex)
{
// Ignore
}
}
}
synchronized void
findObject(Ice.AMD_Locator_findObjectById cb, Ice.Identity id)
{
ObjectRequest request = _objectRequests.get(id);
if(request == null)
{
request = new ObjectRequest(id, _retryCount);
_objectRequests.put(id, request);
}
if(request.addCallback(cb))
{
try
{
request.invoke(_domainId, _lookups);
request.scheduleTimer(_timeout);
}
catch(Ice.LocalException ex)
{
request.finished(null);
_objectRequests.remove(id);
}
}
}
synchronized void
findAdapter(Ice.AMD_Locator_findAdapterById cb, String adapterId)
{
AdapterRequest request = _adapterRequests.get(adapterId);
if(request == null)
{
request = new AdapterRequest(adapterId, _retryCount);
_adapterRequests.put(adapterId, request);
}
if(request.addCallback(cb))
{
try
{
request.invoke(_domainId, _lookups);
request.scheduleTimer(_timeout);
}
catch(Ice.LocalException ex)
{
request.finished(null);
_adapterRequests.remove(adapterId);
}
}
}
synchronized void
foundObject(Ice.Identity id, String requestId, Ice.ObjectPrx proxy)
{
ObjectRequest request = _objectRequests.get(id);
if(request != null && request.getRequestId().equals(requestId)) // Ignore responses from old requests
{
request.response(proxy);
request.cancelTimer();
_objectRequests.remove(id);
}
}
synchronized void
foundAdapter(String adapterId, String requestId, Ice.ObjectPrx proxy, boolean isReplicaGroup)
{
AdapterRequest request = _adapterRequests.get(adapterId);
if(request != null && request.getRequestId().equals(requestId)) // Ignore responses from old requests
{
if(request.response(proxy, isReplicaGroup))
{
request.cancelTimer();
_adapterRequests.remove(adapterId);
}
}
}
synchronized void
objectRequestTimedOut(ObjectRequest request)
{
ObjectRequest r = _objectRequests.get(request.getId());
if(r == null || request != r)
{
return;
}
if(request.retry())
{
try
{
request.invoke(_domainId, _lookups);
request.scheduleTimer(_timeout);
return;
}
catch(Ice.LocalException ex)
{
}
}
request.finished(null);
_objectRequests.remove(request.getId());
}
synchronized void
objectRequestException(ObjectRequest request, Ice.LocalException ex)
{
ObjectRequest r = _objectRequests.get(request.getId());
if(r == null || r != request)
{
return;
}
if(request.exception())
{
if(_warnOnce)
{
StringBuilder s = new StringBuilder();
s.append("failed to lookup object `");
s.append(_lookup.ice_getCommunicator().identityToString(request.getId()));
s.append("' with lookup proxy `");
s.append(_lookup);
s.append("':\n");
s.append(ex.toString());
_lookup.ice_getCommunicator().getLogger().warning(s.toString());
_warnOnce = false;
}
request.cancelTimer();
_objectRequests.remove(request.getId());
}
}
synchronized void
adapterRequestTimedOut(AdapterRequest request)
{
AdapterRequest r = _adapterRequests.get(request.getId());
if(r == null || r != request)
{
return;
}
if(request.retry())
{
try
{
request.invoke(_domainId, _lookups);
request.scheduleTimer(_timeout);
return;
}
catch(Ice.LocalException ex)
{
}
}
request.finished(null);
_adapterRequests.remove(request.getId());
}
synchronized void
adapterRequestException(AdapterRequest request, Ice.LocalException ex)
{
AdapterRequest r = _adapterRequests.get(request.getId());
if(r == null || r != request)
{
return;
}
if(request.exception())
{
if(_warnOnce)
{
StringBuilder s = new StringBuilder();
s.append("failed to lookup adapter `");
s.append(request.getId());
s.append("' with lookup proxy `");
s.append(_lookup);
s.append("':\n");
s.append(ex.toString());
_lookup.ice_getCommunicator().getLogger().warning(s.toString());
_warnOnce = false;
}
request.cancelTimer();
_adapterRequests.remove(request.getId());
}
}
private LocatorRegistryI _registry;
private LookupPrx _lookup;
private java.util.Map<LookupPrx, LookupReplyPrx> _lookups = new java.util.HashMap<>();
private final int _timeout;
private final int _retryCount;
private final int _latencyMultiplier;
private final String _domainId;
private final java.util.concurrent.ScheduledExecutorService _timer;
private boolean _warnOnce = true;
private Map<Ice.Identity, ObjectRequest> _objectRequests = new HashMap<Ice.Identity, ObjectRequest>();
private Map<String, AdapterRequest> _adapterRequests = new HashMap<String, AdapterRequest>();
}
| {
"pile_set_name": "Github"
} |
#pragma once
#include "../Object.h"
namespace kv
{
class UnsyncGenerator : public Object
{
public:
DECLARE_SAVEABLE(UnsyncGenerator, Object);
REGISTER_CLASS_AS(UnsyncGenerator);
UnsyncGenerator();
void PerformUnsync();
private:
QString KV_SAVEABLE(unsync_string_);
};
END_DECLARE(UnsyncGenerator);
}
| {
"pile_set_name": "Github"
} |
/*
This file is part of Ext JS 3.4
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-04-03 15:07:25
*/
/**
* @class Ext.MessageBox
* <p>Utility class for generating different styles of message boxes. The alias Ext.Msg can also be used.<p/>
* <p>Note that the MessageBox is asynchronous. Unlike a regular JavaScript <code>alert</code> (which will halt
* browser execution), showing a MessageBox will not cause the code to stop. For this reason, if you have code
* that should only run <em>after</em> some user feedback from the MessageBox, you must use a callback function
* (see the <code>function</code> parameter for {@link #show} for more details).</p>
* <p>Example usage:</p>
*<pre><code>
// Basic alert:
Ext.Msg.alert('Status', 'Changes saved successfully.');
// Prompt for user data and process the result using a callback:
Ext.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
if (btn == 'ok'){
// process text value and close...
}
});
// Show a dialog using config options:
Ext.Msg.show({
title:'Save Changes?',
msg: 'You are closing a tab that has unsaved changes. Would you like to save your changes?',
buttons: Ext.Msg.YESNOCANCEL,
fn: processResult,
animEl: 'elId',
icon: Ext.MessageBox.QUESTION
});
</code></pre>
* @singleton
*/
Ext.MessageBox = function(){
var dlg, opt, mask, waitTimer,
bodyEl, msgEl, textboxEl, textareaEl, progressBar, pp, iconEl, spacerEl,
buttons, activeTextEl, bwidth, bufferIcon = '', iconCls = '',
buttonNames = ['ok', 'yes', 'no', 'cancel'];
// private
var handleButton = function(button){
buttons[button].blur();
if(dlg.isVisible()){
dlg.hide();
handleHide();
Ext.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value, opt], 1);
}
};
// private
var handleHide = function(){
if(opt && opt.cls){
dlg.el.removeClass(opt.cls);
}
progressBar.reset();
};
// private
var handleEsc = function(d, k, e){
if(opt && opt.closable !== false){
dlg.hide();
handleHide();
}
if(e){
e.stopEvent();
}
};
// private
var updateButtons = function(b){
var width = 0,
cfg;
if(!b){
Ext.each(buttonNames, function(name){
buttons[name].hide();
});
return width;
}
dlg.footer.dom.style.display = '';
Ext.iterate(buttons, function(name, btn){
cfg = b[name];
if(cfg){
btn.show();
btn.setText(Ext.isString(cfg) ? cfg : Ext.MessageBox.buttonText[name]);
width += btn.getEl().getWidth() + 15;
}else{
btn.hide();
}
});
return width;
};
return {
/**
* Returns a reference to the underlying {@link Ext.Window} element
* @return {Ext.Window} The window
*/
getDialog : function(titleText){
if(!dlg){
var btns = [];
buttons = {};
Ext.each(buttonNames, function(name){
btns.push(buttons[name] = new Ext.Button({
text: this.buttonText[name],
handler: handleButton.createCallback(name),
hideMode: 'offsets'
}));
}, this);
dlg = new Ext.Window({
autoCreate : true,
title:titleText,
resizable:false,
constrain:true,
constrainHeader:true,
minimizable : false,
maximizable : false,
stateful: false,
modal: true,
shim:true,
buttonAlign:"center",
width:400,
height:100,
minHeight: 80,
plain:true,
footer:true,
closable:true,
close : function(){
if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
handleButton("no");
}else{
handleButton("cancel");
}
},
fbar: new Ext.Toolbar({
items: btns,
enableOverflow: false
})
});
dlg.render(document.body);
dlg.getEl().addClass('x-window-dlg');
mask = dlg.mask;
bodyEl = dlg.body.createChild({
html:'<div class="ext-mb-icon"></div><div class="ext-mb-content"><span class="ext-mb-text"></span><br /><div class="ext-mb-fix-cursor"><input type="text" class="ext-mb-input" /><textarea class="ext-mb-textarea"></textarea></div></div>'
});
iconEl = Ext.get(bodyEl.dom.firstChild);
var contentEl = bodyEl.dom.childNodes[1];
msgEl = Ext.get(contentEl.firstChild);
textboxEl = Ext.get(contentEl.childNodes[2].firstChild);
textboxEl.enableDisplayMode();
textboxEl.addKeyListener([10,13], function(){
if(dlg.isVisible() && opt && opt.buttons){
if(opt.buttons.ok){
handleButton("ok");
}else if(opt.buttons.yes){
handleButton("yes");
}
}
});
textareaEl = Ext.get(contentEl.childNodes[2].childNodes[1]);
textareaEl.enableDisplayMode();
progressBar = new Ext.ProgressBar({
renderTo:bodyEl
});
bodyEl.createChild({cls:'x-clear'});
}
return dlg;
},
/**
* Updates the message box body text
* @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
* the XHTML-compliant non-breaking space character '&#160;')
* @return {Ext.MessageBox} this
*/
updateText : function(text){
if(!dlg.isVisible() && !opt.width){
dlg.setSize(this.maxWidth, 100); // resize first so content is never clipped from previous shows
}
// Append a space here for sizing. In IE, for some reason, it wraps text incorrectly without one in some cases
msgEl.update(text ? text + ' ' : ' ');
var iw = iconCls != '' ? (iconEl.getWidth() + iconEl.getMargins('lr')) : 0,
mw = msgEl.getWidth() + msgEl.getMargins('lr'),
fw = dlg.getFrameWidth('lr'),
bw = dlg.body.getFrameWidth('lr'),
w;
w = Math.max(Math.min(opt.width || iw+mw+fw+bw, opt.maxWidth || this.maxWidth),
Math.max(opt.minWidth || this.minWidth, bwidth || 0));
if(opt.prompt === true){
activeTextEl.setWidth(w-iw-fw-bw);
}
if(opt.progress === true || opt.wait === true){
progressBar.setSize(w-iw-fw-bw);
}
if(Ext.isIE9m && w == bwidth){
w += 4; //Add offset when the content width is smaller than the buttons.
}
msgEl.update(text || ' ');
dlg.setSize(w, 'auto').center();
return this;
},
/**
* Updates a progress-style message box's text and progress bar. Only relevant on message boxes
* initiated via {@link Ext.MessageBox#progress} or {@link Ext.MessageBox#wait},
* or by calling {@link Ext.MessageBox#show} with progress: true.
* @param {Number} value Any number between 0 and 1 (e.g., .5, defaults to 0)
* @param {String} progressText The progress text to display inside the progress bar (defaults to '')
* @param {String} msg The message box's body text is replaced with the specified string (defaults to undefined
* so that any existing body text will not get overwritten by default unless a new value is passed in)
* @return {Ext.MessageBox} this
*/
updateProgress : function(value, progressText, msg){
progressBar.updateProgress(value, progressText);
if(msg){
this.updateText(msg);
}
return this;
},
/**
* Returns true if the message box is currently displayed
* @return {Boolean} True if the message box is visible, else false
*/
isVisible : function(){
return dlg && dlg.isVisible();
},
/**
* Hides the message box if it is displayed
* @return {Ext.MessageBox} this
*/
hide : function(){
var proxy = dlg ? dlg.activeGhost : null;
if(this.isVisible() || proxy){
dlg.hide();
handleHide();
if (proxy){
// unghost is a private function, but i saw no better solution
// to fix the locking problem when dragging while it closes
dlg.unghost(false, false);
}
}
return this;
},
/**
* Displays a new message box, or reinitializes an existing message box, based on the config options
* passed in. All display functions (e.g. prompt, alert, etc.) on MessageBox call this function internally,
* although those calls are basic shortcuts and do not support all of the config options allowed here.
* @param {Object} config The following config options are supported: <ul>
* <li><b>animEl</b> : String/Element<div class="sub-desc">An id or Element from which the message box should animate as it
* opens and closes (defaults to undefined)</div></li>
* <li><b>buttons</b> : Object/Boolean<div class="sub-desc">A button config object (e.g., Ext.MessageBox.OKCANCEL or {ok:'Foo',
* cancel:'Bar'}), or false to not show any buttons (defaults to false)</div></li>
* <li><b>closable</b> : Boolean<div class="sub-desc">False to hide the top-right close button (defaults to true). Note that
* progress and wait dialogs will ignore this property and always hide the close button as they can only
* be closed programmatically.</div></li>
* <li><b>cls</b> : String<div class="sub-desc">A custom CSS class to apply to the message box's container element</div></li>
* <li><b>defaultTextHeight</b> : Number<div class="sub-desc">The default height in pixels of the message box's multiline textarea
* if displayed (defaults to 75)</div></li>
* <li><b>fn</b> : Function<div class="sub-desc">A callback function which is called when the dialog is dismissed either
* by clicking on the configured buttons, or on the dialog close button, or by pressing
* the return button to enter input.
* <p>Progress and wait dialogs will ignore this option since they do not respond to user
* actions and can only be closed programmatically, so any required function should be called
* by the same code after it closes the dialog. Parameters passed:<ul>
* <li><b>buttonId</b> : String<div class="sub-desc">The ID of the button pressed, one of:<div class="sub-desc"><ul>
* <li><tt>ok</tt></li>
* <li><tt>yes</tt></li>
* <li><tt>no</tt></li>
* <li><tt>cancel</tt></li>
* </ul></div></div></li>
* <li><b>text</b> : String<div class="sub-desc">Value of the input field if either <tt><a href="#show-option-prompt" ext:member="show-option-prompt" ext:cls="Ext.MessageBox">prompt</a></tt>
* or <tt><a href="#show-option-multiline" ext:member="show-option-multiline" ext:cls="Ext.MessageBox">multiline</a></tt> is true</div></li>
* <li><b>opt</b> : Object<div class="sub-desc">The config object passed to show.</div></li>
* </ul></p></div></li>
* <li><b>scope</b> : Object<div class="sub-desc">The scope of the callback function</div></li>
* <li><b>icon</b> : String<div class="sub-desc">A CSS class that provides a background image to be used as the body icon for the
* dialog (e.g. Ext.MessageBox.WARNING or 'custom-class') (defaults to '')</div></li>
* <li><b>iconCls</b> : String<div class="sub-desc">The standard {@link Ext.Window#iconCls} to
* add an optional header icon (defaults to '')</div></li>
* <li><b>maxWidth</b> : Number<div class="sub-desc">The maximum width in pixels of the message box (defaults to 600)</div></li>
* <li><b>minWidth</b> : Number<div class="sub-desc">The minimum width in pixels of the message box (defaults to 100)</div></li>
* <li><b>modal</b> : Boolean<div class="sub-desc">False to allow user interaction with the page while the message box is
* displayed (defaults to true)</div></li>
* <li><b>msg</b> : String<div class="sub-desc">A string that will replace the existing message box body text (defaults to the
* XHTML-compliant non-breaking space character '&#160;')</div></li>
* <li><a id="show-option-multiline"></a><b>multiline</b> : Boolean<div class="sub-desc">
* True to prompt the user to enter multi-line text (defaults to false)</div></li>
* <li><b>progress</b> : Boolean<div class="sub-desc">True to display a progress bar (defaults to false)</div></li>
* <li><b>progressText</b> : String<div class="sub-desc">The text to display inside the progress bar if progress = true (defaults to '')</div></li>
* <li><a id="show-option-prompt"></a><b>prompt</b> : Boolean<div class="sub-desc">True to prompt the user to enter single-line text (defaults to false)</div></li>
* <li><b>proxyDrag</b> : Boolean<div class="sub-desc">True to display a lightweight proxy while dragging (defaults to false)</div></li>
* <li><b>title</b> : String<div class="sub-desc">The title text</div></li>
* <li><b>value</b> : String<div class="sub-desc">The string value to set into the active textbox element if displayed</div></li>
* <li><b>wait</b> : Boolean<div class="sub-desc">True to display a progress bar (defaults to false)</div></li>
* <li><b>waitConfig</b> : Object<div class="sub-desc">A {@link Ext.ProgressBar#waitConfig} object (applies only if wait = true)</div></li>
* <li><b>width</b> : Number<div class="sub-desc">The width of the dialog in pixels</div></li>
* </ul>
* Example usage:
* <pre><code>
Ext.Msg.show({
title: 'Address',
msg: 'Please enter your address:',
width: 300,
buttons: Ext.MessageBox.OKCANCEL,
multiline: true,
fn: saveAddress,
animEl: 'addAddressBtn',
icon: Ext.MessageBox.INFO
});
</code></pre>
* @return {Ext.MessageBox} this
*/
show : function(options){
if(this.isVisible()){
this.hide();
}
opt = options;
var d = this.getDialog(opt.title || " ");
d.setTitle(opt.title || " ");
var allowClose = (opt.closable !== false && opt.progress !== true && opt.wait !== true);
d.tools.close.setDisplayed(allowClose);
activeTextEl = textboxEl;
opt.prompt = opt.prompt || (opt.multiline ? true : false);
if(opt.prompt){
if(opt.multiline){
textboxEl.hide();
textareaEl.show();
textareaEl.setHeight(Ext.isNumber(opt.multiline) ? opt.multiline : this.defaultTextHeight);
activeTextEl = textareaEl;
}else{
textboxEl.show();
textareaEl.hide();
}
}else{
textboxEl.hide();
textareaEl.hide();
}
activeTextEl.dom.value = opt.value || "";
if(opt.prompt){
d.focusEl = activeTextEl;
}else{
var bs = opt.buttons;
var db = null;
if(bs && bs.ok){
db = buttons["ok"];
}else if(bs && bs.yes){
db = buttons["yes"];
}
if (db){
d.focusEl = db;
}
}
if(Ext.isDefined(opt.iconCls)){
d.setIconClass(opt.iconCls);
}
this.setIcon(Ext.isDefined(opt.icon) ? opt.icon : bufferIcon);
bwidth = updateButtons(opt.buttons);
progressBar.setVisible(opt.progress === true || opt.wait === true);
this.updateProgress(0, opt.progressText);
this.updateText(opt.msg);
if(opt.cls){
d.el.addClass(opt.cls);
}
d.proxyDrag = opt.proxyDrag === true;
d.modal = opt.modal !== false;
d.mask = opt.modal !== false ? mask : false;
if(!d.isVisible()){
// force it to the end of the z-index stack so it gets a cursor in FF
document.body.appendChild(dlg.el.dom);
d.setAnimateTarget(opt.animEl);
//workaround for window internally enabling keymap in afterShow
d.on('show', function(){
if(allowClose === true){
d.keyMap.enable();
}else{
d.keyMap.disable();
}
}, this, {single:true});
d.show(opt.animEl);
}
if(opt.wait === true){
progressBar.wait(opt.waitConfig);
}
return this;
},
/**
* Adds the specified icon to the dialog. By default, the class 'ext-mb-icon' is applied for default
* styling, and the class passed in is expected to supply the background image url. Pass in empty string ('')
* to clear any existing icon. This method must be called before the MessageBox is shown.
* The following built-in icon classes are supported, but you can also pass in a custom class name:
* <pre>
Ext.MessageBox.INFO
Ext.MessageBox.WARNING
Ext.MessageBox.QUESTION
Ext.MessageBox.ERROR
*</pre>
* @param {String} icon A CSS classname specifying the icon's background image url, or empty string to clear the icon
* @return {Ext.MessageBox} this
*/
setIcon : function(icon){
if(!dlg){
bufferIcon = icon;
return;
}
bufferIcon = undefined;
if(icon && icon != ''){
iconEl.removeClass('x-hidden');
iconEl.replaceClass(iconCls, icon);
bodyEl.addClass('x-dlg-icon');
iconCls = icon;
}else{
iconEl.replaceClass(iconCls, 'x-hidden');
bodyEl.removeClass('x-dlg-icon');
iconCls = '';
}
return this;
},
/**
* Displays a message box with a progress bar. This message box has no buttons and is not closeable by
* the user. You are responsible for updating the progress bar as needed via {@link Ext.MessageBox#updateProgress}
* and closing the message box when the process is complete.
* @param {String} title The title bar text
* @param {String} msg The message box body text
* @param {String} progressText (optional) The text to display inside the progress bar (defaults to '')
* @return {Ext.MessageBox} this
*/
progress : function(title, msg, progressText){
this.show({
title : title,
msg : msg,
buttons: false,
progress:true,
closable:false,
minWidth: this.minProgressWidth,
progressText: progressText
});
return this;
},
/**
* Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
* interaction while waiting for a long-running process to complete that does not have defined intervals.
* You are responsible for closing the message box when the process is complete.
* @param {String} msg The message box body text
* @param {String} title (optional) The title bar text
* @param {Object} config (optional) A {@link Ext.ProgressBar#waitConfig} object
* @return {Ext.MessageBox} this
*/
wait : function(msg, title, config){
this.show({
title : title,
msg : msg,
buttons: false,
closable:false,
wait:true,
modal:true,
minWidth: this.minProgressWidth,
waitConfig: config
});
return this;
},
/**
* Displays a standard read-only message box with an OK button (comparable to the basic JavaScript alert prompt).
* If a callback function is passed it will be called after the user clicks the button, and the
* id of the button that was clicked will be passed as the only parameter to the callback
* (could also be the top-right close button).
* @param {String} title The title bar text
* @param {String} msg The message box body text
* @param {Function} fn (optional) The callback function invoked after the message box is closed
* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow.
* @return {Ext.MessageBox} this
*/
alert : function(title, msg, fn, scope){
this.show({
title : title,
msg : msg,
buttons: this.OK,
fn: fn,
scope : scope,
minWidth: this.minWidth
});
return this;
},
/**
* Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's confirm).
* If a callback function is passed it will be called after the user clicks either button,
* and the id of the button that was clicked will be passed as the only parameter to the callback
* (could also be the top-right close button).
* @param {String} title The title bar text
* @param {String} msg The message box body text
* @param {Function} fn (optional) The callback function invoked after the message box is closed
* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow.
* @return {Ext.MessageBox} this
*/
confirm : function(title, msg, fn, scope){
this.show({
title : title,
msg : msg,
buttons: this.YESNO,
fn: fn,
scope : scope,
icon: this.QUESTION,
minWidth: this.minWidth
});
return this;
},
/**
* Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to JavaScript's prompt).
* The prompt can be a single-line or multi-line textbox. If a callback function is passed it will be called after the user
* clicks either button, and the id of the button that was clicked (could also be the top-right
* close button) and the text that was entered will be passed as the two parameters to the callback.
* @param {String} title The title bar text
* @param {String} msg The message box body text
* @param {Function} fn (optional) The callback function invoked after the message box is closed
* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow.
* @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
* property, or the height in pixels to create the textbox (defaults to false / single-line)
* @param {String} value (optional) Default value of the text input element (defaults to '')
* @return {Ext.MessageBox} this
*/
prompt : function(title, msg, fn, scope, multiline, value){
this.show({
title : title,
msg : msg,
buttons: this.OKCANCEL,
fn: fn,
minWidth: this.minPromptWidth,
scope : scope,
prompt:true,
multiline: multiline,
value: value
});
return this;
},
/**
* Button config that displays a single OK button
* @type Object
*/
OK : {ok:true},
/**
* Button config that displays a single Cancel button
* @type Object
*/
CANCEL : {cancel:true},
/**
* Button config that displays OK and Cancel buttons
* @type Object
*/
OKCANCEL : {ok:true, cancel:true},
/**
* Button config that displays Yes and No buttons
* @type Object
*/
YESNO : {yes:true, no:true},
/**
* Button config that displays Yes, No and Cancel buttons
* @type Object
*/
YESNOCANCEL : {yes:true, no:true, cancel:true},
/**
* The CSS class that provides the INFO icon image
* @type String
*/
INFO : 'ext-mb-info',
/**
* The CSS class that provides the WARNING icon image
* @type String
*/
WARNING : 'ext-mb-warning',
/**
* The CSS class that provides the QUESTION icon image
* @type String
*/
QUESTION : 'ext-mb-question',
/**
* The CSS class that provides the ERROR icon image
* @type String
*/
ERROR : 'ext-mb-error',
/**
* The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
* @type Number
*/
defaultTextHeight : 75,
/**
* The maximum width in pixels of the message box (defaults to 600)
* @type Number
*/
maxWidth : 600,
/**
* The minimum width in pixels of the message box (defaults to 100)
* @type Number
*/
minWidth : 100,
/**
* The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
* for setting a different minimum width than text-only dialogs may need (defaults to 250).
* @type Number
*/
minProgressWidth : 250,
/**
* The minimum width in pixels of the message box if it is a prompt dialog. This is useful
* for setting a different minimum width than text-only dialogs may need (defaults to 250).
* @type Number
*/
minPromptWidth: 250,
/**
* An object containing the default button text strings that can be overriden for localized language support.
* Supported properties are: ok, cancel, yes and no. Generally you should include a locale-specific
* resource file for handling language support across the framework.
* Customize the default text like so: Ext.MessageBox.buttonText.yes = "oui"; //french
* @type Object
*/
buttonText : {
ok : "OK",
cancel : "Cancel",
yes : "Yes",
no : "No"
}
};
}();
/**
* Shorthand for {@link Ext.MessageBox}
*/
Ext.Msg = Ext.MessageBox; | {
"pile_set_name": "Github"
} |
--- a/script/lib/run-apm-install.js
+++ b/script/lib/run-apm-install.js
@@ -8,11 +8,8 @@
const installEnv = Object.assign({}, process.env)
// Set resource path so that apm can load metadata related to Atom.
installEnv.ATOM_RESOURCE_PATH = CONFIG.repositoryRootPath
- // Set our target (Electron) version so that node-pre-gyp can download the
- // proper binaries.
- installEnv.npm_config_target = CONFIG.appMetadata.electronVersion
childProcess.execFileSync(
- CONFIG.getApmBinPath(),
+ 'apm',
['--loglevel=error', ci ? 'ci' : 'install'],
{env: installEnv, cwd: packagePath, stdio: stdioOptions || 'inherit'}
)
--- a/src/package-manager.js
+++ b/src/package-manager.js
@@ -169,13 +169,7 @@
return configPath || this.apmPath
}
- const commandName = process.platform === 'win32' ? 'apm.cmd' : 'apm'
- const apmRoot = path.join(process.resourcesPath, 'app', 'apm')
- this.apmPath = path.join(apmRoot, 'bin', commandName)
- if (!fs.isFileSync(this.apmPath)) {
- this.apmPath = path.join(apmRoot, 'node_modules', 'atom-package-manager', 'bin', commandName)
- }
- return this.apmPath
+ return '/usr/lib/node_modules/atom-package-manager/bin/apm'
}
// Public: Get the paths being used to look for packages.
| {
"pile_set_name": "Github"
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.jstorm.yarn.model;
/**
* @author fengjian
* @since 17/2/13
*/
public enum DSEntity {
DS_APP_ATTEMPT, DS_CONTAINER
}
| {
"pile_set_name": "Github"
} |
{
"parameters": {
"id": {
"type": "integer",
"format": "int64",
"in": "path",
"required": true
},
"tag": {
"type": "string",
"in": "query",
"required": false
},
"query": {
"$ref": "#/parameters/tag"
}
},
"paths": {
"/cars/{id}": {
"parameters": [
{ "$ref": "#/parameters/id"}
]
}
}
} | {
"pile_set_name": "Github"
} |
# General informations
#**********************
rfmeth 1
asr 1
chneut 2
# Flags
#*******
elaflag 3
piezoflag 3
instrflag 1
| {
"pile_set_name": "Github"
} |
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This package is generated by client-gen with custom arguments.
// This package has the automatically generated typed clients.
package v1beta1
| {
"pile_set_name": "Github"
} |
unless defined?(RSpec)
describe "Chatty#spec" do
it "prints too much" do
STDOUT.puts "Hello\nIt's me!"
1.should == 1
end
end
end
| {
"pile_set_name": "Github"
} |
// Copyright 2015 The etcd 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.
package fileutil
import (
"io"
"os"
)
// Preallocate tries to allocate the space for given
// file. This operation is only supported on linux by a
// few filesystems (btrfs, ext4, etc.).
// If the operation is unsupported, no error will be returned.
// Otherwise, the error encountered will be returned.
func Preallocate(f *os.File, sizeInBytes int64, extendFile bool) error {
if sizeInBytes == 0 {
// fallocate will return EINVAL if length is 0; skip
return nil
}
if extendFile {
return preallocExtend(f, sizeInBytes)
}
return preallocFixed(f, sizeInBytes)
}
func preallocExtendTrunc(f *os.File, sizeInBytes int64) error {
curOff, err := f.Seek(0, io.SeekCurrent)
if err != nil {
return err
}
size, err := f.Seek(sizeInBytes, io.SeekEnd)
if err != nil {
return err
}
if _, err = f.Seek(curOff, io.SeekStart); err != nil {
return err
}
if sizeInBytes > size {
return nil
}
return f.Truncate(sizeInBytes)
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2015 committers of YAKINDU and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* Contributors:
* committers of YAKINDU - initial API and implementation
*
*/
package org.yakindu.sct.model.sexec;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Trace State Exited</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.yakindu.sct.model.sexec.TraceStateExited#getState <em>State</em>}</li>
* </ul>
*
* @see org.yakindu.sct.model.sexec.SexecPackage#getTraceStateExited()
* @model
* @generated
*/
public interface TraceStateExited extends Trace {
/**
* Returns the value of the '<em><b>State</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>State</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>State</em>' reference.
* @see #setState(ExecutionState)
* @see org.yakindu.sct.model.sexec.SexecPackage#getTraceStateExited_State()
* @model
* @generated
*/
ExecutionState getState();
/**
* Sets the value of the '{@link org.yakindu.sct.model.sexec.TraceStateExited#getState <em>State</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>State</em>' reference.
* @see #getState()
* @generated
*/
void setState(ExecutionState value);
} // TraceStateExited
| {
"pile_set_name": "Github"
} |
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.orchestrator.status;
import com.yahoo.vespa.applicationmodel.ApplicationInstanceReference;
import com.yahoo.vespa.applicationmodel.HostName;
/**
* The exclusive lock of an application in the status service, and methods to mutate host status
* and data structures guarded by such a lock.
*
* @author oyving
* @author Tony Vaagenes
* @author bakksjo
*/
public interface ApplicationLock extends AutoCloseable {
/** The reference of the locked application. */
ApplicationInstanceReference getApplicationInstanceReference();
/** Returns all host infos for this application. */
HostInfos getHostInfos();
/** Sets the state for the given host. */
void setHostState(HostName hostName, HostStatus status);
/** Returns the application status. */
ApplicationInstanceStatus getApplicationInstanceStatus();
/** Sets the orchestration status for the application instance. */
void setApplicationInstanceStatus(ApplicationInstanceStatus applicationInstanceStatus);
/** WARNING: Must not throw an exception. */
@Override
void close();
}
| {
"pile_set_name": "Github"
} |
$el.on('click', fn)
.appendTo('body');
| {
"pile_set_name": "Github"
} |
#!/bin/sh
# Copyright 2006 Rob Landley <[email protected]>
# Licensed under GPLv2 or later, see file LICENSE in this source tree.
# Dumb little utility function to print out the assembly dump of a single
# function, or list the functions so dumpable in an executable. You'd think
# there would be a way to get objdump to do this, but I can't find it.
[ $# -lt 1 ] || [ $# -gt 2 ] && { echo "usage: showasm file function"; exit 1; }
[ ! -f $1 ] && { echo "File $1 not found"; exit 1; }
if [ $# -eq 1 ]
then
objdump -d $1 | sed -n -e 's/^[0-9a-fA-F]* <\(.*\)>:$/\1/p'
exit 0
fi
objdump -d $1 | sed -n -e '/./{H;$!d}' -e "x;/^.[0-9a-fA-F]* <$2>:/p"
| {
"pile_set_name": "Github"
} |
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
> Any in
protocol c {
typealias B : B
var a: [c)
func c
| {
"pile_set_name": "Github"
} |
/* cx25840 VBI functions
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <linux/videodev2.h>
#include <linux/i2c.h>
#include <media/v4l2-common.h>
#include <media/cx25840.h>
#include "cx25840-core.h"
static int odd_parity(u8 c)
{
c ^= (c >> 4);
c ^= (c >> 2);
c ^= (c >> 1);
return c & 1;
}
static int decode_vps(u8 * dst, u8 * p)
{
static const u8 biphase_tbl[] = {
0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4,
0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0,
0xd2, 0x5a, 0x52, 0xd2, 0x96, 0x1e, 0x16, 0x96,
0x92, 0x1a, 0x12, 0x92, 0xd2, 0x5a, 0x52, 0xd2,
0xd0, 0x58, 0x50, 0xd0, 0x94, 0x1c, 0x14, 0x94,
0x90, 0x18, 0x10, 0x90, 0xd0, 0x58, 0x50, 0xd0,
0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4,
0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0,
0xe1, 0x69, 0x61, 0xe1, 0xa5, 0x2d, 0x25, 0xa5,
0xa1, 0x29, 0x21, 0xa1, 0xe1, 0x69, 0x61, 0xe1,
0xc3, 0x4b, 0x43, 0xc3, 0x87, 0x0f, 0x07, 0x87,
0x83, 0x0b, 0x03, 0x83, 0xc3, 0x4b, 0x43, 0xc3,
0xc1, 0x49, 0x41, 0xc1, 0x85, 0x0d, 0x05, 0x85,
0x81, 0x09, 0x01, 0x81, 0xc1, 0x49, 0x41, 0xc1,
0xe1, 0x69, 0x61, 0xe1, 0xa5, 0x2d, 0x25, 0xa5,
0xa1, 0x29, 0x21, 0xa1, 0xe1, 0x69, 0x61, 0xe1,
0xe0, 0x68, 0x60, 0xe0, 0xa4, 0x2c, 0x24, 0xa4,
0xa0, 0x28, 0x20, 0xa0, 0xe0, 0x68, 0x60, 0xe0,
0xc2, 0x4a, 0x42, 0xc2, 0x86, 0x0e, 0x06, 0x86,
0x82, 0x0a, 0x02, 0x82, 0xc2, 0x4a, 0x42, 0xc2,
0xc0, 0x48, 0x40, 0xc0, 0x84, 0x0c, 0x04, 0x84,
0x80, 0x08, 0x00, 0x80, 0xc0, 0x48, 0x40, 0xc0,
0xe0, 0x68, 0x60, 0xe0, 0xa4, 0x2c, 0x24, 0xa4,
0xa0, 0x28, 0x20, 0xa0, 0xe0, 0x68, 0x60, 0xe0,
0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4,
0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0,
0xd2, 0x5a, 0x52, 0xd2, 0x96, 0x1e, 0x16, 0x96,
0x92, 0x1a, 0x12, 0x92, 0xd2, 0x5a, 0x52, 0xd2,
0xd0, 0x58, 0x50, 0xd0, 0x94, 0x1c, 0x14, 0x94,
0x90, 0x18, 0x10, 0x90, 0xd0, 0x58, 0x50, 0xd0,
0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4,
0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0,
};
u8 c, err = 0;
int i;
for (i = 0; i < 2 * 13; i += 2) {
err |= biphase_tbl[p[i]] | biphase_tbl[p[i + 1]];
c = (biphase_tbl[p[i + 1]] & 0xf) |
((biphase_tbl[p[i]] & 0xf) << 4);
dst[i / 2] = c;
}
return err & 0xf0;
}
void cx25840_vbi_setup(struct i2c_client *client)
{
struct cx25840_state *state = i2c_get_clientdata(client);
v4l2_std_id std = cx25840_get_v4lstd(client);
int hblank,hactive,burst,vblank,vactive,sc,vblank656,src_decimation;
int luma_lpf,uv_lpf, comb;
u32 pll_int,pll_frac,pll_post;
/* datasheet startup, step 8d */
if (std & ~V4L2_STD_NTSC) {
cx25840_write(client, 0x49f, 0x11);
} else {
cx25840_write(client, 0x49f, 0x14);
}
if (std & V4L2_STD_625_50) {
hblank=0x084;
hactive=0x2d0;
burst=0x5d;
vblank=0x024;
vactive=0x244;
vblank656=0x28;
src_decimation=0x21f;
luma_lpf=2;
if (std & V4L2_STD_SECAM) {
uv_lpf=0;
comb=0;
sc=0x0a425f;
} else if (std == V4L2_STD_PAL_Nc) {
uv_lpf=1;
comb=0x20;
sc=556453;
} else {
uv_lpf=1;
comb=0x20;
sc=0x0a8263;
}
} else {
hactive=720;
hblank=122;
vactive=487;
luma_lpf=1;
uv_lpf=1;
src_decimation=0x21f;
if (std == V4L2_STD_PAL_60) {
vblank=26;
vblank656=26;
burst=0x5b;
luma_lpf=2;
comb=0x20;
sc=0x0a8263;
} else if (std == V4L2_STD_PAL_M) {
vblank=20;
vblank656=24;
burst=0x61;
comb=0x20;
sc=555452;
} else {
vblank=26;
vblank656=26;
burst=0x5b;
comb=0x66;
sc=556063;
}
}
/* DEBUG: Displays configured PLL frequency */
pll_int=cx25840_read(client, 0x108);
pll_frac=cx25840_read4(client, 0x10c)&0x1ffffff;
pll_post=cx25840_read(client, 0x109);
v4l_dbg(1, cx25840_debug, client,
"PLL regs = int: %u, frac: %u, post: %u\n",
pll_int,pll_frac,pll_post);
if (pll_post) {
int fin, fsc;
int pll= (28636363L*((((u64)pll_int)<<25L)+pll_frac)) >>25L;
pll/=pll_post;
v4l_dbg(1, cx25840_debug, client, "PLL = %d.%06d MHz\n",
pll/1000000, pll%1000000);
v4l_dbg(1, cx25840_debug, client, "PLL/8 = %d.%06d MHz\n",
pll/8000000, (pll/8)%1000000);
fin=((u64)src_decimation*pll)>>12;
v4l_dbg(1, cx25840_debug, client, "ADC Sampling freq = "
"%d.%06d MHz\n",
fin/1000000,fin%1000000);
fsc= (((u64)sc)*pll) >> 24L;
v4l_dbg(1, cx25840_debug, client, "Chroma sub-carrier freq = "
"%d.%06d MHz\n",
fsc/1000000,fsc%1000000);
v4l_dbg(1, cx25840_debug, client, "hblank %i, hactive %i, "
"vblank %i , vactive %i, vblank656 %i, src_dec %i,"
"burst 0x%02x, luma_lpf %i, uv_lpf %i, comb 0x%02x,"
" sc 0x%06x\n",
hblank, hactive, vblank, vactive, vblank656,
src_decimation, burst, luma_lpf, uv_lpf, comb, sc);
}
/* Sets horizontal blanking delay and active lines */
cx25840_write(client, 0x470, hblank);
cx25840_write(client, 0x471, 0xff&(((hblank>>8)&0x3)|(hactive <<4)));
cx25840_write(client, 0x472, hactive>>4);
/* Sets burst gate delay */
cx25840_write(client, 0x473, burst);
/* Sets vertical blanking delay and active duration */
cx25840_write(client, 0x474, vblank);
cx25840_write(client, 0x475, 0xff&(((vblank>>8)&0x3)|(vactive <<4)));
cx25840_write(client, 0x476, vactive>>4);
cx25840_write(client, 0x477, vblank656);
/* Sets src decimation rate */
cx25840_write(client, 0x478, 0xff&src_decimation);
cx25840_write(client, 0x479, 0xff&(src_decimation>>8));
/* Sets Luma and UV Low pass filters */
cx25840_write(client, 0x47a, luma_lpf<<6|((uv_lpf<<4)&0x30));
/* Enables comb filters */
cx25840_write(client, 0x47b, comb);
/* Sets SC Step*/
cx25840_write(client, 0x47c, sc);
cx25840_write(client, 0x47d, 0xff&sc>>8);
cx25840_write(client, 0x47e, 0xff&sc>>16);
/* Sets VBI parameters */
if (std & V4L2_STD_625_50) {
cx25840_write(client, 0x47f, 0x01);
state->vbi_line_offset = 5;
} else {
cx25840_write(client, 0x47f, 0x00);
state->vbi_line_offset = 8;
}
}
int cx25840_vbi(struct i2c_client *client, unsigned int cmd, void *arg)
{
struct cx25840_state *state = i2c_get_clientdata(client);
struct v4l2_format *fmt;
struct v4l2_sliced_vbi_format *svbi;
switch (cmd) {
case VIDIOC_G_FMT:
{
static u16 lcr2vbi[] = {
0, V4L2_SLICED_TELETEXT_B, 0, /* 1 */
0, V4L2_SLICED_WSS_625, 0, /* 4 */
V4L2_SLICED_CAPTION_525, /* 6 */
0, 0, V4L2_SLICED_VPS, 0, 0, /* 9 */
0, 0, 0, 0
};
int is_pal = !(cx25840_get_v4lstd(client) & V4L2_STD_525_60);
int i;
fmt = arg;
if (fmt->type != V4L2_BUF_TYPE_SLICED_VBI_CAPTURE)
return -EINVAL;
svbi = &fmt->fmt.sliced;
memset(svbi, 0, sizeof(*svbi));
/* we're done if raw VBI is active */
if ((cx25840_read(client, 0x404) & 0x10) == 0)
break;
if (is_pal) {
for (i = 7; i <= 23; i++) {
u8 v = cx25840_read(client, 0x424 + i - 7);
svbi->service_lines[0][i] = lcr2vbi[v >> 4];
svbi->service_lines[1][i] = lcr2vbi[v & 0xf];
svbi->service_set |=
svbi->service_lines[0][i] | svbi->service_lines[1][i];
}
}
else {
for (i = 10; i <= 21; i++) {
u8 v = cx25840_read(client, 0x424 + i - 10);
svbi->service_lines[0][i] = lcr2vbi[v >> 4];
svbi->service_lines[1][i] = lcr2vbi[v & 0xf];
svbi->service_set |=
svbi->service_lines[0][i] | svbi->service_lines[1][i];
}
}
break;
}
case VIDIOC_S_FMT:
{
int is_pal = !(cx25840_get_v4lstd(client) & V4L2_STD_525_60);
int vbi_offset = is_pal ? 1 : 0;
int i, x;
u8 lcr[24];
fmt = arg;
if (fmt->type != V4L2_BUF_TYPE_SLICED_VBI_CAPTURE)
return -EINVAL;
svbi = &fmt->fmt.sliced;
if (svbi->service_set == 0) {
/* raw VBI */
memset(svbi, 0, sizeof(*svbi));
/* Setup VBI */
cx25840_vbi_setup(client);
/* VBI Offset */
cx25840_write(client, 0x47f, vbi_offset);
cx25840_write(client, 0x404, 0x2e);
break;
}
for (x = 0; x <= 23; x++)
lcr[x] = 0x00;
/* Setup VBI */
cx25840_vbi_setup(client);
/* Sliced VBI */
cx25840_write(client, 0x404, 0x32); /* Ancillary data */
cx25840_write(client, 0x406, 0x13);
cx25840_write(client, 0x47f, vbi_offset);
if (is_pal) {
for (i = 0; i <= 6; i++)
svbi->service_lines[0][i] =
svbi->service_lines[1][i] = 0;
} else {
for (i = 0; i <= 9; i++)
svbi->service_lines[0][i] =
svbi->service_lines[1][i] = 0;
for (i = 22; i <= 23; i++)
svbi->service_lines[0][i] =
svbi->service_lines[1][i] = 0;
}
for (i = 7; i <= 23; i++) {
for (x = 0; x <= 1; x++) {
switch (svbi->service_lines[1-x][i]) {
case V4L2_SLICED_TELETEXT_B:
lcr[i] |= 1 << (4 * x);
break;
case V4L2_SLICED_WSS_625:
lcr[i] |= 4 << (4 * x);
break;
case V4L2_SLICED_CAPTION_525:
lcr[i] |= 6 << (4 * x);
break;
case V4L2_SLICED_VPS:
lcr[i] |= 9 << (4 * x);
break;
}
}
}
if (is_pal) {
for (x = 1, i = 0x424; i <= 0x434; i++, x++) {
cx25840_write(client, i, lcr[6 + x]);
}
}
else {
for (x = 1, i = 0x424; i <= 0x430; i++, x++) {
cx25840_write(client, i, lcr[9 + x]);
}
for (i = 0x431; i <= 0x434; i++) {
cx25840_write(client, i, 0);
}
}
cx25840_write(client, 0x43c, 0x16);
if (is_pal) {
cx25840_write(client, 0x474, 0x2a);
} else {
cx25840_write(client, 0x474, 0x22);
}
break;
}
case VIDIOC_INT_DECODE_VBI_LINE:
{
struct v4l2_decode_vbi_line *vbi = arg;
u8 *p = vbi->p;
int id1, id2, l, err = 0;
if (p[0] || p[1] != 0xff || p[2] != 0xff ||
(p[3] != 0x55 && p[3] != 0x91)) {
vbi->line = vbi->type = 0;
break;
}
p += 4;
id1 = p[-1];
id2 = p[0] & 0xf;
l = p[2] & 0x3f;
l += state->vbi_line_offset;
p += 4;
switch (id2) {
case 1:
id2 = V4L2_SLICED_TELETEXT_B;
break;
case 4:
id2 = V4L2_SLICED_WSS_625;
break;
case 6:
id2 = V4L2_SLICED_CAPTION_525;
err = !odd_parity(p[0]) || !odd_parity(p[1]);
break;
case 9:
id2 = V4L2_SLICED_VPS;
if (decode_vps(p, p) != 0) {
err = 1;
}
break;
default:
id2 = 0;
err = 1;
break;
}
vbi->type = err ? 0 : id2;
vbi->line = err ? 0 : l;
vbi->is_second_field = err ? 0 : (id1 == 0x55);
vbi->p = p;
break;
}
}
return 0;
}
| {
"pile_set_name": "Github"
} |
Gregorian - Monday-based week with week numbers
August 2006 September 2006 October 2006
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
31 1 2 3 4 5 6 35 1 2 3 39 1
32 7 8 9 10 11 12 13 36 4 5 6 7 8 9 10 40 2 3 4 5 6 7 8
33 14 15 16 17 18 19 20 37 11 12 13 14 15 16 17 41 9 10 11 12 13 14 15
34 21 22 23 24 25 26 27 38 18 19 20 21 22 23 24 42 16 17 18 19 20 21 22
35 28 29 30 31 39 25 26 27 28 29 30 43 23 24 25 26 27 28 29
44 30 31
| {
"pile_set_name": "Github"
} |
namespace ClassLib094
{
public class Class083
{
public static string Property => "ClassLib094";
}
}
| {
"pile_set_name": "Github"
} |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2020 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "tabulatedTransport.H"
#include "IOstreams.H"
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class Thermo>
Foam::tabulatedTransport<Thermo>::tabulatedTransport
(
const dictionary& dict
)
:
Thermo(dict),
mu_(dict.subDict("transport").subDict("mu")),
kappa_(dict.subDict("transport").subDict("kappa"))
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class Thermo>
void Foam::tabulatedTransport<Thermo>::write(Ostream& os) const
{
os << this->name() << endl;
os << token::BEGIN_BLOCK << incrIndent << nl;
Thermo::write(os);
dictionary dict("transport");
dictionary muDict("mu");
muDict.add("values", mu_.values());
dict.add("mu", muDict);
dictionary kappaDict("kappa");
kappaDict.add("values", kappa_.values());
dict.add("kappa", kappaDict);
os << indent << dict.dictName() << dict;
os << decrIndent << token::END_BLOCK << nl;
}
// * * * * * * * * * * * * * * * IOstream Operators * * * * * * * * * * * * //
template<class Thermo>
Foam::Ostream& Foam::operator<<
(
Ostream& os,
const tabulatedTransport<Thermo>& pt
)
{
pt.write(os);
return os;
}
// ************************************************************************* //
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>test_css</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<h1 class="toc">Module test_css</h1>
<hr />
<h2 class="toc">Classes</h2>
<a target="mainFrame" href="lxml.tests.test_css.CSSTestCase-class.html"
>CSSTestCase</a><br /> <h2 class="toc">Functions</h2>
<a target="mainFrame" href="lxml.tests.test_css-module.html#test_suite"
>test_suite</a><br /> <h2 class="toc">Variables</h2>
<a target="mainFrame" href="lxml.tests.test_css-module.html#HTML"
>HTML</a><br /> <a target="mainFrame" href="lxml.tests.test_css-module.html#__package__"
>__package__</a><br /><hr />
<span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
using MissionPlanner.Controls;
using System.Windows.Forms;
namespace MissionPlanner.GCSViews.ConfigurationView
{
public partial class ConfigMandatory : MyUserControl, IActivate
{
public ConfigMandatory()
{
InitializeComponent();
}
public void Activate()
{
}
}
} | {
"pile_set_name": "Github"
} |
# verify
常规验证码、滑动验证码、拼图验证码、选字验证码,纯前端验证码。
<a href="http://veui.net">官网</a>
| {
"pile_set_name": "Github"
} |
//
// Input groups
// --------------------------------------------------
// Base styles
// -------------------------
.input-group {
position: relative; // For dropdowns
display: table;
border-collapse: separate; // prevent input groups from inheriting border styles from table cells when placed within a table
// Undo padding and float of grid classes
&.col {
float: none;
padding-left: 0;
padding-right: 0;
}
.form-control {
width: 100%;
margin-bottom: 0;
}
}
// Sizing options
//
// Remix the default form control sizing classes into new ones for easier
// manipulation.
.input-group-lg > .form-control,
.input-group-lg > .input-group-addon,
.input-group-lg > .input-group-btn > .btn { .input-lg(); }
.input-group-sm > .form-control,
.input-group-sm > .input-group-addon,
.input-group-sm > .input-group-btn > .btn { .input-sm(); }
// Display as table-cell
// -------------------------
.input-group-addon,
.input-group-btn,
.input-group .form-control {
display: table-cell;
&:not(:first-child):not(:last-child) {
border-radius: 0;
}
}
// Addon and addon wrapper for buttons
.input-group-addon,
.input-group-btn {
width: 1%;
white-space: nowrap;
vertical-align: middle; // Match the inputs
}
// Text input groups
// -------------------------
.input-group-addon {
padding: @padding-base-vertical @padding-base-horizontal;
font-size: @font-size-base;
font-weight: normal;
line-height: 1;
text-align: center;
background-color: @input-group-addon-bg;
border: 1px solid @input-group-addon-border-color;
border-radius: @border-radius-base;
// Sizing
&.input-sm {
padding: @padding-small-vertical @padding-small-horizontal;
font-size: @font-size-small;
border-radius: @border-radius-small;
}
&.input-lg {
padding: @padding-large-vertical @padding-large-horizontal;
font-size: @font-size-large;
border-radius: @border-radius-large;
}
// Nuke default margins from checkboxes and radios to vertically center within.
input[type="radio"],
input[type="checkbox"] {
margin-top: 0;
}
}
// Reset rounded corners
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle) {
.border-right-radius(0);
}
.input-group-addon:first-child {
border-right: 0;
}
.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .dropdown-toggle,
.input-group-btn:first-child > .btn:not(:first-child) {
.border-left-radius(0);
}
.input-group-addon:last-child {
border-left: 0;
}
// Button input groups
// -------------------------
.input-group-btn {
position: relative;
white-space: nowrap;
}
.input-group-btn > .btn {
position: relative;
// Jankily prevent input button groups from wrapping
+ .btn {
margin-left: -4px;
}
// Bring the "active" button to the front
&:hover,
&:active {
z-index: 2;
}
}
| {
"pile_set_name": "Github"
} |
好奇心原文链接:[今日娱乐:韩寒公司拍新片,《伪装者》要去韩国了_娱乐_好奇心日报-王珊珊 ](https://www.qdaily.com/articles/21994.html)
WebArchive归档链接:[今日娱乐:韩寒公司拍新片,《伪装者》要去韩国了_娱乐_好奇心日报-王珊珊 ](http://web.archive.org/web/20160318183801/http://www.qdaily.com/articles/21994.html)
 | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="ssdk_oks_share">Share</string>
<string name="ssdk_oks_sharing">Sharing operation is working in the background…</string>
<string name="ssdk_oks_share_failed">Operation failed</string>
<string name="ssdk_oks_share_completed">Operation succeeded</string>
<string name="ssdk_oks_share_canceled">Operation canceled</string>
<string name="ssdk_oks_cancel">Cancel</string>
<string name="ssdk_oks_multi_share">Photo Sharing</string>
<string name="ssdk_oks_confirm">Confirm</string>
<string name="ssdk_oks_contacts">Contacts</string>
<string name="ssdk_oks_pull_to_refresh">Pull down to refresh</string>
<string name="ssdk_oks_release_to_refresh">Release to refresh</string>
<string name="ssdk_oks_refreshing">Refreshing…</string>
</resources>
| {
"pile_set_name": "Github"
} |
## 序言
本教程希望让您快速熟悉使用React Native来编写iOS和Android App的技巧。如果你希望知道React Native是什么以及为什么Facebook打造了它,可以读读[这篇博文](http://bbs.reactnative.cn/topic/14)
我们这里假设你已经有了使用React编写Web应用程序的经验。如果还没有,建议你可以先从[React官网](http://facebook.github.io/react/)开始学习。
## 准备工作
React Native需要一些基础的配置工作,你可以参考[开始使用React Native](/docs/getting-started.html)来进行。
在所有依赖的软件都已经安装完毕后,只需要输入两条命令就可以创建一个React Native工程。
1. `npm install -g react-native-cli`
react-native-cli是一个终端命令,它可以完成其余的设置工作。它可以通过npm安装。刚才这条命令会往你的终端安装一个叫做`react-native`的命令。这个安装过程你只需要进行一次。
2. `react-native init AwesomeProject`
这个命令会初始化一个工程、下载React Native的所有源代码和依赖包,最后在`AwesomePrjoect/iOS/AwesomeProject.xcodeproj`和`AwesomeProject/android/app`下分别创建一个新的XCode工程和一个gradle工程。
__译注__:由于众所周知的网络原因,react-native命令行从npm官方源拖代码时会遇上麻烦。请先将npm仓库源替换为国内镜像:
```bash
npm config set registry https://registry.npm.taobao.org
npm config set disturl https://npm.taobao.org/dist
```
另,执行init时切记不要在前面加上sudo(否则新项目的目录所有者会变为root而不是当前用户,导致一系列权限问题,请使用chown修复)。
本站论坛区提供了[完整的绿色纯净新项目包](http://bbs.reactnative.cn/topic/11)。完整打包全部iOS和Android的第三方依赖,只要环境配置正确,无需科学上网漫长等待,解压即可直接运行。
## 开发
想开发iOS版本,你现在可以在XCode中打开刚刚创建的工程(`AwesomePrjoect/iOS/AwesomeProject.xcodeproj`),然后只要按下`⌘+R`就可以构建并运行。这个操作会同时打开一个用于实现动态代码加载的Node服务(React Packager)。所以每当你修改代码,你只需要在模拟器中按下`⌘+R`,而无需重新在XCode中编译。
想开发Android版本,先连接你的设备或启动模拟器,然后在`AwesomeProject`目录下运行`react-native run-android`,就会构建工程并自动安装到你的模拟器或者设备,同时启动用于实现动态代码加载的Node服务。当你修改代码之后,你需要打开摇一摇菜单(摇一下设备,或者按下设备的Menu键,或者在模拟器上按下F2或Page Up,Genymotion按下⌘+M),然后在菜单中点击“Reload JS”。
在本向导中我们会创建一个简单的Movies应用,它可以获取25个上映中的电影,然后把他们在一个ListView中显示。
### Hello World
`react-native init`命令会创建一个指定名字的应用,我们刚才输入的命令就创建了一个名为AwesomePrjoect的应用。这是一个简单的Hello World应用。对于iOS版本,你可以编辑`index.ios.js`来做一些改动,然后在模拟器中按⌘+R来看到修改的结果。对Android版本,你可以编辑`index.android.js`来做一些改动,然后在摇一摇菜单中点击“Reload JS”来看到修改的结果。
### 模拟数据
__译注__:本文的示例代码改用了ES6语法,可能和其他文档写法不一致。但React Native从0.18之后,新建项目默认已经采用了ES6语法,故我们推荐不熟悉ES6与ES5区别的朋友先读读[这篇文章](http://bbs.reactnative.cn/topic/15),另外还可以看看[阮一峰老师的书](http://es6.ruanyifeng.com/)。
在我们真正从Rotten Tomatoes(_译注:一个国外的电影社区_)抓取数据之前,我们先制造一些模拟数据来练一练手。在Facebook我们通常在JS文件的开头,紧跟着import语句之后声明一个常量,不过这不重要,你可以把它放在`index.ios.js`和`index.android.js`的任意位置:
```javascript
var MOCKED_MOVIES_DATA = [
{title: '标题', year: '2015', posters: {thumbnail: 'http://i.imgur.com/UePbdph.jpg'}},
];
```
### 展现一个电影
我们接下来要展现一个电影,绘制它的标题、年份、以及缩略图(_译注:这个过程我们通常会叫做“渲染/render”,后面我们都会用“渲染”这个词_)。渲染缩略图需要用到Image组件,所以把Image添加到对React的import列表中。
```javascript
import React, {
AppRegistry,
Component,
Image,
StyleSheet,
Text,
View,
} from 'react-native';
```
然后修改一下render函数,这样我们可以把上面创建的模拟数据渲染出来。
```javascript
render() {
var movie = MOCKED_MOVIES_DATA[0];
return (
<View style={styles.container}>
<Text>{movie.title}</Text>
<Text>{movie.year}</Text>
<Image source={{uri: movie.posters.thumbnail}} />
</View>
);
}
```
按下`⌘+R`或者`Reload JS`,现在你应该能看到文字"Title"和"2015",但现在Image组件没渲染任何东西,这是因为我们还没有为图片指定我们想要渲染的宽和高。这通过样式来实现。当我们修改样式的时候,我们也应该清理掉我们不再使用的样式。
```javascript
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
thumbnail: {
width: 53,
height: 81,
},
});
```
然后把它应用到Image组件上:
```javascript
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
```
按下`⌘+R`或者`Reload JS`,现在图片应该可以被渲染出来了。
| | |
|--|--|
| ||
### 添加样式
现在我们已经成功的把我们的数据渲染出来了,下面让我们把它弄的更好看一些。我想把文字放在图片的右边,然后把标题弄的大一些,并且水平居中:
```
+---------------------------------+
|+-------++----------------------+|
|| || 标题 ||
|| 图片 || ||
|| || 年份 ||
|+-------++----------------------+|
+---------------------------------+
```
所以我们需要增加一个container来实现一个水平布局内嵌套一个垂直布局。
```javascript
return (
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
);
```
和之前相比并没有太多变化,我们增加了一个container来包装文字,然后把它移到了Image的后面(因为他们最终在图片的右边)。然后我们来看看样式要怎么改:
```javascript
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
```
我们用Flexbox来布局。如果你想了解更多,可以读读[这篇文章](https://css-tricks.com/snippets/css/a-guide-to-flexbox/)。
在上面的代码片段中,我们用了一句`flexDirection: 'row'`来让我们的主容器的成员从左到右横向布局,而非默认的从上到下纵向布局。
现在我们往`style`对象里增加另一个样式:
```javascript
rightContainer: {
flex: 1,
},
```
这句话的作用是让`rightContainer`在父容器中占据Image之外剩下的全部空间。如果你还不是很理解的话,你可以往`rightContainer`里增加一个`backgroundColor`看一看,然后再去掉`flex:1`对比一下。你会发现去掉这一句后,容器会变成能容纳它孩子的最小大小。
给文字添加样式就简单的多了:
```javascript
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
```
再按一次`⌘+R`或者`Reload JS`来看看最新的结果。
| | |
|--|--|
| ||
### 拉取真正的数据
从Rotten Tomatoes的API拉取数据和学习React Native并没有什么直接关系,所以你也可以直接跳过本节。
把下面的常量放到文件的最开头(通常在require下面)来创建我们请求数据所需的地址常量REQUEST_URL
```javascript
/**
* 为了避免骚扰,我们用了一个样例数据来替代Rotten Tomatoes的API
* 请求,这个样例数据放在React Native的Github库中。
*/
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
```
首先在应用中创建一个初始的null状态,这样可以通过`this.state.movies == null`来判断我们的数据是不是已经被抓取到了。我们在服务器响应返回的时候执行`this.setState({movies: moviesData})`来改变这个状态。把下面这段代码放到我们的React类的render函数之前:
```javascript
constructor(props) {
super(props); //这一句不能省略,照抄即可
this.state = {
movies: null, //这里放你自己定义的state变量及初始值
};
}
```
组件加载完毕之后,就可以向服务器请求数据。`componentDidMount`是React组件的一个生命周期方法,它会在组件刚加载完成的时候调用一次,以后不再会被调用。React中的各种生命周期方法请[参阅此文档](http://facebook.github.io/react/docs/component-specs.html)。
```javascript
componentDidMount() {
this.fetchData();
}
```
现在我们来为组件添加`fetchData`函数。你所需要做的就是在Promise调用链结束后执行`this.setState({movies:data})`。在React的工作机制下,`setState`实际上会触发一次重新渲染的流程,此时render函数被触发,发现this.state.movies不再是`null`。注意我们在Promise调用链的最后调用了`done()` —— 这样可以抛出异常而不是简单忽略。
```javascript
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
movies: responseData.movies,
});
})
.done();
}
```
现在我们来修改render函数。在电影数据加载完毕之前,先渲染一个“加载中”的视图;而如果电影数据已经加载完毕了,则渲染第一个电影数据。
```javascript
render() {
if (!this.state.movies) {
return this.renderLoadingView();
}
var movie = this.state.movies[0];
return this.renderMovie(movie);
}
renderLoadingView() {
return (
<View style={styles.container}>
<Text>
正在加载电影数据……
</Text>
</View>
);
}
renderMovie(movie) {
return (
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
);
}
```
现在再按一次`⌘+R`或者`Reload JS`,你会首先看到“正在加载电影数据……”,然后在响应数据到达之后,看到第一个电影的信息。
| | |
|--|--|
| ||
## ListView
现在我们来让我们的应用能够渲染所有的数据而不是仅仅第一部电影。我们要用到的就是ListView组件。
为什么建议把内容放到ListView里?比起直接渲染出所有的元素,或是放到一个ScrollView里有什么优势?这是因为尽管React很高效,渲染一个可能很大的元素列表还是会很慢。`ListView`会安排视图的渲染,只显示当前在屏幕上的那些元素。而那些已经渲染好了但移动到了屏幕之外的元素,则会从原生视图结构中移除(以提高性能)。
首先要做的事情:在文件最开头,从React中引入`ListView`。
```javascript
import React, {
AppRegistry,
Component,
Image,
ListView,
StyleSheet,
Text,
View,
} from 'react-native';
```
现在来修改render函数。当我们已经有了数据之后,渲染一个包含多个电影信息的ListView,而不仅仅是单个的电影。
```javascript
render() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
style={styles.listView}
/>
);
}
```
`dataSource`接口用来在ListView的整个更新过程中判断哪些数据行发生了变化。
你会注意到我们现在用到了`this.state`中的`dataSource`。下一步就是在`constructor`生成的初始状态中添加一个空白的`dataSource`。另外,我们现在要把数据存储在`dataSource`中了,所以不再另外用`this.state.movies`来保存数据。我们可以在state里用一个布尔型的属性(`this.state.loaded`)来判断数据加载是否已经完成了。
```javascript
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
}
```
同时我们也要修改`fetchData`方法来把数据更新到dataSource里:
```javascript
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
loaded: true,
});
})
.done();
}
```
最后,我们再在`styles`对象里给`ListView`添加一些样式。
```javascript
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
},
```
现在可以体现最终的结果了:
| | |
|--|--|
| ||
为了实现一个完整功能的应用,接下来其实还有一些工作要做,譬如:添加导航器,搜索,加载更多,等等等等。可以在[Movies示例](https://github.com/facebook/react-native/tree/master/Examples/Movies)中看看我们做了什么。
### 最终的代码
```javascript
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
import React, {
AppRegistry,
Component,
Image,
ListView,
StyleSheet,
Text,
View,
} from 'react-native';
var API_KEY = '7waqfqbprs7pajbz28mqf6vz';
var API_URL = 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json';
var PAGE_SIZE = 25;
var PARAMS = '?apikey=' + API_KEY + '&page_limit=' + PAGE_SIZE;
var REQUEST_URL = API_URL + PARAMS;
class AwesomeProject extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
}
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
loaded: true,
});
})
.done();
}
render() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
style={styles.listView}
/>
);
}
renderLoadingView() {
return (
<View style={styles.container}>
<Text>
Loading movies...
</Text>
</View>
);
}
renderMovie(movie) {
return (
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
);
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
rightContainer: {
flex: 1,
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
thumbnail: {
width: 53,
height: 81,
},
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
```
| {
"pile_set_name": "Github"
} |
/* Copyright (C) 2014 InfiniDB, Inc.
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; version 2 of
the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */
/***********************************************************************
* $Id: $
*
*
***********************************************************************/
/** @file */
#ifndef LOGGING_SQLLOGGER_H_
#define LOGGING_SQLLOGGER_H_
#include <string>
#include "messageids.h"
#include "messageobj.h"
#include "loggingid.h"
#include "logger.h"
namespace logging
{
extern const unsigned LogDefaultMsg;
extern const unsigned LogStartSql;
extern const unsigned LogEndSql;
/** @brief writes sql start with sql statement in constructor and sql end in destructor in debug.log
if the sql text is not empty
*/
class SQLLogger
{
public:
SQLLogger(const std::string sql, unsigned subsys, unsigned session, unsigned txn = 0, unsigned thread = 0);
SQLLogger(const std::string sql, const LoggingID& logId);
~SQLLogger();
std::string logMessage(logging::LOG_TYPE logLevel, const std::string& msg, logging::Message::MessageID mid = LogDefaultMsg );
private:
void makeMsgMap();
MsgMap fMsgMap;
LoggingID fLogId;
bool fLog;
};
}
#endif
| {
"pile_set_name": "Github"
} |
<?php
/*
* * Zabbix
* * Copyright (C) 2001-2013 Zabbix SIA
* *
* * This program is free software; you can redistribute it and/or modify
* * it under the terms of the GNU General Public License as published by
* * the Free Software Foundation; either version 2 of the License, or
* * (at your option) any later version.
* *
* * This program is distributed in the hope that it will be useful,
* * but WITHOUT ANY WARRANTY; without even the implied warranty of
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* * GNU General Public License for more details.
* *
* * You should have received a copy of the GNU General Public License
* * along with this program; if not, write to the Free Software
* * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* */
/**
* @package API
*/
class CItemValue extends CZBXAPI {
public function GetItemValues($itemInfo) {
$stime = $itemInfo['stime'];
$period = $itemInfo['period'];
$sizeX = $itemInfo['sizeX'];
$now = time(null);
if (!isset($stime)) {
$stime = $now - $period;
}
$diffTZ = (date('Z', $stime) - date('Z', $stime + $period));
$from_time = $stime; // + timeZone offset
$to_time = $stime + $period; // + timeZone offset
$p = $to_time - $from_time; // graph size in time
$z = $p - $from_time % $p; // graphsize - mod(from_time,p) for Oracle...
$x = $sizeX; // graph size in px
$config = select_config();
$real_item = get_item_by_itemid($itemInfo['itemid']);
$type = $itemInfo['calc_type'];
$calc_field = 'round(' . $x . '*' . zbx_sql_mod(zbx_dbcast_2bigint('clock') . '+' . $z, $p) . '/(' . $p . '),0)'; // required for 'group by' support of Oracle
$sql_arr = array();
// override item history setting with housekeeping settings
if ($config['hk_history_global']) {
$real_item['history'] = $config['hk_history'];
}
$trendsEnabled = $config['hk_trends_global'] ? ($config['hk_trends'] > 0) : ($real_item['trends'] > 0);
if (!$trendsEnabled || (($item['history'] * SEC_PER_DAY) > (time() - ($from_time + $period / 2)) && ($period / $sizeX) <= (ZBX_MAX_TREND_DIFF / ZBX_GRAPH_MAX_SKIP_CELL))) { // is reasonable to take data from history?
//$this->dataFrom = 'history';
array_push($sql_arr, 'SELECT itemid,' . $calc_field . ' AS i,' .
'COUNT(*) AS count,AVG(value) AS avg,MIN(value) as min,' .
'MAX(value) AS max,MAX(clock) AS clock' .
' FROM history ' .
' WHERE itemid=' . $itemInfo['itemid'] .
' AND clock>=' . $from_time .
' AND clock<=' . $to_time .
' GROUP BY itemid,' . $calc_field
, 'SELECT itemid,' . $calc_field . ' AS i,' .
'COUNT(*) AS count,AVG(value) AS avg,MIN(value) AS min,' .
'MAX(value) AS max,MAX(clock) AS clock' .
' FROM history_uint ' .
' WHERE itemid=' . $itemInfo['itemid'] .
' AND clock>=' . $from_time .
' AND clock<=' . $to_time .
' GROUP BY itemid,' . $calc_field
);
} else {
//$this->dataFrom = 'trends';
array_push($sql_arr, 'SELECT itemid,' . $calc_field . ' AS i,' .
'SUM(num) AS count,AVG(value_avg) AS avg,MIN(value_min) AS min,' .
'MAX(value_max) AS max,MAX(clock) AS clock' .
' FROM trends' .
' WHERE itemid=' . $itemInfo['itemid'] .
' AND clock>=' . $from_time .
' AND clock<=' . $to_time .
' GROUP BY itemid,' . $calc_field
, 'SELECT itemid,' . $calc_field . ' AS i,' .
'SUM(num) AS count,AVG(value_avg) AS avg,MIN(value_min) AS min,' .
'MAX(value_max) AS max,MAX(clock) AS clock' .
' FROM trends_uint ' .
' WHERE itemid=' . $itemInfo['itemid'] .
' AND clock>=' . $from_time .
' AND clock<=' . $to_time .
' GROUP BY itemid,' . $calc_field
);
$itemInfo['delay'] = max($itemInfo['delay'], SEC_PER_HOUR);
}
$curr_data['count'] = null;
$curr_data['min'] = null;
$curr_data['max'] = null;
$curr_data['avg'] = null;
$curr_data['clock'] = null;
foreach ($sql_arr as $sql) {
$result = DBselect($sql);
while ($row = DBfetch($result)) {
$idx = $row['i'] - 1;
if ($idx < 0) {
continue;
}
$curr_data['count'][$idx] = $row['count'];
$curr_data['min'][$idx] = $row['min'];
$curr_data['max'][$idx] = $row['max'];
$curr_data['avg'][$idx] = $row['avg'];
$curr_data['clock'][$idx] = $row['clock'];
$curr_data['shift_min'][$idx] = 0;
$curr_data['shift_max'][$idx] = 0;
$curr_data['shift_avg'][$idx] = 0;
}
unset($row);
}
$curr_data['avg_orig'] = is_array($curr_data['avg']) ? zbx_avg($curr_data['avg']) : null;
return $curr_data;
}
public function getLastValueBy($data) {
//$data = &$this->newData[$item['itemid']][$item['calc_type']];
if (isset($data)) {
for ($i = 286 - 1; $i >= 0; $i--) {
if (!empty($data['count'][$i])) {
switch ($item['calc_fnc']) {
case CALC_FNC_MIN:
return $data['min'][$i];
case CALC_FNC_MAX:
return $data['max'][$i];
case CALC_FNC_ALL:
case CALC_FNC_AVG:
default:
return $data['avg'][$i];
}
}
}
}
return 0;
}
public function getItemListFormat($list = array()) {
$itemList = $list['list_item'];
$parame = $list['parame'];
$search_key = $parame['item_name_search'];
$order_result_list = array();
$search = 0;
if (empty($search_key)) {
$search_key_list = array();
} else {
$search_key_list = explode(",", $search_key);
}
if (count($search_key_list) >= 1) {
$search = 1;
}
foreach ($itemList as $each_item) {
$each_item = (array) $each_item;
$item = get_item_by_itemid($each_item['itemid']);
$newItem = $item;
// $newItem['name'] = itemName($item);
$newItem['name'] = $item['name'];
$newItem['delay'] = getItemDelay($item['delay'], $item['delay_flex']);
$host = get_host_by_hostid($item['hostid']);
$newItem['hostname'] = $host['name'];
if (strpos($item['units'], ',') !== false) {
list($newItem['units'], $newItem['unitsLong']) = explode(',', $item['units']);
} else {
$newItem['unitsLong'] = '';
}
if ($search == 0) {
$newItem['graphid'] = $each_item['graphid'];
$order_result_list[$newItem['graphid']] = array("graphid" => $newItem['graphid'], "itemname" => $newItem['name'], "lastvalue" => 0, 'min' => 0, 'avg' => 0, 'max' => 0, 'hostname' => $newItem['hostname'], 'chazhi' => 0);
} else {
foreach ($search_key_list as $each_search_key) {
$each_search_key = trim($each_search_key);
//按关键字进行筛选
if (strpos(strtolower($newItem['name']), strtolower($each_search_key)) === false) {
} else {
$newItem['calc_fnc'] = is_null($each_item['calc_fnc']) ? CALC_FNC_AVG : $each_item->calc_fnc;
$newItem['calc_type'] = GRAPH_ITEM_SIMPLE;
$newItem['graphid'] = $each_item['graphid'];
$item_info_new = array_merge($newItem, $parame);
$data = self::GetItemValues($item_info_new);
if (isset($data) && isset($data['min'])) {
$lastvalue = convert_units(self::getLastValueBy($data), $newItem['units'], ITEM_CONVERT_NO_UNITS);
$min = convert_units(min($data['min']), $newItem['units'], ITEM_CONVERT_NO_UNITS);
$avg = convert_units($data['avg_orig'], $newItem['units'], ITEM_CONVERT_NO_UNITS);
$max = convert_units(max($data['max']), $newItem['units'], ITEM_CONVERT_NO_UNITS);
//return array("lastvalue"=>$lastvalue,'min'=>$min,'avg'=>$avg,'max'=>$max);
$order_result_list[$each_search_key][$newItem['graphid']] = array("graphid" => $newItem['graphid'], "itemname" => $newItem['name'], "lastvalue" => self::getLastValueBy($data), 'min' => min($data['min']), 'avg' => $data['avg_orig'], 'max' => max($data['max']), 'hostname' => $newItem['hostname'], 'chazhi' => max($data['max']) - min($data['min']));
} else {
$order_result_list[$each_search_key][$newItem['graphid']] = array("graphid" => $newItem['graphid'], "itemname" => $newItem['name'], "lastvalue" => 0, 'min' => 0, 'avg' => 0, 'max' => 0, 'hostname' => $newItem['hostname'], 'chazhi' => 0);
}
break;
}
}
}
}
return $order_result_list;
}
}
| {
"pile_set_name": "Github"
} |
{include file='header.tpl'}
<main class="content">
<div class="container">
<div class="row">
<div class="col-lg-4 col-lg-push-4 col-sm-6 col-sm-push-3">
<section class="content-inner">
<div class="card">
<div class="card-main">
<div class="card-header">
<div class="card-inner">
<h1 class="card-heading">和我签订契约,成为魔法少女吧。</h1>
</div>
</div>
<div class="card-inner">
<p class="text-center">
<span class="avatar avatar-inline avatar-lg">
<img alt="Login" src="/theme/material/images/users/avatar-001.jpg">
</span>
</p>
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="name">昵称</label>
<input class="form-control" id="name" type="text">
</div>
</div>
</div>
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="email">邮箱</label>
<input class="form-control" id="email" type="text">
</div>
</div>
</div>
{if $enable_email_verify == 'true'}
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="email_code">邮箱验证码</label>
<input class="form-control" id="email_code" type="text">
<button id="email_verify" class="btn btn-block btn-brand-accent waves-attach waves-light">获取验证码</button>
</div>
</div>
</div>
{/if}
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="passwd">密码</label>
<input class="form-control" id="passwd" type="password">
</div>
</div>
</div>
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="repasswd">重复密码</label>
<input class="form-control" id="repasswd" type="password">
</div>
</div>
</div>
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="imtype">选择您的联络方式</label>
<select class="form-control" id="imtype">
<option></option>
<option value="1">微信</option>
<option value="2">QQ</option>
<option value="3">Google+</option>
<option value="4">Telegram</option>
</select>
</div>
</div>
</div>
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="wechat">在这输入联络方式账号</label>
<input class="form-control" id="wechat" type="text">
</div>
</div>
</div>
{if $enable_invite_code == 'true'}
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="code">邀请码</label>
<input class="form-control" id="code" type="text" value="{$code}">
</div>
</div>
</div>
{/if}
{if $geetest_html != null}
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<div id="embed-captcha"></div>
</div>
</div>
</div>
{/if}
<div class="form-group">
<div class="row">
<div class="col-md-10 col-md-push-1">
<button id="tos" type="submit" class="btn btn-block btn-brand waves-attach waves-light">注册</button>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-10 col-md-push-1">
<p>注册即代表同意<a href="/tos">服务条款</a>,以及保证所录入信息的真实性,如有不实信息会导致账号被删除。</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clearfix">
<p class="margin-no-top pull-left"><a class="btn btn-flat btn-brand waves-attach" href="/auth/login">已经注册?请登录</a></p>
</div>
{include file='dialog.tpl'}
<div aria-hidden="true" class="modal modal-va-middle fade" id="tos_modal" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-heading">
<h2 class="modal-title">注册 TOS</h2>
</div>
<div class="modal-inner">
{include file='reg_tos.tpl'}
</div>
<div clUass="modal-footer">
<p class="text-right"><button class="btn btn-flat btn-brand-accent waves-attach waves-effect" data-dismiss="modal" type="button" id="cancel">我不服</button><button class="btn btn-flat btn-brand-accent waves-attach waves-effect" data-dismiss="modal" id="reg" type="button">资慈</button></p>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</main>
{include file='footer.tpl'}
<script>
$(document).ready(function(){
function register(){
document.getElementById("tos").disabled = true;
$.ajax({
type:"POST",
url:"/auth/register",
dataType:"json",
data:{
email: $("#email").val(),
name: $("#name").val(),
passwd: $("#passwd").val(),
repasswd: $("#repasswd").val(),
wechat: $("#wechat").val(),
imtype: $("#imtype").val(){if $enable_invite_code == 'true'},
code: $("#code").val(){/if}{if $enable_email_verify == 'true'},
emailcode: $("#email_code").val(){/if}{if $geetest_html != null},
geetest_challenge: validate.geetest_challenge,
geetest_validate: validate.geetest_validate,
geetest_seccode: validate.geetest_seccode
{/if}
},
success:function(data){
if(data.ret == 1){
$("#result").modal();
$("#msg").html(data.msg);
window.setTimeout("location.href='/auth/login'", {$config['jump_delay']});
}else{
$("#result").modal();
$("#msg").html(data.msg);
document.getElementById("tos").disabled = false;
{if $geetest_html != null}
captcha.refresh();
{/if}
}
},
error:function(jqXHR){
$("#msg-error").hide(10);
$("#msg-error").show(100);
$("#msg-error-p").html("发生错误:"+jqXHR.status);
document.getElementById("tos").disabled = false;
{if $geetest_html != null}
captcha.refresh();
{/if}
}
});
}
$("html").keydown(function(event){
if(event.keyCode==13){
$("#tos_modal").modal();
}
});
{if $geetest_html != null}
$('div.modal').on('shown.bs.modal', function() {
$("div.gt_slider_knob").hide();
});
$('div.modal').on('hidden.bs.modal', function() {
$("div.gt_slider_knob").show();
});
{/if}
$("#reg").click(function(){
register();
});
$("#tos").click(function(){
{if $geetest_html != null}
if(typeof validate == 'undefined')
{
$("#result").modal();
$("#msg").html("请滑动验证码来完成验证。");
return;
}
if (!validate) {
$("#result").modal();
$("#msg").html("请滑动验证码来完成验证。");
return;
}
{/if}
$("#tos_modal").modal();
});
})
</script>
{if $enable_email_verify == 'true'}
<script>
var wait=60;
function time(o) {
if (wait == 0) {
o.removeAttr("disabled");
o.text("获取验证码");
wait = 60;
} else {
o.attr("disabled","disabled");
o.text("重新发送(" + wait + ")");
wait--;
setTimeout(function() {
time(o)
},
1000)
}
}
$(document).ready(function () {
$("#email_verify").click(function () {
time($("#email_verify"));
$.ajax({
type: "POST",
url: "send",
dataType: "json",
data: {
email: $("#email").val()
},
success: function (data) {
if (data.ret) {
$("#result").modal();
$("#msg").html(data.msg);
} else {
$("#result").modal();
$("#msg").html(data.msg);
}
},
error: function (jqXHR) {
$("#result").modal();
$("#msg").html(data.msg+" 出现了一些错误。");
}
})
})
})
</script>
{/if}
{if $geetest_html != null}
<script>
var handlerEmbed = function (captchaObj) {
// 将验证码加到id为captcha的元素里
captchaObj.onSuccess(function () {
validate = captchaObj.getValidate();
});
captchaObj.appendTo("#embed-captcha");
captcha = captchaObj;
// 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
initGeetest({
gt: "{$geetest_html->gt}",
challenge: "{$geetest_html->challenge}",
product: "embed", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
offline: {if $geetest_html->success}0{else}1{/if} // 表示用户后台检测极验服务器是否宕机,与SDK配合,用户一般不需要关注
}, handlerEmbed);
</script>
{/if}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<!-- ============================================================= -->
<!-- Configure the Jetty Server instance with an ID "Server" -->
<!-- by adding a HTTP connector. -->
<!-- This configuration must be used in conjunction with jetty.xml -->
<!-- ============================================================= -->
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<!-- =========================================================== -->
<!-- Add a HTTP Connector. -->
<!-- Configure an o.e.j.server.ServerConnector with a single -->
<!-- HttpConnectionFactory instance using the common httpConfig -->
<!-- instance defined in jetty.xml -->
<!-- -->
<!-- Consult the javadoc of o.e.j.server.ServerConnector and -->
<!-- o.e.j.server.HttpConnectionFactory for all configuration -->
<!-- that may be set here. -->
<!-- =========================================================== -->
<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.ServerConnector">
<Arg name="server"><Ref refid="Server" /></Arg>
<Arg name="factories">
<Array type="org.eclipse.jetty.server.ConnectionFactory">
<Item>
<New class="org.eclipse.jetty.server.HttpConnectionFactory">
<Arg name="config"><Ref refid="httpConfig" /></Arg>
</New>
</Item>
</Array>
</Arg>
<Set name="host"><Property name="jetty.host" /></Set>
<Set name="port"><Property name="jetty.port" default="8080" /></Set>
<Set name="idleTimeout"><Property name="http.timeout" default="30000"/></Set>
</New>
</Arg>
</Call>
</Configure> | {
"pile_set_name": "Github"
} |
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/SAObjects.framework/SAObjects
*/
@interface SAUILocalImageResource : AceObject <SAAceSerializable>
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (readonly) unsigned long long hash;
@property (nonatomic, copy) NSString *imageCode;
@property (readonly) Class superclass;
+ (id)localImageResource;
+ (id)localImageResourceWithDictionary:(id)arg1 context:(id)arg2;
- (id)encodedClassName;
- (id)groupIdentifier;
- (id)imageCode;
- (void)setImageCode:(id)arg1;
@end
| {
"pile_set_name": "Github"
} |
package io.nutz.demo.simple.service.impl;
import com.github.threefish.nutz.dto.PageDataDTO;
import com.github.threefish.nutz.sqltpl.ISqlDaoExecuteService;
import com.github.threefish.nutz.sqltpl.SqlsTplHolder;
import com.github.threefish.nutz.sqltpl.SqlsXml;
import io.nutz.demo.simple.bean.User;
import io.nutz.demo.simple.service.IUserService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.service.EntityService;
import java.util.List;
/**
* @author 黄川 [email protected]
* @date: 2019/4/3
*/
@IocBean(args = {"refer:dao"})
@SqlsXml
public class UserServiceImpl extends EntityService<User> implements IUserService, ISqlDaoExecuteService {
/**
* 1、我是必须要有的
* 2、可以不实现 ISqlDaoExecuteService 接口,用 SqlsTplHolder 直接渲染sql自己再进行操作
*/
private SqlsTplHolder sqlsTplHolder;
public UserServiceImpl(Dao dao) {
super(dao);
}
@Override
public PageDataDTO queryLikeName(NutMap param, Pager pager) {
return queryEntityBySql("queryLikeName", param, pager);
}
@Override
public List<User> queryLikeNameByCnd(Cnd cnd, Pager pager) {
return queryEntityBySql("queryLikeNameByCnd", NutMap.NEW(), cnd);
}
@Override
public List<NutMap> queryMapslikeName(NutMap param) {
return queryMapBySql("queryMapslikeName", param);
}
@Override
public SqlsTplHolder getSqlsTplHolder() {
return this.sqlsTplHolder;
}
@Override
public Dao getDao() {
return super.dao();
}
}
| {
"pile_set_name": "Github"
} |
/*
* Compiler main file
*
* Copyright 2000 Ryszard Glab <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file LICENSE.txt. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA (or visit https://www.gnu.org/licenses/).
*
* As a special exception, the Harbour Project gives permission for
* additional uses of the text contained in its release of Harbour.
*
* The exception is that, if you link the Harbour libraries with other
* files to produce an executable, this does not by itself cause the
* resulting executable to be covered by the GNU General Public License.
* Your use of that executable is in no way restricted on account of
* linking the Harbour library code into it.
*
* This exception does not however invalidate any other reasons why
* the executable file might be covered by the GNU General Public License.
*
* This exception applies only to the code released by the Harbour
* Project under the name Harbour. If you copy code from other
* Harbour Project or Free Software Foundation releases into a copy of
* Harbour, as the General Public License permits, the exception does
* not apply to the code that you add in this way. To avoid misleading
* anyone as to the status of such modified files, you must delete
* this exception notice from them.
*
* If you write modifications of your own for Harbour, it is your choice
* whether to permit this exception to apply to your modifications.
* If you do not wish that, delete this exception notice.
*
*/
#include "hbcomp.h"
#include "hbassert.h"
/* helper structure to pass information */
typedef struct HB_stru_fix_info
{
HB_COMP_DECL;
} HB_FIX_INFO, * PHB_FIX_INFO;
#define HB_FIX_FUNC( func ) HB_PCODE_FUNC( func, PHB_FIX_INFO )
typedef HB_FIX_FUNC( HB_FIX_FUNC_ );
typedef HB_FIX_FUNC_ * PHB_FIX_FUNC;
static HB_FIX_FUNC( hb_p_pushblock )
{
HB_BYTE * pLocal = &pFunc->pCode[ nPCodePos + 7 ];
HB_USHORT wVar;
HB_SYMBOL_UNUSED( cargo );
/* opcode + codeblock size + number of parameters + number of local variables */
wVar = HB_PCODE_MKUSHORT( &pFunc->pCode[ nPCodePos + 5 ] );
/* fix local variable's reference */
while( wVar-- )
{
HB_USHORT wLocal = HB_PCODE_MKUSHORT( pLocal ) + pFunc->wParamCount;
pLocal[ 0 ] = HB_LOBYTE( wLocal );
pLocal[ 1 ] = HB_HIBYTE( wLocal );
pLocal += 2;
}
/* only local variables used outside of a codeblock need fixing
* skip the codeblock body
*/
return HB_PCODE_MKUSHORT( &pFunc->pCode[ nPCodePos + 1 ] );
}
static HB_FIX_FUNC( hb_p_pushblocklarge )
{
HB_BYTE * pLocal = &pFunc->pCode[ nPCodePos + 8 ];
HB_USHORT wVar;
HB_SYMBOL_UNUSED( cargo );
/* opcode + codeblock size + number of parameters + number of local variables */
wVar = HB_PCODE_MKUSHORT( &pFunc->pCode[ nPCodePos + 6 ] );
/* fix local variable's reference */
while( wVar-- )
{
HB_USHORT wLocal = HB_PCODE_MKUSHORT( pLocal ) + pFunc->wParamCount;
pLocal[ 0 ] = HB_LOBYTE( wLocal );
pLocal[ 1 ] = HB_HIBYTE( wLocal );
pLocal += 2;
}
/* only local variables used outside of a codeblock need fixing
* skip the codeblock body
*/
return HB_PCODE_MKUINT24( &pFunc->pCode[ nPCodePos + 1 ] );
}
static HB_FIX_FUNC( hb_p_localfix )
{
HB_BYTE * pVar = &pFunc->pCode[ nPCodePos + 1 ];
HB_SHORT iVar = HB_PCODE_MKSHORT( pVar );
HB_SYMBOL_UNUSED( cargo );
iVar += pFunc->wParamCount;
pVar[ 0 ] = HB_LOBYTE( iVar );
pVar[ 1 ] = HB_HIBYTE( iVar );
return 0;
}
static HB_FIX_FUNC( hb_p_localnearerr )
{
HB_SYMBOL_UNUSED( pFunc );
HB_SYMBOL_UNUSED( nPCodePos );
/*
* this code should never be executed because compiler should
* generate only non size optimized HB_P_POPLOCAL pcodes
* for function body
*/
hb_compGenError( cargo->HB_COMP_PARAM, hb_comp_szErrors, 'F', HB_COMP_ERR_OPTIMIZEDLOCAL_OUT_OF_RANGE, "", "" );
return 0;
}
/* NOTE: The order of functions have to match the order of opcodes
* mnemonics
*/
static const PHB_FIX_FUNC s_fixlocals_table[] =
{
NULL, /* HB_P_AND */
NULL, /* HB_P_ARRAYPUSH */
NULL, /* HB_P_ARRAYPOP */
NULL, /* HB_P_ARRAYDIM */
NULL, /* HB_P_ARRAYGEN */
NULL, /* HB_P_EQUAL */
NULL, /* HB_P_ENDBLOCK */
NULL, /* HB_P_ENDPROC */
NULL, /* HB_P_EXACTLYEQUAL */
NULL, /* HB_P_FALSE */
NULL, /* HB_P_FORTEST */
NULL, /* HB_P_FUNCTION */
NULL, /* HB_P_FUNCTIONSHORT */
NULL, /* HB_P_FRAME */
NULL, /* HB_P_FUNCPTR */
NULL, /* HB_P_GREATER */
NULL, /* HB_P_GREATEREQUAL */
NULL, /* HB_P_DEC */
NULL, /* HB_P_DIVIDE */
NULL, /* HB_P_DO */
NULL, /* HB_P_DOSHORT */
NULL, /* HB_P_DUPLICATE */
NULL, /* HB_P_PUSHTIMESTAMP */
NULL, /* HB_P_INC */
NULL, /* HB_P_INSTRING */
NULL, /* HB_P_JUMPNEAR */
NULL, /* HB_P_JUMP */
NULL, /* HB_P_JUMPFAR */
NULL, /* HB_P_JUMPFALSENEAR */
NULL, /* HB_P_JUMPFALSE */
NULL, /* HB_P_JUMPFALSEFAR */
NULL, /* HB_P_JUMPTRUENEAR */
NULL, /* HB_P_JUMPTRUE */
NULL, /* HB_P_JUMPTRUEFAR */
NULL, /* HB_P_LESSEQUAL */
NULL, /* HB_P_LESS */
NULL, /* HB_P_LINE */
hb_p_localfix, /* HB_P_LOCALNAME */
NULL, /* HB_P_MACROPOP */
NULL, /* HB_P_MACROPOPALIASED */
NULL, /* HB_P_MACROPUSH */
NULL, /* HB_P_MACROARRAYGEN */
NULL, /* HB_P_MACROPUSHLIST */
NULL, /* HB_P_MACROPUSHINDEX */
NULL, /* HB_P_MACROPUSHPARE */
NULL, /* HB_P_MACROPUSHALIASED */
NULL, /* HB_P_MACROSYMBOL */
NULL, /* HB_P_MACROTEXT */
NULL, /* HB_P_MESSAGE */
NULL, /* HB_P_MINUS */
NULL, /* HB_P_MODULUS */
NULL, /* HB_P_MODULENAME */
/* start: pcodes generated by macro compiler */
NULL, /* HB_P_MMESSAGE */
NULL, /* HB_P_MPOPALIASEDFIELD */
NULL, /* HB_P_MPOPALIASEDVAR */
NULL, /* HB_P_MPOPFIELD */
NULL, /* HB_P_MPOPMEMVAR */
NULL, /* HB_P_MPUSHALIASEDFIELD */
NULL, /* HB_P_MPUSHALIASEDVAR */
NULL, /* HB_P_MPUSHBLOCK */
NULL, /* HB_P_MPUSHFIELD */
NULL, /* HB_P_MPUSHMEMVAR */
NULL, /* HB_P_MPUSHMEMVARREF */
NULL, /* HB_P_MPUSHSYM */
NULL, /* HB_P_MPUSHVARIABLE */
/* end: */
NULL, /* HB_P_MULT */
NULL, /* HB_P_NEGATE */
NULL, /* HB_P_NOOP */
NULL, /* HB_P_NOT */
NULL, /* HB_P_NOTEQUAL */
NULL, /* HB_P_OR */
NULL, /* HB_P_PARAMETER */
NULL, /* HB_P_PLUS */
NULL, /* HB_P_POP */
NULL, /* HB_P_POPALIAS */
NULL, /* HB_P_POPALIASEDFIELD */
NULL, /* HB_P_POPALIASEDFIELDNEAR */
NULL, /* HB_P_POPALIASEDVAR */
NULL, /* HB_P_POPFIELD */
hb_p_localfix, /* HB_P_POPLOCAL */
hb_p_localnearerr, /* HB_P_POPLOCALNEAR */
NULL, /* HB_P_POPMEMVAR */
NULL, /* HB_P_POPSTATIC */
NULL, /* HB_P_POPVARIABLE */
NULL, /* HB_P_POWER */
NULL, /* HB_P_PUSHALIAS */
NULL, /* HB_P_PUSHALIASEDFIELD */
NULL, /* HB_P_PUSHALIASEDFIELDNEAR */
NULL, /* HB_P_PUSHALIASEDVAR */
hb_p_pushblock, /* HB_P_PUSHBLOCK */
NULL, /* HB_P_PUSHBLOCKSHORT */
NULL, /* HB_P_PUSHFIELD */
NULL, /* HB_P_PUSHBYTE */
NULL, /* HB_P_PUSHINT */
hb_p_localfix, /* HB_P_PUSHLOCAL */
hb_p_localnearerr, /* HB_P_PUSHLOCALNEAR */
hb_p_localfix, /* HB_P_PUSHLOCALREF */
NULL, /* HB_P_PUSHLONG */
NULL, /* HB_P_PUSHMEMVAR */
NULL, /* HB_P_PUSHMEMVARREF */
NULL, /* HB_P_PUSHNIL */
NULL, /* HB_P_PUSHDOUBLE */
NULL, /* HB_P_PUSHSELF */
NULL, /* HB_P_PUSHSTATIC */
NULL, /* HB_P_PUSHSTATICREF */
NULL, /* HB_P_PUSHSTR */
NULL, /* HB_P_PUSHSTRSHORT */
NULL, /* HB_P_PUSHSYM */
NULL, /* HB_P_PUSHSYMNEAR */
NULL, /* HB_P_PUSHVARIABLE */
NULL, /* HB_P_RETVALUE */
NULL, /* HB_P_SEND */
NULL, /* HB_P_SENDSHORT */
NULL, /* HB_P_SEQBEGIN */
NULL, /* HB_P_SEQEND */
NULL, /* HB_P_SEQRECOVER */
NULL, /* HB_P_SFRAME */
NULL, /* HB_P_STATICS */
NULL, /* HB_P_STATICNAME */
NULL, /* HB_P_SWAPALIAS */
NULL, /* HB_P_TRUE */
NULL, /* HB_P_ZERO */
NULL, /* HB_P_ONE */
NULL, /* HB_P_MACROFUNC */
NULL, /* HB_P_MACRODO */
NULL, /* HB_P_MPUSHSTR */
hb_p_localnearerr, /* HB_P_LOCALNEARADDINT */
NULL, /* HB_P_MACROPUSHREF */
NULL, /* HB_P_PUSHLONGLONG */
NULL, /* HB_P_ENUMSTART */
NULL, /* HB_P_ENUMNEXT */
NULL, /* HB_P_ENUMPREV */
NULL, /* HB_P_ENUMEND */
NULL, /* HB_P_SWITCH */
NULL, /* HB_P_PUSHDATE */
NULL, /* HB_P_PLUSEQPOP */
NULL, /* HB_P_MINUSEQPOP */
NULL, /* HB_P_MULTEQPOP */
NULL, /* HB_P_DIVEQPOP */
NULL, /* HB_P_PLUSEQ */
NULL, /* HB_P_MINUSEQ */
NULL, /* HB_P_MULTEQ */
NULL, /* HB_P_DIVEQ */
NULL, /* HB_P_WITHOBJECTSTART */
NULL, /* HB_P_WITHOBJECTMESSAGE */
NULL, /* HB_P_WITHOBJECTEND */
NULL, /* HB_P_MACROSEND */
NULL, /* HB_P_PUSHOVARREF */
NULL, /* HB_P_ARRAYPUSHREF */
NULL, /* HB_P_VFRAME */
NULL, /* HB_P_LARGEFRAME */
NULL, /* HB_P_LARGEVFRAME */
NULL, /* HB_P_PUSHSTRHIDDEN */
hb_p_localfix, /* HB_P_LOCALADDINT */
NULL, /* HB_P_MODEQPOP */
NULL, /* HB_P_EXPEQPOP */
NULL, /* HB_P_MODEQ */
NULL, /* HB_P_EXPEQ */
NULL, /* HB_P_DUPLUNREF */
NULL, /* HB_P_MPUSHBLOCKLARGE */
NULL, /* HB_P_MPUSHSTRLARGE */
hb_p_pushblocklarge, /* HB_P_PUSHBLOCKLARGE */
NULL, /* HB_P_PUSHSTRLARGE */
NULL, /* HB_P_SWAP */
NULL, /* HB_P_PUSHVPARAMS */
NULL, /* HB_P_PUSHUNREF */
NULL, /* HB_P_SEQALWAYS */
NULL, /* HB_P_ALWAYSBEGIN */
NULL, /* HB_P_ALWAYSEND */
NULL, /* HB_P_DECEQPOP */
NULL, /* HB_P_INCEQPOP */
NULL, /* HB_P_DECEQ */
NULL, /* HB_P_INCEQ */
hb_p_localfix, /* HB_P_LOCALDEC */
hb_p_localfix, /* HB_P_LOCALINC */
hb_p_localfix, /* HB_P_LOCALINCPUSH */
NULL, /* HB_P_PUSHFUNCSYM */
NULL, /* HB_P_HASHGEN */
NULL, /* HB_P_SEQBLOCK */
NULL, /* HB_P_THREADSTATICS */
NULL /* HB_P_PUSHAPARAMS */
};
void hb_compFixFuncPCode( HB_COMP_DECL, PHB_HFUNC pFunc )
{
const PHB_FIX_FUNC * pFuncTable = s_fixlocals_table;
HB_FIX_INFO fix_info;
fix_info.HB_COMP_PARAM = HB_COMP_PARAM;
assert( HB_P_LAST_PCODE == sizeof( s_fixlocals_table ) / sizeof( PHB_FIX_FUNC ) );
hb_compPCodeEval( pFunc, ( const PHB_PCODE_FUNC * ) pFuncTable, ( void * ) &fix_info );
}
| {
"pile_set_name": "Github"
} |
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = ["fuzzer.go"],
importpath = "k8s.io/kubernetes/pkg/apis/auditregistration/fuzzer",
visibility = ["//visibility:public"],
deps = [
"//pkg/apis/auditregistration:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library",
"//vendor/github.com/google/gofuzz:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
| {
"pile_set_name": "Github"
} |
# -*- mode: snippet -*-
# name: ... := ...
# key: :=
# uuid: :=
# --
${1:x} := ${2:`%`} | {
"pile_set_name": "Github"
} |
# The MIT License
#
# Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Seiji Sogabe
#
# 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.
New\ View=\u65B0\u898F\u30D3\u30E5\u30FC
| {
"pile_set_name": "Github"
} |
#if !__building_module(a) && !BUILDING_A_PCH
#error "should only get here when building module a"
#endif
const int a = 1;
| {
"pile_set_name": "Github"
} |
// Copyright 2018 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,!gccgo
package unix
// SyscallNoError may be used instead of Syscall for syscalls that don't fail.
func SyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr)
// RawSyscallNoError may be used instead of RawSyscall for syscalls that don't
// fail.
func RawSyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr)
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2019, 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.
~
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.marsrealestate">
<!-- In order for our app to access the Internet, we need to define this permission. -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.example.android.marsrealestate.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest> | {
"pile_set_name": "Github"
} |
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.NamingRules
{
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using StyleCop.Analyzers.Helpers;
/// <summary>
/// Implements a code fix for <see cref="SA1316TupleElementNamesShouldUseCorrectCasing"/>.
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SA1316CodeFixProvider))]
[Shared]
internal class SA1316CodeFixProvider : CodeFixProvider
{
/// <inheritdoc/>
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(SA1316TupleElementNamesShouldUseCorrectCasing.DiagnosticId);
/// <inheritdoc/>
public override FixAllProvider GetFixAllProvider()
{
// Fix All is not yet supported
return null;
}
/// <inheritdoc/>
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
if (diagnostic.Properties.TryGetValue(SA1316TupleElementNamesShouldUseCorrectCasing.ExpectedTupleElementNameKey, out string fixedTupleElementName))
{
context.RegisterCodeFix(
CodeAction.Create(
NamingResources.SA1316CodeFix,
cancellationToken => GetTransformedDocumentAsync(context.Document, diagnostic, fixedTupleElementName, cancellationToken),
nameof(SA1316CodeFixProvider)),
diagnostic);
}
}
return SpecializedTasks.CompletedTask;
}
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, string fixedTupleElementName, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var identifierToken = syntaxRoot.FindToken(diagnostic.Location.SourceSpan.Start);
var newSyntaxRoot = syntaxRoot.ReplaceToken(identifierToken, SyntaxFactory.Identifier(fixedTupleElementName).WithTriviaFrom(identifierToken));
return document.WithSyntaxRoot(newSyntaxRoot);
}
}
}
| {
"pile_set_name": "Github"
} |
#  Json.NET
[](https://www.nuget.org/packages/Newtonsoft.Json/)
[](https://dev.azure.com/jamesnk/Public/_build/latest?definitionId=8)
- [Homepage](https://www.newtonsoft.com/json)
- [Documentation](https://www.newtonsoft.com/json/help)
- [NuGet Package](https://www.nuget.org/packages/Newtonsoft.Json)
- [Release Notes](https://github.com/JamesNK/Newtonsoft.Json/releases)
- [Contributing Guidelines](CONTRIBUTING.md)
- [License](LICENSE.md)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/json.net)
| {
"pile_set_name": "Github"
} |
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v1
import (
"context"
"time"
v1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
scheme "k8s.io/client-go/deprecated/scheme"
rest "k8s.io/client-go/rest"
)
// DaemonSetsGetter has a method to return a DaemonSetInterface.
// A group's client should implement this interface.
type DaemonSetsGetter interface {
DaemonSets(namespace string) DaemonSetInterface
}
// DaemonSetInterface has methods to work with DaemonSet resources.
type DaemonSetInterface interface {
Create(*v1.DaemonSet) (*v1.DaemonSet, error)
Update(*v1.DaemonSet) (*v1.DaemonSet, error)
UpdateStatus(*v1.DaemonSet) (*v1.DaemonSet, error)
Delete(name string, options *metav1.DeleteOptions) error
DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error
Get(name string, options metav1.GetOptions) (*v1.DaemonSet, error)
List(opts metav1.ListOptions) (*v1.DaemonSetList, error)
Watch(opts metav1.ListOptions) (watch.Interface, error)
Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.DaemonSet, err error)
DaemonSetExpansion
}
// daemonSets implements DaemonSetInterface
type daemonSets struct {
client rest.Interface
ns string
}
// newDaemonSets returns a DaemonSets
func newDaemonSets(c *AppsV1Client, namespace string) *daemonSets {
return &daemonSets{
client: c.RESTClient(),
ns: namespace,
}
}
// Get takes name of the daemonSet, and returns the corresponding daemonSet object, and an error if there is any.
func (c *daemonSets) Get(name string, options metav1.GetOptions) (result *v1.DaemonSet, err error) {
result = &v1.DaemonSet{}
err = c.client.Get().
Namespace(c.ns).
Resource("daemonsets").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do(context.TODO()).
Into(result)
return
}
// List takes label and field selectors, and returns the list of DaemonSets that match those selectors.
func (c *daemonSets) List(opts metav1.ListOptions) (result *v1.DaemonSetList, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
result = &v1.DaemonSetList{}
err = c.client.Get().
Namespace(c.ns).
Resource("daemonsets").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Do(context.TODO()).
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested daemonSets.
func (c *daemonSets) Watch(opts metav1.ListOptions) (watch.Interface, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Namespace(c.ns).
Resource("daemonsets").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch(context.TODO())
}
// Create takes the representation of a daemonSet and creates it. Returns the server's representation of the daemonSet, and an error, if there is any.
func (c *daemonSets) Create(daemonSet *v1.DaemonSet) (result *v1.DaemonSet, err error) {
result = &v1.DaemonSet{}
err = c.client.Post().
Namespace(c.ns).
Resource("daemonsets").
Body(daemonSet).
Do(context.TODO()).
Into(result)
return
}
// Update takes the representation of a daemonSet and updates it. Returns the server's representation of the daemonSet, and an error, if there is any.
func (c *daemonSets) Update(daemonSet *v1.DaemonSet) (result *v1.DaemonSet, err error) {
result = &v1.DaemonSet{}
err = c.client.Put().
Namespace(c.ns).
Resource("daemonsets").
Name(daemonSet.Name).
Body(daemonSet).
Do(context.TODO()).
Into(result)
return
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *daemonSets) UpdateStatus(daemonSet *v1.DaemonSet) (result *v1.DaemonSet, err error) {
result = &v1.DaemonSet{}
err = c.client.Put().
Namespace(c.ns).
Resource("daemonsets").
Name(daemonSet.Name).
SubResource("status").
Body(daemonSet).
Do(context.TODO()).
Into(result)
return
}
// Delete takes name of the daemonSet and deletes it. Returns an error if one occurs.
func (c *daemonSets) Delete(name string, options *metav1.DeleteOptions) error {
return c.client.Delete().
Namespace(c.ns).
Resource("daemonsets").
Name(name).
Body(options).
Do(context.TODO()).
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *daemonSets) DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error {
var timeout time.Duration
if listOptions.TimeoutSeconds != nil {
timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Namespace(c.ns).
Resource("daemonsets").
VersionedParams(&listOptions, scheme.ParameterCodec).
Timeout(timeout).
Body(options).
Do(context.TODO()).
Error()
}
// Patch applies the patch and returns the patched daemonSet.
func (c *daemonSets) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.DaemonSet, err error) {
result = &v1.DaemonSet{}
err = c.client.Patch(pt).
Namespace(c.ns).
Resource("daemonsets").
SubResource(subresources...).
Name(name).
Body(data).
Do(context.TODO()).
Into(result)
return
}
| {
"pile_set_name": "Github"
} |
#
# Copyright (c) 2008-2016 Haulmont.
#
# 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.
#
#
cardHistoryBrowse.caption=History
cardHistoryBrowse.name=Name
cardHistoryBrowse.createTs=Date
entityOpenHistoryFrame.createTs=Date
entityOpenHistoryFrame.user=User
userMessage=%s on behalf of %s
| {
"pile_set_name": "Github"
} |
# md5 and sha256 from https://pypi.python.org/pypi/docker/json
md5 496237b9e0826eff8436b1a786943a86 docker-3.5.1.tar.gz
sha256 fbe82af9b94ccced752527c8de07fa20267f9634b48674ba478a0bb4000a0b1e docker-3.5.1.tar.gz
sha256 f2f0b07fa5e492c11d27aa0d2f3f1a0e64b9d17f32d8aa489ae2af9609af33b2 LICENSE
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* 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
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <time.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/x509v3.h>
#include <openssl/ocsp.h>
#include "ocsp_lcl.h"
/*
* Utility functions related to sending OCSP requests and extracting relevant
* information from the response.
*/
/*
* Add an OCSP_CERTID to an OCSP request. Return new OCSP_ONEREQ pointer:
* useful if we want to add extensions.
*/
OCSP_ONEREQ *OCSP_request_add0_id(OCSP_REQUEST *req, OCSP_CERTID *cid)
{
OCSP_ONEREQ *one = NULL;
if ((one = OCSP_ONEREQ_new()) == NULL)
return NULL;
OCSP_CERTID_free(one->reqCert);
one->reqCert = cid;
if (req && !sk_OCSP_ONEREQ_push(req->tbsRequest.requestList, one)) {
one->reqCert = NULL; /* do not free on error */
goto err;
}
return one;
err:
OCSP_ONEREQ_free(one);
return NULL;
}
/* Set requestorName from an X509_NAME structure */
int OCSP_request_set1_name(OCSP_REQUEST *req, X509_NAME *nm)
{
GENERAL_NAME *gen;
gen = GENERAL_NAME_new();
if (gen == NULL)
return 0;
if (!X509_NAME_set(&gen->d.directoryName, nm)) {
GENERAL_NAME_free(gen);
return 0;
}
gen->type = GEN_DIRNAME;
GENERAL_NAME_free(req->tbsRequest.requestorName);
req->tbsRequest.requestorName = gen;
return 1;
}
/* Add a certificate to an OCSP request */
int OCSP_request_add1_cert(OCSP_REQUEST *req, X509 *cert)
{
OCSP_SIGNATURE *sig;
if (req->optionalSignature == NULL)
req->optionalSignature = OCSP_SIGNATURE_new();
sig = req->optionalSignature;
if (sig == NULL)
return 0;
if (cert == NULL)
return 1;
if (sig->certs == NULL
&& (sig->certs = sk_X509_new_null()) == NULL)
return 0;
if (!sk_X509_push(sig->certs, cert))
return 0;
X509_up_ref(cert);
return 1;
}
/*
* Sign an OCSP request set the requestorName to the subject name of an
* optional signers certificate and include one or more optional certificates
* in the request. Behaves like PKCS7_sign().
*/
int OCSP_request_sign(OCSP_REQUEST *req,
X509 *signer,
EVP_PKEY *key,
const EVP_MD *dgst,
STACK_OF(X509) *certs, unsigned long flags)
{
int i;
X509 *x;
if (!OCSP_request_set1_name(req, X509_get_subject_name(signer)))
goto err;
if ((req->optionalSignature = OCSP_SIGNATURE_new()) == NULL)
goto err;
if (key) {
if (!X509_check_private_key(signer, key)) {
OCSPerr(OCSP_F_OCSP_REQUEST_SIGN,
OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
goto err;
}
if (!OCSP_REQUEST_sign(req, key, dgst))
goto err;
}
if (!(flags & OCSP_NOCERTS)) {
if (!OCSP_request_add1_cert(req, signer))
goto err;
for (i = 0; i < sk_X509_num(certs); i++) {
x = sk_X509_value(certs, i);
if (!OCSP_request_add1_cert(req, x))
goto err;
}
}
return 1;
err:
OCSP_SIGNATURE_free(req->optionalSignature);
req->optionalSignature = NULL;
return 0;
}
/* Get response status */
int OCSP_response_status(OCSP_RESPONSE *resp)
{
return ASN1_ENUMERATED_get(resp->responseStatus);
}
/*
* Extract basic response from OCSP_RESPONSE or NULL if no basic response
* present.
*/
OCSP_BASICRESP *OCSP_response_get1_basic(OCSP_RESPONSE *resp)
{
OCSP_RESPBYTES *rb;
rb = resp->responseBytes;
if (!rb) {
OCSPerr(OCSP_F_OCSP_RESPONSE_GET1_BASIC, OCSP_R_NO_RESPONSE_DATA);
return NULL;
}
if (OBJ_obj2nid(rb->responseType) != NID_id_pkix_OCSP_basic) {
OCSPerr(OCSP_F_OCSP_RESPONSE_GET1_BASIC, OCSP_R_NOT_BASIC_RESPONSE);
return NULL;
}
return ASN1_item_unpack(rb->response, ASN1_ITEM_rptr(OCSP_BASICRESP));
}
const ASN1_OCTET_STRING *OCSP_resp_get0_signature(const OCSP_BASICRESP *bs)
{
return bs->signature;
}
const X509_ALGOR *OCSP_resp_get0_tbs_sigalg(const OCSP_BASICRESP *bs)
{
return &bs->signatureAlgorithm;
}
const OCSP_RESPDATA *OCSP_resp_get0_respdata(const OCSP_BASICRESP *bs)
{
return &bs->tbsResponseData;
}
/*
* Return number of OCSP_SINGLERESP responses present in a basic response.
*/
int OCSP_resp_count(OCSP_BASICRESP *bs)
{
if (!bs)
return -1;
return sk_OCSP_SINGLERESP_num(bs->tbsResponseData.responses);
}
/* Extract an OCSP_SINGLERESP response with a given index */
OCSP_SINGLERESP *OCSP_resp_get0(OCSP_BASICRESP *bs, int idx)
{
if (!bs)
return NULL;
return sk_OCSP_SINGLERESP_value(bs->tbsResponseData.responses, idx);
}
const ASN1_GENERALIZEDTIME *OCSP_resp_get0_produced_at(const OCSP_BASICRESP* bs)
{
return bs->tbsResponseData.producedAt;
}
const STACK_OF(X509) *OCSP_resp_get0_certs(const OCSP_BASICRESP *bs)
{
return bs->certs;
}
int OCSP_resp_get0_id(const OCSP_BASICRESP *bs,
const ASN1_OCTET_STRING **pid,
const X509_NAME **pname)
{
const OCSP_RESPID *rid = &bs->tbsResponseData.responderId;
if (rid->type == V_OCSP_RESPID_NAME) {
*pname = rid->value.byName;
*pid = NULL;
} else if (rid->type == V_OCSP_RESPID_KEY) {
*pid = rid->value.byKey;
*pname = NULL;
} else {
return 0;
}
return 1;
}
int OCSP_resp_get1_id(const OCSP_BASICRESP *bs,
ASN1_OCTET_STRING **pid,
X509_NAME **pname)
{
const OCSP_RESPID *rid = &bs->tbsResponseData.responderId;
if (rid->type == V_OCSP_RESPID_NAME) {
*pname = X509_NAME_dup(rid->value.byName);
*pid = NULL;
} else if (rid->type == V_OCSP_RESPID_KEY) {
*pid = ASN1_OCTET_STRING_dup(rid->value.byKey);
*pname = NULL;
} else {
return 0;
}
if (*pname == NULL && *pid == NULL)
return 0;
return 1;
}
/* Look single response matching a given certificate ID */
int OCSP_resp_find(OCSP_BASICRESP *bs, OCSP_CERTID *id, int last)
{
int i;
STACK_OF(OCSP_SINGLERESP) *sresp;
OCSP_SINGLERESP *single;
if (!bs)
return -1;
if (last < 0)
last = 0;
else
last++;
sresp = bs->tbsResponseData.responses;
for (i = last; i < sk_OCSP_SINGLERESP_num(sresp); i++) {
single = sk_OCSP_SINGLERESP_value(sresp, i);
if (!OCSP_id_cmp(id, single->certId))
return i;
}
return -1;
}
/*
* Extract status information from an OCSP_SINGLERESP structure. Note: the
* revtime and reason values are only set if the certificate status is
* revoked. Returns numerical value of status.
*/
int OCSP_single_get0_status(OCSP_SINGLERESP *single, int *reason,
ASN1_GENERALIZEDTIME **revtime,
ASN1_GENERALIZEDTIME **thisupd,
ASN1_GENERALIZEDTIME **nextupd)
{
int ret;
OCSP_CERTSTATUS *cst;
if (!single)
return -1;
cst = single->certStatus;
ret = cst->type;
if (ret == V_OCSP_CERTSTATUS_REVOKED) {
OCSP_REVOKEDINFO *rev = cst->value.revoked;
if (revtime)
*revtime = rev->revocationTime;
if (reason) {
if (rev->revocationReason)
*reason = ASN1_ENUMERATED_get(rev->revocationReason);
else
*reason = -1;
}
}
if (thisupd)
*thisupd = single->thisUpdate;
if (nextupd)
*nextupd = single->nextUpdate;
return ret;
}
/*
* This function combines the previous ones: look up a certificate ID and if
* found extract status information. Return 0 is successful.
*/
int OCSP_resp_find_status(OCSP_BASICRESP *bs, OCSP_CERTID *id, int *status,
int *reason,
ASN1_GENERALIZEDTIME **revtime,
ASN1_GENERALIZEDTIME **thisupd,
ASN1_GENERALIZEDTIME **nextupd)
{
int i;
OCSP_SINGLERESP *single;
i = OCSP_resp_find(bs, id, -1);
/* Maybe check for multiple responses and give an error? */
if (i < 0)
return 0;
single = OCSP_resp_get0(bs, i);
i = OCSP_single_get0_status(single, reason, revtime, thisupd, nextupd);
if (status)
*status = i;
return 1;
}
/*
* Check validity of thisUpdate and nextUpdate fields. It is possible that
* the request will take a few seconds to process and/or the time won't be
* totally accurate. Therefore to avoid rejecting otherwise valid time we
* allow the times to be within 'nsec' of the current time. Also to avoid
* accepting very old responses without a nextUpdate field an optional maxage
* parameter specifies the maximum age the thisUpdate field can be.
*/
int OCSP_check_validity(ASN1_GENERALIZEDTIME *thisupd,
ASN1_GENERALIZEDTIME *nextupd, long nsec, long maxsec)
{
int ret = 1;
time_t t_now, t_tmp;
time(&t_now);
/* Check thisUpdate is valid and not more than nsec in the future */
if (!ASN1_GENERALIZEDTIME_check(thisupd)) {
OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY, OCSP_R_ERROR_IN_THISUPDATE_FIELD);
ret = 0;
} else {
t_tmp = t_now + nsec;
if (X509_cmp_time(thisupd, &t_tmp) > 0) {
OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY, OCSP_R_STATUS_NOT_YET_VALID);
ret = 0;
}
/*
* If maxsec specified check thisUpdate is not more than maxsec in
* the past
*/
if (maxsec >= 0) {
t_tmp = t_now - maxsec;
if (X509_cmp_time(thisupd, &t_tmp) < 0) {
OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY, OCSP_R_STATUS_TOO_OLD);
ret = 0;
}
}
}
if (!nextupd)
return ret;
/* Check nextUpdate is valid and not more than nsec in the past */
if (!ASN1_GENERALIZEDTIME_check(nextupd)) {
OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY, OCSP_R_ERROR_IN_NEXTUPDATE_FIELD);
ret = 0;
} else {
t_tmp = t_now - nsec;
if (X509_cmp_time(nextupd, &t_tmp) < 0) {
OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY, OCSP_R_STATUS_EXPIRED);
ret = 0;
}
}
/* Also don't allow nextUpdate to precede thisUpdate */
if (ASN1_STRING_cmp(nextupd, thisupd) < 0) {
OCSPerr(OCSP_F_OCSP_CHECK_VALIDITY,
OCSP_R_NEXTUPDATE_BEFORE_THISUPDATE);
ret = 0;
}
return ret;
}
const OCSP_CERTID *OCSP_SINGLERESP_get0_id(const OCSP_SINGLERESP *single)
{
return single->certId;
}
| {
"pile_set_name": "Github"
} |
package main
import (
"machine"
"time"
"tinygo.org/x/drivers/lsm303agr"
)
func main() {
machine.I2C0.Configure(machine.I2CConfig{})
accel_mag := lsm303agr.New(machine.I2C0)
if !accel_mag.Connected() {
println("LSM303AGR/MAG not connected!")
return
}
accel_mag.Configure(lsm303agr.Configuration{}) //default settings
for {
accel_x, accel_y, accel_z := accel_mag.ReadAcceleration()
pitch, roll := accel_mag.ReadPitchRoll()
mag_x, mag_y, mag_z := accel_mag.ReadMagneticField()
heading := accel_mag.ReadCompass()
temp, _ := accel_mag.ReadTemperature()
println("ACCEL_X:", accel_x, " ACCEL_Y:", accel_y, " ACCEL_Z:", accel_z)
println("MAG_X:", mag_x, " MAG_Y:", mag_y, " MAG_Z:", mag_z)
println("Pitch:", pitch, " Roll:", roll)
println("Heading:", heading)
println("Temperature:", temp/1000)
println("\n")
time.Sleep(time.Millisecond * 100)
}
}
| {
"pile_set_name": "Github"
} |
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
#ifndef SHAPE_ANIMATION_ASSET_H
#define SHAPE_ANIMATION_ASSET_H
#ifndef _ASSET_BASE_H_
#include "assets/assetBase.h"
#endif
#ifndef _ASSET_DEFINITION_H_
#include "assets/assetDefinition.h"
#endif
#ifndef _STRINGUNIT_H_
#include "string/stringUnit.h"
#endif
#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
#ifndef _TSSHAPE_H_
#include "ts/tsShape.h"
#endif
#ifndef __RESOURCE_H__
#include "core/resource.h"
#endif
//-----------------------------------------------------------------------------
class ShapeAnimationAsset : public AssetBase
{
typedef AssetBase Parent;
protected:
StringTableEntry mFileName;
bool mIsEmbedded;
bool mIsCyclical;
bool mIsBlend;
StringTableEntry mBlendAnimAssetName;
S32 mBlendFrame;
//
StringTableEntry mAnimationName;
S32 mStartFrame;
S32 mEndFrame;
bool mPadRotation;
bool mPadTransforms;
Resource<TSShape> mSourceShape;
public:
ShapeAnimationAsset();
virtual ~ShapeAnimationAsset();
/// Engine.
static void initPersistFields();
virtual void copyTo(SimObject* object);
/// Declare Console Object.
DECLARE_CONOBJECT(ShapeAnimationAsset);
protected:
virtual void initializeAsset(void);
virtual void onAssetRefresh(void);
public:
StringTableEntry getAnimationFilename() { return mFileName; }
StringTableEntry getAnimationName() { return mAnimationName; }
StringTableEntry getBlendAnimationName() { return mBlendAnimAssetName; }
S32 getStartFrame() { return mStartFrame; }
S32 getEndFrame() { return mEndFrame; }
bool getPadRotation() { return mPadRotation; }
bool getPadTransforms() { return mPadTransforms; }
bool isEmbedded() { return mIsEmbedded; }
bool isCyclic() { return mIsCyclical; }
bool isBlend() { return mIsBlend; }
S32 getBlendFrame() { return mBlendFrame; }
};
DefineConsoleType(TypeShapeAnimationAssetPtr, ShapeAnimationAsset)
//-----------------------------------------------------------------------------
// TypeAssetId GuiInspectorField Class
//-----------------------------------------------------------------------------
/*class GuiInspectorTypeShapeAnimationAssetPtr : public GuiInspectorTypeFileName
{
typedef GuiInspectorTypeFileName Parent;
public:
GuiBitmapButtonCtrl *mShapeEdButton;
DECLARE_CONOBJECT(GuiInspectorTypeShapeAnimationAssetPtr);
static void consoleInit();
virtual GuiControl* constructEditControl();
virtual bool updateRects();
};*/
#endif // _ASSET_BASE_H_
| {
"pile_set_name": "Github"
} |
A: [1, 3, 5]
| {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Integration\Test\Constraint;
use Magento\Integration\Test\Fixture\Integration;
use Magento\Integration\Test\Page\Adminhtml\IntegrationIndex;
use Magento\Mtf\Constraint\AbstractConstraint;
/**
* Class AssertIntegrationInGrid
* Assert Integration availability in integration grid
*/
class AssertIntegrationInGrid extends AbstractConstraint
{
/**
* Assert that data in grid on Integrations page according to fixture by name field
*
* @param IntegrationIndex $integrationIndexPage
* @param Integration $integration
* @param Integration|null $initialIntegration
* @return void
*/
public function processAssert(
IntegrationIndex $integrationIndexPage,
Integration $integration,
Integration $initialIntegration = null
) {
$filter = [
'name' => ($initialIntegration !== null && !$integration->hasData('name'))
? $initialIntegration->getName()
: $integration->getName(),
];
$integrationIndexPage->open();
\PHPUnit\Framework\Assert::assertTrue(
$integrationIndexPage->getIntegrationGrid()->isRowVisible($filter),
'Integration \'' . $filter['name'] . '\' is absent in Integration grid.'
);
}
/**
* Returns a string representation of successful assertion
*
* @return string
*/
public function toString()
{
return 'Integration is present in grid.';
}
}
| {
"pile_set_name": "Github"
} |
%
% Pigeon hole problem in MiniZinc.
% ftp://ftp.inria.fr/INRIA/Projects/contraintes/publications/CLP-FD/plilp94.html
% """
% pigeon: the pigeon-hole problem consists in putting n pigeons in m pigeon-holes (at most 1 pigeon per hole). The boolean formulation uses n × m variables to indicate, for each pigeon, its hole number. Obviously, there is a solution iff n <= m.
% """
%
% Model created by Hakan Kjellerstrand, [email protected]
% See also my MiniZinc page: http://www.hakank.org/minizinc
include "globals.mzn";
int: N = 2; % N pigeons
int: M = 10; % M pigeon holes
% i pigeon at j pigeon holes
array[1..N,1..M] of var 0..1: pigeon_holes_ip;
%
% integer programming version
%
predicate pigeon_ip(int: N, int: M, array[1..N, 1..M] of var 0..1: p) =
% max 1 pigeon per pigeon hole
forall(j in 1..M) (
sum([p[i,j] | i in 1..N]) <= 1
)
/\ % all pigeon must be placed and only at one hole
forall(i in 1..N) (
sum([p[i,j] | j in 1..M]) = 1
)
;
solve satisfy;
constraint
% integer programming version
pigeon_ip(N, M, pigeon_holes_ip)
% /\ pigeon_holes_ip[1,1] = 1 % some symmetry breaking
;
output [
if j = 1 then "\n" else " " endif ++
show(pigeon_holes_ip[i,j]) ++ " "
| i in 1..N, j in 1..M
] ++ ["\n"];
| {
"pile_set_name": "Github"
} |
Redmine is a flexible project management web application. Written using
the Ruby on Rails framework, it is cross-platform and cross-database.
Some of the main features of Redmine are:
* Flexible role based access control
* Flexible issue tracking system
* Gantt chart and calendar
* News, documents & files management
* Feeds & email notifications
* Per project wiki and forums
* Time tracking
* Custom fields for issues, time-entries, projects and users
* SCM integration (SVN, CVS, Git, Mercurial, Bazaar and Darcs)
* Issue creation via email
* Multiple LDAP authentication support
* User self-registration support
* Multilanguage support
| {
"pile_set_name": "Github"
} |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RandomIdPage.aspx.cs" Inherits="Wa45Aspx.RandomIdPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RandomIdPageTitle</title>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 389px">
<label id="label1" runat="server">---</label>
</div>
</form>
</body>
</html>
| {
"pile_set_name": "Github"
} |
#import "SWGObject.h"
@implementation SWGObject
/**
* Workaround for JSONModel multithreading issues
* https://github.com/icanzilb/JSONModel/issues/441
*/
- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err {
static NSMutableSet *classNames;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
classNames = [NSMutableSet new];
});
BOOL initSync;
@synchronized([self class])
{
NSString *className = NSStringFromClass([self class]);
initSync = ![classNames containsObject:className];
if(initSync)
{
[classNames addObject:className];
self = [super initWithDictionary:dict error:err];
}
}
if(!initSync)
{
self = [super initWithDictionary:dict error:err];
}
return self;
}
/**
* Gets the string presentation of the object.
* This method will be called when logging model object using `NSLog`.
*/
- (NSString *)description {
return [[self toDictionary] description];
}
@end
| {
"pile_set_name": "Github"
} |
// Copyright 2013 the V8 project authors. All rights reserved.
// Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
description(
'Test regular expression processing with many capturing brackets (200).'
);
var count = 200;
var regexp = "";
for (var i = 0; i < count; ++i)
regexp += "(";
regexp += "hello";
for (var i = 0; i < count; ++i)
regexp += ")";
var manyHellosArray = new Array;
for (var i = 0; i <= count; ++i)
manyHellosArray[i] = "hello";
var manyBracketsRegExp = new RegExp(regexp);
shouldBe("'hello'.match(manyBracketsRegExp)", "manyHellosArray");
debug('');
| {
"pile_set_name": "Github"
} |
[{
"http://example.org/input": [{
"@graph": [{
"http://example.org/value": [{"@value": "x"}]
}],
"@index": "ndx"
}]
}] | {
"pile_set_name": "Github"
} |
1 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
2 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
3 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
4 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
5 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
6 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
7 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
8 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
9 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
10 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
11 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
12 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
13 05:27:12.808464432 30:30:30:30:30:30 > 30:30:30:30:30:30, ethertype Unknown (0x3030), length 262144:
0x0000: 3030 3030 30 00000
14 05:27:12.808464432 [|stp]
| {
"pile_set_name": "Github"
} |
{
"client" : {
"version" : "0.1",
"url" : "http://wepieces.cn/unity/zero/demo/zero.exe"
},
"netResRoot" : "http://wepieces.cn/unity/zero/demo/res",
"startupResGroups" : [
"/"
],
"startupParams" : {
"host" : "0.0.0.0",
"port" : "9999"
}
} | {
"pile_set_name": "Github"
} |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH & Co. KG, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.test;
import org.opencms.i18n.A_CmsMessageBundle;
import org.opencms.i18n.I_CmsMessageBundle;
/**
* Convenience class to access the localized messages of this OpenCms package.<p>
*
* @since 6.0.0
*/
public final class Messages extends A_CmsMessageBundle {
/** Message constant for key in the resource bundle. */
public static final String ERR_RESOURCE_STORAGE_NOT_FOUND_0 = "ERR_RESOURCE_STORAGE_NOT_FOUND_0";
/** Name of the used resource bundle. */
private static final String BUNDLE_NAME = "org.opencms.test.messages";
/** Static instance member. */
private static final I_CmsMessageBundle INSTANCE = new Messages();
/** Message constant for key in the resource bundle. */
public static final String ERR_MISSING_CLASSLOADER_RESOURCE_1 = "ERR_MISSING_CLASSLOADER_RESOURCE_1";
/** Message constant for key in the resource bundle. */
public static final String ERR_MISSING_CLASSLOADER_RESOURCE_2 = "ERR_MISSING_CLASSLOADER_RESOURCE_2";
/**
* Hides the public constructor for this utility class.<p>
*/
private Messages() {
// hide the constructor
}
/**
* Returns an instance of this localized message accessor.<p>
*
* @return an instance of this localized message accessor
*/
public static I_CmsMessageBundle get() {
return INSTANCE;
}
/**
* Returns the bundle name for this OpenCms package.<p>
*
* @return the bundle name for this OpenCms package
*/
public String getBundleName() {
return BUNDLE_NAME;
}
} | {
"pile_set_name": "Github"
} |
TARGET = toggl
TEMPLATE = lib
SOURCES += *.cc
HEADERS += *.h
headers.files = $$HEADERS
headers.path = $$PREFIX/include
target.path = $$PREFIX/lib
INSTALLS += headers target
CONFIG += create_prl create_pc link_pkgconfig
PKGCONFIG += jsoncpp openssl lua poco sqlite3 x11
QMAKE_PKGCONFIG_NAME = $$TARGET
QMAKE_PKGCONFIG_PREFIX = $$PREFIX
QMAKE_PKGCONFIG_LIBDIR = $$target.path
QMAKE_PKGCONFIG_INCDIR = $$headers.path
QMAKE_PKGCONFIG_DESTDIR = pkgconfig
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include <folly/IPAddress.h>
#include "common/network/if/gen-cpp2/Address_types.h"
namespace facebook::network {
// Trait for V4 vs V6
template <typename T>
struct IPVersion;
template <>
struct IPVersion<folly::IPAddressV4> {
static const thrift::AddressType value = thrift::AddressType::V4;
};
template <>
struct IPVersion<folly::IPAddressV6> {
static const thrift::AddressType value = thrift::AddressType::V6;
};
template <class T>
thrift::Address toAddressImpl(const T& addr) {
thrift::Address result;
result.addr = addr.toFullyQualified();
result.type = IPVersion<T>::value;
return result;
}
inline thrift::Address toAddress(const folly::IPAddress& ip) {
return ip.isV4() ? toAddressImpl(ip.asV4())
: ip.isV6() ? toAddressImpl(ip.asV6()) : thrift::Address();
}
template <class IPAddressVx>
thrift::BinaryAddress toBinaryAddressImpl(const IPAddressVx& addr) {
thrift::BinaryAddress result;
result.addr.append(
reinterpret_cast<const char*>(addr.bytes()), IPAddressVx::byteCount());
return result;
}
inline thrift::BinaryAddress toBinaryAddress(const folly::IPAddress& addr) {
return addr.isV4() ? toBinaryAddressImpl(addr.asV4())
: addr.isV6() ? toBinaryAddressImpl(addr.asV6())
: thrift::BinaryAddress();
}
template <typename T>
inline folly::IPAddress toIPAddress(const T& input) {
return input.type != decltype(input.type)::VUNSPEC
? folly::IPAddress(input.addr)
: folly::IPAddress();
}
inline folly::IPAddress toIPAddress(const thrift::BinaryAddress& addr) {
return folly::IPAddress::fromBinary(folly::ByteRange(
reinterpret_cast<const unsigned char*>(addr.addr.data()),
addr.addr.size()));
}
} // namespace facebook::network
| {
"pile_set_name": "Github"
} |
//
// detail/impl/service_registry.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_DETAIL_IMPL_SERVICE_REGISTRY_IPP
#define ASIO_DETAIL_IMPL_SERVICE_REGISTRY_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <vector>
#include "asio/detail/service_registry.hpp"
#include "asio/detail/throw_exception.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
service_registry::service_registry(execution_context& owner)
: owner_(owner),
first_service_(0)
{
}
service_registry::~service_registry()
{
}
void service_registry::shutdown_services()
{
execution_context::service* service = first_service_;
while (service)
{
service->shutdown();
service = service->next_;
}
}
void service_registry::destroy_services()
{
while (first_service_)
{
execution_context::service* next_service = first_service_->next_;
destroy(first_service_);
first_service_ = next_service;
}
}
void service_registry::notify_fork(execution_context::fork_event fork_ev)
{
// Make a copy of all of the services while holding the lock. We don't want
// to hold the lock while calling into each service, as it may try to call
// back into this class.
std::vector<execution_context::service*> services;
{
asio::detail::mutex::scoped_lock lock(mutex_);
execution_context::service* service = first_service_;
while (service)
{
services.push_back(service);
service = service->next_;
}
}
// If processing the fork_prepare event, we want to go in reverse order of
// service registration, which happens to be the existing order of the
// services in the vector. For the other events we want to go in the other
// direction.
std::size_t num_services = services.size();
if (fork_ev == execution_context::fork_prepare)
for (std::size_t i = 0; i < num_services; ++i)
services[i]->notify_fork(fork_ev);
else
for (std::size_t i = num_services; i > 0; --i)
services[i - 1]->notify_fork(fork_ev);
}
void service_registry::init_key(execution_context::service::key& key,
const execution_context::id& id)
{
key.type_info_ = 0;
key.id_ = &id;
}
bool service_registry::keys_match(
const execution_context::service::key& key1,
const execution_context::service::key& key2)
{
if (key1.id_ && key2.id_)
if (key1.id_ == key2.id_)
return true;
if (key1.type_info_ && key2.type_info_)
if (*key1.type_info_ == *key2.type_info_)
return true;
return false;
}
void service_registry::destroy(execution_context::service* service)
{
delete service;
}
execution_context::service* service_registry::do_use_service(
const execution_context::service::key& key,
factory_type factory, void* owner)
{
asio::detail::mutex::scoped_lock lock(mutex_);
// First see if there is an existing service object with the given key.
execution_context::service* service = first_service_;
while (service)
{
if (keys_match(service->key_, key))
return service;
service = service->next_;
}
// Create a new service object. The service registry's mutex is not locked
// at this time to allow for nested calls into this function from the new
// service's constructor.
lock.unlock();
auto_service_ptr new_service = { factory(owner) };
new_service.ptr_->key_ = key;
lock.lock();
// Check that nobody else created another service object of the same type
// while the lock was released.
service = first_service_;
while (service)
{
if (keys_match(service->key_, key))
return service;
service = service->next_;
}
// Service was successfully initialised, pass ownership to registry.
new_service.ptr_->next_ = first_service_;
first_service_ = new_service.ptr_;
new_service.ptr_ = 0;
return first_service_;
}
void service_registry::do_add_service(
const execution_context::service::key& key,
execution_context::service* new_service)
{
if (&owner_ != &new_service->context())
asio::detail::throw_exception(invalid_service_owner());
asio::detail::mutex::scoped_lock lock(mutex_);
// Check if there is an existing service object with the given key.
execution_context::service* service = first_service_;
while (service)
{
if (keys_match(service->key_, key))
asio::detail::throw_exception(service_already_exists());
service = service->next_;
}
// Take ownership of the service object.
new_service->key_ = key;
new_service->next_ = first_service_;
first_service_ = new_service;
}
bool service_registry::do_has_service(
const execution_context::service::key& key) const
{
asio::detail::mutex::scoped_lock lock(mutex_);
execution_context::service* service = first_service_;
while (service)
{
if (keys_match(service->key_, key))
return true;
service = service->next_;
}
return false;
}
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_DETAIL_IMPL_SERVICE_REGISTRY_IPP
| {
"pile_set_name": "Github"
} |
#!/usr/bin/perl
##########################################################################
# nagios_plugin_wrapper
#
# Executes the given nagios plugin and produces an XML with data for pandora
# to be used as agent plugin. This allows to have DATA based on the errorlevel
# and use the descriptive information on description for the module
#
# Usage: nagios_plugin_wrapper <module_name> <nagios plugin execution with its parameters>
##########################################################################
# Copyright (c) 2010 Artica Soluciones Tecnologicas S.L
#
# 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; version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
##########################################################################
use strict;
use warnings;
my $command = "";
my @opts = @ARGV;
my $module_name = shift(@opts);
$command = join(' ', @opts);
if ($command ne ""){
my $module_data = `$command`;
my $module_description = $module_data;
my $ReturnCode = ($? >> 8) & 0xff;
# Get the errorlevel if is a Nagios plugin type (parsing the errorlevel)
# Nagios errorlevels:
#('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3,'DEPENDENT'=>4);
# By default is unknown
$module_data = "";
if ($ReturnCode == 2){
$module_data = 0;
}
elsif ($ReturnCode == 3){
$module_data = ''; # not defined = Uknown
}
elsif ($ReturnCode == 0){
$module_data = 1;
}
elsif ($ReturnCode == 1){
$module_data = 2; # need to be managed on module thresholds
}
elsif ($ReturnCode == 4){
$module_data = 3; # need to be managed on module thresholds
}
print "<module>";
print "<name><![CDATA[".$module_name."]]></name>\n";
print "<type><![CDATA[generic_proc]]></type>\n";
print "<data><![CDATA[".$module_data."]]></data>\n";
print "<description><![CDATA[" . $module_description . "]]></description>\n";
print "</module>\n";
}
| {
"pile_set_name": "Github"
} |
[
{
"BriefDescription": "Cycles per thread when 4 or more uops are not delivered to Resource Allocation Table (RAT) when backend of the machine is not stalled",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "4",
"EventCode": "0x9C",
"EventName": "IDQ_UOPS_NOT_DELIVERED.CYCLES_0_UOPS_DELIV.CORE",
"PublicDescription": "Counts, on the per-thread basis, cycles when no uops are delivered to Resource Allocation Table (RAT). IDQ_Uops_Not_Delivered.core =4.",
"SampleAfterValue": "2000003",
"UMask": "0x1"
},
{
"BriefDescription": "Retired Instructions who experienced Instruction L2 Cache true miss.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.L2_MISS",
"MSRIndex": "0x3F7",
"MSRValue": "0x13",
"PEBS": "1",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Uops initiated by MITE and delivered to Instruction Decode Queue (IDQ) while Microcode Sequenser (MS) is busy",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"EventCode": "0x79",
"EventName": "IDQ.MS_MITE_UOPS",
"PublicDescription": "Counts the number of uops initiated by MITE and delivered to Instruction Decode Queue (IDQ) while the Microcode Sequencer (MS) is busy. Counting includes uops that may 'bypass' the IDQ.",
"SampleAfterValue": "2000003",
"UMask": "0x20"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end had at least 2 bubble-slots for a period of 2 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_2_BUBBLES_GE_2",
"MSRIndex": "0x3F7",
"MSRValue": "0x200206",
"PEBS": "1",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end had at least 3 bubble-slots for a period of 2 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_2_BUBBLES_GE_3",
"MSRIndex": "0x3F7",
"MSRValue": "0x300206",
"PEBS": "1",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end had at least 1 bubble-slot for a period of 2 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_2_BUBBLES_GE_1",
"MSRIndex": "0x3F7",
"MSRValue": "0x100206",
"PEBS": "1",
"PublicDescription": "Counts retired instructions that are delivered to the back-end after the front-end had at least 1 bubble-slot for a period of 2 cycles. A bubble-slot is an empty issue-pipeline slot while there was no RAT stall.",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Counts cycles FE delivered 4 uops or Resource Allocation Table (RAT) was stalling FE.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "1",
"EventCode": "0x9C",
"EventName": "IDQ_UOPS_NOT_DELIVERED.CYCLES_FE_WAS_OK",
"Invert": "1",
"SampleAfterValue": "2000003",
"UMask": "0x1"
},
{
"BriefDescription": "Uops delivered to Instruction Decode Queue (IDQ) while Microcode Sequenser (MS) is busy",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"EventCode": "0x79",
"EventName": "IDQ.MS_UOPS",
"PublicDescription": "Counts the total number of uops delivered by the Microcode Sequencer (MS). Any instruction over 4 uops will be delivered by the MS. Some instructions such as transcendentals may additionally generate uops from the MS.",
"SampleAfterValue": "2000003",
"UMask": "0x30"
},
{
"BriefDescription": "Retired Instructions who experienced Instruction L1 Cache true miss.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.L1I_MISS",
"MSRIndex": "0x3F7",
"MSRValue": "0x12",
"PEBS": "1",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Cycles with less than 3 uops delivered by the front end.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "1",
"EventCode": "0x9C",
"EventName": "IDQ_UOPS_NOT_DELIVERED.CYCLES_LE_3_UOP_DELIV.CORE",
"PublicDescription": "Cycles with less than 3 uops delivered by the front-end.",
"SampleAfterValue": "2000003",
"UMask": "0x1"
},
{
"BriefDescription": "Cycles when uops are being delivered to Instruction Decode Queue (IDQ) from Decode Stream Buffer (DSB) path",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "1",
"EventCode": "0x79",
"EventName": "IDQ.DSB_CYCLES",
"PublicDescription": "Counts cycles during which uops are being delivered to Instruction Decode Queue (IDQ) from the Decode Stream Buffer (DSB) path. Counting includes uops that may 'bypass' the IDQ.",
"SampleAfterValue": "2000003",
"UMask": "0x8"
},
{
"BriefDescription": "Retired Instructions who experienced decode stream buffer (DSB - the decoded instruction-cache) miss.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.DSB_MISS",
"MSRIndex": "0x3F7",
"MSRValue": "0x11",
"PEBS": "1",
"PublicDescription": "Counts retired Instructions that experienced DSB (Decode stream buffer i.e. the decoded instruction-cache) miss.",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Uops delivered to Instruction Decode Queue (IDQ) from MITE path",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"EventCode": "0x79",
"EventName": "IDQ.MITE_UOPS",
"PublicDescription": "Counts the number of uops delivered to Instruction Decode Queue (IDQ) from the MITE path. Counting includes uops that may 'bypass' the IDQ. This also means that uops are not being delivered from the Decode Stream Buffer (DSB).",
"SampleAfterValue": "2000003",
"UMask": "0x4"
},
{
"BriefDescription": "Cycles when uops are being delivered to Instruction Decode Queue (IDQ) while Microcode Sequenser (MS) is busy",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "1",
"EventCode": "0x79",
"EventName": "IDQ.MS_CYCLES",
"PublicDescription": "Counts cycles during which uops are being delivered to Instruction Decode Queue (IDQ) while the Microcode Sequencer (MS) is busy. Counting includes uops that may 'bypass' the IDQ. Uops maybe initiated by Decode Stream Buffer (DSB) or MITE.",
"SampleAfterValue": "2000003",
"UMask": "0x30"
},
{
"BriefDescription": "Cycles when uops are being delivered to Instruction Decode Queue (IDQ) from MITE path",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "1",
"EventCode": "0x79",
"EventName": "IDQ.MITE_CYCLES",
"PublicDescription": "Counts cycles during which uops are being delivered to Instruction Decode Queue (IDQ) from the MITE path. Counting includes uops that may 'bypass' the IDQ.",
"SampleAfterValue": "2000003",
"UMask": "0x4"
},
{
"BriefDescription": "Uops not delivered to Resource Allocation Table (RAT) per thread when backend of the machine is not stalled",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"EventCode": "0x9C",
"EventName": "IDQ_UOPS_NOT_DELIVERED.CORE",
"PublicDescription": "Counts the number of uops not delivered to Resource Allocation Table (RAT) per thread adding 4 x when Resource Allocation Table (RAT) is not stalled and Instruction Decode Queue (IDQ) delivers x uops to Resource Allocation Table (RAT) (where x belongs to {0,1,2,3}). Counting does not cover cases when: a. IDQ-Resource Allocation Table (RAT) pipe serves the other thread. b. Resource Allocation Table (RAT) is stalled for the thread (including uop drops and clear BE conditions). c. Instruction Decode Queue (IDQ) delivers four uops.",
"SampleAfterValue": "2000003",
"UMask": "0x1"
},
{
"BriefDescription": "Decode Stream Buffer (DSB)-to-MITE switch true penalty cycles.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"EventCode": "0xAB",
"EventName": "DSB2MITE_SWITCHES.PENALTY_CYCLES",
"PublicDescription": "Counts Decode Stream Buffer (DSB)-to-MITE switch true penalty cycles. These cycles do not include uops routed through because of the switch itself, for example, when Instruction Decode Queue (IDQ) pre-allocation is unavailable, or Instruction Decode Queue (IDQ) is full. SBD-to-MITE switch true penalty cycles happen after the merge mux (MM) receives Decode Stream Buffer (DSB) Sync-indication until receiving the first MITE uop. MM is placed before Instruction Decode Queue (IDQ) to merge uops being fed from the MITE and Decode Stream Buffer (DSB) paths. Decode Stream Buffer (DSB) inserts the Sync-indication whenever a Decode Stream Buffer (DSB)-to-MITE switch occurs.Penalty: A Decode Stream Buffer (DSB) hit followed by a Decode Stream Buffer (DSB) miss can cost up to six cycles in which no uops are delivered to the IDQ. Most often, such switches from the Decode Stream Buffer (DSB) to the legacy pipeline cost 02 cycles.",
"SampleAfterValue": "2000003",
"UMask": "0x2"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end delivered no uops for a period of 8 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_8",
"MSRIndex": "0x3F7",
"MSRValue": "0x400806",
"PEBS": "1",
"PublicDescription": "Counts retired instructions that are delivered to the back-end after a front-end stall of at least 8 cycles. During this period the front-end delivered no uops.",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end delivered no uops for a period of 2 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_2",
"MSRIndex": "0x3F7",
"MSRValue": "0x400206",
"PEBS": "1",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end delivered no uops for a period of 4 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_4",
"MSRIndex": "0x3F7",
"MSRValue": "0x400406",
"PEBS": "1",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Cycles when uops initiated by Decode Stream Buffer (DSB) are being delivered to Instruction Decode Queue (IDQ) while Microcode Sequenser (MS) is busy",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "1",
"EventCode": "0x79",
"EventName": "IDQ.MS_DSB_CYCLES",
"PublicDescription": "Counts cycles during which uops initiated by Decode Stream Buffer (DSB) are being delivered to Instruction Decode Queue (IDQ) while the Microcode Sequencer (MS) is busy. Counting includes uops that may 'bypass' the IDQ.",
"SampleAfterValue": "2000003",
"UMask": "0x10"
},
{
"BriefDescription": "Instruction fetch tag lookups that miss in the instruction cache (L1I). Counts at 64-byte cache-line granularity.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"EventCode": "0x83",
"EventName": "ICACHE_64B.IFTAG_MISS",
"SampleAfterValue": "200003",
"UMask": "0x2"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end delivered no uops for a period of 128 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_128",
"MSRIndex": "0x3F7",
"MSRValue": "0x408006",
"PEBS": "1",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Cycles per thread when 3 or more uops are not delivered to Resource Allocation Table (RAT) when backend of the machine is not stalled",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "3",
"EventCode": "0x9C",
"EventName": "IDQ_UOPS_NOT_DELIVERED.CYCLES_LE_1_UOP_DELIV.CORE",
"PublicDescription": "Counts, on the per-thread basis, cycles when less than 1 uop is delivered to Resource Allocation Table (RAT). IDQ_Uops_Not_Delivered.core >= 3.",
"SampleAfterValue": "2000003",
"UMask": "0x1"
},
{
"BriefDescription": "Instruction fetch tag lookups that hit in the instruction cache (L1I). Counts at 64-byte cache-line granularity.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"EventCode": "0x83",
"EventName": "ICACHE_64B.IFTAG_HIT",
"SampleAfterValue": "200003",
"UMask": "0x1"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end delivered no uops for a period of 64 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_64",
"MSRIndex": "0x3F7",
"MSRValue": "0x404006",
"PEBS": "1",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Retired Instructions who experienced STLB (2nd level TLB) true miss.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.STLB_MISS",
"MSRIndex": "0x3F7",
"MSRValue": "0x15",
"PEBS": "1",
"PublicDescription": "Counts retired Instructions that experienced STLB (2nd level TLB) true miss.",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Uops delivered to Instruction Decode Queue (IDQ) from the Decode Stream Buffer (DSB) path",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"EventCode": "0x79",
"EventName": "IDQ.DSB_UOPS",
"PublicDescription": "Counts the number of uops delivered to Instruction Decode Queue (IDQ) from the Decode Stream Buffer (DSB) path. Counting includes uops that may 'bypass' the IDQ.",
"SampleAfterValue": "2000003",
"UMask": "0x8"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end delivered no uops for a period of 256 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_256",
"MSRIndex": "0x3F7",
"MSRValue": "0x410006",
"PEBS": "1",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Cycles where a code fetch is stalled due to L1 instruction cache miss.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"EventCode": "0x80",
"EventName": "ICACHE_16B.IFDATA_STALL",
"PublicDescription": "Cycles where a code line fetch is stalled due to an L1 instruction cache miss. The legacy decode pipeline works at a 16 Byte granularity.",
"SampleAfterValue": "2000003",
"UMask": "0x4"
},
{
"BriefDescription": "Cycles MITE is delivering any Uop",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "1",
"EventCode": "0x79",
"EventName": "IDQ.ALL_MITE_CYCLES_ANY_UOPS",
"PublicDescription": "Counts the number of cycles uops were delivered to the Instruction Decode Queue (IDQ) from the MITE (legacy decode pipeline) path. Counting includes uops that may 'bypass' the IDQ. During these cycles uops are not being delivered from the Decode Stream Buffer (DSB).",
"SampleAfterValue": "2000003",
"UMask": "0x24"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end delivered no uops for a period of 16 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_16",
"MSRIndex": "0x3F7",
"MSRValue": "0x401006",
"PEBS": "1",
"PublicDescription": "Counts retired instructions that are delivered to the back-end after a front-end stall of at least 16 cycles. During this period the front-end delivered no uops.",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Cycles with less than 2 uops delivered by the front end.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "2",
"EventCode": "0x9C",
"EventName": "IDQ_UOPS_NOT_DELIVERED.CYCLES_LE_2_UOP_DELIV.CORE",
"PublicDescription": "Cycles with less than 2 uops delivered by the front-end.",
"SampleAfterValue": "2000003",
"UMask": "0x1"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end delivered no uops for a period of 32 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_32",
"MSRIndex": "0x3F7",
"MSRValue": "0x402006",
"PEBS": "1",
"PublicDescription": "Counts retired instructions that are delivered to the back-end after a front-end stall of at least 32 cycles. During this period the front-end delivered no uops.",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Number of switches from DSB (Decode Stream Buffer) or MITE (legacy decode pipeline) to the Microcode Sequencer",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "1",
"EdgeDetect": "1",
"EventCode": "0x79",
"EventName": "IDQ.MS_SWITCHES",
"PublicDescription": "Number of switches from DSB (Decode Stream Buffer) or MITE (legacy decode pipeline) to the Microcode Sequencer.",
"SampleAfterValue": "2000003",
"UMask": "0x30"
},
{
"BriefDescription": "Retired Instructions who experienced iTLB true miss.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.ITLB_MISS",
"MSRIndex": "0x3F7",
"MSRValue": "0x14",
"PEBS": "1",
"PublicDescription": "Counts retired Instructions that experienced iTLB (Instruction TLB) true miss.",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Cycles Decode Stream Buffer (DSB) is delivering any Uop",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "1",
"EventCode": "0x79",
"EventName": "IDQ.ALL_DSB_CYCLES_ANY_UOPS",
"PublicDescription": "Counts the number of cycles uops were delivered to Instruction Decode Queue (IDQ) from the Decode Stream Buffer (DSB) path. Count includes uops that may 'bypass' the IDQ.",
"SampleAfterValue": "2000003",
"UMask": "0x18"
},
{
"BriefDescription": "Retired instructions that are fetched after an interval where the front-end delivered no uops for a period of 512 cycles which was not interrupted by a back-end stall.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3",
"EventCode": "0xC6",
"EventName": "FRONTEND_RETIRED.LATENCY_GE_512",
"MSRIndex": "0x3F7",
"MSRValue": "0x420006",
"PEBS": "1",
"SampleAfterValue": "100007",
"TakenAlone": "1",
"UMask": "0x1"
},
{
"BriefDescription": "Cycles MITE is delivering 4 Uops",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "4",
"EventCode": "0x79",
"EventName": "IDQ.ALL_MITE_CYCLES_4_UOPS",
"PublicDescription": "Counts the number of cycles 4 uops were delivered to the Instruction Decode Queue (IDQ) from the MITE (legacy decode pipeline) path. Counting includes uops that may 'bypass' the IDQ. During these cycles uops are not being delivered from the Decode Stream Buffer (DSB).",
"SampleAfterValue": "2000003",
"UMask": "0x24"
},
{
"BriefDescription": "Cycles Decode Stream Buffer (DSB) is delivering 4 Uops",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"CounterMask": "4",
"EventCode": "0x79",
"EventName": "IDQ.ALL_DSB_CYCLES_4_UOPS",
"PublicDescription": "Counts the number of cycles 4 uops were delivered to Instruction Decode Queue (IDQ) from the Decode Stream Buffer (DSB) path. Count includes uops that may 'bypass' the IDQ.",
"SampleAfterValue": "2000003",
"UMask": "0x18"
},
{
"BriefDescription": "Cycles where a code fetch is stalled due to L1 instruction cache tag miss.",
"Counter": "0,1,2,3",
"CounterHTOff": "0,1,2,3,4,5,6,7",
"EventCode": "0x83",
"EventName": "ICACHE_64B.IFTAG_STALL",
"SampleAfterValue": "200003",
"UMask": "0x4"
}
] | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns="http://www.portalfiscal.inf.br/nfe" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.portalfiscal.inf.br/nfe" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:include schemaLocation="leiauteConsultaCadastro_v1.01.xsd"/>
<xs:element name="retConsCad" type="TRetConsCad">
<xs:annotation>
<xs:documentation>Schema XML de validação do retorno da consulta cadastro contribuintes</xs:documentation>
</xs:annotation>
</xs:element>
</xs:schema>
| {
"pile_set_name": "Github"
} |
<?php
declare(strict_types=1);
namespace Tests\Commands\Upgrade\Databases\V6_13_0\Migrations;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateConsolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('consoles', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->default('')->comment('名称');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('consoles');
}
}
| {
"pile_set_name": "Github"
} |
---
layout: page
title: Spies - Sinon.JS
breadcrumb: spies
---
### Introduction
### What is a test spy?
A test spy is a function that records arguments, return value, the value of
`this` and exception thrown (if any) for all its [calls][call]. There are two types of spies:
Some are anonymous functions, while others wrap methods that already exist in
the system under test.
### Creating a spy as an anonymous function
When the behavior of the spied-on function is not under test, you can use an
anonymous function spy. The spy won't do anything except record information
about its [calls][call]. A common use case for this type of spy is testing how a function
handles a callback, as in the following simplified example:
```javascript
"test should call subscribers on publish": function () {
var callback = sinon.spy();
PubSub.subscribe("message", callback);
PubSub.publishSync("message");
assertTrue(callback.called);
}
```
### Using a spy to wrap an existing method
`sinon.spy(object, "method")` creates a spy that wraps the existing function
`object.method`. The spy will behave exactly like the original method
(including when used as a constructor), but you will have access to data about
all [calls][call]. The following is a slightly contrived example:
```javascript
{
setUp: function () {
sinon.spy(jQuery, "ajax");
},
tearDown: function () {
jQuery.ajax.restore(); // Unwraps the spy
},
"test should inspect jQuery.getJSON's usage of jQuery.ajax": function () {
jQuery.getJSON("/some/resource");
assert(jQuery.ajax.calledOnce);
assertEquals("/some/resource", jQuery.ajax.getCall(0).args[0].url);
assertEquals("json", jQuery.ajax.getCall(0).args[0].dataType);
}
}
```
### Using a spy to wrap property getter and setter
`sinon.spy(object, "property", ["get", "set"])` creates spies that wrap the
getters and setters for `object.property`. The spies will behave exactly like
the original getters and setters, but you will have access to data about all
[calls][call]. Example:
```javascript
var object = {
get test() {
return this.property;
},
set test(value) {
this.property = value * 2;
}
};
var spy = sinon.spy(object, "test", ["get", "set"]);
object.test = 42;
assert(spy.set.calledOnce);
assert.equals(object.test, 84);
assert(spy.get.calledOnce);
```
### Creating spies: `sinon.spy()` Method Signatures
<dl>
<dt><code>var spy = sinon.spy();</code></dt>
<dd>
Creates an anonymous function that records arguments, <code>this</code> value,
exceptions and return values for all calls.
</dd>
<dt><code>var spy = sinon.spy(myFunc);</code></dt>
<dd>Spies on the provided function</dd>
<dt><code>var spy = sinon.spy(object, "method");</code></dt>
<dd>
Creates a spy for <code>object.method</code> and
replaces the original method with the spy. An exception is thrown if the property
is not already a function. The spy acts exactly like the original method in
all cases. The original method can be restored by calling
<code>object.method.restore()</code>. The returned spy is the function
object which replaced the original method. <code>spy === object.method</code>.
</dd>
<dt><code>var spy = sinon.spy(object, "property", types);</code></dt>
<dd>
Creates a spy for <code>object.property</code> descriptor and replaces the
original accessor methods (`get`, `set`) listed in the <code>types</code>
array with a spy. The spies act exactly like the original accessors in all
cases. The original accessors can be restored by calling
<code>spy.restore()</code>. The returned spy is the object which replaced
the original property descriptor. <code>spy.get ===
Object.getOwnPropertyDescriptor(object, 'property').get</code>.
</dd>
</dl>
### Spy API
Spies provide a rich interface to inspect their usage. The above examples showed
the `calledOnce` boolean property as well as the `getCall` method and the
returned object's `args` property. There are three ways of inspecting [call][call] data.
The preferred approach is to use the spy's `calledWith` method (and friends)
because it keeps your test from being too specific about which call did what and
so on. It will return `true` if the spy was ever called with the provided
arguments.
```javascript
"test should call subscribers with message as first argument" : function () {
var message = 'an example message';
var spy = sinon.spy();
PubSub.subscribe(message, spy);
PubSub.publishSync(message, "some payload");
assert(spy.calledWith(message));
}
```
If you want to be specific, you can directly check the first argument of the
first [call][call]. There are two ways of achieving this:
```javascript
"test should call subscribers with message as first argument" : function () {
var message = 'an example message';
var spy = sinon.spy();
PubSub.subscribe(message, spy);
PubSub.publishSync(message, "some payload");
assertEquals(message, spy.args[0][0]);
}
```
```javascript
"test should call subscribers with message as first argument" : function () {
var message = 'an example message';
var spy = sinon.spy();
PubSub.subscribe(message, spy);
PubSub.publishSync(message, "some payload");
assertEquals(message, spy.getCall(0).args[0]);
}
```
The first example uses the two-dimensional `args` array directly on the spy,
while the second example fetches the first [call][call] object and then accesses its
`args` array. Which one to use is a matter of preference, but the recommended
approach is going with `spy.calledWith(arg1, arg2, ...)` unless there's a need
to make the tests highly specific.
## API
Spy objects are objects returned from `sinon.spy()`. When spying on existing
methods with `sinon.spy(object, method)`, the following properties and methods
are also available on `object.method`.
### Properties
#### `spy.withArgs(arg1[, arg2, ...]);`
Creates a spy that only records [calls][call] when the received arguments match those passed to `withArgs`. This is useful to be more expressive in your assertions, where you can access the spy with the same [call][call].
```javascript
"should call method once with each argument": function () {
var object = { method: function () {} };
var spy = sinon.spy(object, "method");
object.method(42);
object.method(1);
assert(spy.withArgs(42).calledOnce);
assert(spy.withArgs(1).calledOnce);
}
```
#### `spy.callCount`
The number of recorded [calls][call].
#### `spy.called`
`true` if the spy was called at least once
#### `spy.notCalled`
`true` if the spy was not called
#### `spy.calledOnce`
`true` if spy was called exactly once
#### `spy.calledTwice`
`true` if the spy was called exactly twice
#### `spy.calledThrice`
`true` if the spy was called exactly thrice
#### `spy.firstCall`
The first [call][call]
#### `spy.secondCall`
The second [call][call]
#### `spy.thirdCall`
The third [call][call]
#### `spy.lastCall`
The last [call][call]
#### `spy.calledBefore(anotherSpy);`
Returns `true` if the spy was called before `anotherSpy`
#### `spy.calledAfter(anotherSpy);`
Returns `true` if the spy was called after `anotherSpy`
#### `spy.calledImmediatelyBefore(anotherSpy);`
Returns `true` if `spy` was called before `anotherSpy`, and no spy [calls][call]
occurred between `spy` and `anotherSpy`.
#### `spy.calledImmediatelyAfter(anotherSpy);`
Returns `true` if `spy` was called after `anotherSpy`, and no spy [calls][call]
occurred between `anotherSpy` and `spy`.
#### `spy.calledOn(obj);`
Returns `true` if the spy was called at least once with `obj` as `this`. `calledOn` also accepts a matcher `spyCall.calledOn(sinon.match(fn))` (see [matchers][matchers]).
#### `spy.alwaysCalledOn(obj);`
Returns `true` if the spy was always called with `obj` as `this`.
#### `spy.calledWith(arg1, arg2, ...);`
Returns `true` if spy was called at least once with the provided arguments.
Can be used for partial matching, Sinon only checks the provided arguments against actual arguments, so a call that received the provided arguments (in the same spots) and possibly others as well will return `true`.
#### `spy.alwaysCalledWith(arg1, arg2, ...);`
Returns `true` if spy was always called with the provided arguments (and possibly others).
#### `spy.calledWithExactly(arg1, arg2, ...);`
Returns `true` if spy was called at least once with the provided arguments and no others.
#### `spy.alwaysCalledWithExactly(arg1, arg2, ...);`
Returns `true` if spy was always called with the exact provided arguments.
#### `spy.calledWithMatch(arg1, arg2, ...);`
Returns `true` if spy was called with matching arguments (and possibly others).
This behaves the same as `spy.calledWith(sinon.match(arg1), sinon.match(arg2), ...)`.
#### `spy.alwaysCalledWithMatch(arg1, arg2, ...);`
Returns `true` if spy was always called with matching arguments (and possibly others).
This behaves the same as `spy.alwaysCalledWith(sinon.match(arg1), sinon.match(arg2), ...)`.
#### `spy.calledWithNew();`
Returns `true` if spy/stub was called the `new` operator.
Beware that this is inferred based on the value of the `this` object and the spy function's `prototype`, so it may give false positives if you actively return the right kind of object.
#### `spy.neverCalledWith(arg1, arg2, ...);`
Returns `true` if the spy/stub was never called with the provided arguments.
#### `spy.neverCalledWithMatch(arg1, arg2, ...);`
Returns `true` if the spy/stub was never called with matching arguments.
This behaves the same as `spy.neverCalledWith(sinon.match(arg1), sinon.match(arg2), ...)`.
#### `spy.threw();`
Returns `true` if spy threw an exception at least once.
#### `spy.threw("TypeError");`
Returns `true` if spy threw an exception of the provided type at least once.
#### `spy.threw(obj);`
Returns `true` if spy threw the provided exception object at least once.
#### `spy.alwaysThrew();`
Returns `true` if spy always threw an exception.
#### `spy.alwaysThrew("TypeError");`
Returns `true` if spy always threw an exception of the provided type.
#### `spy.alwaysThrew(obj);`
Returns `true` if spy always threw the provided exception object.
#### `spy.returned(obj);`
Returns `true` if spy returned the provided value at least once.
Uses deep comparison for objects and arrays. Use `spy.returned(sinon.match.same(obj))` for strict comparison (see [matchers][matchers]).
#### `spy.alwaysReturned(obj);`
Returns `true` if spy always returned the provided value.
#### `var spyCall = spy.getCall(n);`
Returns the *nth* [call](#spycall).
Accessing individual calls helps with more detailed behavior verification when the spy is called more than once.
```javascript
sinon.spy(jQuery, "ajax");
jQuery.ajax("/stuffs");
var spyCall = jQuery.ajax.getCall(0);
assertEquals("/stuffs", spyCall.args[0]);
```
#### `var spyCalls = spy.getCalls();`
Returns an `Array` of all [calls][call] recorded by the spy.
#### `spy.thisValues`
Array of `this` objects, `spy.thisValues[0]` is the `this` object for the first [call][call].
#### `spy.args`
Array of arguments received, `spy.args[0]` is an array of arguments received in the first [call][call].
#### `spy.exceptions`
Array of exception objects thrown, `spy.exceptions[0]` is the exception thrown by the first [call][call].
If the call did not throw an error, the value at the call's location in `.exceptions` will be `undefined`.
#### `spy.returnValues`
Array of return values, `spy.returnValues[0]` is the return value of the first [call][call].
If the call did not explicitly return a value, the value at the call's location in `.returnValues` will be `undefined`.
#### `spy.reset()`
Resets the state of a spy.
#### `spy.restore()`
Replaces the spy with the original method. Only available if the spy replaced an existing method.
#### `spy.printf("format string", [arg1, arg2, ...])`
Returns the passed format string with the following replacements performed:
<dl>
<dt><code>%n</code></dt>
<dd>the name of the spy "spy" by default)</dd>
<dt><code>%c</code></dt>
<dd>the number of times the spy was called, in words ("once", "twice", etc.)</dd>
<dt><code>%C</code></dt>
<dd>a list of string representations of the calls to the spy, with each call prefixed by a newline and four spaces</dd>
<dt><code>%t</code></dt>
<dd>a comma-delimited list of <code>this</code> values the spy was called on</dd>
<dt><code>%<var>n</var></code></dt>
<dd>the formatted value of the <var>n</var>th argument passed to <code>printf</code></dd>
<dt><code>%*</code></dt>
<dd>a comma-delimited list of the (non-format string) arguments passed to <code>printf</code></dd>
</dl>
[call]: ../spy-call
[matchers]: ../matchers
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.