text
stringlengths 2
100k
| meta
dict |
---|---|
# Sony XBA-N3AP
See [usage instructions](https://github.com/jaakkopasanen/AutoEq#usage) for more options and info.
### Parametric EQs
In case of using parametric equalizer, apply preamp of **-6.2dB** and build filters manually
with these parameters. The first 5 filters can be used independently.
When using independent subset of filters, apply preamp of **-6.2dB**.
| Type | Fc | Q | Gain |
|:--------|:---------|:-----|:--------|
| Peaking | 62 Hz | 0.42 | -4.6 dB |
| Peaking | 181 Hz | 0.9 | -2.5 dB |
| Peaking | 3294 Hz | 1.67 | 5.1 dB |
| Peaking | 6001 Hz | 3.28 | 4.8 dB |
| Peaking | 22050 Hz | 2.62 | 3.4 dB |
| Peaking | 809 Hz | 1.73 | 1.3 dB |
| Peaking | 1465 Hz | 2.6 | -1.2 dB |
| Peaking | 4570 Hz | 4.33 | 1.0 dB |
| Peaking | 11358 Hz | 2.38 | 1.5 dB |
| Peaking | 20402 Hz | 0.3 | -7.0 dB |
### Fixed Band EQs
In case of using fixed band (also called graphic) equalizer, apply preamp of **-6.2dB**
(if available) and set gains manually with these parameters.
| Type | Fc | Q | Gain |
|:--------|:---------|:-----|:--------|
| Peaking | 31 Hz | 1.41 | -2.9 dB |
| Peaking | 62 Hz | 1.41 | -4.1 dB |
| Peaking | 125 Hz | 1.41 | -4.2 dB |
| Peaking | 250 Hz | 1.41 | -2.9 dB |
| Peaking | 500 Hz | 1.41 | 0.4 dB |
| Peaking | 1000 Hz | 1.41 | 0.3 dB |
| Peaking | 2000 Hz | 1.41 | 0.1 dB |
| Peaking | 4000 Hz | 1.41 | 5.6 dB |
| Peaking | 8000 Hz | 1.41 | 1.1 dB |
| Peaking | 16000 Hz | 1.41 | -4.4 dB |
### Graphs
 | {
"pile_set_name": "Github"
} |
{
"_args": [
[
"qs@~6.0.2",
"/Users/akirodic/Projects/dreemgl/system/lib/node_modules/twitter/node_modules/request"
]
],
"_from": "qs@>=6.0.2 <6.1.0",
"_id": "[email protected]",
"_inCache": true,
"_installable": true,
"_location": "/twitter/qs",
"_nodeVersion": "5.4.1",
"_npmUser": {
"email": "[email protected]",
"name": "ljharb"
},
"_npmVersion": "3.3.12",
"_phantomChildren": {},
"_requested": {
"name": "qs",
"raw": "qs@~6.0.2",
"rawSpec": "~6.0.2",
"scope": null,
"spec": ">=6.0.2 <6.1.0",
"type": "range"
},
"_requiredBy": [
"/twitter/request"
],
"_resolved": "https://registry.npmjs.org/qs/-/qs-6.0.2.tgz",
"_shasum": "88c68d590e8ed56c76c79f352c17b982466abfcd",
"_shrinkwrap": null,
"_spec": "qs@~6.0.2",
"_where": "/Users/akirodic/Projects/dreemgl/system/lib/node_modules/twitter/node_modules/request",
"bugs": {
"url": "https://github.com/ljharb/qs/issues"
},
"contributors": [
{
"name": "Jordan Harband",
"email": "[email protected]",
"url": "http://ljharb.codes"
}
],
"dependencies": {},
"description": "A querystring parser that supports nesting and arrays, with a depth limit",
"devDependencies": {
"@ljharb/eslint-config": "^1.6.1",
"browserify": "^12.0.1",
"covert": "^1.1.0",
"eslint": "^1.10.3",
"evalmd": "^0.0.16",
"mkdirp": "^0.5.1",
"parallelshell": "^2.0.0",
"tape": "^4.3.0"
},
"directories": {},
"dist": {
"shasum": "88c68d590e8ed56c76c79f352c17b982466abfcd",
"tarball": "http://registry.npmjs.org/qs/-/qs-6.0.2.tgz"
},
"engines": {
"node": ">=0.6"
},
"gitHead": "47dfbd6740b3cc1593847825701c8aa136f636e3",
"homepage": "https://github.com/ljharb/qs",
"keywords": [
"qs",
"querystring"
],
"license": "BSD-3-Clause",
"main": "lib/index.js",
"maintainers": [
{
"name": "hueniverse",
"email": "[email protected]"
},
{
"name": "ljharb",
"email": "[email protected]"
},
{
"name": "nlf",
"email": "[email protected]"
}
],
"name": "qs",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/ljharb/qs.git"
},
"scripts": {
"coverage": "covert test",
"dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js",
"lint": "eslint lib/*.js text/*.js",
"prepublish": "npm run dist",
"readme": "evalmd README.md",
"test": "parallelshell 'npm run readme' 'npm run lint' 'npm run coverage'",
"tests-only": "node test"
},
"version": "6.0.2"
}
| {
"pile_set_name": "Github"
} |
DocDefList [_×_ (DocString "foo") (DocString "bar")]
| {
"pile_set_name": "Github"
} |
import FWCore.ParameterSet.Config as cms
# AlCaPi0RecHits producer
alCaPi0RecHits = cms.EDProducer("AlCaPi0RecHitsProducer",
pi0BarrelHitCollection = cms.string('pi0EcalRecHitsEB'),
seleNRHMax = cms.int32(1000),
clusPhiSize = cms.int32(3),
seleMinvMaxPi0 = cms.double(0.2),
gammaCandEtaSize = cms.int32(21),
selePtGammaOne = cms.double(1.0),
ecalRecHitsProducer = cms.string('ecalRecHit'),
clusEtaSize = cms.int32(3),
VerbosityLevel = cms.string('ERROR'),
gammaCandPhiSize = cms.int32(21),
selePtGammaTwo = cms.double(1.0),
selePtPi0 = cms.double(2.5),
seleXtalMinEnergy = cms.double(0.0),
barrelHitCollection = cms.string('EcalRecHitsEB'),
seleMinvMinPi0 = cms.double(0.0),
clusSeedThr = cms.double(0.5)
)
| {
"pile_set_name": "Github"
} |
var inspectBasis = require('devpanel').inspectBasis;
var inspectBasisL10n = inspectBasis.require('basis.l10n');
var Value = require('basis.data').Value;
var Menu = require('./Menu.js');
module.exports = new Menu({
childClass: {
binding: {
title: 'value',
selected: Value
.from(inspectBasisL10n.culture)
.compute(function(node, value){
return node.value == value;
})
},
action: {
select: function(){
inspectBasisL10n.setCulture(this.value);
}
}
},
childNodes: inspectBasisL10n.getCultureList().map(function(culture){
return {
value: culture
};
})
});
| {
"pile_set_name": "Github"
} |
#N canvas 425 78 664 201 10;
#X obj 174 77 cnv 15 460 15 empty empty empty 20 12 0 14 -261148 -66577
0;
#X obj 8 157 cnv 15 640 30 empty empty empty 20 12 0 14 -261148 -66577
0;
#X text 306 159 Copyright Ben Bogart \, Franz Hildgen & \; The Societe
des arts technologiques (SAT) 2004;
#X obj 8 6 cnv 15 640 50 empty empty empty 20 12 0 14 -233017 -66577
0;
#X text 12 23 Type: Footer. Effects only its own layer;
#X text 12 39 Creation Arguments: None;
#X obj 24 124 pt.model;
#X text 177 77 3D Model Functions:;
#X obj 184 101 cnv 15 450 15 empty empty empty 20 12 0 14 -233017 -66577
0;
#X text 187 101 *Notes:;
#X text 12 6 pixelTANGO HELP - pt.model - Load an 3D Model as layer
;
#X obj 24 77 pt.file;
#X text 197 122 To load a model use an immediatly preceeding pt.file.
Support Alias|Wavefront obj models.;
#X connect 11 0 6 0;
#X connect 11 1 6 1;
| {
"pile_set_name": "Github"
} |
# [Snow Report for Camden Snow Bowl](http://alexa.amazon.com/#skills/amzn1.ask.skill.7306dec2-e25c-4b82-a503-37dda0bccbce)
 0
To use the Snow Report for Camden Snow Bowl skill, try saying...
* *Alexa, open Camden Snow Bowl*
* *Alexa, ask Camden Snow Bowl for the snow report*
* *Alexa, ask Camden Snow Bowl for latest conditions*
The Camden Snow Bowl Snow Report brought to you by SnoCountry brings you the latest snow fall, snow surface conditions, base depth, trail, and lift operations information.
***
### Skill Details
* **Invocation Name:** camden snow bowl
* **Category:** null
* **ID:** amzn1.ask.skill.7306dec2-e25c-4b82-a503-37dda0bccbce
* **ASIN:** B01MCVYXTY
* **Author:** SnoCountry
* **Release Date:** October 21, 2016 @ 15:16:10
* **In-App Purchasing:** No
| {
"pile_set_name": "Github"
} |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"walkThrough.editor.label": "Playground interattivo",
"help": "Guida",
"interactivePlayground": "Playground interattivo"
} | {
"pile_set_name": "Github"
} |
{
"_args": [
[
{
"name": "http-signature",
"raw": "http-signature@~1.1.0",
"rawSpec": "~1.1.0",
"scope": null,
"spec": ">=1.1.0 <1.2.0",
"type": "range"
},
"/Users/lvruheng/android_interview/node_modules/request"
]
],
"_cnpm_publish_time": 1453759488994,
"_from": "http-signature@>=1.1.0 <1.2.0",
"_hasShrinkwrap": false,
"_id": "[email protected]",
"_inCache": true,
"_installable": true,
"_location": "/http-signature",
"_nodeVersion": "0.12.9",
"_npmUser": {
"email": "[email protected]",
"name": "arekinath"
},
"_npmVersion": "2.14.9",
"_phantomChildren": {},
"_requested": {
"name": "http-signature",
"raw": "http-signature@~1.1.0",
"rawSpec": "~1.1.0",
"scope": null,
"spec": ">=1.1.0 <1.2.0",
"type": "range"
},
"_requiredBy": [
"/request"
],
"_resolved": "https://registry.npm.taobao.org/http-signature/download/http-signature-1.1.1.tgz",
"_shasum": "df72e267066cd0ac67fb76adf8e134a8fbcf91bf",
"_shrinkwrap": null,
"_spec": "http-signature@~1.1.0",
"_where": "/Users/lvruheng/android_interview/node_modules/request",
"author": {
"name": "Joyent, Inc"
},
"bugs": {
"url": "https://github.com/joyent/node-http-signature/issues"
},
"contributors": [
{
"email": "[email protected]",
"name": "Mark Cavage"
},
{
"email": "[email protected]",
"name": "David I. Lehn"
},
{
"email": "[email protected]",
"name": "Patrick Mooney"
}
],
"dependencies": {
"assert-plus": "^0.2.0",
"jsprim": "^1.2.2",
"sshpk": "^1.7.0"
},
"description": "Reference implementation of Joyent's HTTP Signature scheme.",
"devDependencies": {
"node-uuid": "^1.4.1",
"tap": "0.4.2"
},
"directories": {},
"dist": {
"noattachment": false,
"shasum": "df72e267066cd0ac67fb76adf8e134a8fbcf91bf",
"size": 15230,
"tarball": "http://registry.npm.taobao.org/http-signature/download/http-signature-1.1.1.tgz"
},
"engines": {
"node": ">=0.8",
"npm": ">=1.3.7"
},
"gitHead": "74d3f35e3aa436d83723c53b01e266f448e8149a",
"homepage": "https://github.com/joyent/node-http-signature/",
"keywords": [
"https",
"request"
],
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"email": "[email protected]",
"name": "arekinath"
},
{
"email": "[email protected]",
"name": "mcavage"
},
{
"email": "[email protected]",
"name": "pfmooney"
}
],
"name": "http-signature",
"optionalDependencies": {},
"publish_time": 1453759488994,
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/joyent/node-http-signature.git"
},
"scripts": {
"test": "tap test/*.js"
},
"version": "1.1.1"
}
| {
"pile_set_name": "Github"
} |
package client
import (
"sync"
"time"
hclog "github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/nomad/structs"
)
type heartbeatStop struct {
lastOk time.Time
startupGrace time.Time
allocInterval map[string]time.Duration
allocHookCh chan *structs.Allocation
getRunner func(string) (AllocRunner, error)
logger hclog.InterceptLogger
shutdownCh chan struct{}
lock *sync.RWMutex
}
func newHeartbeatStop(
getRunner func(string) (AllocRunner, error),
timeout time.Duration,
logger hclog.InterceptLogger,
shutdownCh chan struct{}) *heartbeatStop {
h := &heartbeatStop{
startupGrace: time.Now().Add(timeout),
allocInterval: make(map[string]time.Duration),
allocHookCh: make(chan *structs.Allocation),
getRunner: getRunner,
logger: logger,
shutdownCh: shutdownCh,
lock: &sync.RWMutex{},
}
return h
}
// allocHook is called after (re)storing a new AllocRunner in the client. It registers the
// allocation to be stopped if the taskgroup is configured appropriately
func (h *heartbeatStop) allocHook(alloc *structs.Allocation) {
tg := allocTaskGroup(alloc)
if tg.StopAfterClientDisconnect != nil {
h.allocHookCh <- alloc
}
}
// shouldStop is called on a restored alloc to determine if lastOk is sufficiently in the
// past that it should be prevented from restarting
func (h *heartbeatStop) shouldStop(alloc *structs.Allocation) bool {
tg := allocTaskGroup(alloc)
if tg.StopAfterClientDisconnect != nil {
return h.shouldStopAfter(time.Now(), *tg.StopAfterClientDisconnect)
}
return false
}
func (h *heartbeatStop) shouldStopAfter(now time.Time, interval time.Duration) bool {
lastOk := h.getLastOk()
if lastOk.IsZero() {
return now.After(h.startupGrace)
}
return now.After(lastOk.Add(interval))
}
// watch is a loop that checks for allocations that should be stopped. It also manages the
// registration of allocs to be stopped in a single thread.
func (h *heartbeatStop) watch() {
// If we never manage to successfully contact the server, we want to stop our allocs
// after duration + start time
h.lastOk = time.Now()
stop := make(chan string, 1)
var now time.Time
var interval time.Duration
checkAllocs := false
for {
// minimize the interval
interval = 5 * time.Second
for _, t := range h.allocInterval {
if t < interval {
interval = t
}
}
checkAllocs = false
timeout := time.After(interval)
select {
case allocID := <-stop:
if err := h.stopAlloc(allocID); err != nil {
h.logger.Warn("error stopping on heartbeat timeout", "alloc", allocID, "error", err)
continue
}
delete(h.allocInterval, allocID)
case alloc := <-h.allocHookCh:
tg := allocTaskGroup(alloc)
if tg.StopAfterClientDisconnect != nil {
h.allocInterval[alloc.ID] = *tg.StopAfterClientDisconnect
}
case <-timeout:
checkAllocs = true
case <-h.shutdownCh:
return
}
if !checkAllocs {
continue
}
now = time.Now()
for allocID, d := range h.allocInterval {
if h.shouldStopAfter(now, d) {
stop <- allocID
}
}
}
}
// setLastOk sets the last known good heartbeat time to the current time, and persists that time to disk
func (h *heartbeatStop) setLastOk(t time.Time) {
h.lock.Lock()
defer h.lock.Unlock()
h.lastOk = t
}
func (h *heartbeatStop) getLastOk() time.Time {
h.lock.RLock()
defer h.lock.RUnlock()
return h.lastOk
}
// stopAlloc actually stops the allocation
func (h *heartbeatStop) stopAlloc(allocID string) error {
runner, err := h.getRunner(allocID)
if err != nil {
return err
}
h.logger.Debug("stopping alloc for stop_after_client_disconnect", "alloc", allocID)
runner.Destroy()
return nil
}
func allocTaskGroup(alloc *structs.Allocation) *structs.TaskGroup {
for _, tg := range alloc.Job.TaskGroups {
if tg.Name == alloc.TaskGroup {
return tg
}
}
return nil
}
| {
"pile_set_name": "Github"
} |
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------M-------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---
--------------------------------------------------------------------------------h-------------------------------------------------------------------------------------------|---
--------------------MBB-----------------------------------------------------BBBBBB----+----------------------------------------BBBBB------------------------------##--------|---
--------------------------------------------------------------------------------------------------------------------------------------------------BB------------t###--------|---
---------------------------------------------------------C---------------------------------------------------------------------------------------------#--------####--------|---
---------------------------------------------------------c-------------------h--------------------------------------------------h-------------BB------##-------#####--------|---
--------------------------------????-------------------BB#OB---------V-----BBBBBBB----V---------------V------------------------BBBBB-----------------###------######--------|---
-----------------K---C-----------------C-----K---C-------------------[]---------------[]--------------[]----V------------V------------#----C--------####-----#######--------|---
------------C--------c-------C--K------c---------c-----------C-------pP---------------pP---------C----pP----[]-----C-----[]-----------#----c----Y--#####----########--------|---
------------c--------C-------c---------c---------C-----------c-------pP---------------pP---------c----pP-k--pP-----c-----pP------h----#----C----y-######---#########--------#---
##################################################################--#############################################################################-##############################
| {
"pile_set_name": "Github"
} |
{ lib, stdenv, fetchFromGitHub, cmake }:
stdenv.mkDerivation rec {
pname = "aws-c-common";
version = "0.3.11";
src = fetchFromGitHub {
owner = "awslabs";
repo = pname;
rev = "v${version}";
sha256 = "0a7hi4crnc3j1j39qcnd44zqdfwzw1xghcf80marx5vdf1qdzy6p";
};
nativeBuildInputs = [ cmake ];
NIX_CFLAGS_COMPILE = lib.optionalString stdenv.isDarwin
"-Wno-nullability-extension -Wno-typedef-redefinition";
meta = with lib; {
description = "AWS SDK for C common core";
homepage = "https://github.com/awslabs/aws-c-common";
license = licenses.asl20;
platforms = platforms.unix;
maintainers = with maintainers; [ orivej eelco ];
};
}
| {
"pile_set_name": "Github"
} |
The Cauldron
When a group of clonks are trapped in the Cauldron, the outcome is certain. Only the last clonk left alive will rise from its depths.
Goal: Last Man Standing (Be the last one alive to win)
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2015 Ronald S. Bultje <[email protected]>
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/x86/cpu.h"
#include "libavfilter/ssim.h"
void ff_ssim_4x4_line_ssse3(const uint8_t *buf, ptrdiff_t buf_stride,
const uint8_t *ref, ptrdiff_t ref_stride,
int (*sums)[4], int w);
void ff_ssim_4x4_line_xop (const uint8_t *buf, ptrdiff_t buf_stride,
const uint8_t *ref, ptrdiff_t ref_stride,
int (*sums)[4], int w);
float ff_ssim_end_line_sse4(const int (*sum0)[4], const int (*sum1)[4], int w);
void ff_ssim_init_x86(SSIMDSPContext *dsp)
{
int cpu_flags = av_get_cpu_flags();
if (ARCH_X86_64 && EXTERNAL_SSSE3(cpu_flags))
dsp->ssim_4x4_line = ff_ssim_4x4_line_ssse3;
if (EXTERNAL_SSE4(cpu_flags))
dsp->ssim_end_line = ff_ssim_end_line_sse4;
if (EXTERNAL_XOP(cpu_flags))
dsp->ssim_4x4_line = ff_ssim_4x4_line_xop;
}
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2001-2011 Hartmut Kaiser
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)
=============================================================================*/
#if !defined(SPIRIT_ALTERNATIVE_FUNCTION_APRIL_23_2007_1046AM)
#define SPIRIT_ALTERNATIVE_FUNCTION_APRIL_23_2007_1046AM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/qi/domain.hpp>
#include <boost/spirit/home/qi/detail/assign_to.hpp>
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/qi/detail/attributes.hpp>
#include <boost/variant.hpp>
#include <boost/mpl/bool.hpp>
namespace boost { namespace spirit { namespace qi { namespace detail
{
template <typename Variant, typename Expected>
struct find_substitute
{
// Get the typr from the variant that can be a substitute for Expected.
// If none is found, just return Expected
typedef Variant variant_type;
typedef typename variant_type::types types;
typedef typename mpl::end<types>::type end;
typedef typename
mpl::find_if<types, is_same<mpl::_1, Expected> >::type
iter_1;
typedef typename
mpl::eval_if<
is_same<iter_1, end>,
mpl::find_if<types, traits::is_substitute<mpl::_1, Expected> >,
mpl::identity<iter_1>
>::type
iter;
typedef typename
mpl::eval_if<
is_same<iter, end>,
mpl::identity<Expected>,
mpl::deref<iter>
>::type
type;
};
template <typename Iterator, typename Context, typename Skipper,
typename Attribute>
struct alternative_function
{
alternative_function(
Iterator& first_, Iterator const& last_, Context& context_,
Skipper const& skipper_, Attribute& attr_)
: first(first_), last(last_), context(context_), skipper(skipper_),
attr(attr_)
{
}
template <typename Component>
bool call(Component const& component, mpl::true_) const
{
// if Attribute is not a variant, then pass it as-is
return component.parse(first, last, context, skipper, attr);
}
template <typename Component>
bool call_optional_or_variant(Component const& component, mpl::true_) const
{
// If Attribute is an optional, then create an attribute for the Component
// with the type optional::value_type. If the expected attribute is unused type,
// use it instead.
typedef typename
traits::attribute_of<Component, Context, Iterator>::type
expected_type;
typename mpl::if_<
is_same<expected_type, unused_type>,
unused_type,
typename Attribute::value_type>::type
val;
if (component.parse(first, last, context, skipper, val))
{
traits::assign_to(val, attr);
return true;
}
return false;
}
template <typename Component>
bool call_variant(Component const& component, mpl::false_) const
{
// If Attribute is a variant, then search the variant types for a
// suitable substitute type.
typename
find_substitute<Attribute,
typename traits::attribute_of<Component, Context, Iterator>::type
>::type
val;
if (component.parse(first, last, context, skipper, val))
{
traits::assign_to(val, attr);
return true;
}
return false;
}
template <typename Component>
bool call_variant(Component const& component, mpl::true_) const
{
// If Attribute is a variant and the expected attribute is
// the same type (pass the variant as-is).
return component.parse(first, last, context, skipper, attr);
}
template <typename Component>
bool call_optional_or_variant(Component const& component, mpl::false_) const
{
// Attribute is a variant...
typedef typename
traits::attribute_of<Component, Context, Iterator>::type
expected;
return call_variant(component,
is_same<Attribute, expected>());
}
template <typename Component>
bool call(Component const& component, mpl::false_) const
{
return call_optional_or_variant(
component, spirit::traits::not_is_variant<Attribute, qi::domain>());
}
template <typename Component>
bool call_unused(Component const& component, mpl::true_) const
{
// return true if the parser succeeds
return call(component,
mpl::and_<
spirit::traits::not_is_variant<Attribute, qi::domain>,
spirit::traits::not_is_optional<Attribute, qi::domain>
>());
}
template <typename Component>
bool call_unused(Component const& component, mpl::false_) const
{
return component.parse(first, last, context, skipper, unused);
}
template <typename Component>
bool operator()(Component const& component) const
{
// return true if the parser succeeds
typedef typename traits::not_is_unused<
typename traits::attribute_of<Component, Context, Iterator>::type
>::type predicate;
return call_unused(component, predicate());
}
Iterator& first;
Iterator const& last;
Context& context;
Skipper const& skipper;
Attribute& attr;
private:
// silence MSVC warning C4512: assignment operator could not be generated
alternative_function& operator= (alternative_function const&);
};
template <typename Iterator, typename Context, typename Skipper>
struct alternative_function<Iterator, Context, Skipper, unused_type const>
{
alternative_function(
Iterator& first_, Iterator const& last_, Context& context_,
Skipper const& skipper_, unused_type)
: first(first_), last(last_), context(context_), skipper(skipper_)
{
}
template <typename Component>
bool operator()(Component const& component) const
{
// return true if the parser succeeds
return component.parse(first, last, context, skipper,
unused);
}
Iterator& first;
Iterator const& last;
Context& context;
Skipper const& skipper;
private:
// silence MSVC warning C4512: assignment operator could not be generated
alternative_function& operator= (alternative_function const&);
};
}}}}
#endif
| {
"pile_set_name": "Github"
} |
---
layout: postag
title: 'PRON'
shortdef: 'pronoun'
udver: '2'
---
### Definition
Pronouns are words that substitute for [nouns](NOUN) or noun phrases,
whose meaning is recoverable from the linguistic or extralinguistic
context.
Pronouns under this definition function like nouns. Note that some
languages traditionally extend the term _pronoun_ to words that
substitute for [adjectives](ADJ). Such words are not tagged `PRON`
under our universal scheme. They are tagged as [determiners](DET) in
order to annotate the same thing the same way across languages.
It is not always crystal clear where pronouns end and determiners start.
Unlike in UD v1 it is no longer required that they are told apart solely on
the base of the context. The words can be pre-classified in the dictionary
as either `PRON` or `DET`, based on their _typical_ syntactic distribution
(and morphology, when applicable).
Language-specific documentation should list all pronouns (it is a closed class)
and point out ambiguities, if any.
See also [general principles on pronominal words](../overview/morphology.html#pronominal-words)
for more tips on how to define pronouns.
In particular:
* Non-possessive personal, reflexive or reciprocal pronouns are always tagged `PRON`.
* Possessives vary across languages. In some languages the above tests put them in the `DET` category.
In others, they are more like a normal personal pronoun in a specific case (often the genitive), or a personal pronoun with an adposition; they are tagged `PRON`.
### Examples
- personal pronouns: _I, you, he, she, it, we, they_
- reflexive pronouns: _myself, yourself, himself, herself, itself, ourselves, yourselves, theirselves_
- interrogative pronouns: _who, what_ as in _<b>What</b> do you think?_
- relative pronouns: _who, what_ as in _I wonder <b>what</b> you think._ (Note, however, that some relative clause introducing words, such as [en] _that_ are better analyzed as subordinating conjunctions (otherwise known as “complementizers” in the literature), and so are tagged as [SCONJ]().)
- indefinite pronouns: _somebody, something, anybody, anything_
- total pronouns: _everybody, everything_
- negative pronouns: _nobody, nothing_
- possessive pronouns (which usually stand alone as a nominal): _mine, yours, (his), hers, (its), ours, theirs_
### References
- [Loos, Eugene E., et al. 2003. Glossary of linguistic terms: What is a pronoun?](http://www-01.sil.org/linguistics/GlossaryOfLinguisticTerms/WhatIsAPronoun.htm)
- [Wikipedia](http://en.wikipedia.org/wiki/Pronoun)
| {
"pile_set_name": "Github"
} |
package com.zandero.rest.data;
import com.zandero.rest.exception.*;
import com.zandero.rest.reader.*;
import com.zandero.rest.test.data.SimulatedUser;
import com.zandero.rest.test.handler.IllegalArgumentExceptionHandler;
import io.vertx.ext.auth.AbstractUser;
import org.junit.jupiter.api.Test;
import javax.ws.rs.*;
import java.lang.reflect.Type;
import static com.zandero.rest.data.ClassUtils.*;
import static org.junit.jupiter.api.Assertions.*;
public class ClassUtilsTest {
@Test
void getGenericTypeTest() {
assertNull(getGenericType(DummyBodyReader.class)); // type erasure ... we can't tell
assertEquals(Integer.class, getGenericType(IntegerBodyReader.class)); // at least we know so much
assertEquals(IllegalArgumentException.class, getGenericType(IllegalArgumentExceptionHandler.class)); // at least we know so much
assertEquals(WebApplicationException.class, getGenericType(WebApplicationExceptionHandler.class)); // at least we know so much
}
@Test
void typeAreCompatibleTest() {
Type type = getGenericType(NumberFormatException.class);
try {
checkIfCompatibleType(IllegalArgumentException.class, type, "Fail");
} catch (Exception e) {
fail(e.getMessage());
}
}
@Test
void checkIfCompatibleTypes() {
assertTrue(checkIfCompatibleType(SimulatedUser.class, AbstractUser.class));
}
@Test
void inheritedTypeAreCompatibleTest() {
Type type = getGenericType(WebApplicationExceptionHandler.class);
checkIfCompatibleType(WebApplicationException.class, type, "Fail");
checkIfCompatibleType(NotAllowedException.class, type, "Fail");
}
@Test
void convertPrimitiveTypes() throws ClassFactoryException {
assertEquals(1, stringToPrimitiveType("1", int.class));
assertEquals(false, stringToPrimitiveType("FALSE", boolean.class));
assertEquals('a', stringToPrimitiveType("a", char.class));
assertEquals((short) 100, stringToPrimitiveType("100", short.class));
assertEquals(100_100_100L, stringToPrimitiveType("100100100", long.class));
assertEquals((float) 100100.98, stringToPrimitiveType("100100.98", float.class));
assertEquals(100100.987, stringToPrimitiveType("100100.987", double.class));
}
@Test
void convertNullableTypes() throws ClassFactoryException {
assertEquals(1, stringToPrimitiveType("1", Integer.class));
assertEquals(false, stringToPrimitiveType("FALSE", Boolean.class));
assertEquals('a', stringToPrimitiveType("a", Character.class));
assertEquals((short) 100, stringToPrimitiveType("100", Short.class));
assertEquals(100_100_100L, stringToPrimitiveType("100100100", Long.class));
assertEquals((float) 100100.98, stringToPrimitiveType("100100.98", Float.class));
assertEquals(100100.987, stringToPrimitiveType("100100.987", Double.class));
}
@Test
void convertFail() {
ClassFactoryException e = assertThrows(ClassFactoryException.class,
() -> stringToPrimitiveType("A", Integer.class));
assertEquals("Failed to convert value: 'A', to primitive type: java.lang.Integer", e.getMessage());
}
}
| {
"pile_set_name": "Github"
} |
/*<FILE_LICENSE>
* Azos (A to Z Application Operating System) Framework
* The A to Z Foundation (a.k.a. Azist) licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
</FILE_LICENSE>*/
using Azos.Conf;
using Azos.Glue;
using Azos.Instrumentation;
using Azos.Security;
using Azos.Serialization.BSON;
using Azos.Serialization.JSON;
using Azos.Web;
namespace Azos.Data.Access.MongoDb.Connector.Instrumentation
{
/// <summary>
/// Provides direct Mongo command execution capability
/// </summary>
[SystemAdministratorPermission(AccessLevel.ADVANCED)]
public sealed class DirectDb : ExternalCallRequest<MongoClient>
{
public DirectDb(MongoClient mongo) : base(mongo) { }
[Config("$s|$srv|$svr|$server|$node|$uri|$host")]
public string Server { get; set; }
[Config("$d|$db|$data|$database")]
public string Database { get; set; }
[Config("$c|$cmd|$command")]
public string Command { get; set; }
public override ExternalCallResponse Describe()
=> new ExternalCallResponse(ContentType.TEXT,
@"Pipes Mongo JSON command directly into database.
For the list of commands see:
https://docs.mongodb.com/manual/reference/command/find/
https://docs.mongodb.com/manual/reference/command/delete/
https://docs.mongodb.com/manual/reference/command/createIndexes/");
public override ExternalCallResponse Execute()
{
var request = new BSONDocument(Command, false);
var server = Context[new Node(Server)];
var db = server[Database];
var response = db.RunCommand(request);
var json = response.ToJson(JsonWritingOptions.PrettyPrintASCII);
return new ExternalCallResponse(ContentType.JSON, json);
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="PythonScript" module="Products.PythonScripts.PythonScript"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>Script_magic</string> </key>
<value> <int>3</int> </value>
</item>
<item>
<key> <string>_bind_names</string> </key>
<value>
<object>
<klass>
<global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/>
</klass>
<tuple/>
<state>
<dictionary>
<item>
<key> <string>_asgns</string> </key>
<value>
<dictionary>
<item>
<key> <string>name_container</string> </key>
<value> <string>container</string> </value>
</item>
<item>
<key> <string>name_context</string> </key>
<value> <string>context</string> </value>
</item>
<item>
<key> <string>name_m_self</string> </key>
<value> <string>script</string> </value>
</item>
<item>
<key> <string>name_subpath</string> </key>
<value> <string>traverse_subpath</string> </value>
</item>
</dictionary>
</value>
</item>
</dictionary>
</state>
</object>
</value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>GlossaryModule_getTemplateList</string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
| {
"pile_set_name": "Github"
} |
name: Isabelle
version: 0.01
release: September 21, 2005
src: http://www.cse.ogi.edu/~hallgren/Programatica/
description: Formal proof by embedding of Haskell in Isabelle HOL-CF
attribute: name=conc, type=string/assertion, label=Conclusion, required
attribute: name=hyp, type=string, label="Depends on", optional
attribute: name=file/proof, type=string/file, required
attribute: name=proof, type=string/identifier, required
attribute: name=Comment, type=string
attribute: name=SimplePatterns, type=bool, label="Simple Patterns"
| {
"pile_set_name": "Github"
} |
//===--- DefaultOperatorNewCheck.h - clang-tidy -----------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CERT_DEFAULTOPERATORNEWALIGNMENTCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CERT_DEFAULTOPERATORNEWALIGNMENTCHECK_H
#include "../ClangTidyCheck.h"
namespace clang {
namespace tidy {
namespace cert {
/// Checks if an object of type with extended alignment is allocated by using
/// the default operator new.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/cert-mem57-cpp.html
class DefaultOperatorNewAlignmentCheck : public ClangTidyCheck {
public:
DefaultOperatorNewAlignmentCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
return !LangOpts.CPlusPlus17;
}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace cert
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CERT_DEFAULTOPERATORNEWALIGNMENTCHECK_H
| {
"pile_set_name": "Github"
} |
application: astute-curve-100822
version: 1
runtime: go
api_version: go1
handlers:
- url: /.*
script: _go_app
| {
"pile_set_name": "Github"
} |
Just a [URL](/url/).
[URL and title](/url/ "title").
[URL and title](/url/ "title preceded by two spaces").
[URL and title](/url/ "title preceded by a tab").
[URL and title](/url/ "title has spaces afterward" ).
[URL and title]( /url/has space ).
[URL and title]( /url/has space/ "url has space and title").
[Empty]().
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nl.bryanderidder.demo_horizontal_scroll">
<application
android:allowBackup="true"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".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"
} |
//
// main.m
// SinaMBlogNimbus
//
// Created by jimneylee on 13-10-30.
// Copyright (c) 2013年 jimneylee. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utilities for working with W3C multi-part ranges.
*
* @author [email protected] (Robby Walker)
*/
goog.provide('goog.dom.MultiRange');
goog.provide('goog.dom.MultiRangeIterator');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.AbstractMultiRange');
goog.require('goog.dom.AbstractRange');
goog.require('goog.dom.RangeIterator');
goog.require('goog.dom.RangeType');
goog.require('goog.dom.SavedRange');
goog.require('goog.dom.TextRange');
goog.require('goog.iter');
goog.require('goog.iter.StopIteration');
goog.require('goog.log');
/**
* Creates a new multi part range with no properties. Do not use this
* constructor: use one of the goog.dom.Range.createFrom* methods instead.
* @constructor
* @extends {goog.dom.AbstractMultiRange}
* @final
*/
goog.dom.MultiRange = function() {
/**
* Logging object.
* @private {goog.log.Logger}
*/
this.logger_ = goog.log.getLogger('goog.dom.MultiRange');
/**
* Array of browser sub-ranges comprising this multi-range.
* @private {Array<Range>}
*/
this.browserRanges_ = [];
/**
* Lazily initialized array of range objects comprising this multi-range.
* @private {Array<goog.dom.TextRange>}
*/
this.ranges_ = [];
/**
* Lazily computed sorted version of ranges_, sorted by start point.
* @private {Array<goog.dom.TextRange>?}
*/
this.sortedRanges_ = null;
/**
* Lazily computed container node.
* @private {Node}
*/
this.container_ = null;
};
goog.inherits(goog.dom.MultiRange, goog.dom.AbstractMultiRange);
/**
* Creates a new range wrapper from the given browser selection object. Do not
* use this method directly - please use goog.dom.Range.createFrom* instead.
* @param {Selection} selection The browser selection object.
* @return {!goog.dom.MultiRange} A range wrapper object.
*/
goog.dom.MultiRange.createFromBrowserSelection = function(selection) {
var range = new goog.dom.MultiRange();
for (var i = 0, len = selection.rangeCount; i < len; i++) {
range.browserRanges_.push(selection.getRangeAt(i));
}
return range;
};
/**
* Creates a new range wrapper from the given browser ranges. Do not
* use this method directly - please use goog.dom.Range.createFrom* instead.
* @param {Array<Range>} browserRanges The browser ranges.
* @return {!goog.dom.MultiRange} A range wrapper object.
*/
goog.dom.MultiRange.createFromBrowserRanges = function(browserRanges) {
var range = new goog.dom.MultiRange();
range.browserRanges_ = goog.array.clone(browserRanges);
return range;
};
/**
* Creates a new range wrapper from the given goog.dom.TextRange objects. Do
* not use this method directly - please use goog.dom.Range.createFrom* instead.
* @param {Array<goog.dom.TextRange>} textRanges The text range objects.
* @return {!goog.dom.MultiRange} A range wrapper object.
*/
goog.dom.MultiRange.createFromTextRanges = function(textRanges) {
var range = new goog.dom.MultiRange();
range.ranges_ = textRanges;
range.browserRanges_ = goog.array.map(
textRanges, function(range) { return range.getBrowserRangeObject(); });
return range;
};
// Method implementations
/**
* Clears cached values. Should be called whenever this.browserRanges_ is
* modified.
* @private
*/
goog.dom.MultiRange.prototype.clearCachedValues_ = function() {
this.ranges_ = [];
this.sortedRanges_ = null;
this.container_ = null;
};
/**
* @return {!goog.dom.MultiRange} A clone of this range.
* @override
*/
goog.dom.MultiRange.prototype.clone = function() {
return goog.dom.MultiRange.createFromBrowserRanges(this.browserRanges_);
};
/** @override */
goog.dom.MultiRange.prototype.getType = function() {
return goog.dom.RangeType.MULTI;
};
/** @override */
goog.dom.MultiRange.prototype.getBrowserRangeObject = function() {
// NOTE(robbyw): This method does not make sense for multi-ranges.
if (this.browserRanges_.length > 1) {
goog.log.warning(
this.logger_,
'getBrowserRangeObject called on MultiRange with more than 1 range');
}
return this.browserRanges_[0];
};
/** @override */
goog.dom.MultiRange.prototype.setBrowserRangeObject = function(nativeRange) {
// TODO(robbyw): Look in to adding setBrowserSelectionObject.
return false;
};
/** @override */
goog.dom.MultiRange.prototype.getTextRangeCount = function() {
return this.browserRanges_.length;
};
/** @override */
goog.dom.MultiRange.prototype.getTextRange = function(i) {
if (!this.ranges_[i]) {
this.ranges_[i] =
goog.dom.TextRange.createFromBrowserRange(this.browserRanges_[i]);
}
return this.ranges_[i];
};
/** @override */
goog.dom.MultiRange.prototype.getContainer = function() {
if (!this.container_) {
var nodes = [];
for (var i = 0, len = this.getTextRangeCount(); i < len; i++) {
nodes.push(this.getTextRange(i).getContainer());
}
this.container_ = goog.dom.findCommonAncestor.apply(null, nodes);
}
return this.container_;
};
/**
* @return {!Array<goog.dom.TextRange>} An array of sub-ranges, sorted by start
* point.
*/
goog.dom.MultiRange.prototype.getSortedRanges = function() {
if (!this.sortedRanges_) {
this.sortedRanges_ = this.getTextRanges();
this.sortedRanges_.sort(function(a, b) {
var aStartNode = a.getStartNode();
var aStartOffset = a.getStartOffset();
var bStartNode = b.getStartNode();
var bStartOffset = b.getStartOffset();
if (aStartNode == bStartNode && aStartOffset == bStartOffset) {
return 0;
}
/**
* @suppress {missingRequire} Cannot depend on goog.dom.Range because
* it creates a circular dependency.
*/
return goog.dom.Range.isReversed(
aStartNode, aStartOffset, bStartNode, bStartOffset) ?
1 :
-1;
});
}
return this.sortedRanges_;
};
/** @override */
goog.dom.MultiRange.prototype.getStartNode = function() {
return this.getSortedRanges()[0].getStartNode();
};
/** @override */
goog.dom.MultiRange.prototype.getStartOffset = function() {
return this.getSortedRanges()[0].getStartOffset();
};
/** @override */
goog.dom.MultiRange.prototype.getEndNode = function() {
// NOTE(robbyw): This may return the wrong node if any subranges overlap.
return goog.array.peek(this.getSortedRanges()).getEndNode();
};
/** @override */
goog.dom.MultiRange.prototype.getEndOffset = function() {
// NOTE(robbyw): This may return the wrong value if any subranges overlap.
return goog.array.peek(this.getSortedRanges()).getEndOffset();
};
/** @override */
goog.dom.MultiRange.prototype.isRangeInDocument = function() {
return goog.array.every(this.getTextRanges(), function(range) {
return range.isRangeInDocument();
});
};
/** @override */
goog.dom.MultiRange.prototype.isCollapsed = function() {
return this.browserRanges_.length == 0 ||
this.browserRanges_.length == 1 && this.getTextRange(0).isCollapsed();
};
/** @override */
goog.dom.MultiRange.prototype.getText = function() {
return goog.array
.map(this.getTextRanges(), function(range) { return range.getText(); })
.join('');
};
/** @override */
goog.dom.MultiRange.prototype.getHtmlFragment = function() {
return this.getValidHtml();
};
/** @override */
goog.dom.MultiRange.prototype.getValidHtml = function() {
// NOTE(robbyw): This does not behave well if the sub-ranges overlap.
return goog.array
.map(
this.getTextRanges(),
function(range) { return range.getValidHtml(); })
.join('');
};
/** @override */
goog.dom.MultiRange.prototype.getPastableHtml = function() {
// TODO(robbyw): This should probably do something smart like group TR and TD
// selections in to the same table.
return this.getValidHtml();
};
/** @override */
goog.dom.MultiRange.prototype.__iterator__ = function(opt_keys) {
return new goog.dom.MultiRangeIterator(this);
};
// RANGE ACTIONS
/** @override */
goog.dom.MultiRange.prototype.select = function() {
var selection =
goog.dom.AbstractRange.getBrowserSelectionForWindow(this.getWindow());
selection.removeAllRanges();
for (var i = 0, len = this.getTextRangeCount(); i < len; i++) {
selection.addRange(this.getTextRange(i).getBrowserRangeObject());
}
};
/** @override */
goog.dom.MultiRange.prototype.removeContents = function() {
goog.array.forEach(
this.getTextRanges(), function(range) { range.removeContents(); });
};
// SAVE/RESTORE
/** @override */
goog.dom.MultiRange.prototype.saveUsingDom = function() {
return new goog.dom.DomSavedMultiRange_(this);
};
// RANGE MODIFICATION
/**
* Collapses this range to a single point, either the first or last point
* depending on the parameter. This will result in the number of ranges in this
* multi range becoming 1.
* @param {boolean} toAnchor Whether to collapse to the anchor.
* @override
*/
goog.dom.MultiRange.prototype.collapse = function(toAnchor) {
if (!this.isCollapsed()) {
var range = toAnchor ? this.getTextRange(0) :
this.getTextRange(this.getTextRangeCount() - 1);
this.clearCachedValues_();
range.collapse(toAnchor);
this.ranges_ = [range];
this.sortedRanges_ = [range];
this.browserRanges_ = [range.getBrowserRangeObject()];
}
};
// SAVED RANGE OBJECTS
/**
* A SavedRange implementation using DOM endpoints.
* @param {goog.dom.MultiRange} range The range to save.
* @constructor
* @extends {goog.dom.SavedRange}
* @private
*/
goog.dom.DomSavedMultiRange_ = function(range) {
/**
* Array of saved ranges.
* @type {Array<goog.dom.SavedRange>}
* @private
*/
this.savedRanges_ = goog.array.map(
range.getTextRanges(), function(range) { return range.saveUsingDom(); });
};
goog.inherits(goog.dom.DomSavedMultiRange_, goog.dom.SavedRange);
/**
* @return {!goog.dom.MultiRange} The restored range.
* @override
*/
goog.dom.DomSavedMultiRange_.prototype.restoreInternal = function() {
var ranges = goog.array.map(
this.savedRanges_, function(savedRange) { return savedRange.restore(); });
return goog.dom.MultiRange.createFromTextRanges(ranges);
};
/** @override */
goog.dom.DomSavedMultiRange_.prototype.disposeInternal = function() {
goog.dom.DomSavedMultiRange_.superClass_.disposeInternal.call(this);
goog.array.forEach(
this.savedRanges_, function(savedRange) { savedRange.dispose(); });
delete this.savedRanges_;
};
// RANGE ITERATION
/**
* Subclass of goog.dom.TagIterator that iterates over a DOM range. It
* adds functions to determine the portion of each text node that is selected.
*
* @param {goog.dom.MultiRange} range The range to traverse.
* @constructor
* @extends {goog.dom.RangeIterator}
* @final
*/
goog.dom.MultiRangeIterator = function(range) {
/**
* The list of range iterators left to traverse.
* @private {Array<goog.dom.RangeIterator>}
*/
this.iterators_ = null;
/**
* The index of the current sub-iterator being traversed.
* @private {number}
*/
this.currentIdx_ = 0;
if (range) {
this.iterators_ = goog.array.map(range.getSortedRanges(), function(r) {
return goog.iter.toIterator(r);
});
}
goog.dom.MultiRangeIterator.base(
this, 'constructor', range ? this.getStartNode() : null, false);
};
goog.inherits(goog.dom.MultiRangeIterator, goog.dom.RangeIterator);
/** @override */
goog.dom.MultiRangeIterator.prototype.getStartTextOffset = function() {
return this.iterators_[this.currentIdx_].getStartTextOffset();
};
/** @override */
goog.dom.MultiRangeIterator.prototype.getEndTextOffset = function() {
return this.iterators_[this.currentIdx_].getEndTextOffset();
};
/** @override */
goog.dom.MultiRangeIterator.prototype.getStartNode = function() {
return this.iterators_[0].getStartNode();
};
/** @override */
goog.dom.MultiRangeIterator.prototype.getEndNode = function() {
return goog.array.peek(this.iterators_).getEndNode();
};
/** @override */
goog.dom.MultiRangeIterator.prototype.isLast = function() {
return this.iterators_[this.currentIdx_].isLast();
};
/** @override */
goog.dom.MultiRangeIterator.prototype.next = function() {
try {
var it = this.iterators_[this.currentIdx_];
var next = it.next();
this.setPosition(it.node, it.tagType, it.depth);
return next;
} catch (ex) {
if (ex !== goog.iter.StopIteration ||
this.iterators_.length - 1 == this.currentIdx_) {
throw ex;
} else {
// In case we got a StopIteration, increment counter and try again.
this.currentIdx_++;
return this.next();
}
}
};
/** @override */
goog.dom.MultiRangeIterator.prototype.copyFrom = function(other) {
this.iterators_ = goog.array.clone(other.iterators_);
goog.dom.MultiRangeIterator.superClass_.copyFrom.call(this, other);
};
/**
* @return {!goog.dom.MultiRangeIterator} An identical iterator.
* @override
*/
goog.dom.MultiRangeIterator.prototype.clone = function() {
var copy = new goog.dom.MultiRangeIterator(null);
copy.copyFrom(this);
return copy;
};
| {
"pile_set_name": "Github"
} |
package org.wicketstuff.datatables.res;
import org.apache.wicket.request.resource.CssResourceReference;
/**
*
*/
public class DataTablesCssReference extends CssResourceReference {
public DataTablesCssReference() {
super(DataTablesCssReference.class, "css/jquery.dataTables.css");
}
}
| {
"pile_set_name": "Github"
} |
// ---------------------------------------------------------------------------------------
// <copyright file="SpectrumCycling.cs" company="Corale">
// Copyright © 2015-2016 by Adam Hellberg and Brandon Scott.
//
// 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.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Corale.Colore.Razer.Mouse.Effects
{
using System;
using Corale.Colore.Annotations;
/// <summary>
/// Spectrum cycling effect.
/// </summary>
[Obsolete("Use custom effects instead.")]
public struct SpectrumCycling
{
/// <summary>
/// The LED on which to apply the effect.
/// </summary>
[UsedImplicitly]
public readonly Led Led;
/// <summary>
/// Initializes a new instance of the <see cref="SpectrumCycling" /> struct.
/// </summary>
/// <param name="led">The LED on which to apply the effect.</param>
public SpectrumCycling(Led led)
{
Led = led;
}
}
}
| {
"pile_set_name": "Github"
} |
From 4b5a135fa681e85eb6988a379f59f3c7a41cc48c Mon Sep 17 00:00:00 2001
From: Gilles Talis <[email protected]>
Date: Fri, 21 Jun 2013 15:25:11 -0700
Subject: [PATCH 1/2] Disable building test programs
We are not really interested in building test programs.
Moreover, these programs use fork() function that is
not available on MMU-less architectures.
Signed-off-by: Gilles Talis <[email protected]>
[[email protected]: Updated for 2.1.8]
Signed-off-by: Adam Duskett <[email protected]>
---
Makefile.am | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Makefile.am b/Makefile.am
index 42879a3..dc90359 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -144,7 +144,6 @@
BUILT_SOURCES =
include include/include.am
include sample/include.am
-include test/include.am
if BUILD_WIN32
--
2.1.1
| {
"pile_set_name": "Github"
} |
cout << MatrixXd::Identity(4, 3) << endl;
| {
"pile_set_name": "Github"
} |
Emacspeak-17.0 (HappyDog) Unleashed!
----------------------------------
For Immediate Release:
San Jose, Calif., (November 23, 2002)
Emacspeak-2003: Empowering Experienced Users
--Zero cost of ownership makes priceless software affordable!
Emacspeak Inc (NASDOG: ESPK) --http://emacspeak.sf.net--
announces the immediate world-wide availability of Emacspeak 17.0
--a powerful audio desktop for leveraging today's evolving
semantic WWW.
Investors Note:
---------------
With several prominent analysts initiating coverage, NASDOG: ESPK
is now trading over the net at levels close to that recently
attained by last year's DogCom high-fliers.
What Is It?
-----------
Emacspeak is a fully functional audio desktop that provides
complete eyes-free access to all major 32 and 64 bit operating
environments. By seamlessly blending all aspects of the Internet
such as Web-surfing and electronic messaging into the audio
desktop, Emacspeak enables speech access to local and remote
information with a consistent and well-integrated user interface.
A rich suite of task-oriented tools provides efficient
speech-enabled access to the evolving semantic WWW.
Major Enhancements:
-------------------
1) Enhanced Emacs 21 support.
2) emacspeak-w3.el --smart content filters using XSLT.
3) emacspeak-websearch.el --Search wizards using content filters.
4) emacspeak-url-template.el --Programmable url templates using content filters.
5) emacspeak-wizards.el --Additional productivity wizards.
6) Software Dectalk --Speech server for Software Dectalk TTS.
7) emacspeak-rpm-spec.el --Editing RPM spec files.
8) emacspeak-m-player.el --Media player interface.
9) emacspeak-pronounce.el Custom dictionaries for smileys and XMl namespaces.
10) emacspeak-ecb.el --Enhanced ECB support.
See the NEWS file for additional details.
Establishing Freedom:
---------------------
Emacspeak is now voluntarily bundled with all major Linux
distributions. Though designed to be modular, distributors have
freely chosen to bundle the entire system without any undue
pressure. The integrity of the Emacspeak codebase is ensured by
the reliable and secure Linux platform used to develop the
software.
Extensive studies have shown that thanks to these features, users
consider Emacspeak to be absolutely priceless. Thanks to this
wide-spread user demand, the present version is being made
available at the same zero-cost as earlier releases.
At the same time, Emacspeak-2003 continues to innovate in the
area of speech and multimodal interaction and carries forward the
well-established Open Source tradition of introducing user
interface features that eventually show up in luser environments.
On this theme, when once challenged by a proponent of a
crash-prone but well-marketed windowing system with the assertion
"Emacs is a system from the 70's", the creator of Emacspeak
expressed surprise at the unusual candor manifest in the
assertion that it would take popular idiot-proven interfaces
until the year 2070 to catch up to where the Emacspeak audio
desktop is today. Industry experts welcomed this refreshing
breath of Courage Certainty and Clarity (CCC) at a time when
users are reeling from the Fear Uncertainty and Doubt (FUD)
unleashed by complex software systems backed by even more
convoluted press releases.
Independent Test Results:
-------------------------
Independent test results have proven that unlike some modern
software, Emacspeak can be safely uninstalled without adversely
affecting the continued performance of the computer. These same
tests also revealed that once uninstalled, the user stopped
functioning altogether. Speaking with Aster Labrador, the creator
of Emacspeak once pointed out that these results re-emphasize the
user-centric design of Emacspeak; "It is the user --and not the
computer-- that stops functioning when Emacspeak is
uninstalled!".
Note from Aster and Bubbles:
----------------------------
UnDoctored Videos Inc. is currently looking for volunteers to
star in a video demonstrating such complete user failure.
Obtaining Emacspeak:
--------------------
Emacspeak can be downloaded from sourceforge --see
http://prdownloads.sourceforge.net/emacspeak/ You can visit
Emacspeak on the WWW at http://emacspeak.sf.net or
http://www.cs.cornell.edu/home/raman/emacspeak. You can subscribe
to the emacspeak mailing list [email protected] by sending
mail to the list request address [email protected].
The latest development snapshot of Emacspeak is available via
anonymous CVS from sourceforge.
History:
--------
Emacspeak-17.0 --code named HappyDog-- enhances user productivity by
exploiting today's evolving WWW standards. Emacspeak-16.0 --code named
CleverDog-- the follow-up to SmartDog-- continued the tradition of
working better, faster, smarter. Emacspeak-15.0 --code named
SmartDog--followed up on TopDog as the next in a continuing a series
of award-winning audio desktop releases from Emacspeak Inc.
Emacspeak-14.0 --code named TopDog--was the first release of this
millennium. Emacspeak-13.0 --codenamed YellowLab-- was the closing
release of the 20th. century. Emacspeak-12.0 --code named GoldenDog--
began leveraging the evolving semantic WWW to provide task-oriented
speech access to Webformation. Emacspeak-11.0 --code named Aster--
went the final step in making Linux a zero-cost Internet access
solution for blind and visually impaired users. Emacspeak-10.0 --(AKA
Emacspeak-2000) code named WonderDog-- continued the tradition of
award-winning software releases designed to make eyes-free computing a
productive and pleasurable experience. Emacspeak-9.0 --(AKA Emacspeak
99) code named BlackLab-- continued to innovate in the areas of speech
interaction and interactive accessibility. Emacspeak-8.0 --(AKA
Emacspeak-98++) code named BlackDog-- was a major upgrade to the
speech output extension to Emacs.
Emacspeak-95 (code named Illinois) was released as OpenSource on
the Internet in May 1995 as the first complete speech interface
to UNIX workstations. The subsequent release, Emacspeak-96 (code
named Egypt) made available in May 1996 provided significant
enhancements to the interface. Emacspeak-97 (Tennessee) went
further in providing a true audio desktop. Emacspeak-98
integrated Internetworking into all aspects of the audio desktop
to provide the first fully interactive speech-enabled WebTop.
About Emacspeak:
----------------
Based at Cornell (NY) http://www.cs.cornell.edu/home/raman
--home to Auditory User Interfaces (AUI) on the WWW-- and
SourceForge --http://emacspeak.sf.net-- Emacspeak is mirrored
world-wide by an international network of software archives
and bundled voluntarily with all major Linux distributions. On
Monday, April 12, 1999, Emacspeak became part of the
Smithsonian's Permanent Research Collection on Information
Technology at the Smithsonian's National Museum of American
History.
The Emacspeak mailing list is archived at Vassar --the home of the
Emacspeak mailing list-- thanks to Greg Priest-Dorman, and provides a
valuable knowledge base for new users.
Press/Analyst Contact: Hubbell Labrador
Going forward, BubbleDog acknowledges her monopoly on setting the
direction of the Emacspeak Audio Desktop, and promises to exercise
this freedom to innovate and her resulting power responsibly (as
before).
About This Release:
------------------
According to Hubbell Labrador, this release does not contain
the much-vaunted SmartTag feature --despite the codename.
Emacspeak Inc. promises to introduce SmartDogs soon based on
customer demand.
Windows-Free (WF) is a favorite battle-cry of The League Against
Forced Fenestration (LAFF). --see
http://www.usdoj.gov/atr/cases/f3800/msjudgex.htm for details on
the ill-effects of Forced Fenestration.
CopyWrite )C( Aster and Hubbell Labrador. All Writes Reserved.
GoldenDog (DM), BlackDog (DM) etc., are Registered Dogmarks of Aster and Hubbell Labrador.
All other dogs belong to their respective owners.
| {
"pile_set_name": "Github"
} |
#include <stdio.h>
int x;
int y;
int main() {
for (x=0, y=1; x < 6; x++, y=y+2) {
printf("%d %d\n", x, y);
}
return(0);
}
| {
"pile_set_name": "Github"
} |
from CommonServerPython import *
RETURN_ERROR_TARGET = 'AbuseDB.return_error'
class DotDict(dict):
"""dot.notation access to dictionary attributes"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def test_ip_command_when_api_quota_reached(mocker):
from requests import Session
def json_func():
return {}
api_quota_reached_request_response = {
'status_code': 429,
'json': json_func
}
params = {
'server': 'test',
'proxy': True,
'disregard_quota': True
}
api_quota_reached_request_response_with_dot_access = DotDict(api_quota_reached_request_response)
mocker.patch.object(demisto, 'params', return_value=params)
mocker.patch.object(Session, 'request', return_value=api_quota_reached_request_response_with_dot_access)
return_error_mock = mocker.patch(RETURN_ERROR_TARGET)
from AbuseDB import check_ip_command
check_ip_command(['1.1.1.1'], days=7, verbose=False, threshold=10)
assert return_error_mock.call_count == 0
| {
"pile_set_name": "Github"
} |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. 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 apmtest
import (
"log"
"go.elastic.co/apm"
"go.elastic.co/apm/transport/transporttest"
)
// DiscardTracer is an apm.Tracer that discards all events.
//
// This tracer may be used by multiple tests, and so should
// not be modified or closed.
//
// Importing apmttest will close apm.DefaultTracer, and update
// it to this value.
var DiscardTracer *apm.Tracer
// NewDiscardTracer returns a new apm.Tracer that discards all events.
func NewDiscardTracer() *apm.Tracer {
tracer, err := apm.NewTracerOptions(apm.TracerOptions{
Transport: transporttest.Discard,
})
if err != nil {
log.Fatal(err)
}
return tracer
}
func init() {
apm.DefaultTracer.Close()
tracer := NewDiscardTracer()
DiscardTracer = tracer
apm.DefaultTracer = DiscardTracer
}
| {
"pile_set_name": "Github"
} |
package ssh
import (
"errors"
"io"
"net"
)
// streamLocalChannelOpenDirectMsg is a struct used for SSH_MSG_CHANNEL_OPEN message
// with "[email protected]" string.
//
// See openssh-portable/PROTOCOL, section 2.4. connection: Unix domain socket forwarding
// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL#L235
type streamLocalChannelOpenDirectMsg struct {
socketPath string
reserved0 string
reserved1 uint32
}
// forwardedStreamLocalPayload is a struct used for SSH_MSG_CHANNEL_OPEN message
// with "[email protected]" string.
type forwardedStreamLocalPayload struct {
SocketPath string
Reserved0 string
}
// streamLocalChannelForwardMsg is a struct used for SSH2_MSG_GLOBAL_REQUEST message
// with "[email protected]"/"[email protected]" string.
type streamLocalChannelForwardMsg struct {
socketPath string
}
// ListenUnix is similar to ListenTCP but uses a Unix domain socket.
func (c *Client) ListenUnix(socketPath string) (net.Listener, error) {
m := streamLocalChannelForwardMsg{
socketPath,
}
// send message
ok, _, err := c.SendRequest("[email protected]", true, Marshal(&m))
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("ssh: [email protected] request denied by peer")
}
ch := c.forwards.add(&net.UnixAddr{Name: socketPath, Net: "unix"})
return &unixListener{socketPath, c, ch}, nil
}
func (c *Client) dialStreamLocal(socketPath string) (Channel, error) {
msg := streamLocalChannelOpenDirectMsg{
socketPath: socketPath,
}
ch, in, err := c.OpenChannel("[email protected]", Marshal(&msg))
if err != nil {
return nil, err
}
go DiscardRequests(in)
return ch, err
}
type unixListener struct {
socketPath string
conn *Client
in <-chan forward
}
// Accept waits for and returns the next connection to the listener.
func (l *unixListener) Accept() (net.Conn, error) {
s, ok := <-l.in
if !ok {
return nil, io.EOF
}
ch, incoming, err := s.newCh.Accept()
if err != nil {
return nil, err
}
go DiscardRequests(incoming)
return &chanConn{
Channel: ch,
laddr: &net.UnixAddr{
Name: l.socketPath,
Net: "unix",
},
raddr: &net.UnixAddr{
Name: "@",
Net: "unix",
},
}, nil
}
// Close closes the listener.
func (l *unixListener) Close() error {
// this also closes the listener.
l.conn.forwards.remove(&net.UnixAddr{Name: l.socketPath, Net: "unix"})
m := streamLocalChannelForwardMsg{
l.socketPath,
}
ok, _, err := l.conn.SendRequest("[email protected]", true, Marshal(&m))
if err == nil && !ok {
err = errors.New("ssh: [email protected] failed")
}
return err
}
// Addr returns the listener's network address.
func (l *unixListener) Addr() net.Addr {
return &net.UnixAddr{
Name: l.socketPath,
Net: "unix",
}
}
| {
"pile_set_name": "Github"
} |
(function() {var implementors = {};
implementors['std'] = ["impl <a class='trait' href='std/ops/trait.Div.html' title='std::ops::Div'>Div</a><<a class='primitive' href='primitive.u32.html'>u32</a>> for <a class='struct' href='std/time/struct.Duration.html' title='std::time::Duration'>Duration</a>",];
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
})()
| {
"pile_set_name": "Github"
} |
import DatePicker from '../date-picker/DatePicker';
import { ViewMode } from '../date-picker/enum';
export default class MonthPicker extends DatePicker {
static displayName = 'MonthPicker';
static defaultProps = {
...DatePicker.defaultProps,
mode: ViewMode.month,
};
}
| {
"pile_set_name": "Github"
} |
var binary = require('../');
var test = require('tap').test;
var EventEmitter = require('events').EventEmitter;
test('split', function (t) {
t.plan(1);
var em = new EventEmitter;
binary.stream(em)
.word8('a')
.word16be('bc')
.word32ls('x')
.word32bs('y')
.tap(function (vars) {
t.same(vars, {
a : 97,
bc : 25187,
x : 621609828,
y : 621609828,
});
})
;
em.emit('data', new Buffer([ 97, 98 ]));
setTimeout(function () {
em.emit('data', new Buffer([ 99, 100 ]));
}, 25);
setTimeout(function () {
em.emit('data', new Buffer([ 3, 13, 37, 37 ]));
}, 30);
setTimeout(function () {
em.emit('data', new Buffer([ 13, 3, 100 ]));
}, 40);
});
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.adapter.vector.query.gwql;
import org.locationtech.geowave.core.store.CloseableIterator;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
/**
* Interface for a set of results from a GeoWave query.
*/
public interface ResultSet extends CloseableIterator<Result> {
/**
* @return the number of columns that each result contains
*/
public int columnCount();
/**
* @param index the index of the column
* @return the display name of the column at the given index
*/
public String columnName(final int index);
/**
* @param index the index of the column
* @return the Class of the objects that can be found in the given column
*/
public Class<?> columnType(final int index);
/**
* @return the coordinate reference system of the geometries in this result set
*/
public CoordinateReferenceSystem getCRS();
}
| {
"pile_set_name": "Github"
} |
#ifdef BLOG_CURRENT_CHANNEL
#undef BLOG_CURRENT_CHANNEL
#endif
#define BLOG_CURRENT_CHANNEL BLOG_CHANNEL_ncd_arithmetic
| {
"pile_set_name": "Github"
} |
var assocIndexOf = require('./_assocIndexOf');
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
| {
"pile_set_name": "Github"
} |
from anvil.util import WrappedObject, WrappedList
from anvil.server import serializable_type
@serializable_type
class Font(WrappedObject):
_name = "Font"
_module = "plotly.graph_objs.cone.colorbar.title"
__all__ = [
'Font',
] | {
"pile_set_name": "Github"
} |
Array3d v(2,3,4);
cout << v.square() << endl;
| {
"pile_set_name": "Github"
} |
(:
Syntax error with an improved error message:
missing semicolon ";" and the location
:)
declare namespace test = "test";
declare variable $var1 := 1;
declare variable $var2 := 2;
declare variable $var3 := 3
$var1
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
import rosbag, rospy
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from filterpy.kalman import KalmanFilter, MerweScaledSigmaPoints
from filterpy.kalman import UnscentedKalmanFilter as UKF
from filterpy.common import Q_discrete_white_noise
from parse_tracklet import parse_xml
# from sync import generate_frame_map
from generate_tracklet import Tracklet, TrackletCollection
from shapely.geometry import Polygon
import pandas as pd
import random, math
from bisect import bisect_left
import numpy as np
from numba import jit
from itertools import combinations
from sklearn.utils.linear_assignment_ import linear_assignment
from scipy.cluster.hierarchy import linkage, fcluster
def normalize_angle(x):
x = x % (2 * np.pi) # force in range [0, 2 pi)
if x > np.pi: # move to [-pi, pi)
x -= 2 * np.pi
return x
def f_cv(x, dt):
""" state transition function for a
constant velocity model (vx,vy)"""
# state x, vx, y, vy, z, yaw
F = np.array([[1, dt, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, dt, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1]])
res = np.dot(F,x)
return np.dot(F, x)
def h_lidar(x):
return np.array([x[0], x[2], x[4], normalize_angle(x[5])])
def h_radar(x):
offset = 0.5 #lidar-radar offset
px,py,vx,vy = (x[0]-offset,x[2],x[1],x[3])
r = (px**2 + py**2)
if (r < 0.1) :
px=py=0.0707
r=0.1
phi = math.atan2(-py,px) # phi positive clockwise but right is negative y
radial_vel = (vx*px + vy*py)/r
lat_vel = (py*vx - px*py)/r
return np.array([r, phi, radial_vel, lat_vel])
def residual_radar(x,y):
res = np.subtract(x,y)
res[1] = (res[1] + np.pi) % (2*np.pi) - np.pi
return res
def intersect_bbox_with_yaw(box_a, box_b):
"""
A simplified calculation of 3d bounding box intersection.
It is assumed that the bounding box is only rotated
around Z axis (yaw) from an axis-aligned box.
:param box_a, box_b: obstacle bounding boxes for comparison
:return: intersection volume (float)
"""
# height (Z) overlap
min_h_a = np.min(box_a[2])
max_h_a = np.max(box_a[2])
min_h_b = np.min(box_b[2])
max_h_b = np.max(box_b[2])
max_of_min = np.max([min_h_a, min_h_b])
min_of_max = np.min([max_h_a, max_h_b])
z_intersection = np.max([0, min_of_max - max_of_min])
if z_intersection == 0:
return 0.
# oriented XY overlap
xy_poly_a = Polygon(zip(*box_a[0:2, 0:4]))
xy_poly_b = Polygon(zip(*box_b[0:2, 0:4]))
xy_intersection = xy_poly_a.intersection(xy_poly_b).area
if xy_intersection == 0:
return 0.
return z_intersection * xy_intersection
def iou_old(bbox_a,bbox_b):
dims_a, dims_b = bbox_a[4:], bbox_b[4:]
box_a = get_bbox(bbox_a[:3], dims_a, bbox_a[3])
box_b = get_bbox(bbox_b[:3], dims_b, bbox_b[3])
vol_intersect = intersect_bbox_with_yaw(box_a, box_b)
union = get_vol_box(dims_a) + get_vol_box(dims_b) - vol_intersect
return vol_intersect / union
def eucl_dist(x,y):
return math.sqrt((x[1]-x[0])**2 + (y[1]-y[0])**2)
def iou(bbox_a, bbox_b):
xa,ya = bbox_a[:2]
xb,yb = bbox_b[:2]
return max(0, 1.-math.sqrt((xa-xb)**2 + (ya-yb)**2)/7) # upto 7m overlap
def get_vol_box(dims):
return dims[0] * dims[1] * dims[2]
def convert_x_to_bbox(x, dims):
return np.concatenate((x[[0,2,4,5]], dims))
def lwh_to_box(l, w, h):
box = np.array([
[-l / 2, -l / 2, l / 2, l / 2, -l / 2, -l / 2, l / 2, l / 2],
[w / 2, -w / 2, -w / 2, w / 2, w / 2, -w / 2, -w / 2, w / 2],
[-h / 2, -h / 2, -h / 2, -h / 2, h / 2, h / 2, h / 2, h / 2],
])
return box
def get_bbox(centroid, dims, yaw):
bbox = lwh_to_box(*dims)
# calc 3D bound box in capture vehicle oriented coordinates
rot_mat = np.array([
[np.cos(yaw), -np.sin(yaw), 0.0],
[np.sin(yaw), np.cos(yaw), 0.0],
[0.0, 0.0, 1.0]])
oriented_bbox = np.dot(rot_mat, bbox) + np.tile(position, (8, 1)).T
return oriented_bbox
class KalmanBoxTracker(object):
"""
This class represents the internel state of individual tracked objects observed as bbox.
"""
count = 0
def __init__(self, bbox, start_time):
"""
Initialises a tracker using initial bounding box or radar measurement
dt is the time between two measurements in seconds.
"""
dt_lidar = 0.10 # default lidar dt
dt_radar = 0.05 # default radar dt
# sigma points
sigmas = MerweScaledSigmaPoints(6, alpha=.001, beta=2., kappa=-2.)
# constant vx,vy and constant z,yaw model
self.ukf_lidar = UKF(dim_x=6, dim_z=4, fx=f_cv,
hx=h_lidar, dt=dt_lidar, points=sigmas)
self.ukf_radar = UKF(dim_x=6, dim_z=4, fx=f_cv,
hx=h_radar, dt=dt_radar, points=sigmas, residual_z=residual_radar)
# state process noise
self.set_process_noise(dt_radar)
# measurement noise
std_x = std_y = 0.1 # detector error for x,y (in meters)
std_z = 0.1 # detector error for z (in meters)
std_yaw = 1 # error in yaw (in radians)
std_r = 5 # radar range error (in meters)
std_phi = 0.6 # radar angle error (in radians)
std_vel_r = 0.01 # radial vel error (in m/s)
std_vel_l = 2. # lateral vel error (in m/s)
self.ukf_lidar.R = np.diag([std_x ** 2, std_y ** 2, std_z ** 2, std_yaw ** 2])
self.ukf_radar.R = np.diag([std_r ** 2, std_phi ** 2, std_vel_r ** 2, std_vel_l ** 2])
self.x = np.zeros(6) # state
self.P = np.eye(6) * 0.5 # state covariance matrix
self.x[[0, 2, 4, 5]] = bbox[:4]
self.P[1, 1] = self.P[3, 3] = 100.
self.ukf_lidar.x = self.ukf_radar.x = self.x
self.ukf_lidar.P = self.ukf_radar.P = self.P
self.dims = [4.359, 1.824, 1.466] # l,w,h
self.current_time = start_time
self.time_since_update = 0
self.id = KalmanBoxTracker.count
KalmanBoxTracker.count += 1
self.history = []
self.hits = 0
self.hit_streak = 0
self.age = 0
def set_process_noise(self, dt):
Q = np.eye(6)
Q[0:2, 0:2] = Q_discrete_white_noise(2, dt=dt, var=2.2) # x-accel
Q[2:4, 2:4] = Q_discrete_white_noise(2, dt=dt, var=2.2) # y_accel
Q[4, 4] = (1.5 * dt) ** 2 # z-vel
Q[5, 5] = (0.6 * dt) ** 2 # yaw-rate
self.ukf_lidar.Q = Q
self.ukf_radar.Q = Q
def update(self, time, measurement, sensor='lidar'):
"""
Updates the state vector with observed bbox.
"""
self.time_since_update = 0
self.history = []
self.hits += 1
self.hit_streak += 1
if sensor == 'radar':
self.ukf_radar.update(measurement)
self.x = self.ukf_lidar.x = self.ukf_radar.x
self.P = self.ukf_lidar.P = self.ukf_radar.P
elif sensor == 'lidar':
self.ukf_lidar.update(measurement[:4])
self.x = self.ukf_radar.x = self.ukf_lidar.x
self.P = self.ukf_radar.P = self.ukf_lidar.P
self.current_time = time
def predict(self, time, tracking=True):
"""
Advances the state vector and returns the predicted bounding box estimate.
"""
# constraints
# self.kf.x[4,0] = min(1.0, max(-0.4, self.kf.x[4,0])) # z constraint
dt = (time - self.current_time) / 1000000000.
self.current_time = time
self.set_process_noise(dt)
self.ukf_lidar.predict(dt)
# sync radar and lidar states, covariance matrix and sigma points
self.x = self.ukf_radar.x = self.ukf_lidar.x
self.P = self.ukf_radar.P = self.ukf_lidar.P
self.ukf_radar.sigmas_f = self.ukf_lidar.sigmas_f
self.age += dt
if (self.time_since_update > 0 and tracking):
self.hit_streak = 0
self.time_since_update += dt
self.history.append(convert_x_to_bbox(self.x, self.dims))
return self.history[-1]
def get_state(self):
"""
Returns the current bounding box estimate.
"""
return convert_x_to_bbox(self.x, self.dims)
def associate_detections_to_trackers(detections, trackers, iou_threshold):
"""
Assigns detections to tracked object (both represented as bounding boxes)
Returns 3 lists of matches, unmatched_detections and unmatched_trackers
"""
if (len(trackers) == 0):
return np.empty((0, 2), dtype=int), np.arange(len(detections)), np.empty((0, 7), dtype=int)
iou_matrix = np.zeros((len(detections), len(trackers)), dtype=np.float32)
for d, det in enumerate(detections):
for t, trk in enumerate(trackers):
iou_matrix[d, t] = iou(det, trk)
matched_indices = linear_assignment(-iou_matrix)
unmatched_detections = []
for d, det in enumerate(detections):
if (d not in matched_indices[:, 0]):
unmatched_detections.append(d)
unmatched_trackers = []
for t, trk in enumerate(trackers):
if (t not in matched_indices[:, 1]):
unmatched_trackers.append(t)
# filter out matched with low IOU
matches = []
for m in matched_indices:
if (iou_matrix[m[0], m[1]] < iou_threshold):
unmatched_detections.append(m[0])
unmatched_trackers.append(m[1])
else:
matches.append(m.reshape(1, 2))
if (len(matches) == 0):
matches = np.empty((0, 2), dtype=int)
else:
matches = np.concatenate(matches, axis=0)
return matches, np.array(unmatched_detections), np.array(unmatched_trackers)
def merge_detections(dets, distance_threshold=2.):
if len(dets) == 0:
return dets
if len(dets) == 1:
return np.array(dets)
merged_dets = []
clusters = fcluster(linkage(dets[:, :2]), 2, criterion='distance')
for c in np.unique(clusters):
indices = np.where(clusters == c)[0]
# if len(indices)==1 :
# x,y,z,h = dets[indices, 0:4]
# r = max(0.4, (dets[indices, 4] + dets[indices, 5])/2 )
# else :
# weights = 1- np.minimum(1, .5*(np.abs(dets[indices][:,4]-0.8)+np.abs(dets[indices][:,5]-0.8)))
# x,y,z,h = np.average(dets[indices][:,0:4], axis=0, weights=weights)
# r = max(0.4, (np.max(dets[indices][:,4])+ np.max(dets[indices][:,5]))/2 )
# x_min,y_min = np.minimum(dets[indices][0:2], axis=0)[0]
# x_max,y_max = np.maximum(dets[indices][0:2], axis=0)[0]
# x0,y0 = (x_min+x_max)/2., (y_min+y_max)/2.
merged_det = np.average(dets[indices], axis=0)
# merged_dets[0:2] = [x0,y0]
merged_dets.append(merged_det)
return merged_dets
class Sort(object):
def __init__(self, max_age=0.1, min_hits=3, iou_threshold=0.05, max_time_elapsed=0.1):
"""
Sets key parameters for SORT
"""
self.max_age = max_age
self.min_hits = min_hits
self.trackers = []
self.frame_count = 0
self.iou_threshold = iou_threshold
self.max_time_elapsed = max_time_elapsed
def update(self, dets, time):
"""
Params:
dets - a numpy array of detections in the format [[x,y,z,yaw,l,w,h],[x,y,z,yaw,l,w,h],...]
Requires: this method must be called once for each frame even with empty detections.
Returns a similar array, where the last column is the object ID.
NOTE: The number of objects returned may differ from the number of detections provided.
"""
self.frame_count += 1
# get predicted locations from existing trackers.
trks = np.zeros((len(self.trackers), 7))
to_del = []
ret = []
for t, trk in enumerate(trks):
pos = self.trackers[t].predict(time)
trk[:] = pos
if (np.any(np.isnan(pos))):
to_del.append(t)
trks = np.ma.compress_rows(np.ma.masked_invalid(trks))
for t in reversed(to_del):
self.trackers.pop(t)
# merge detections
merged_dets = merge_detections(dets)
matched, unmatched_dets, unmatched_trks = associate_detections_to_trackers(merged_dets,
trks, self.iou_threshold)
# update matched trackers with assigned detections
for t, trk in enumerate(self.trackers):
if (t not in unmatched_trks):
d = matched[np.where(matched[:, 1] == t)[0][0], 0]
trk.update(time, dets[d, :])
# create and initialise new trackers for unmatched detections
for i in unmatched_dets:
trk = KalmanBoxTracker(dets[i, :], time)
self.trackers.append(trk)
i = len(self.trackers)
for trk in reversed(self.trackers):
d = trk.get_state()
if ((trk.time_since_update < self.max_time_elapsed)
and (trk.hit_streak >= self.min_hits - 1
or self.frame_count <= self.min_hits)):
ret.append(
np.concatenate((d, [trk.id + 1])).reshape(1, -1)) # +1 as MOT benchmark requires positive
i -= 1
# remove dead tracklet
if (trk.time_since_update > self.max_age):
self.trackers.pop(i)
if (len(ret) > 0):
return np.concatenate(ret)
return np.empty((0, 8))
def radar_update(self, timestamp, radar_tracks):
# find the closest radar track
for radar_trk in radar_tracks:
r, phi = radar_trk[1:3]
radar_pos = [r * math.cos(phi) + 3, -r * math.sin(phi)]
for trk in self.trackers:
d = trk.get_state()
if eucl_dist(radar_pos, d[0:2]) < 5:
trk.predict(timestamp)
trk.update(timestamp, [r, phi, radar_trk[3], radar_trk[4]], sensor='radar') | {
"pile_set_name": "Github"
} |
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2017 Kamax Sarl
*
* https://www.kamax.io/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.kamax.mxisd.config.threepid.connector;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EmailSmtpConfig {
private transient final Logger log = LoggerFactory.getLogger(EmailSmtpConfig.class);
private String host = "";
private int port = 587;
private int tls = 1;
private String login;
private String password;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getTls() {
return tls;
}
public void setTls(int tls) {
this.tls = tls;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public EmailSmtpConfig build() {
log.info("--- E-mail SMTP Connector config ---");
log.info("Host: {}", getHost());
log.info("Port: {}", getPort());
log.info("TLS Mode: {}", getTls());
log.info("Login: {}", getLogin());
log.info("Has password: {}", StringUtils.isNotBlank(getPassword()));
return this;
}
}
| {
"pile_set_name": "Github"
} |
<HTML><HEAD>
<TITLE>Invalid URL</TITLE>
</HEAD><BODY>
<H1>Invalid URL</H1>
The requested URL "[no URL]", is invalid.<p>
Reference #9.72b1102.1507199536.65ca97f
</BODY></HTML>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- This file was written by the internal XML-Handler of Y-Files.-->
<!DOCTYPE graphml SYSTEM "http://www.graphdrawing.org/dtds/graphml.dtd">
<graphml>
<graph id="G">
<node id="n0"/>
<node id="n1"/>
<node id="n2"/>
<node id="n3"/>
<node id="n4"/>
<node id="n5"/>
<node id="n6"/>
<node id="n7"/>
<node id="n8"/>
<node id="n9"/>
<node id="n10"/>
<node id="n11"/>
<node id="n12"/>
<node id="n13"/>
<node id="n14"/>
<node id="n15"/>
<node id="n16"/>
<node id="n17"/>
<node id="n18"/>
<node id="n19"/>
<node id="n20"/>
<node id="n21"/>
<node id="n22"/>
<node id="n23"/>
<node id="n24"/>
<node id="n25"/>
<node id="n26"/>
<node id="n27"/>
<node id="n28"/>
<node id="n29"/>
<node id="n30"/>
<node id="n31"/>
<node id="n32"/>
<node id="n33"/>
<node id="n34"/>
<node id="n35"/>
<node id="n36"/>
<node id="n37"/>
<node id="n38"/>
<node id="n39"/>
<node id="n40"/>
<node id="n41"/>
<node id="n42"/>
<node id="n43"/>
<node id="n44"/>
<node id="n45"/>
<node id="n46"/>
<node id="n47"/>
<node id="n48"/>
<node id="n49"/>
<node id="n50"/>
<node id="n51"/>
<node id="n52"/>
<node id="n53"/>
<node id="n54"/>
<node id="n55"/>
<node id="n56"/>
<node id="n57"/>
<node id="n58"/>
<node id="n59"/>
<node id="n60"/>
<node id="n61"/>
<node id="n62"/>
<node id="n63"/>
<node id="n64"/>
<node id="n65"/>
<node id="n66"/>
<node id="n67"/>
<node id="n68"/>
<node id="n69"/>
<node id="n70"/>
<node id="n71"/>
<node id="n72"/>
<node id="n73"/>
<node id="n74"/>
<node id="n75"/>
<node id="n76"/>
<node id="n77"/>
<node id="n78"/>
<node id="n79"/>
<node id="n80"/>
<node id="n81"/>
<node id="n82"/>
<node id="n83"/>
<node id="n84"/>
<node id="n85"/>
<node id="n86"/>
<node id="n87"/>
<node id="n88"/>
<node id="n89"/>
<node id="n90"/>
<node id="n91"/>
<node id="n92"/>
<node id="n93"/>
<edge id="e0" source="n0" target="n1"/>
<edge id="e1" source="n0" target="n2"/>
<edge id="e2" source="n0" target="n3"/>
<edge id="e3" source="n0" target="n4"/>
<edge id="e4" source="n0" target="n5"/>
<edge id="e5" source="n0" target="n6"/>
<edge id="e6" source="n0" target="n7"/>
<edge id="e7" source="n0" target="n8"/>
<edge id="e8" source="n0" target="n9"/>
<edge id="e9" source="n10" target="n11"/>
<edge id="e10" source="n10" target="n12"/>
<edge id="e11" source="n10" target="n13"/>
<edge id="e12" source="n10" target="n14"/>
<edge id="e13" source="n10" target="n15"/>
<edge id="e14" source="n20" target="n11"/>
<edge id="e15" source="n20" target="n12"/>
<edge id="e16" source="n20" target="n13"/>
<edge id="e17" source="n20" target="n14"/>
<edge id="e18" source="n20" target="n15"/>
<edge id="e19" source="n20" target="n21"/>
<edge id="e20" source="n22" target="n11"/>
<edge id="e21" source="n22" target="n12"/>
<edge id="e22" source="n22" target="n13"/>
<edge id="e23" source="n22" target="n14"/>
<edge id="e24" source="n22" target="n15"/>
<edge id="e25" source="n13" target="n16"/>
<edge id="e26" source="n14" target="n17"/>
<edge id="e27" source="n17" target="n23"/>
<edge id="e28" source="n17" target="n24"/>
<edge id="e29" source="n23" target="n25"/>
<edge id="e30" source="n23" target="n26"/>
<edge id="e31" source="n23" target="n27"/>
<edge id="e32" source="n23" target="n28"/>
<edge id="e33" source="n23" target="n29"/>
<edge id="e34" source="n23" target="n30"/>
<edge id="e35" source="n23" target="n31"/>
<edge id="e36" source="n25" target="n32"/>
<edge id="e37" source="n25" target="n33"/>
<edge id="e38" source="n32" target="n36"/>
<edge id="e39" source="n32" target="n37"/>
<edge id="e40" source="n32" target="n38"/>
<edge id="e41" source="n32" target="n39"/>
<edge id="e42" source="n32" target="n40"/>
<edge id="e43" source="n32" target="n41"/>
<edge id="e44" source="n32" target="n42"/>
<edge id="e45" source="n32" target="n43"/>
<edge id="e46" source="n32" target="n44"/>
<edge id="e47" source="n36" target="n45"/>
<edge id="e48" source="n39" target="n45"/>
<edge id="e49" source="n39" target="n46"/>
<edge id="e50" source="n46" target="n47"/>
<edge id="e51" source="n46" target="n48"/>
<edge id="e52" source="n46" target="n49"/>
<edge id="e53" source="n46" target="n50"/>
<edge id="e54" source="n46" target="n51"/>
<edge id="e55" source="n46" target="n52"/>
<edge id="e56" source="n46" target="n53"/>
<edge id="e57" source="n47" target="n57"/>
<edge id="e58" source="n47" target="n59"/>
<edge id="e59" source="n47" target="n61"/>
<edge id="e60" source="n57" target="n62"/>
<edge id="e61" source="n62" target="n64"/>
<edge id="e62" source="n62" target="n65"/>
<edge id="e63" source="n62" target="n66"/>
<edge id="e64" source="n62" target="n67"/>
<edge id="e65" source="n62" target="n68"/>
<edge id="e66" source="n64" target="n69"/>
<edge id="e67" source="n64" target="n70"/>
<edge id="e68" source="n64" target="n71"/>
<edge id="e69" source="n69" target="n75"/>
<edge id="e70" source="n69" target="n76"/>
<edge id="e71" source="n69" target="n77"/>
<edge id="e72" source="n75" target="n86"/>
<edge id="e73" source="n71" target="n75"/>
<edge id="e74" source="n71" target="n81"/>
<edge id="e75" source="n71" target="n82"/>
<edge id="e76" source="n81" target="n87"/>
<edge id="e77" source="n81" target="n88"/>
<edge id="e78" source="n81" target="n90"/>
<edge id="e79" source="n84" target="n87"/>
<edge id="e80" source="n84" target="n88"/>
<edge id="e81" source="n84" target="n89"/>
<edge id="e82" source="n74" target="n75"/>
<edge id="e83" source="n74" target="n76"/>
<edge id="e84" source="n74" target="n80"/>
<edge id="e85" source="n74" target="n81"/>
<edge id="e86" source="n74" target="n82"/>
<edge id="e87" source="n74" target="n83"/>
<edge id="e88" source="n74" target="n84"/>
<edge id="e89" source="n70" target="n76"/>
<edge id="e90" source="n70" target="n77"/>
<edge id="e91" source="n70" target="n78"/>
<edge id="e92" source="n70" target="n79"/>
<edge id="e93" source="n70" target="n80"/>
<edge id="e94" source="n77" target="n92"/>
<edge id="e95" source="n77" target="n93"/>
<edge id="e96" source="n73" target="n77"/>
<edge id="e97" source="n73" target="n81"/>
<edge id="e98" source="n73" target="n82"/>
<edge id="e99" source="n73" target="n83"/>
<edge id="e100" source="n82" target="n91"/>
<edge id="e101" source="n83" target="n90"/>
<edge id="e102" source="n83" target="n91"/>
<edge id="e103" source="n65" target="n71"/>
<edge id="e104" source="n65" target="n72"/>
<edge id="e105" source="n65" target="n73"/>
<edge id="e106" source="n72" target="n75"/>
<edge id="e107" source="n72" target="n78"/>
<edge id="e108" source="n72" target="n79"/>
<edge id="e109" source="n78" target="n85"/>
<edge id="e110" source="n67" target="n73"/>
<edge id="e111" source="n67" target="n74"/>
<edge id="e112" source="n68" target="n70"/>
<edge id="e113" source="n68" target="n73"/>
<edge id="e114" source="n68" target="n74"/>
<edge id="e115" source="n66" target="n71"/>
<edge id="e116" source="n66" target="n74"/>
<edge id="e117" source="n54" target="n62"/>
<edge id="e118" source="n48" target="n54"/>
<edge id="e119" source="n48" target="n55"/>
<edge id="e120" source="n55" target="n62"/>
<edge id="e121" source="n53" target="n54"/>
<edge id="e122" source="n53" target="n57"/>
<edge id="e123" source="n53" target="n60"/>
<edge id="e124" source="n53" target="n61"/>
<edge id="e125" source="n60" target="n62"/>
<edge id="e126" source="n61" target="n63"/>
<edge id="e127" source="n56" target="n63"/>
<edge id="e128" source="n49" target="n56"/>
<edge id="e129" source="n50" target="n56"/>
<edge id="e130" source="n50" target="n57"/>
<edge id="e131" source="n52" target="n56"/>
<edge id="e132" source="n52" target="n57"/>
<edge id="e133" source="n52" target="n59"/>
<edge id="e134" source="n59" target="n63"/>
<edge id="e135" source="n51" target="n58"/>
<edge id="e136" source="n37" target="n46"/>
<edge id="e137" source="n34" target="n36"/>
<edge id="e138" source="n34" target="n37"/>
<edge id="e139" source="n34" target="n38"/>
<edge id="e140" source="n34" target="n39"/>
<edge id="e141" source="n34" target="n40"/>
<edge id="e142" source="n34" target="n41"/>
<edge id="e143" source="n34" target="n42"/>
<edge id="e144" source="n34" target="n43"/>
<edge id="e145" source="n34" target="n44"/>
<edge id="e146" source="n38" target="n46"/>
<edge id="e147" source="n35" target="n36"/>
<edge id="e148" source="n35" target="n37"/>
<edge id="e149" source="n35" target="n38"/>
<edge id="e150" source="n35" target="n39"/>
<edge id="e151" source="n35" target="n40"/>
<edge id="e152" source="n35" target="n41"/>
<edge id="e153" source="n35" target="n42"/>
<edge id="e154" source="n35" target="n43"/>
<edge id="e155" source="n35" target="n44"/>
<edge id="e156" source="n40" target="n45"/>
<edge id="e157" source="n42" target="n45"/>
<edge id="e158" source="n43" target="n45"/>
<edge id="e159" source="n44" target="n45"/>
<edge id="e160" source="n29" target="n32"/>
<edge id="e161" source="n29" target="n33"/>
<edge id="e162" source="n29" target="n35"/>
<edge id="e163" source="n27" target="n32"/>
<edge id="e164" source="n27" target="n33"/>
<edge id="e165" source="n30" target="n33"/>
<edge id="e166" source="n26" target="n34"/>
<edge id="e167" source="n31" target="n32"/>
<edge id="e168" source="n19" target="n23"/>
<edge id="e169" source="n19" target="n24"/>
<edge id="e170" source="n15" target="n18"/>
<edge id="e171" source="n15" target="n19"/>
<edge id="e172" source="n21" target="n17"/>
<edge id="e173" source="n1" target="n16"/>
</graph>
</graphml> | {
"pile_set_name": "Github"
} |
class AddRoleToChatChannelMemberships < ActiveRecord::Migration[5.1]
def change
add_column :chat_channel_memberships, :role, :string, default: "member"
end
end
| {
"pile_set_name": "Github"
} |
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in D:\AndroidSDK/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Android Support Library
-keep class !android.support.v7.internal.view.menu.**,android.support.** {*;}
-keep class android.support.v7.graphics.** { *; }
-dontwarn android.support.v7.graphics.**
-keep class android.support.design.widget.** { *; }
-keep interface android.support.design.widget.** { *; }
-dontwarn android.support.design.**
# Keep the source line when using ProGuard
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable
# LoganSquare JSON parser
-keep class com.bluelinelabs.logansquare.** { *; }
-keep @com.bluelinelabs.logansquare.annotation.JsonObject class *
-keep class **$$JsonObjectMapper { *; }
# Java 8
-dontwarn java.lang.invoke.*
-dontwarn **$$Lambda$*
# OkHttp
-dontwarn okhttp3.**
-dontwarn okio.**
-dontwarn javax.annotation.**
| {
"pile_set_name": "Github"
} |
# 哪些东西买了之后,会让人因生活质量和幸福感提升而感觉相见恨晚?
## 作者: 姜智 赞同: 864
看大家说来说去,什么苹果三件套,kindle之类的,其实都是小case啊
我觉得必须是 **房子 啊** !!
感觉开始扎根了啊,对城市有归属感了啊,心里有底了啊!!
不用被房东催租了啊,不用担心来年涨房租考虑再搬家了啊!!!
还房贷压力让你换工作更谨慎,不跳槽结果还升职了啊!!!
回家觉得更温暖了啊,自己做饭更有味道了啊!!
随便怎么折腾都不用和别人交代、考虑赔偿了啊!!
生活圈子开始以小区向外辐射了啊!!
长辈的啰嗦明显减少了啊,变成赞美了啊!!
小孩读书有着落了啊 !!
感觉人模狗样了啊!!!
房子解决后,剩余的钱可以从容的考虑投资理财了啊!!
#### 原链接: http://www.zhihu.com/question/20840874/answer/16367466 | {
"pile_set_name": "Github"
} |
@file:Suppress("UNCHECKED_CAST")
package com.wrbug.developerhelper.mmkv.manager
import android.app.Application
import android.content.Context
import androidx.collection.ArrayMap
import com.tencent.mmkv.MMKV
import java.lang.reflect.Proxy
object MMKVManager {
lateinit var application: Application
fun register(ctx: Context) {
application = ctx.applicationContext as Application
MMKV.initialize(application)
}
val map = ArrayMap<Class<*>, Any>()
fun <T> get(clazz: Class<T>): T {
if (map.containsKey(clazz)) {
return map[clazz] as T
}
val instance = obtainImpl(clazz)
map[clazz] = instance
return instance
}
private fun <T> obtainImpl(clazz: Class<T>): T {
val instance = Proxy.newProxyInstance(
clazz.classLoader, arrayOf(clazz),
MMKVInvocationHandler(clazz)
)
return instance as T
}
}
| {
"pile_set_name": "Github"
} |
package Iterator;
public class App {
public static void main(String[] args) {
EmployeeListAggregate employeeListAggregate = new EmployeeListAggregate();
Employee yusuf = new Employee(1, "Yusuf", "Yılmaz");
Employee arafat = new Employee(2, "Arafat", "Önlük");
Employee derya = new Employee(3, "Derya", "Obi");
employeeListAggregate.add(yusuf);
employeeListAggregate.add(arafat);
employeeListAggregate.add(derya);
var iterator = employeeListAggregate.createIterator();
while (iterator.hasNext()) {
Employee currentEmployee = iterator.getCurrentItem();
String message = String.format("%s %s", currentEmployee.firstName, currentEmployee.lastName);
System.out.println(message);
}
// output:
// Yusuf Yılmaz
// Arafat Önlük
// Derya Obi
}
}
| {
"pile_set_name": "Github"
} |
//
// AppDelegate.h
// CYLDeallocExecutor
//
// Created by 微博@iOS程序犭袁 ( http://weibo.com/luohanchenyilong/ ) on 15/12/27.
// Copyright © 2015年 https://github.com/ChenYilong . All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/lib" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
<excludeFolder url="file://$MODULE_DIR$/.pub" />
<excludeFolder url="file://$MODULE_DIR$/build" />
<excludeFolder url="file://$MODULE_DIR$/example/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/example/.pub" />
<excludeFolder url="file://$MODULE_DIR$/example/build" />
<excludeFolder url="file://$MODULE_DIR$/example/flutter_app/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/example/flutter_app/.pub" />
<excludeFolder url="file://$MODULE_DIR$/example/flutter_app/build" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Flutter Plugins" level="project" />
</component>
</module> | {
"pile_set_name": "Github"
} |
#include "Hitters.as"
#include "KnockedCommon.as"
shared class TreeSegment
{
f32 angle;
f32 length;
Vec2f start_pos;
Vec2f end_pos;
u8 height;
u8 grown_times;
bool flip;
bool gotsprites;
Random r;
};
shared class TreeVars
{
s32 growth_time;
u8 height;
u16 seed;
u8 max_height;
u8 grown_times;
u8 max_grow_times;
s32 last_grew_time;
Random r;
};
TreeSegment@ getLastSegment(CBlob@ this)
{
TreeSegment[]@ segments;
this.get("TreeSegments", @segments);
if (segments is null || segments.length < 1)
{
return null;
}
return segments[segments.length - 1];
}
void GrowSegments(CBlob@ this, TreeVars@ vars)
{
TreeSegment[]@ segments;
this.get("TreeSegments", @segments);
if (segments is null)
{
return;
}
for (uint i = 0; i < segments.length; i++)
{
TreeSegment@ segment = segments[i];
if (segment !is null && segment.grown_times < vars.max_grow_times)
{
segment.grown_times++;
segment.gotsprites = false; //ask for more sprites :)
}
}
}
//returns if the segments are overlapping terrain
bool CollapseToGround(CBlob@ this, f32 angle)
{
if (!this.exists("tree_fall_angle"))
{
this.set_f32("tree_fall_angle", angle);
}
else
{
this.set_f32("tree_fall_angle", angle + this.get_f32("tree_fall_angle"));
}
CSprite@ sprite = this.getSprite();
Vec2f rotateAround = Vec2f(0.0f, -this.getHeight() * 0.5f);
sprite.RotateAllBy(angle, rotateAround);
CMap@ map = getMap();
Vec2f pos = this.getPosition();
TreeSegment[]@ segments;
this.get("TreeSegments", @segments);
if (segments is null)
return false;
// rotate all
Vec2f segRotateAround = rotateAround * -1;
for (uint i = 0; i < segments.length; i++)
{
TreeSegment@ segment = segments[i];
if (segment !is null)
{
segment.start_pos.RotateBy(angle, segRotateAround);
segment.end_pos.RotateBy(angle, segRotateAround);
}
}
// collide with map and blobs
if (segments.length > 2)
{
// offset the raycast angle so it doesnt look like it falls into the ground
if (angle > 0.0f)
{
angle += 5;
}
else
{
angle -= 5;
}
bool hitsomething = false;
Vec2f start_pos = segments[0].start_pos;
Vec2f end_pos = segments[segments.length - 1].end_pos;
Vec2f vector = (end_pos - start_pos);
// HIT //
Vec2f worldpos = pos + rotateAround * -0.8f;
HitInfo@[] hitInfos;
//printf("segRotateAround " + segRotateAround.x + " " + segRotateAround.y + " v " + vector.Length() + " a " + (-90 + this.get_f32("tree_fall_angle") + angle) );
const f32 hitAngle = -90 + this.get_f32("tree_fall_angle") + angle;
// printf("hit " + hitAngle );
if (hitAngle < -360.0f || hitAngle > 360.0f)
return true;
if (map.getHitInfosFromArc(worldpos, hitAngle, 25.0f, vector.Length(), this, @hitInfos))
{
for (uint i = 0; i < hitInfos.length; i++)
{
HitInfo@ hi = hitInfos[i];
if (hi.blob !is null && hi.blob.hasTag("flesh")) // blob
{
f32 dist = (worldpos - hi.blob.getPosition()).Length();
if (dist > 24.0f && angle > 20.0f)
{
hitsomething = true;
setKnocked(hi.blob, 15);
}
}
else // map
if (hi.blob is null)
{
hitsomething = true;
}
}
}
return hitsomething;
}
// too small to collpase - kill
return true;
}
bool DoCollapseWhenBelow(CBlob@ this, f32 hp)
{
if (this.getHealth() <= hp && !this.exists("felldown"))
{
this.getCurrentScript().tickFrequency = 1;
f32 COLLAPSE_TIME = 200000.0f;
u32 fell_time;
bool fall_switch;
if (!this.exists("cut_down_time"))
{
// START COLLAPSE
fell_time = getGameTime();
this.set_u32("cut_down_time", fell_time);
fall_switch = this.get_bool("cut_down_fall_side");
// sound
this.getSprite().SetEmitSound("Entities/Natural/Trees/TreeFall.ogg");
this.getSprite().SetEmitSoundPaused(false);
//remove sectors
CMap@ map = getMap();
Vec2f pos = this.getPosition();
map.RemoveSectorsAtPosition(pos, "no build", this.getNetworkID());
map.RemoveSectorsAtPosition(pos, "tree", this.getNetworkID());
}
else
{
fell_time = this.get_u32("cut_down_time");
fall_switch = this.get_bool("cut_down_fall_side");
}
f32 time_diff = (getGameTime() - fell_time);
f32 rate = (time_diff * time_diff) / COLLAPSE_TIME;
// END COLLAPSE
bool hitground = CollapseToGround(this, (fall_switch ? -1 : 1) * 90.0f * rate);
if (hitground)
{
this.getSprite().PlaySound("Entities/Natural/Trees/TreeDestruct.ogg");
this.getSprite().SetEmitSoundPaused(true);
this.Tag("felldown"); // so client stops falling tree and playing sound
if (getNet().isServer())
{
this.server_SetHealth(-1.0f);
this.server_Die(); // Tree dying too early? Did it spawn a bit underground?
}
}
return true;
}
return false;
}
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.javafx2.scenebuilder.impl;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.netbeans.modules.javafx2.scenebuilder.Home;
import org.netbeans.modules.javafx2.scenebuilder.HomeFactory;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.NbBundle;
import org.openide.util.Parameters;
import org.openide.util.Utilities;
/**
* Creates {@linkplain Home} instance for an SB installation path
* @author Jaroslav Bachorik
* @author Petr Somol
*/
public class SBHomeFactory {
private static final String PATH_DELIMITER = ";"; //NOI18N
private static final String VER_DELIMITER = "$ver$"; //NOI18N
private static final String APPDATA_DELIMITER = "$AppData$"; //NOI18N
private static final String EMPTY_STRING = "$empty$"; //NOI18N
private static final String DEFAULT_VERSION = "1.0"; //NOI18N
private static final List<String> VER_CURRENT = tokenize(NbBundle.getMessage(SBHomeFactory.class, "SB_Version"), PATH_DELIMITER); // NOI18N
private static HomeFactory WINDOWS_HOME_LOCATOR = null;
private static HomeFactory MAC_HOME_LOCATOR = null;
private static HomeFactory UX_HOME_LOCATOR = null;
/**
* Return default Home factory depending on current OS
* @return default Home factory
*/
public static HomeFactory getDefault() {
if (Utilities.isWindows()) {
return getDefaultWindows();
} else if (Utilities.isMac()) {
return getDefaultMac();
} else {
return getDefaultUx();
}
}
private static HomeFactory getDefaultWindows() {
if(WINDOWS_HOME_LOCATOR == null) {
WINDOWS_HOME_LOCATOR = new HomeFactoryCommon(
tokenize(NbBundle.getMessage(SBHomeFactory.class, "WIN_WKIP"), PATH_DELIMITER), // NOI18N
tokenize(NbBundle.getMessage(SBHomeFactory.class, "WIN_LAUNCHER"), PATH_DELIMITER), // NOI18N
tokenize(NbBundle.getMessage(SBHomeFactory.class, "WIN_PROPERTIES"), PATH_DELIMITER) // NOI18N
);
}
return WINDOWS_HOME_LOCATOR;
}
private static HomeFactory getDefaultMac() {
if(MAC_HOME_LOCATOR == null) {
MAC_HOME_LOCATOR = new HomeFactoryCommon(
tokenize(NbBundle.getMessage(SBHomeFactory.class, "MAC_WKIP"), PATH_DELIMITER), // NOI18N
tokenize(NbBundle.getMessage(SBHomeFactory.class, "MAC_LAUNCHER"), PATH_DELIMITER), // NOI18N
tokenize(NbBundle.getMessage(SBHomeFactory.class, "MAC_PROPERTIES"), PATH_DELIMITER) // NOI18N
);
}
return MAC_HOME_LOCATOR;
}
private static HomeFactory getDefaultUx() {
if(UX_HOME_LOCATOR == null) {
UX_HOME_LOCATOR = new HomeFactoryCommon(
tokenize(NbBundle.getMessage(SBHomeFactory.class, "UX_WKIP"), PATH_DELIMITER), // NOI18N
tokenize(NbBundle.getMessage(SBHomeFactory.class, "UX_LAUNCHER"), PATH_DELIMITER), // NOI18N
tokenize(NbBundle.getMessage(SBHomeFactory.class, "UX_PROPERTIES"), PATH_DELIMITER) // NOI18N
);
}
return UX_HOME_LOCATOR;
}
/**
* Home factory implementation to be shared across different OSs.
* See Bundle.properties for OS specific definitions
*/
private static final class HomeFactoryCommon implements HomeFactory {
final private List<String> WKIP;
final private List<String> LAUNCHER_PATH;
final private List<String> PROPERTIES_PATH;
HomeFactoryCommon(List<String> WKIP, List<String> LAUNCHER_PATH, List<String> PROPERTIES_PATH) {
Parameters.notNull("WKIP", WKIP); //NOI18N
Parameters.notNull("LAUNCHER_PATH", LAUNCHER_PATH); //NOI18N
Parameters.notNull("PROPERTIES_PATH", PROPERTIES_PATH); //NOI18N
this.WKIP = WKIP;
this.LAUNCHER_PATH = LAUNCHER_PATH;
this.PROPERTIES_PATH = PROPERTIES_PATH;
}
/**
* Return Home for default SB location, if SB can be found there
* @return Home
*/
@Override
public Home defaultHome() {
Home h = null;
for (String ver : VER_CURRENT) {
for (String path : WKIP) {
if (Utilities.isWindows() && path.contains("AppData")) { //NOI18N
// issue #251710 - Gluon SceneBuilder by default installs to C:\Users\<username>\AppData\Local\SceneBuilder
final String appDataPath = System.getenv("AppData"); //NOI18N
if (appDataPath != null) {
final FileObject appDataFo = FileUtil.toFileObject(new File(appDataPath)).getParent();
h = loadHome(path.replace(VER_DELIMITER, ver).replace(APPDATA_DELIMITER, appDataFo.getPath()));
}
} else {
h = loadHome(path.replace(VER_DELIMITER, ver), ver);
}
if (h != null) {
return h;
}
}
}
return h;
}
/**
* Return SB Home for given customPath, if it is a valid SB location
* @param customPath
* @return Home
*/
@Override
public Home loadHome(String customPath) {
return loadHome(customPath, DEFAULT_VERSION);
}
private Home loadHome(String customPath, String defaultVersion) {
Home h = null;
for(String ver : VER_CURRENT) {
for(String launcher : LAUNCHER_PATH) {
for(String props : PROPERTIES_PATH) {
try {
h = getHomeForPath(customPath, launcher.replace(VER_DELIMITER, ver), props.replace(VER_DELIMITER, ver), defaultVersion.isEmpty() ? (ver.isEmpty() ? DEFAULT_VERSION : ver) : defaultVersion);
if(h != null) {
return h;
}
} catch(PathDoesNotExist e) {
// stop search only if customPath does not exits, otherwise try other version/launcher/properties combination
return null;
}
}
}
}
return null;
}
};
/**
* Returns Home if path is valid path and launcherPath points at existing launcher file
* @param path
* @param launcherPath
* @param propertiesPath
* @return Home
*/
private static Home getHomeForPath(String path, String launcherPath, String propertiesPath, String defaultVersion) throws PathDoesNotExist {
Parameters.notNull("path", path); //NOI18N
Parameters.notNull("launcherPath", launcherPath); //NOI18N
Parameters.notNull("propertiesPath", propertiesPath); //NOI18N
String homePath = path;
if(path.startsWith("~")) { // NOI18N
String userHome = System.getProperty("user.home"); // NOI18N
homePath = userHome + path.substring(1);
}
File installDir = new File(homePath);
if (installDir != null && installDir.exists() && installDir.isDirectory()) {
FileObject installDirFO = FileUtil.toFileObject(installDir);
File launcher = new File(homePath + File.separator + launcherPath);
if(launcher != null && launcher.exists() && launcher.isFile()) {
FileObject propertiesFO = installDirFO.getFileObject(propertiesPath); // NOI18N
if (propertiesFO != null && propertiesFO.isValid() && propertiesFO.isData()) {
try {
Properties props = new Properties();
FileReader reader = new FileReader(FileUtil.toFile(propertiesFO));
try {
props.load(reader);
} finally {
reader.close();
}
String version = props.getProperty("version"); //NOI18N
if (version == null) {
version = props.getProperty("app.version"); //NOI18N
}
return new Home(homePath, launcherPath, propertiesPath, version == null ? defaultVersion : version);
} catch (IOException e) {
}
} else if (Utilities.isMac() && path.equals(NbBundle.getMessage(SBHomeFactory.class, "MAC_GLUON_HOME"))) { //NOI18N
// Gluon SceneBuilder 8.0.0 does not have scenebuilder.properties file
return new Home(homePath, launcherPath, propertiesPath, defaultVersion);
}
}
} else {
throw new PathDoesNotExist();
}
return null;
}
private static final class PathDoesNotExist extends IOException {
int code;
PathDoesNotExist(int code) {
this.code = code;
}
PathDoesNotExist() {
this.code = 0;
}
int getCode() {
return code;
}
}
private static List<String> tokenize(String sequence, String delimiter) {
StringTokenizer st = new StringTokenizer(sequence, delimiter);
List<String> r = new ArrayList<String>();
while(st.hasMoreTokens()) {
String next = st.nextToken();
r.add(next.equals(EMPTY_STRING) ? "" : next); // NOI18N
}
return r;
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="files_4.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div id="SRResults"></div>
<script type="text/javascript"><!--
createResults();
--></script>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
# CRUST - Change Log
## [0.32.0]
- Update version to allow further local testing
## [0.31.0]
- Update to dual license (MIT/BSD)
- Upgrade unwrap version to 1.2.0
- Use rust 1.28.0 stable / 2018-07-07 nightly
- rustfmt 0.99.2 and clippy-0.0.212
## [0.30.1]
- crate updated to reflect licence changes from GPL to MIT/BSD
## [0.30.0]
- Use rust 1.22.1 stable / 2017-11-23 nightly
- rustfmt 0.9.0 and clippy-0.0.174
## [0.29.0]
- Replace `get_if_addrs` module with crate of the same name and fix build issues on mobile platforms.
## [0.28.1]
- Call shutdown() on sockets before dropping them because this fixes a bug under windows.
## [0.28.0]
- Use rust 1.19 stable / 2017-07-20 nightly
- rustfmt 0.9.0 and clippy-0.0.144
- Replace -Zno-trans with cargo check
- Make appveyor script using fixed version of stable
- Add dev config option
- Avoid dropping unexpired messages unnecessarily
## [0.27.0]
- Crust handles the whitelist completely by itself instead of delegating it to the upper layers.
- Config file expanded to cover the cases for node and client whitelists separately.
## [0.26.0]
- Deny bootstrapping off us until explicitly allowed.
## [0.25.0]
- Crust is now templatised on a Uid
- Replace rust_sodium sha256 with tiny-keccak sha3_256
- Rustfmt 0.8.3 and clippy 0.0.128.
- Rust stable 1.17
## [0.24.0]
- Update to mio-v0.6.6
- Switch from rustc-serialize to serde
- Remove module containing custom SocketAddr and IpAddr and use `std::net` equivalents with serde
## [0.23.0]
- Indicate to the crust user if the remote crust trying to bootstrap off us presents itself as a `CrustUser::Client` (in which case external reacheability check will be subverted) or a `CrustUser::Node` (in which case external reacheability check will be mandated).
## [0.22.1]
- Add tests for checking the handling of connection to ourselves.
- Do not spam log Listener wouldblocks.
- CI, README, Contributor Agreement and clippy clean up.
- rustfmt 0.8.0 refactor.
- Fix timer overflow bug.
- Allow users to force include TCP acceptor port in connection info via new option in crust config file.
- `Debug`, `Info`, `Warn` and `Error` levels are reserved strictly for error logging. `Trace` to log logic flows, specific code-path hits etc.
- Fix mio to 0.6.4 as 0.6.5 has deprecations and hence breaking changes for us (we treat deprecation warnings as errors currently).
## [0.22.0]
- Port to the new paradigm of mio-v6.
- Crust can now do echo/stun service on Windows too.
- Re-enable tests which were ignored on Windows due to prior mio bugs.
## [0.21.0]
- Allow routing to indicate whether we want to bootstrap as a node or as a client. If bootstrapping as a node, message to the bootstrapee will be sent indicating so and bootstrapee will check if we are reacheable externally. Only if this condition is satisfied will we be allowed to successfully bootstrap else it will trigger an immediate BootstrapFailed event.
## [0.20.2]
- Disable hole punching to limit concurrent socket usage.
## [0.20.1]
- Expose functionality to check if the connected peer is one of the hard-coded contacts from the config.
## [0.20.0]
- Expose `Config` structure.
- Update `rustfmt` options.
- Update documentation links.
- Add `crust_peer` example.
## [0.19.0]
- Update to maidsafe_utilities v0.10.0 and adapt to its removal of deprecated API's.
## [0.18.0]
- Provide an API to find out if the connected peer has a whitelisted IP as mentioned in config file.
- This will currently not work properly on Windows due to (mio-bug)[https://github.com/carllerche/mio/issues/397].
## [0.17.0]
- Use `rust_sodium` instead of `sodiumoxide` crate.
- Use latest `config_file_handler` (0.4.0) to derive the file paths for config and bootstrap cache on various platforms.
- Use latest `maidsafe_utilities` (0.9.0).
## [0.16.2]
- Shuffle the bootstrap list, otherwise there is a higher probability of connecting to the ones at the beginning of the list even with parallel bootstrap.
- Update dependencies to their latest.
## [0.16.1]
- Fix sodiumoxide to v0.0.10 as the new released v0.0.12 does not support rustc-serializable types anymore and breaks builds
## [0.16.0]
- Do not drop messages with Priority value below 2
- Pull in socket_addr and get_if_addrs crate
- Refactor to have hole punch and direct connects take the same code route - update NAT Traversal logic
- Refactor timeout type so that we dont need the indirect mapping of token <-> context and context <-> state
- Bug fixes
- Alphabetize imports and use rustfmt.toml which is committed
- Add temporary function for routing to determine if there are other instances of Crust running on LAN and take actions based on it
## [0.15.0]
- Integrate with mio
- This currently uses a temporary mio fork (`tmp_mio`) [with windows bug fix](https://github.com/carllerche/mio/pull/401).
- Redesign with State Pattern.
- Bring number of persistent threads in crust to 1.
- Previously we would have multiple threads _per connection_ leading to huge number of context switches which was inefficient. It was not uncommon to see more than 200 threads for a little over 60 connections (Routing Table size > 60).
- Now in many of our tests where cpu would constantly hover around 100%, we have cpu now calm at around 1-5% and peaks to 30% temporarily only during peak stress (Lot of churn and data exchange).
- Make all system calls async.
- Switch from application level concurrency primitives to operating system level concurrency.
- Now with event based mechanism, when kernel is not ready for some state we steal that opportunity to have it service some other state it is ready for which keeps the event pipeline hot and optimal.
- Attempt bootstrapping in parallel.
- This increases the speed of bootstrap process. Previously the sequential bootstrap meant we went to next potential peer only if the currently attempted one failed.
- Remove some of the 1st party dependant crates and move it in as modules.
- Cleaned out crust config file removing deprecated options.
- Integrate stun service into connection listeners instead of having them as separate peers.
- Crust API updates to rename OurConnectionInfo, TheirConnectionInfo to PrivConnectionInfo and PubConnectionInfo.
- Support bootstrap blacklist.
## [0.14.0]
- Depend on maidsafe_utilities 0.6.0.
- Fix endianness issue.
## [0.13.2]
- Tweak the algorithm for dropping messages when the bandwitdh is insufficient.
## [0.13.1]
- Ensure dropped duplicate connections dont have messages in transit
## [0.13.0]
- Add message priority to send high-priority messages first and if bandwidth is
insufficient, drop the low-priority ones.
- Add the `network_name` option to prevent unwanted connections and facilitate
starting separate test networks.
- Avoid duplicate connections to the same peer.
## [0.12.0]
- Remove uTP support.
- Implement heartbeat messages to detect lost connections more quickly.
- Add a version number to the protocol to avoid connecting to incompatible
peers.
- Re-implement TCP send/receive using payload size + data.
## [0.11.1]
- Make deserialisation errors as debug instead of error.
## [0.11.0]
- Minor cleanup.
- Removed unneeded dependency.
- Tests fixed.
## [0.10.0]
- Peer connections wait for both sides before sending `NewPeer` events.
- Enable uTP (still buggy).
- Add TCP rendezvous.
- Support port forwarding with ports specified as TCP acceptors.
- Never raise `NewPeer` and `LostPeer` events for ourselves.
- Update config file format to include service discovery port bootstrap cache
name.
- Fix duplicate `NewPeer` events.
- Fix issues 619, 606, 605, 601, 589 and 595.
## [0.9.0]
- Remove cbor and ip dependencies.
- Expose the PeerId in TheirConnectionInfo.
## [0.8.5]
- Implement Rand for PeerId.
## [0.8.4]
- Update dependencies
## [0.8.3]
- Bugfixes
- Disable uTP
## [0.8.2]
- Randomise the bootstrap contact order.
## [0.8.1]
- Restrict to TCP only until the UTP problems are fixed.
- Add peer IDs, and identify connections with them instead of `Connection`
objects.
## [0.8.0]
- Removes feature gates, Crust can now compile on stable rust compiler.
## [0.7.0]
- OnConnect, OnAccept and OnRendezvousConnect events now report what the remote
peer sees this peer's endpoint as
## [0.6.1]
- Replaced Event with EventSender from maidsafe_utilities
## [0.6.0]
- Change API to notify failures (e.g. now it is
`OnConnect(io::Result<Connection>, u32 /* token */)`.
- Don't start any acceptor implicitly.
- Remove default acceptors settings from config file.
- Use memory mapped file abstractions to manage bootstrap cache files. We no
longer rely on a "file cache owner" that is chosen based on whoever is
successful to start some default acceptor implicitly.
- A bugfix to uTP code.
- Lint changes.
- A new benchmark.
## [0.5.1]
- Remove wildcards from dependencies.
## [0.5.0]
- Update lint checks
- Style changes
- Documentation updates
- Hole punching API
- Functions to use the P2P network to help punch an UDP hole
- Rendezvous connections using custom UDP sockets
- Breakages in network protocol (handshake strucutre changed)
- Updated examples
- New example: reporter
- Bug fixes
- API updates (now an `u32` token is associated with connections)
- Remove dependency on packages that were unnecessary and were
causing stability issues on crust
- Tests are more predictable.
- Tests are more stable (tests can contain bugs too).
- Changes to build against most recent Rust (and libraries).
## [0.4.2]
- Adapts to new rust-utp API
## [0.4.1]
- Fixes
- `service::test::network` test is working again
## [0.4.0]
- Small change in protocol as preparation for UDP hole punching
- Impl of Ord for transport::Endpoint no longer panics
- Exports util function `ifaddrs_if_unspecified`
- Calls which start accepting connections now return real socket addresses where
IP is usually 0.0.0.0 (to be used with the fn from previous bullet)
## [0.3.2]
- Fixes explicit panic when trying to send on a closed connection
## [0.3.1]
- Reduces number of threads by using channels.
- Renames ConnectionManager to Service
- All Service public API functions are now async
- Removes NewConnection and NewBootstrapConnection events in favor of OnConnect and OnAccept
- Code reduction by doing encoding and decoding at one place (helped fixing a decoder bug we had)
- Consistent usage of the 5483 and 5484 ports
## [0.3.0]
- Revert-revert ConnectionManager::new API change
## [0.2.10]
- Revert ConnectionManager::new API change
## [0.2.9]
- ConnectionManager starts accepting connections as soon as constructed now
- Config file now also specifies optional TCP and UTP listening ports
- Improved documentation
- Fixed [#288](https://github.com/maidsafe/crust/issues/288) unsafe multithreaded access to the bootstrap file.
## [0.2.8]
- Updated sample config file
- Updated crust_peer example to use config file
- Changed config- and bootstrap-file-handling to terminate application if file is unreadable
- Fixed bug causing infinite bootstrap loop in Routing
## [0.2.7]
- Refactored config- and bootstrap-file-handling
## [0.2.6]
- [MAID-1142](https://maidsafe.atlassian.net/browse/MAID-1142) Add UTP protocol support to crust
- [#259](https://github.com/maidsafe/crust/issues/259) Build failure on Win32
- Added AppVeyor script
## [0.2.5]
- [#221](https://github.com/maidsafe/crust/issues/221) getting more bootstrap connections than expected
## [0.2.4]
- [#215](https://github.com/maidsafe/crust/issues/215) `connection_manager::get_own_endpoints()` should not return loopback address
## [0.2.3]
- [#230](https://github.com/maidsafe/crust/issues/230) Cannot compile crust - crust_peer - #[forbid(unused_mut)]
## [0.2.2]
- [#223](https://github.com/maidsafe/crust/issues/223) Error: use of unstable library feature 'udp_extras': available through the `net2` crate on crates.io
## [0.2.1]
- [#207](https://github.com/maidsafe/crust/issues/207) `ConnectionManager::get_own_endpoints` returns 0 as port
##### RUST-3 Sprint tasks
- [MAID-1149](https://maidsafe.atlassian.net/browse/MAID-1149) Split bootstrap cache file in two files (config & cache)
- [MAID-1136](https://maidsafe.atlassian.net/browse/MAID-1136) Add a new event NewBootstrapConnection and make bootstrap method non blocking.
- [MAID-1146](https://maidsafe.atlassian.net/browse/MAID-1146) Attempt Bootstrap continuously until it succeeds
- [MAID-1148](https://maidsafe.atlassian.net/browse/MAID-1148) Update bootstrap handler to maintain recent endpoints
- [MAID-1161](https://maidsafe.atlassian.net/browse/MAID-1161) Update start_listening() to take no parameters
- [MAID-1162](https://maidsafe.atlassian.net/browse/MAID-1162) Add get_beacon_acceptor_port() method only for tests
- [MAID-1264](https://maidsafe.atlassian.net/browse/MAID-1264) Update API to hide configuration file path
## [0.2.0]
- [MAID-1132](https://maidsafe.atlassian.net/browse/MAID-1132) Integrate UPnP
- [MAID-1139](https://maidsafe.atlassian.net/browse/MAID-1139) Remove Crust API’s start_listening2() and expose `get_own_endpoints()`
## [0.1.5]
- Updated dependency's version
## [0.1.4]
- Made ConnectionManager::seek_peers() private
## [0.1.3]
- Travis document generation build script updated
## [0.1.2]
- Fixed documentation links
## [0.1.1]
- Removed sodiumoxide dependency
## [0.1.0]
## [0.0.66]
- [#140](https://github.com/maidsafe/crust/issues/140) Bootstrap file format
## [0.0.65]
- [#148](https://github.com/maidsafe/crust/issues/148) Ensure contents of Bootstrap file are unique Fixes
- [#151](https://github.com/maidsafe/crust/issues/151) fix build failures with rust nightly
## [0.0.64]
- Code clean up
## [0.0.63]
- [#134](https://github.com/maidsafe/crust/issues/134) First node doesn't read its own bootstrap list
## [0.0.62]
- [MAID-1125](https://maidsafe.atlassian.net/browse/MAID-1125) Update Bootstrap Handler to use Json format.
## [0.0.61]
- [MAID-1124](https://maidsafe.atlassian.net/browse/MAID-1124) Get a list of public IPs for others to connect to
## [0.0.60]
- [MAID-1075](https://maidsafe.atlassian.net/browse/MAID-1075) Correct bug; listening on local port (127.0.0.1)
- [MAID-1122](https://maidsafe.atlassian.net/browse/MAID-1122) Windows ifaddr resolution
## [0.0.1 - 0.0.8]
- Remove FailedToConnect Event
- Update process for Connecting in TCP
- Tcp Networking
- Tcp live port and backup random port selection
- Create send/rcv channel from routing to connections object
- Implement test for basic "hello world" two way communication
- Set up Udp broadcast and respond when we have a port (we listen on any random port above 1024 [user space port]) available (broadcast port is 5484)
- Add connection established/lost/ new messages to be passed to routing (via channel)
- Implement connect() in connection manager
- Allow tcp and then utp connections option and wrap in connection object.
](http://maidsafe.net/Whitepapers/pdf/DHTbasedNATTraversal.pdf)
- Update handle connect for TCP
- Remove FailedToConnect event
- Integrate bootstrap (Link ability to read and write bootstrap file)
- Integrate beacon (Have connection manger start, broadcast on udp broadcast for port 5484 (later multicast for ipv6)
- Send serialised bootstrap info as part of beacon reply (Link ability to send bootstrap file to any node requesting it)
- Examples:
- Broadcaster
- Broadcast receiver
- CLI Example - options:
- Join / Start a node(optionally provide bootstrap info)
- Allow sending messages at various rates per second
- Print Incomming message rate per second
- Local Network Test. 12 Linux, 2 OSX, 2 WIN
- 101 Droplet test
- Version 0.0.8
| {
"pile_set_name": "Github"
} |
namespace StripeTests
{
using Newtonsoft.Json;
using Stripe;
using Xunit;
public class ApplePayDomainTest : BaseStripeTest
{
public ApplePayDomainTest(StripeMockFixture stripeMockFixture)
: base(stripeMockFixture)
{
}
[Fact]
public void Deserialize()
{
string json = this.GetFixture("/v1/apple_pay/domains/apwc_123");
var domain = JsonConvert.DeserializeObject<ApplePayDomain>(json);
Assert.NotNull(domain);
Assert.IsType<ApplePayDomain>(domain);
Assert.NotNull(domain.Id);
Assert.Equal("apple_pay_domain", domain.Object);
}
}
}
| {
"pile_set_name": "Github"
} |
# iOS Extensions Test
Integration test to test building an iOS app with
non-Flutter features:
- watchOS app and extension
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <MMCommon/MMObject.h>
@class NSArray, NSString;
@interface WCGiftCardData : MMObject
{
_Bool _needJump;
unsigned int _picDataLength;
unsigned int _videoDataLength;
unsigned int _thumbDataLength;
unsigned int _layoutMode;
unsigned int _bizUin;
unsigned int _outOfCard;
NSString *_toUserName;
NSString *_fromUserName;
NSString *_fromUserHeadImgUrl;
NSString *_content;
NSString *_contentPicUrl;
NSString *_contentVideoUrl;
NSString *_contentVideoThumbPicUrl;
NSString *_picAesKey;
NSString *_videoAesKey;
NSString *_thumbPicAesKey;
NSString *_cardBackgroundPicUrl;
NSString *_cardLogoUrl;
NSString *_cardTitle;
NSString *_cardPrice;
NSString *_footerWording;
NSString *_color;
NSString *_descriptionTitle;
NSString *_descriptionIconUrl;
NSString *_giftingMediaTitle;
NSString *_orderId;
NSString *_descriptionTitleColor;
NSString *_cardTitleColor;
NSString *_cardPriceTitleColor;
NSString *_userCardId;
NSString *_operationTitle;
NSString *_operationUrl;
NSString *_cardTpId;
NSString *_cardCode;
NSArray *_acceptedCardList;
NSArray *_accepterList;
NSString *_acceptedListTitle;
NSString *_appBrandUserName;
NSString *_appBrandPath;
}
@property(retain, nonatomic) NSString *appBrandPath; // @synthesize appBrandPath=_appBrandPath;
@property(retain, nonatomic) NSString *appBrandUserName; // @synthesize appBrandUserName=_appBrandUserName;
@property(nonatomic) unsigned int outOfCard; // @synthesize outOfCard=_outOfCard;
@property(retain, nonatomic) NSString *acceptedListTitle; // @synthesize acceptedListTitle=_acceptedListTitle;
@property(retain, nonatomic) NSArray *accepterList; // @synthesize accepterList=_accepterList;
@property(retain, nonatomic) NSArray *acceptedCardList; // @synthesize acceptedCardList=_acceptedCardList;
@property(retain, nonatomic) NSString *cardCode; // @synthesize cardCode=_cardCode;
@property(retain, nonatomic) NSString *cardTpId; // @synthesize cardTpId=_cardTpId;
@property(retain, nonatomic) NSString *operationUrl; // @synthesize operationUrl=_operationUrl;
@property(retain, nonatomic) NSString *operationTitle; // @synthesize operationTitle=_operationTitle;
@property(retain, nonatomic) NSString *userCardId; // @synthesize userCardId=_userCardId;
@property(retain, nonatomic) NSString *cardPriceTitleColor; // @synthesize cardPriceTitleColor=_cardPriceTitleColor;
@property(retain, nonatomic) NSString *cardTitleColor; // @synthesize cardTitleColor=_cardTitleColor;
@property(retain, nonatomic) NSString *descriptionTitleColor; // @synthesize descriptionTitleColor=_descriptionTitleColor;
@property(retain, nonatomic) NSString *orderId; // @synthesize orderId=_orderId;
@property(nonatomic) unsigned int bizUin; // @synthesize bizUin=_bizUin;
@property(retain, nonatomic) NSString *giftingMediaTitle; // @synthesize giftingMediaTitle=_giftingMediaTitle;
@property(nonatomic) unsigned int layoutMode; // @synthesize layoutMode=_layoutMode;
@property(retain, nonatomic) NSString *descriptionIconUrl; // @synthesize descriptionIconUrl=_descriptionIconUrl;
@property(retain, nonatomic) NSString *descriptionTitle; // @synthesize descriptionTitle=_descriptionTitle;
@property(retain, nonatomic) NSString *color; // @synthesize color=_color;
@property(nonatomic) unsigned int thumbDataLength; // @synthesize thumbDataLength=_thumbDataLength;
@property(nonatomic) unsigned int videoDataLength; // @synthesize videoDataLength=_videoDataLength;
@property(nonatomic) unsigned int picDataLength; // @synthesize picDataLength=_picDataLength;
@property(nonatomic) _Bool needJump; // @synthesize needJump=_needJump;
@property(retain, nonatomic) NSString *footerWording; // @synthesize footerWording=_footerWording;
@property(retain, nonatomic) NSString *cardPrice; // @synthesize cardPrice=_cardPrice;
@property(retain, nonatomic) NSString *cardTitle; // @synthesize cardTitle=_cardTitle;
@property(retain, nonatomic) NSString *cardLogoUrl; // @synthesize cardLogoUrl=_cardLogoUrl;
@property(retain, nonatomic) NSString *cardBackgroundPicUrl; // @synthesize cardBackgroundPicUrl=_cardBackgroundPicUrl;
@property(retain, nonatomic) NSString *thumbPicAesKey; // @synthesize thumbPicAesKey=_thumbPicAesKey;
@property(retain, nonatomic) NSString *videoAesKey; // @synthesize videoAesKey=_videoAesKey;
@property(retain, nonatomic) NSString *picAesKey; // @synthesize picAesKey=_picAesKey;
@property(retain, nonatomic) NSString *contentVideoThumbPicUrl; // @synthesize contentVideoThumbPicUrl=_contentVideoThumbPicUrl;
@property(retain, nonatomic) NSString *contentVideoUrl; // @synthesize contentVideoUrl=_contentVideoUrl;
@property(retain, nonatomic) NSString *contentPicUrl; // @synthesize contentPicUrl=_contentPicUrl;
@property(retain, nonatomic) NSString *content; // @synthesize content=_content;
@property(retain, nonatomic) NSString *fromUserHeadImgUrl; // @synthesize fromUserHeadImgUrl=_fromUserHeadImgUrl;
@property(retain, nonatomic) NSString *fromUserName; // @synthesize fromUserName=_fromUserName;
@property(retain, nonatomic) NSString *toUserName; // @synthesize toUserName=_toUserName;
- (void).cxx_destruct;
@end
| {
"pile_set_name": "Github"
} |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Linq;
namespace Microsoft.Azure.PowerShell.Cmdlets.MariaDb.Runtime.Json
{
internal class SerializationOptions
{
internal static readonly SerializationOptions Default = new SerializationOptions();
internal SerializationOptions() { }
internal SerializationOptions(
string[] include = null,
bool ingoreNullValues = false)
{
Include = include;
IgnoreNullValues = ingoreNullValues;
}
internal string[] Include { get; set; }
internal string[] Exclude { get; set; }
internal bool IgnoreNullValues { get; set; }
internal PropertyTransformation[] Transformations { get; set; }
internal Func<string, string> PropertyNameTransformer { get; set; }
internal int MaxDepth { get; set; } = 5;
internal bool IsIncluded(string name)
{
if (Exclude != null)
{
return !Exclude.Any(exclude => exclude.Equals(name, StringComparison.OrdinalIgnoreCase));
}
else if (Include != null)
{
return Include.Any(exclude => exclude.Equals(name, StringComparison.OrdinalIgnoreCase));
}
return true;
}
internal PropertyTransformation GetTransformation(string propertyName)
{
if (Transformations == null) return null;
foreach (var t in Transformations)
{
if (t.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase))
{
return t;
}
}
return null;
}
}
} | {
"pile_set_name": "Github"
} |
#
# Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
#!/bin/sh
| {
"pile_set_name": "Github"
} |
#Testing Accelerated Mutation. Target is a Grizzly Bears.
#It should get +4/+4 because of Giant Mantis on your battlefield.
[INIT]
COMBATATTACKERS
[PLAYER1]
hand:Accelerated Mutation
inplay:Grizzly Bears,Giant Mantis
manapool:{3}{G}{G}
[PLAYER2]
life:20
[DO]
Accelerated Mutation
Grizzly Bears
Grizzly Bears
next
#blockers
next
#combatdamage 2
next
#endofcombat 2
[ASSERT]
COMBATEND
[PLAYER1]
inplay:Grizzly Bears,Giant Mantis
graveyard:Accelerated Mutation
manapool:{0}
[PLAYER2]
life:14
[END] | {
"pile_set_name": "Github"
} |
# Mutt - Terminal Email Client
Mutt is a small but very powerful text based program for reading and sending electronic mail under unix operating systems, including support for color terminals, MIME, OpenPGP, and a threaded sorting mode.
* tutorial video: [Link](https://www.youtube.com/watch?v=_Unn7fysiE0)
* offical website: [Link](http://www.mutt.org/)
### install requirements
mutt
### create folder
mkdir ~/.mutt
### add email accounts
- create the text files for each account you want to use
- replace **gotbletu** with your username and **realname** to whatever you want to showup
- edit **PASSWORD**
GMAIL
> Make sure to enable "IMAP" and "Allow less secure apps" so mutt can work with gmail
> https://mail.google.com/mail/u/0/#settings/fwdandpop
> Enable IMAP
> https://myaccount.google.com/security#activity
> Allow less secure apps: ON
> Some non-Google apps and devices use less secure sign-in technology, which could leave your account vulnerable. You can turn off access for these apps (which we recommend) or choose to use them despite the risks.
vim ~/.mutt/account.com.gmail.gotbletu
unmailboxes *
set imap_user = "[email protected]"
set imap_pass = "PASSWORD"
set smtp_url = "smtp://[email protected]:587/"
set smtp_pass = "PASSWORD"
set from = "[email protected]"
set realname = "Lord Mizukage"
set folder = "imaps://imap.gmail.com:993"
set spoolfile = "+INBOX"
set postponed = "+[Gmail]/Drafts"
set header_cache = ~/.mutt/com.gmail.gotbletu/cache/headers
set message_cachedir = ~/.mutt/com.gmail.gotbletu/cache/bodies
set certificate_file = ~/.mutt/com.gmail.gotbletu/certificates
set ssl_starttls = yes
set ssl_force_tls = yes
set status_format = "$from -%r-Mutt: %f [Msgs:%?M?%M/?%m%?n? New:%n?%?o? Old:%o?%?d? Del:%d?%?F? Flag:%F?%?t? Tag:%t?%?p? Post:%p?%?b? Inc:%b?%?l? %l?]---(%s/%S)-%>-(%P)---"
YAHOO
> Make sure to "Allow apps that use less secure sign in" so mutt can work with yahoo
> https://login.yahoo.com/account/security#other-apps
> Hit Skip password change ...etc until you get to "Account security"
> Allow apps that use less secure sign in: ON
> Some non-Yahoo apps and devices use less secure sign-in technology, which could leave your account vulnerable. You can turn off access (which we recommend) or choose to use them despite the risks.
vim ~/.mutt/account.com.yahoo.gotbletu
unmailboxes *
set imap_user = "[email protected]"
set imap_pass = "PASSWORD"
set smtp_url = "smtps://[email protected]:465"
set smtp_pass = "PASSWORD"
set from = "[email protected]"
set realname = "Lord Raikage"
set folder = "imaps://imap.mail.yahoo.com:993"
set spoolfile = "+INBOX"
set postponed = "+[Yahoo]/Drafts"
set header_cache = ~/.mutt/com.yahoo.gotbletu/cache/headers
set message_cachedir = ~/.mutt/com.yahoo.gotbletu/cache/bodies
set certificate_file = ~/.mutt/com.yahoo.gotbletu/certificates
set status_format = "$from -%r-Mutt: %f [Msgs:%?M?%M/?%m%?n? New:%n?%?o? Old:%o?%?d? Del:%d?%?F? Flag:%F?%?t? Tag:%t?%?p? Post:%p?%?b? Inc:%b?%?l? %l?]---(%s/%S)-%>-(%P)---"
LIVE/msn/hotmail/outlook
vim ~/.mutt/account.com.live.gotbletu
unmailboxes *
set imap_user = "[email protected]"
set imap_pass = "PASSWORD"
set smtp_url = "smtp://[email protected]@smtp.live.com:587/"
set smtp_pass = "PASSWORD"
set from = "[email protected]"
set realname = "Lord Kazekage"
set folder = "imaps://imap-mail.outlook.com:993"
set spoolfile = "+INBOX"
set postponed = "+[Live]/Drafts"
set header_cache = ~/.mutt/com.live.gotbletu/cache/headers
set message_cachedir = ~/.mutt/com.live.gotbletu/cache/bodies
set certificate_file = ~/.mutt/com.live.gotbletu/certificates
set ssl_force_tls = yes
set status_format = "$from -%r-Mutt: %f [Msgs:%?M?%M/?%m%?n? New:%n?%?o? Old:%o?%?d? Del:%d?%?F? Flag:%F?%?t? Tag:%t?%?p? Post:%p?%?b? Inc:%b?%?l? %l?]---(%s/%S)-%>-(%P)---"
Hotmail example
vim ~/.mutt/account.com.hotmail.gotbletu
unmailboxes *
set imap_user = "[email protected]"
set imap_pass = "PASSWORD"
set smtp_url = "smtp://[email protected]@smtp.live.com:587/"
set smtp_pass = "PASSWORD"
set from = "[email protected]"
set realname = "Lord Hokage"
set folder = "imaps://imap-mail.outlook.com:993"
set spoolfile = "+INBOX"
set postponed = "+[Hotmail]/Drafts"
set header_cache = ~/.mutt/com.hotmail.gotbletu/cache/headers
set message_cachedir = ~/.mutt/com.hotmail.gotbletu/cache/bodies
set certificate_file = ~/.mutt/com.hotmail.gotbletu/certificates
set ssl_force_tls = yes
set status_format = "$from -%r-Mutt: %f [Msgs:%?M?%M/?%m%?n? New:%n?%?o? Old:%o?%?d? Del:%d?%?F? Flag:%F?%?t? Tag:%t?%?p? Post:%p?%?b? Inc:%b?%?l? %l?]---(%s/%S)-%>-(%P)---"
Openmailbox https://www.openmailbox.org/
vim ~/.mutt/account.org.openmailbox.gotbletu
# imaps
unmailboxes *
set spoolfile = "imaps://imap.openmailbox.org:993/INBOX"
set folder = "imaps://imap.openmailbox.org:993"
set imap_user = "[email protected]"
set imap_pass = "PASSWORD"
set imap_authenticators = "login"
set imap_passive = "no"
set imap_check_subscribed = "yes"
set imap_list_subscribed = "yes"
set mail_check = 60
#smtps
set smtp_url = "smtps://[email protected]@openmailbox.org:465"
set smtp_pass = "XXX"
set from = "[email protected]"
# charset
set charset = "utf-8"
set assumed_charset = "utf-8"
set send_charset = "utf-8:iso-8859-15:us-ascii"
set status_format = "$from -%r-Mutt: %f [Msgs:%?M?%M/?%m%?n? New:%n?%?o? Old:%o?%?d? Del:%d?%?F? Flag:%F?%?t? Tag:%t?%?p? Post:%p?%?b? Inc:%b?%?l? %l?]---(%s/%S)-%>-(%P)---"
# force SSL
set ssl_starttls = "yes"
set ssl_force_tls = "yes"
### configuration
set your folder hooks, macros hotkey, default account and text editor
vim ~/.muttrc
# Folder hooks
folder-hook 'account.com.gmail.gotbletu' 'source ~/.mutt/account.com.gmail.gotbletu'
folder-hook 'account.com.yahoo.gotbletu' 'source ~/.mutt/account.com.yahoo.gotbletu'
folder-hook 'account.com.live.gotbletu' 'source ~/.mutt/account.com.live.gotbletu'
folder-hook 'account.com.hotmail.gotbletu' 'source ~/.mutt/account.com.hotmail.gotbletu'
# Default account
source ~/.mutt/account.com.gmail.gotbletu
# Macros for switching accounts
macro index <F12> '<sync-mailbox><enter-command>source ~/.mutt/account.com.gmail.gotbletu<enter><change-folder>!<enter>'
macro index <F11> '<sync-mailbox><enter-command>source ~/.mutt/account.com.yahoo.gotbletu<enter><change-folder>!<enter>'
macro index <F10> '<sync-mailbox><enter-command>source ~/.mutt/account.com.live.gotbletu<enter><change-folder>!<enter>'
macro index <F9> '<sync-mailbox><enter-command>source ~/.mutt/account.com.hotmail.gotbletu<enter><change-folder>!<enter>'
# Set default text editor
set editor = "$EDITOR"
#-------- Basic Config {{{
#------------------------------------------------------
set ssl_starttls = yes
set ssl_force_tls = yes
set imap_check_subscribed
# set hostname = gmail.com
set mail_check = 120
set timeout = 300
set imap_keepalive = 300
# set record = "+[GMail]/Sent Mail"
set move = no
set include
set sort = 'threads'
set sort_aux = 'reverse-last-date-received'
set auto_tag = yes
ignore "Authentication-Results:"
ignore "DomainKey-Signature:"
ignore "DKIM-Signature:"
hdr_order Date From To Cc
alternative_order text/plain text/html *
auto_view text/html
bind editor <Tab> complete-query
bind editor ^T complete
bind editor <space> noop
# }}}
#-------- Color Theme {{{
#------------------------------------------------------
color hdrdefault cyan default
color attachment yellow default
color header brightyellow default "From: "
color header brightyellow default "Subject: "
color header brightyellow default "Date: "
color quoted green default
color quoted1 cyan default
color quoted2 green default
color quoted3 cyan default
color error red default # error messages
color message white default # message informational messages
color indicator white red # indicator for the "current message"
color status white blue # status lines in the folder index sed for the mini-help line
color tree red default # the "tree" display of threads within the folder index
color search white blue # search matches found with search within the internal pager
color markers red default # The markers indicate a wrapped line hen showing messages with looong lines
color index yellow default '~O'
color index yellow default '~N'
color index brightred default '~F' # Flagged Messages are important!
color index blue default '~D' # Deleted Mails - use dark color as these are already "dealt with"
# }}}
### hotkeys to remember
Ctrl+g = cancle a prompt
F1-F12 = switch email account
y = change to different mailboxes
$ = sync-mailbox
### references
- https://gist.github.com/miguelmota/9456162
- https://github.com/narkoleptik/dotfiles/blob/master/.mutt/account.yahoo
- http://profectium.blogspot.com/2013/12/how-to-set-up-hotmail-in-mutt.html
- http://lifehacker.com/5574557/how-to-use-the-fast-and-powerful-mutt-email-client-with-gmail
### contact
_ _ _ _
__ _ ___ | |_| |__ | | ___| |_ _ _
/ _` |/ _ \| __| '_ \| |/ _ \ __| | | |
| (_| | (_) | |_| |_) | | __/ |_| |_| |
\__, |\___/ \__|_.__/|_|\___|\__|\__,_|
|___/
- http://www.youtube.com/user/gotbletu
- https://twitter.com/gotbletu
- https://plus.google.com/+gotbletu
- https://github.com/gotbletu
- [email protected]
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=fn.visit_return_type.html">
</head>
<body>
<p>Redirecting to <a href="fn.visit_return_type.html">fn.visit_return_type.html</a>...</p>
<script>location.replace("fn.visit_return_type.html" + location.search + location.hash);</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
/***************************************************************************
* *
* Copyright (C) 2017 Seamly, LLC *
* *
* https://github.com/fashionfreedom/seamly2d *
* *
***************************************************************************
**
** Seamly2D 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.
**
** Seamly2D 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 Seamly2D. If not, see <http://www.gnu.org/licenses/>.
**
**************************************************************************
************************************************************************
**
** @file renamepp.cpp
** @author Roman Telezhynskyi <dismine(at)gmail.com>
** @date 17 7, 2014
**
** @brief
** @copyright
** This source code is part of the Valentine project, a pattern making
** program, whose allow create and modeling patterns of clothing.
** Copyright (C) 2013-2015 Seamly2D project
** <https://github.com/fashionfreedom/seamly2d> All Rights Reserved.
**
** Seamly2D 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.
**
** Seamly2D 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 Seamly2D. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include "renamepp.h"
#include <QComboBox>
#include <QDomElement>
#include "../vmisc/def.h"
#include "../vmisc/logging.h"
#include "../ifc/xml/vabstractpattern.h"
#include "vundocommand.h"
//---------------------------------------------------------------------------------------------------------------------
RenamePP::RenamePP(VAbstractPattern *doc, const QString &newPPname, QComboBox *combo, QUndoCommand *parent)
:VUndoCommand(QDomElement(), doc, parent), combo(combo), newPPname(newPPname), oldPPname(QString())
{
setText(tr("rename pattern piece"));
SCASSERT(combo != nullptr)
oldPPname = doc->GetNameActivPP();
}
//---------------------------------------------------------------------------------------------------------------------
RenamePP::~RenamePP()
{}
//---------------------------------------------------------------------------------------------------------------------
void RenamePP::undo()
{
qCDebug(vUndo, "Undo.");
ChangeName(newPPname, oldPPname);
}
//---------------------------------------------------------------------------------------------------------------------
void RenamePP::redo()
{
qCDebug(vUndo, "Redo.");
ChangeName(oldPPname, newPPname);
}
//---------------------------------------------------------------------------------------------------------------------
bool RenamePP::mergeWith(const QUndoCommand *command)
{
const RenamePP *renameCommand = static_cast<const RenamePP *>(command);
SCASSERT(renameCommand != nullptr)
const QString oldName = renameCommand->getOldPPname();
if (newPPname != oldName)
{
return false;
}
newPPname = renameCommand->getNewPPname();
return true;
}
//---------------------------------------------------------------------------------------------------------------------
int RenamePP::id() const
{
return static_cast<int>(UndoCommand::RenamePP);
}
//---------------------------------------------------------------------------------------------------------------------
void RenamePP::ChangeName(const QString &oldName, const QString &newName)
{
if (doc->ChangeNamePP(oldName, newName))
{
combo->setItemText(combo->findText(oldName), newName);
}
else
{
qCWarning(vUndo, "Can't change pattern piece name");
}
}
| {
"pile_set_name": "Github"
} |
package driver
type ISlice interface {
Data() []byte
Size() int
Free()
}
type GoSlice []byte
func (s GoSlice) Data() []byte {
return []byte(s)
}
func (s GoSlice) Size() int {
return len(s)
}
func (s GoSlice) Free() {
}
| {
"pile_set_name": "Github"
} |
Contributing
========================================
See the [official contributors' guide to CKEditor 5](https://ckeditor.com/docs/ckeditor5/latest/framework/guides/contributing/contributing.html) to learn more.
| {
"pile_set_name": "Github"
} |
#
# Copyright (C) 2013 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper.rb')
describe OverrideListPresenter do
include TextHelper
before do
allow(AssignmentOverrideApplicator).to receive(:assignment_overridden_for).
with(assignment,user).and_return overridden_assignment
allow(AssignmentOverrideApplicator).to receive(:assignment_overridden_for).
with(assignment,nil).and_return assignment
allow(assignment).to receive(:has_active_overrides?).and_return true
end
around do |example|
Timecop.freeze(Time.zone.local(2013,3,13,0,0), &example)
end
let(:course) { course_factory(active_all: true) }
let(:assignment) { course.assignments.create!(title: "Testing") }
let(:user) { student_in_course(course: course, name: "Testing").user }
let(:second_user) { student_in_course(course: course, name: "Testing 2").user }
let(:overridden_assignment) { assignment }
let(:presenter) { OverrideListPresenter.new assignment,user }
describe "#initialize" do
it "keeps a reference to the user" do
presenter = OverrideListPresenter.new nil,user
expect(presenter.user).to eq user
end
context "assignment present? and user present?" do
it "stores a reference to the overridden assignment for that user" do
presenter = OverrideListPresenter.new assignment,user
expect(presenter.assignment).to eq overridden_assignment
end
end
context "assignment or user not present?" do
it "stores the assignment as nil if assignment not present?" do
presenter = OverrideListPresenter.new nil,user
expect(presenter.assignment).to eq nil
expect(presenter.user).to eq user
end
end
end
describe "#formatted_date_string" do
context "due_at" do
it "returns - if due_at isn't present" do
due_date_hash = {:due_at => nil }
expect(presenter.formatted_date_string(:due_at, due_date_hash)).to eq '-'
due_date_hash[:due_at] = ""
expect(presenter.formatted_date_string(:due_at, due_date_hash)).to eq '-'
end
it "returns a shortened version with just the date if time is 11:59" do
fancy_midnight = CanvasTime.fancy_midnight Time.zone.now
due_date_hash = {:due_at => fancy_midnight }
expect(presenter.formatted_date_string(:due_at, due_date_hash)).to eq(
date_string(fancy_midnight, :no_words)
)
end
it "returns returns datetime_string if not all day but date present" do
due_date_hash = {:due_at => Time.now }
expect(presenter.formatted_date_string(:due_at, due_date_hash)).to eq(
datetime_string(Time.now)
)
end
end
context "lock_at and unlock_at" do
it "returns returns datetime_string of not all day but date present" do
due_date_hash = {:lock_at => Time.now, :unlock_at => Time.now - 1.day }
expect(presenter.formatted_date_string(:lock_at, due_date_hash)).to eq(
datetime_string(Time.now)
)
expect(presenter.formatted_date_string(:unlock_at, due_date_hash)).to eq(
datetime_string(Time.now - 1.day)
)
end
it "returns - if due_at isn't present" do
due_date_hash = {:lock_at => nil }
expect(presenter.formatted_date_string(:lock_at , due_date_hash)).to eq '-'
due_date_hash[:lock_at] = ""
expect(presenter.formatted_date_string(:lock_at, due_date_hash)).to eq '-'
due_date_hash = {:unlock_at => nil }
expect(presenter.formatted_date_string(:unlock_at , due_date_hash)).to eq '-'
due_date_hash[:unlock_at] = ""
expect(presenter.formatted_date_string(:unlock_at, due_date_hash)).to eq '-'
end
it "never takes all_day into effect" do
due_date_hash = {:lock_at => Time.now, :all_day => true }
expect(presenter.formatted_date_string(:lock_at, due_date_hash)).to eq(
datetime_string(Time.now)
)
due_date_hash = {:unlock_at => Time.now, :all_day => true }
expect(presenter.formatted_date_string(:unlock_at, due_date_hash)).to eq(
datetime_string(Time.now)
)
end
end
end
describe "#multiple_due_dates?" do
it "returns the result of assignment.multiple_due_dates_apply_to?(user)" do
expect(assignment).to receive(:has_active_overrides?).and_return true
expect(presenter.multiple_due_dates?).to eq true
expect(assignment).to receive(:has_active_overrides?).and_return false
expect(presenter.multiple_due_dates?).to eq false
end
it "returns false if its assignment is nil" do
presenter = OverrideListPresenter.new nil,user
expect(presenter.multiple_due_dates?).to eq false
end
end
describe "#due_for" do
it "returns the due date's title if it is present?" do
due_date = {:title => "default"}
expect(presenter.due_for(due_date)).to eq 'default'
end
it "returns 'Everyone else' if multiple due dates for assignment" do
expect(assignment).to receive(:has_active_overrides?).once.and_return true
due_date = {}
expect(presenter.due_for(due_date)).to eq(
I18n.t('overrides.everyone_else','Everyone else')
)
end
it "returns 'Everyone' translated if not multiple due dates" do
expect(assignment).to receive(:has_active_overrides?).once.and_return false
due_date = {}
expect(presenter.due_for(due_date)).to eq(
I18n.t('overrides.everyone', 'Everyone')
)
end
context "for ADHOC overrides" do
before :each do
override = assignment.assignment_overrides.create!(due_at: 1.week.from_now)
override.assignment_override_students.create!(user: user, assignment: assignment)
override.assignment_override_students.create!(user: second_user, assignment: assignment)
override.save!
@due_date = presenter.assignment.dates_hash_visible_to(user).first
end
it "returns a dynamically generated title based on the number of current and invited users" do
expect(presenter.due_for(@due_date)).to eql('2 students')
end
it "does not count concluded students" do
course.enrollments.find_by(user: second_user).conclude
expect(presenter.due_for(@due_date)).to eql('1 student')
end
it "does not count inactive students" do
course.enrollments.find_by(user: second_user).deactivate
expect(presenter.due_for(@due_date)).to eql('1 student')
end
it "does not count deleted students" do
course.enrollments.find_by(user: second_user).destroy
expect(presenter.due_for(@due_date)).to eql('1 student')
end
it "does not double-count students that have multiple enrollments in the course" do
section = course.course_sections.create!
course.enroll_student(user, section: section, enrollment_state: 'active', allow_multiple_enrollments: true)
expect(presenter.due_for(@due_date)).to eql('2 students')
end
end
end
describe "#visible_due_dates" do
def visible_due_dates; @visible_due_dates; end
let(:sections) do
# the count is the important part, the actual course sections are
# not used
[ double, double, double ]
end
def dates_visible_to_user
[
{:due_at => "", :lock_at => nil, :unlock_at => nil, :set_type => 'CourseSection'},
{:due_at => Time.now + 1.day, :lock_at => nil, :unlock_at => nil, :set_type => 'CourseSection'},
{:due_at => Time.now + 2.days, :lock_at => nil, :unlock_at => nil, :set_type => 'CourseSection'},
{:due_at => Time.now - 2.days, :lock_at => nil, :unlock_at => nil, :base => true}
]
end
it "returns empty array if assignment is not present" do
presenter = OverrideListPresenter.new nil,user
expect(presenter.visible_due_dates).to eq []
end
context "when all sections have overrides" do
before do
allow(assignment.context).to receive(:active_section_count).
and_return sections.count
allow(assignment).to receive(:all_dates_visible_to).with(user).
and_return dates_visible_to_user
@visible_due_dates = presenter.visible_due_dates
end
it "doesn't include the default due date" do
expect(visible_due_dates.length).to eq 3
visible_due_dates.each do |override|
expect(override[:base]).not_to be_truthy
end
end
it "sorts due dates by due_at, placing not present?/nil after dates" do
expect(visible_due_dates.first[:due_at]).to eq(
presenter.formatted_date_string(:due_at, dates_visible_to_user.second)
)
expect(visible_due_dates.second[:due_at]).to eq(
presenter.formatted_date_string(:due_at,dates_visible_to_user.third)
)
expect(visible_due_dates.third[:due_at]).to eq(
presenter.formatted_date_string(:due_at,dates_visible_to_user.first)
)
end
it "includes the actual Time for presentation transforms in templates" do
expect(visible_due_dates.second[:raw][:due_at]).to be_a(Time)
end
end
context "only some sections have overrides" do
let(:dates_visible) { dates_visible_to_user[1..-1] }
before do
allow(assignment.context).to receive(:active_section_count).
and_return sections.count
allow(assignment).to receive(:all_dates_visible_to).with(user).
and_return dates_visible
@visible_due_dates = presenter.visible_due_dates
end
it "includes the default due date" do
expect(visible_due_dates.detect { |due_date| due_date[:base] == true }).
not_to be_nil
end
end
end
end
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
@interface PIError : NSObject
{
}
+ (id)errorWithCode:(long long)arg1 description:(id)arg2;
+ (id)errorForCode:(long long)arg1;
@end
| {
"pile_set_name": "Github"
} |
from arm.logicnode.arm_nodes import *
class HasContactNode(ArmLogicTreeNode):
"""Use to get if a rigid body has contact with another rigid body."""
bl_idname = 'LNHasContactNode'
bl_label = 'Has Contact'
arm_version = 1
def init(self, context):
super(HasContactNode, self).init(context)
self.add_input('ArmNodeSocketObject', 'Rigid Body 1')
self.add_input('ArmNodeSocketObject', 'Rigid Body 2')
self.add_output('NodeSocketBool', 'Has Contact')
add_node(HasContactNode, category=PKG_AS_CATEGORY, section='contact')
| {
"pile_set_name": "Github"
} |
/**
This file is part of Adguard for iOS (https://github.com/AdguardTeam/AdguardForiOS).
Copyright © Adguard Software Limited. All rights reserved.
Adguard for iOS 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.
Adguard for iOS 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 Adguard for iOS. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
// MARK: - service protocol
/**
ContentBlockerService is responsible for the composition of safari content blocker rules files
*/
protocol ContentBlockerServiceProtocol {
/**
recompile all content blocker files and reloads it to safari
*/
func reloadJsons(backgroundUpdate: Bool, completion:@escaping (Error?)->Void)
/**
validates rule text
It returns true if rule can be converted to safari content blocker rule by converter, false for unsupported rules
*/
func validateRule(_ ruleText: String)->Bool
}
@objc
class ContentBlockerService: NSObject, ContentBlockerServiceProtocol {
var antibanner: AESAntibannerProtocol
// MARK: - error constants
static let contentBlockerServiceErrorDomain = "ContentBlockerServiceErrorDomain"
static let contentBlockerConverterErrorCode = 1
static let contentBlockerDBErrorCode = 2
// MARK: - private properties
private var resources: AESharedResourcesProtocol
private var safariService: SafariServiceProtocol
private var rulesProcessor: RulesProcessorProtocol = RulesProcessor()
private var safariProtection: SafariProtectionServiceProtocol
private let workQueue = DispatchQueue(label: "content_blocker")
static let groupsByContentBlocker: [ContentBlockerType: [Int]] =
[.general: [FilterGroupId.ads, FilterGroupId.languageSpecific, FilterGroupId.user],
.privacy: [FilterGroupId.privacy, FilterGroupId.user],
.socialWidgetsAndAnnoyances: [FilterGroupId.socialWidgets, FilterGroupId.annoyances, FilterGroupId.user],
.other: [FilterGroupId.other, FilterGroupId.user],
.custom: [FilterGroupId.custom, FilterGroupId.user],
.security: [FilterGroupId.security, FilterGroupId.user]
]
static let defaultsCountKeyByBlocker: [ContentBlockerType: String] = [
.general: AEDefaultsGeneralContentBlockerRulesCount,
.privacy: AEDefaultsPrivacyContentBlockerRulesCount,
.socialWidgetsAndAnnoyances: AEDefaultsSocialContentBlockerRulesCount,
.other: AEDefaultsOtherContentBlockerRulesCount,
.custom: AEDefaultsCustomContentBlockerRulesCount,
.security: AEDefaultsSecurityContentBlockerRulesCount
]
static let defaultsOverLimitCountKeyByBlocker: [ContentBlockerType: String] = [
.general: AEDefaultsGeneralContentBlockerRulesOverLimitCount,
.privacy: AEDefaultsPrivacyContentBlockerRulesOverLimitCount,
.socialWidgetsAndAnnoyances: AEDefaultsSocialContentBlockerRulesOverLimitCount,
.other: AEDefaultsOtherContentBlockerRulesOverLimitCount,
.custom: AEDefaultsCustomContentBlockerRulesOverLimitCount,
.security: AEDefaultsSecurityContentBlockerRulesOverLimitCount
]
// MARK: - init
init(resources: AESharedResourcesProtocol, safariService: SafariServiceProtocol, antibanner: AESAntibannerProtocol, safariProtection: SafariProtectionServiceProtocol) {
self.resources = resources
self.safariService = safariService
self.antibanner = antibanner
self.safariProtection = safariProtection
super.init()
}
// MARK: - public methods
@objc
func reloadJsons(backgroundUpdate: Bool, completion:@escaping (Error?)->Void) {
DDLogInfo("(ContentBlockerService) reloadJsons")
#if !APP_EXTENSION
let backgroundTaskId = UIApplication.shared.beginBackgroundTask { }
#endif
workQueue.async { [weak self] in
guard let self = self else { return }
let error = self.updateContentBlockers(background: backgroundUpdate)
#if !APP_EXTENSION
UIApplication.shared.endBackgroundTask(backgroundTaskId)
#endif
completion(error)
return
}
}
func validateRule(_ ruleText: String) -> Bool {
let trimmedRule = ruleText.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmedRule.count == 0 {
return false
}
if trimmedRule.contains(OLD_INJECT_RULES) ||
trimmedRule.contains(MASK_CONTENT_RULE) ||
trimmedRule.contains(MASK_CONTENT_EXCEPTION_RULE) ||
trimmedRule.contains(MASK_JS_RULE) ||
trimmedRule.contains(MASK_FILTER_UNSUPPORTED_RULE){
return false
}
return true
}
// MARK: - whitelist operations
/**
Adds whitelist domain, modifies content blocking JSONs
and replaces these JSONs in shared resources asynchronously.
Method performs completionBlock when done on service working queue.
*/
func addWhitelistDomain(_ domain: String, completion: @escaping (Error?)->Void) {
processWhitelistDomain(domain, enabled: true, completion: completion, processRules: {(rules) in
let rule = AEWhitelistDomainObject(domain: domain).rule
rule.isEnabled = NSNumber(booleanLiteral: true)
return (rules + [rule], true)
}, processData: { [weak self] (jsonData, jsonRuleData, contentBlocker) in
guard let sSelf = self else { return Data() }
let converted = sSelf.resources.sharedDefaults().integer(forKey: ContentBlockerService.defaultsCountKeyByBlocker[contentBlocker]!)
let limit = sSelf.resources.sharedDefaults().integer(forKey: AEDefaultsJSONMaximumConvertedRules)
let overlimit = converted == limit
let (resultData, _) = sSelf.rulesProcessor.addDomainToWhitelist(domain: domain, enabled: true, jsonData: jsonData as Data, overlimit: overlimit)
return resultData ?? Data()
})
}
func removeWhitelistDomain(_ domain: String, completion: @escaping (Error?)->Void) {
processWhitelistDomain(domain, enabled: false, completion: completion, processRules: {(rules) in
var found = false
let rule = AEWhitelistDomainObject(domain: domain).rule
let resultRules = rules.filter() { (testRule) in
if rule.isEqualRuleText(testRule) {
found = true
return false
}
return true
}
return (resultRules, found)
}, processData: { [weak self] (jsonData, domain, _) in
guard let sSelf = self else { return Data() }
let (resultJsonData, _) = sSelf.rulesProcessor.removeWhitelistDomain(domain: domain, jsonData: jsonData)
return resultJsonData ?? Data()
})
}
func replaceWhitelistDomain(_ domain: String, with newDomain: String, enabled: Bool, completion: @escaping (Error?)->Void) {
processWhitelistDomain(domain, enabled: enabled, completion: completion, processRules: {(rules) in
var found = false
let rule = AEWhitelistDomainObject(domain: domain).rule
let resultRules = rules.map() { (testRule)->ASDFilterRule in
if rule.isEqualRuleText(testRule) {
found = true
let newRule = AEWhitelistDomainObject(domain: newDomain).rule
newRule.isEnabled = NSNumber(booleanLiteral: enabled)
return newRule
}
return testRule
}
return (resultRules, found)
}, processData: { [weak self] (jsonData, ruleData, _) in
guard let sSelf = self else { return jsonData }
let (removed, _) = sSelf.rulesProcessor.removeWhitelistDomain(domain: domain, jsonData: jsonData)
let (result, _) = sSelf.rulesProcessor.addDomainToWhitelist(domain: newDomain, enabled: enabled, jsonData: removed ?? Data(), overlimit: false)
return result ?? Data()
})
}
// MARK: - inverted whitelist rules
func addInvertedWhitelistDomain(_ domain: String, completion: @escaping (Error?)->Void) {
processInvertedWhitelistDomain(processRules: { (rules) -> ([ASDFilterRule], Bool) in
var newRules = rules
newRules.append(ASDFilterRule(text: domain, enabled: true))
return (newRules, true)
}, processData: { [weak self] (jsonData, contentBlocker) -> Data in
guard let self = self else { return Data() }
let converted = self.resources.sharedDefaults().integer(forKey: ContentBlockerService.defaultsCountKeyByBlocker[contentBlocker]!)
let limit = self.resources.sharedDefaults().integer(forKey: AEDefaultsJSONMaximumConvertedRules)
let overlimit = converted == limit
let (data, _) = self.rulesProcessor.addDomainToInvertedWhitelist(rule: domain, jsonData: jsonData, overlimit: overlimit)
return data ?? Data()
}) { (error) in
completion(error)
}
}
func removeInvertedWhitelistDomain(_ ruleToRemove: String, completion: @escaping (Error?)->Void) {
processInvertedWhitelistDomain(processRules: { (rules) -> ([ASDFilterRule], Bool) in
let filteredDomains = rules.filter({ (rule) -> Bool in
return ruleToRemove != rule.ruleText
})
return(filteredDomains, true)
}, processData: { [weak self] (jsonData, contentBlocker) -> Data in
guard let sSelf = self else { return Data() }
let (data, _) = sSelf.rulesProcessor.removeInvertedWhitelistDomain(rule: ruleToRemove, jsonData: jsonData)
return data ?? Data()
}) { (error) in
completion(error)
}
}
// MARK: - private methods
private func updateContentBlockers(background: Bool)->Error? {
DDLogInfo("(ContentBlockerService) updateContentBlockers")
let filtersByGroup = activeGroups()
let allFilters = filtersByGroup.flatMap { $0.value }
let rulesByFilter = rules(forFilters: allFilters)
// get map of rules by content blocker
var rulesByContentBlocker = [ContentBlockerType: [ASDFilterRule]]()
var rulesByAffinityBlocks = [ContentBlockerType: [ASDFilterRule]]()
for (contentBlocker, groups) in ContentBlockerService.groupsByContentBlocker {
var contentBlockerRules = [ASDFilterRule]()
for groupID in groups {
guard let filters = filtersByGroup[groupID as NSNumber] else { continue }
for filterID in filters {
guard let filterRules = rulesByFilter[filterID] else { continue }
sortWithAffinityBlocks(filterRules: filterRules, contentBlockerRules: &contentBlockerRules, rulesByAffinityBlocks: &rulesByAffinityBlocks)
}
}
rulesByContentBlocker[contentBlocker] = contentBlockerRules
}
for type in ContentBlockerType.allCases {
if rulesByContentBlocker[type] == nil {
rulesByContentBlocker[type] = [ASDFilterRule]()
}
rulesByContentBlocker[type]?.append(contentsOf: rulesByAffinityBlocks[type] ?? [])
}
return convertRulesAndInvalidateSafari(background: background,rulesByContentBlocker: rulesByContentBlocker)
}
private func convertRulesAndInvalidateSafari(background: Bool, rulesByContentBlocker: [ContentBlockerType: [ASDFilterRule]])->Error? {
var resultError: Error?
let concurrentQueue = DispatchQueue(label: "update_cb", attributes: DispatchQueue.Attributes.concurrent)
let group = DispatchGroup()
// run conversion to jsons in concurrent queue.
for type in ContentBlockerType.allCases {
group.enter()
concurrentQueue.async { [weak self] in
guard let self = self else { return }
let error = self.updateJson(blockerRules: rulesByContentBlocker[type]!, forContentBlocker: type)
if error == nil {
if background {
group.leave()
}
else {
// immediately update the safari without waiting for the conversion of other jsons
self.safariService.invalidateBlockingJson(type: type) { (error) in
if error != nil {
resultError = error
}
group.leave()
}
}
}
else {
resultError = error
group.leave()
}
}
}
group.wait()
let result = resultError == nil ? "SUCCCESS" : "FAILURE"
DDLogInfo("(ContentBlockerService) convertRulesAndInvalidateSafari - all content blockers are updated. Result - \(result)")
return resultError
}
private func sortWithAffinityBlocks(filterRules: [ASDFilterRule], contentBlockerRules: inout [ASDFilterRule], rulesByAffinityBlocks: inout [ContentBlockerType: [ASDFilterRule]]) {
for rule in filterRules {
if rule.affinity != nil {
for type in ContentBlockerType.allCases {
let affinity = affinityMaskByContentBlockerType[type]
if (affinity != nil) {
if (rule.affinity == 0 || Affinity(rawValue: UInt8(truncating: rule.affinity!)).contains(affinity!)) {
if rulesByAffinityBlocks[type] == nil {
rulesByAffinityBlocks[type] = [ASDFilterRule]()
}
rulesByAffinityBlocks[type]?.append(rule)
}
}
}
} else {
contentBlockerRules.append(rule)
}
}
}
private let affinityMaskByContentBlockerType: [ContentBlockerType: Affinity] =
[.general: Affinity.general,
.privacy: Affinity.privacy,
.socialWidgetsAndAnnoyances: Affinity.socialWidgetsAndAnnoyances,
.other: Affinity.other,
.custom: Affinity.custom,
.security: Affinity.security ]
private func updateJson(blockerRules: [ASDFilterRule], forContentBlocker contentBlocker: ContentBlockerType)->Error? {
DDLogInfo("(ContentBlockerService) updateJson for contentBlocker \(contentBlocker) rulesCount: \(blockerRules.count)")
let safariProtectionEnabled = safariProtection.safariProtectionEnabled
if safariProtectionEnabled{
return autoreleasepool {
var rules = blockerRules
// add user rules
let userFilterEnabled = resources.safariUserFilterEnabled
let userRules = userFilterEnabled ? antibanner.activeRules(forFilter: ASDF_USER_FILTER_ID as NSNumber) : [ASDFilterRule]()
DDLogInfo("(ContentBlockerService) updateJson append \(userRules.count) user rules")
rules = userRules + rules
// add whitelist rules
let inverted = resources.sharedDefaults().bool(forKey: AEDefaultsInvertedWhitelist)
let whitelistEnabled = resources.safariWhitelistEnabled
if whitelistEnabled {
if inverted {
if resources.invertedWhitelistContentBlockingObject == nil {
resources.invertedWhitelistContentBlockingObject = AEInvertedWhitelistDomainsObject(rules: [])
}
if let invertedRule = resources.invertedWhitelistContentBlockingObject?.rule {
DDLogInfo("(ContentBlockerService) updateJson append inverted whitelist rule")
rules.append(invertedRule)
}
}
else {
if let whitelistRules = resources.whitelistContentBlockingRules {
DDLogInfo("(ContentBlockerService) updateJson append \(whitelistRules.count) user rules")
rules.append(contentsOf: whitelistRules as! [ASDFilterRule])
}
}
}
var resultData = Data()
var resultError: Error?
if rules.count != 0 {
DDLogInfo("(ContentBlockerService) updateJson - convert \(rules.count) rules")
let (jsonData, converted, overLimit, _, error) = convertRulesToJson(rules)
resources.sharedDefaults().set(overLimit, forKey: ContentBlockerService.defaultsOverLimitCountKeyByBlocker[contentBlocker]!)
if jsonData != nil { resultData = jsonData! }
resources.sharedDefaults().set(converted, forKey: ContentBlockerService.defaultsCountKeyByBlocker[contentBlocker]!)
resultError = error
if error != nil {
DDLogError("(ContentBlockerService) updateJson - error converting rules - \(error!.localizedDescription)")
}
} else {
DDLogInfo("(ContentBlockerService) updateJson - no rules to convert")
resources.sharedDefaults().set(0, forKey: ContentBlockerService.defaultsOverLimitCountKeyByBlocker[contentBlocker]!)
resources.sharedDefaults().set(0, forKey: ContentBlockerService.defaultsCountKeyByBlocker[contentBlocker]!)
}
safariService.save(json: resultData, type: contentBlocker)
return resultError
}
} else {
DDLogInfo("(ContentBlockerService) updateJson safari protection is disabled. Save empty data instead of rules json")
safariService.save(json: Data(), type: contentBlocker)
return nil
}
}
/** returns map [filterID: [Rule]]*/
private func rules(forFilters filterIDs: [NSNumber]) -> [NSNumber: [ASDFilterRule]] {
var rulesByFilter = [NSNumber: [ASDFilterRule]]()
for filterID in filterIDs {
rulesByFilter[filterID] = antibanner.activeRules(forFilter: filterID)
}
return rulesByFilter
}
/** returns map [groupId: [filterId]] */
private func activeGroups()->[NSNumber: [NSNumber]] {
var filterByGroup = [NSNumber:[NSNumber]]()
let groupIDs = antibanner.activeGroupIDs()
for groupID in groupIDs {
let filterIDs = antibanner.activeFilterIDs(byGroupID: groupID)
filterByGroup[groupID] = filterIDs
}
return filterByGroup
}
private func processWhitelistDomain(_ domain: String, enabled: Bool, completion: @escaping (Error?)->Void, processRules: @escaping(_ rules: [ASDFilterRule])->([ASDFilterRule], Bool), processData: @escaping(_ jsonData: Data, _ domain: String, _ contentBlocker: ContentBlockerType)->Data) {
workQueue.async { [weak self] in
guard let sSelf = self else { return }
var error: Error?
var modified = false
var savedDatas:[ContentBlockerType: Data] = [:]
var savedRules:[ASDFilterRule] = []
var rollback: ()->Void = {
for (_, obj) in savedDatas.enumerated() {
sSelf.safariService.save(json: obj.value, type: obj.key)
sSelf.resources.whitelistContentBlockingRules = (savedRules as NSArray).mutableCopy() as? NSMutableArray
}
}
defer {
if error != nil {
sSelf.finishReloadingConetentBlocker(completion: completion, error: error)
rollback()
}
else if error == nil && modified {
sSelf.safariService.invalidateBlockingJsons { (error) in
sSelf.finishReloadingConetentBlocker(completion: completion, error: error)
if error != nil {
rollback()
sSelf.safariService.invalidateBlockingJsons { (error) in
}
}
}
}
else {
sSelf.finishReloadingConetentBlocker(completion: completion, error: error)
}
}
var whitelistRules = sSelf.resources.whitelistContentBlockingRules as? [ASDFilterRule] ?? []
savedRules = Array(whitelistRules)
var succeded = false
(whitelistRules, succeded) = processRules(whitelistRules)
if !succeded {
error = NSError(domain: ContentBlockerService.contentBlockerServiceErrorDomain,
code: ContentBlockerService.contentBlockerDBErrorCode,
userInfo: [NSLocalizedDescriptionKey: ACLocalizedString("support_unexpected_error", "")])
return
}
sSelf.resources.whitelistContentBlockingRules = (whitelistRules as NSArray).mutableCopy() as? NSMutableArray
// change all content blocker jsons
ContentBlockerType.allCases.forEach { (type) in
autoreleasepool {
guard let data = sSelf.safariService.readJson(forType: type) else { return }
savedDatas[type] = data
let jsonData = processData(data, domain, type)
sSelf.safariService.save(json: jsonData as Data, type: type)
}
}
modified = true
return
}
}
private func processInvertedWhitelistDomain(processRules: @escaping(_ rules: [ASDFilterRule])->([ASDFilterRule], Bool), processData: @escaping(_ jsonData: Data, _ contentBlocker: ContentBlockerType)->Data, completion: @escaping (Error?)->Void) {
workQueue.async { [weak self] in
guard let sSelf = self else { return }
var error: Error?
var modified = false
var savedDatas:[ContentBlockerType: Data] = [:]
let invertedObject = sSelf.resources.invertedWhitelistContentBlockingObject
var rollback: ()->Void = {
for (_, obj) in savedDatas.enumerated() {
sSelf.safariService.save(json: obj.value, type: obj.key)
sSelf.resources.invertedWhitelistContentBlockingObject = invertedObject
}
}
defer {
if error != nil {
sSelf.finishReloadingConetentBlocker(completion: completion, error: error)
rollback()
}
else if error == nil && modified {
sSelf.safariService.invalidateBlockingJsons { (error) in
sSelf.finishReloadingConetentBlocker(completion: completion, error: error)
}
}
else {
sSelf.finishReloadingConetentBlocker(completion: completion, error: error)
}
}
var rules = invertedObject?.rules ?? []
var succeded = false
(rules, succeded) = processRules(rules)
if !succeded {
error = NSError(domain: ContentBlockerService.contentBlockerServiceErrorDomain,
code: ContentBlockerService.contentBlockerDBErrorCode,
userInfo: [NSLocalizedDescriptionKey: ACLocalizedString("support_unexpected_error", "")])
return
}
let newInvertedObject = AEInvertedWhitelistDomainsObject(rules: rules)
sSelf.resources.invertedWhitelistContentBlockingObject = newInvertedObject
// change all content blocker jsons
ContentBlockerType.allCases.forEach { (type) in
autoreleasepool {
guard let data = sSelf.safariService.readJson(forType: type) else { return }
savedDatas[type] = data
let jsonData = processData(data, type)
sSelf.safariService.save(json: jsonData, type: type)
}
}
modified = true
return
}
}
private func finishReloadingConetentBlocker(completion: ((Error?)->Void)?, error: Error?) {
workQueue.async {
if completion != nil {
self.workQueue.async {
completion!(error)
}
}
}
}
private func convertRulesToJson(_ rules: [ASDFilterRule])->(data: Data?, converted: Int, overlimit: Int, totalConverted: Int, error: Error?) {
NotificationCenter.default.post(name: NSNotification.Name.ShowStatusView, object: self, userInfo: [AEDefaultsShowStatusViewInfo : ACLocalizedString("converting_rules", nil)])
defer {
NotificationCenter.default.post(name: NSNotification.Name.HideStatusView, object: self)
}
var error: Error?
var converted = 0
var overLimit = 0
var totalConverted = 0
var rulesData: Data?
if rules.count == 0 {
return (nil, 0, 0, 0, NSError(domain: ContentBlockerService.contentBlockerServiceErrorDomain, code: 0, userInfo: [:]))
}
// run converter
let limit = UInt(resources.sharedDefaults().integer(forKey: AEDefaultsJSONMaximumConvertedRules))
let optimize = resources.sharedDefaults().bool(forKey: AEDefaultsJSONConverterOptimize)
let (converter, converterError) = createConverter()
if converterError != nil {
return (nil, 0, 0, 0, converterError)
}
if converter == nil {
error = NSError(domain: ContentBlockerService.contentBlockerServiceErrorDomain,
code: ContentBlockerService.contentBlockerConverterErrorCode,
userInfo: nil)
return (nil, 0, 0, 0, error)
}
let converterResult = converter!.json(fromRules: rules, upTo: limit, optimize: optimize) as? [String: Any]
error = converterResult?[AESFConvertedErrorKey] as? Error
if error != nil {
return (nil, 0, 0, 0, error)
}
converted = converterResult?[AESFConvertedCountKey] as? Int ?? 0
totalConverted = converterResult?[AESFTotalConvertedCountKey] as? Int ?? 0
overLimit = totalConverted - converted
// obtain rules
let jsonString = converterResult?[AESFConvertedRulesKey] as? String
if jsonString == nil || jsonString! == "undefined" {
error = NSError(domain: ContentBlockerService.contentBlockerServiceErrorDomain,
code: ContentBlockerService.contentBlockerConverterErrorCode,
userInfo: nil)
return (nil, 0, 0, 0, error)
}
rulesData = jsonString?.data(using: .utf8)
return (rulesData, converted, overLimit, totalConverted, error)
}
func replaceUserFilter(_ rules: [ASDFilterRule])->Error? {
let success = antibanner.import(rules, filterId: ASDF_USER_FILTER_ID as NSNumber)
return success ? nil : NSError(domain: ContentBlockerService.contentBlockerServiceErrorDomain,
code: ContentBlockerService.contentBlockerDBErrorCode,
userInfo: [NSLocalizedDescriptionKey: ACLocalizedString("support_unexpected_error", "")])
}
func convertOneRule(_ rule: ASDFilterRule)->([String: Any]?, Error?) {
let optimize = resources.sharedDefaults().bool(forKey: AEDefaultsJSONConverterOptimize)
var convertResult: [String: Any]?
let (converter, converterError) = createConverter()
if converterError != nil { return (nil, converterError) }
convertResult = converter!.json(fromRules: [rule], upTo: 1, optimize: optimize) as? [String: Any]
if let error = convertResult?[AESFConvertedErrorKey] as? Error { return (nil, error) }
let convertedCount = convertResult?[AESFConvertedCountKey] as? Int
let errorsCount = convertResult?[AESErrorsCountKey] as? Int
if convertedCount == 0 || errorsCount ?? 0 > 0 {
let errorDescription = ACLocalizedString("rule_converting_error", nil)
let error = NSError(domain: ContentBlockerService.contentBlockerServiceErrorDomain,
code: ContentBlockerService.contentBlockerConverterErrorCode,
userInfo: [NSLocalizedDescriptionKey: errorDescription])
return(nil, error)
}
return (convertResult, nil)
}
var createConverter:()->(AESFilterConverterProtocol?, Error?) = {
guard let converter = AESFilterConverter() else {
DDLogError("(ContentBlockerService) Can't initialize converter to JSON format!")
let errorDescription = ACLocalizedString("json_converting_error", nil)
let error = NSError(domain: ContentBlockerService.contentBlockerServiceErrorDomain,
code: ContentBlockerService.contentBlockerConverterErrorCode,
userInfo: [NSLocalizedDescriptionKey: errorDescription])
return (nil, error)
}
return (converter, nil)
}
}
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: ISC
/*
* Copyright (C) 2016 Felix Fietkau <[email protected]>
* Copyright (C) 2018 Lorenzo Bianconi <[email protected]>
*/
#include <linux/kernel.h>
#include "mt76x02.h"
#include "mt76x02_phy.h"
void mt76x02_phy_set_rxpath(struct mt76x02_dev *dev)
{
u32 val;
val = mt76_rr(dev, MT_BBP(AGC, 0));
val &= ~BIT(4);
switch (dev->chainmask & 0xf) {
case 2:
val |= BIT(3);
break;
default:
val &= ~BIT(3);
break;
}
mt76_wr(dev, MT_BBP(AGC, 0), val);
mb();
val = mt76_rr(dev, MT_BBP(AGC, 0));
}
EXPORT_SYMBOL_GPL(mt76x02_phy_set_rxpath);
void mt76x02_phy_set_txdac(struct mt76x02_dev *dev)
{
int txpath;
txpath = (dev->chainmask >> 8) & 0xf;
switch (txpath) {
case 2:
mt76_set(dev, MT_BBP(TXBE, 5), 0x3);
break;
default:
mt76_clear(dev, MT_BBP(TXBE, 5), 0x3);
break;
}
}
EXPORT_SYMBOL_GPL(mt76x02_phy_set_txdac);
static u32
mt76x02_tx_power_mask(u8 v1, u8 v2, u8 v3, u8 v4)
{
u32 val = 0;
val |= (v1 & (BIT(6) - 1)) << 0;
val |= (v2 & (BIT(6) - 1)) << 8;
val |= (v3 & (BIT(6) - 1)) << 16;
val |= (v4 & (BIT(6) - 1)) << 24;
return val;
}
int mt76x02_get_max_rate_power(struct mt76_rate_power *r)
{
s8 ret = 0;
int i;
for (i = 0; i < sizeof(r->all); i++)
ret = max(ret, r->all[i]);
return ret;
}
EXPORT_SYMBOL_GPL(mt76x02_get_max_rate_power);
void mt76x02_limit_rate_power(struct mt76_rate_power *r, int limit)
{
int i;
for (i = 0; i < sizeof(r->all); i++)
if (r->all[i] > limit)
r->all[i] = limit;
}
EXPORT_SYMBOL_GPL(mt76x02_limit_rate_power);
void mt76x02_add_rate_power_offset(struct mt76_rate_power *r, int offset)
{
int i;
for (i = 0; i < sizeof(r->all); i++)
r->all[i] += offset;
}
EXPORT_SYMBOL_GPL(mt76x02_add_rate_power_offset);
void mt76x02_phy_set_txpower(struct mt76x02_dev *dev, int txp_0, int txp_1)
{
struct mt76_rate_power *t = &dev->mt76.rate_power;
mt76_rmw_field(dev, MT_TX_ALC_CFG_0, MT_TX_ALC_CFG_0_CH_INIT_0, txp_0);
mt76_rmw_field(dev, MT_TX_ALC_CFG_0, MT_TX_ALC_CFG_0_CH_INIT_1, txp_1);
mt76_wr(dev, MT_TX_PWR_CFG_0,
mt76x02_tx_power_mask(t->cck[0], t->cck[2], t->ofdm[0],
t->ofdm[2]));
mt76_wr(dev, MT_TX_PWR_CFG_1,
mt76x02_tx_power_mask(t->ofdm[4], t->ofdm[6], t->ht[0],
t->ht[2]));
mt76_wr(dev, MT_TX_PWR_CFG_2,
mt76x02_tx_power_mask(t->ht[4], t->ht[6], t->ht[8],
t->ht[10]));
mt76_wr(dev, MT_TX_PWR_CFG_3,
mt76x02_tx_power_mask(t->ht[12], t->ht[14], t->stbc[0],
t->stbc[2]));
mt76_wr(dev, MT_TX_PWR_CFG_4,
mt76x02_tx_power_mask(t->stbc[4], t->stbc[6], 0, 0));
mt76_wr(dev, MT_TX_PWR_CFG_7,
mt76x02_tx_power_mask(t->ofdm[7], t->vht[8], t->ht[7],
t->vht[9]));
mt76_wr(dev, MT_TX_PWR_CFG_8,
mt76x02_tx_power_mask(t->ht[14], 0, t->vht[8], t->vht[9]));
mt76_wr(dev, MT_TX_PWR_CFG_9,
mt76x02_tx_power_mask(t->ht[7], 0, t->stbc[8], t->stbc[9]));
}
EXPORT_SYMBOL_GPL(mt76x02_phy_set_txpower);
void mt76x02_phy_set_bw(struct mt76x02_dev *dev, int width, u8 ctrl)
{
int core_val, agc_val;
switch (width) {
case NL80211_CHAN_WIDTH_80:
core_val = 3;
agc_val = 7;
break;
case NL80211_CHAN_WIDTH_40:
core_val = 2;
agc_val = 3;
break;
default:
core_val = 0;
agc_val = 1;
break;
}
mt76_rmw_field(dev, MT_BBP(CORE, 1), MT_BBP_CORE_R1_BW, core_val);
mt76_rmw_field(dev, MT_BBP(AGC, 0), MT_BBP_AGC_R0_BW, agc_val);
mt76_rmw_field(dev, MT_BBP(AGC, 0), MT_BBP_AGC_R0_CTRL_CHAN, ctrl);
mt76_rmw_field(dev, MT_BBP(TXBE, 0), MT_BBP_TXBE_R0_CTRL_CHAN, ctrl);
}
EXPORT_SYMBOL_GPL(mt76x02_phy_set_bw);
void mt76x02_phy_set_band(struct mt76x02_dev *dev, int band,
bool primary_upper)
{
switch (band) {
case NL80211_BAND_2GHZ:
mt76_set(dev, MT_TX_BAND_CFG, MT_TX_BAND_CFG_2G);
mt76_clear(dev, MT_TX_BAND_CFG, MT_TX_BAND_CFG_5G);
break;
case NL80211_BAND_5GHZ:
mt76_clear(dev, MT_TX_BAND_CFG, MT_TX_BAND_CFG_2G);
mt76_set(dev, MT_TX_BAND_CFG, MT_TX_BAND_CFG_5G);
break;
}
mt76_rmw_field(dev, MT_TX_BAND_CFG, MT_TX_BAND_CFG_UPPER_40M,
primary_upper);
}
EXPORT_SYMBOL_GPL(mt76x02_phy_set_band);
bool mt76x02_phy_adjust_vga_gain(struct mt76x02_dev *dev)
{
u8 limit = dev->cal.low_gain > 0 ? 16 : 4;
bool ret = false;
u32 false_cca;
false_cca = FIELD_GET(MT_RX_STAT_1_CCA_ERRORS,
mt76_rr(dev, MT_RX_STAT_1));
dev->cal.false_cca = false_cca;
if (false_cca > 800 && dev->cal.agc_gain_adjust < limit) {
dev->cal.agc_gain_adjust += 2;
ret = true;
} else if ((false_cca < 10 && dev->cal.agc_gain_adjust > 0) ||
(dev->cal.agc_gain_adjust >= limit && false_cca < 500)) {
dev->cal.agc_gain_adjust -= 2;
ret = true;
}
dev->cal.agc_lowest_gain = dev->cal.agc_gain_adjust >= limit;
return ret;
}
EXPORT_SYMBOL_GPL(mt76x02_phy_adjust_vga_gain);
void mt76x02_init_agc_gain(struct mt76x02_dev *dev)
{
dev->cal.agc_gain_init[0] = mt76_get_field(dev, MT_BBP(AGC, 8),
MT_BBP_AGC_GAIN);
dev->cal.agc_gain_init[1] = mt76_get_field(dev, MT_BBP(AGC, 9),
MT_BBP_AGC_GAIN);
memcpy(dev->cal.agc_gain_cur, dev->cal.agc_gain_init,
sizeof(dev->cal.agc_gain_cur));
dev->cal.low_gain = -1;
dev->cal.gain_init_done = true;
}
EXPORT_SYMBOL_GPL(mt76x02_init_agc_gain);
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css">
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="Start" href="index.html">
<link rel="previous" href="Arg.html">
<link rel="next" href="Array.html">
<link rel="Up" href="index.html">
<link title="Index of types" rel=Appendix href="index_types.html">
<link title="Index of exceptions" rel=Appendix href="index_exceptions.html">
<link title="Index of values" rel=Appendix href="index_values.html">
<link title="Index of modules" rel=Appendix href="index_modules.html">
<link title="Index of module types" rel=Appendix href="index_module_types.html">
<link title="Arg" rel="Chapter" href="Arg.html">
<link title="Arg_helper" rel="Chapter" href="Arg_helper.html">
<link title="Array" rel="Chapter" href="Array.html">
<link title="ArrayLabels" rel="Chapter" href="ArrayLabels.html">
<link title="Ast_helper" rel="Chapter" href="Ast_helper.html">
<link title="Ast_invariants" rel="Chapter" href="Ast_invariants.html">
<link title="Ast_iterator" rel="Chapter" href="Ast_iterator.html">
<link title="Ast_mapper" rel="Chapter" href="Ast_mapper.html">
<link title="Asttypes" rel="Chapter" href="Asttypes.html">
<link title="Attr_helper" rel="Chapter" href="Attr_helper.html">
<link title="Bigarray" rel="Chapter" href="Bigarray.html">
<link title="Buffer" rel="Chapter" href="Buffer.html">
<link title="Build_path_prefix_map" rel="Chapter" href="Build_path_prefix_map.html">
<link title="Builtin_attributes" rel="Chapter" href="Builtin_attributes.html">
<link title="Bytes" rel="Chapter" href="Bytes.html">
<link title="BytesLabels" rel="Chapter" href="BytesLabels.html">
<link title="Callback" rel="Chapter" href="Callback.html">
<link title="CamlinternalFormat" rel="Chapter" href="CamlinternalFormat.html">
<link title="CamlinternalFormatBasics" rel="Chapter" href="CamlinternalFormatBasics.html">
<link title="CamlinternalLazy" rel="Chapter" href="CamlinternalLazy.html">
<link title="CamlinternalMod" rel="Chapter" href="CamlinternalMod.html">
<link title="CamlinternalOO" rel="Chapter" href="CamlinternalOO.html">
<link title="Ccomp" rel="Chapter" href="Ccomp.html">
<link title="Char" rel="Chapter" href="Char.html">
<link title="Clflags" rel="Chapter" href="Clflags.html">
<link title="Complex" rel="Chapter" href="Complex.html">
<link title="Condition" rel="Chapter" href="Condition.html">
<link title="Config" rel="Chapter" href="Config.html">
<link title="Consistbl" rel="Chapter" href="Consistbl.html">
<link title="Depend" rel="Chapter" href="Depend.html">
<link title="Digest" rel="Chapter" href="Digest.html">
<link title="Docstrings" rel="Chapter" href="Docstrings.html">
<link title="Dynlink" rel="Chapter" href="Dynlink.html">
<link title="Ephemeron" rel="Chapter" href="Ephemeron.html">
<link title="Event" rel="Chapter" href="Event.html">
<link title="Filename" rel="Chapter" href="Filename.html">
<link title="Float" rel="Chapter" href="Float.html">
<link title="Format" rel="Chapter" href="Format.html">
<link title="Gc" rel="Chapter" href="Gc.html">
<link title="Genlex" rel="Chapter" href="Genlex.html">
<link title="Graphics" rel="Chapter" href="Graphics.html">
<link title="GraphicsX11" rel="Chapter" href="GraphicsX11.html">
<link title="Hashtbl" rel="Chapter" href="Hashtbl.html">
<link title="Identifiable" rel="Chapter" href="Identifiable.html">
<link title="Int32" rel="Chapter" href="Int32.html">
<link title="Int64" rel="Chapter" href="Int64.html">
<link title="Lazy" rel="Chapter" href="Lazy.html">
<link title="Lexer" rel="Chapter" href="Lexer.html">
<link title="Lexing" rel="Chapter" href="Lexing.html">
<link title="List" rel="Chapter" href="List.html">
<link title="ListLabels" rel="Chapter" href="ListLabels.html">
<link title="Location" rel="Chapter" href="Location.html">
<link title="Longident" rel="Chapter" href="Longident.html">
<link title="Map" rel="Chapter" href="Map.html">
<link title="Marshal" rel="Chapter" href="Marshal.html">
<link title="Misc" rel="Chapter" href="Misc.html">
<link title="MoreLabels" rel="Chapter" href="MoreLabels.html">
<link title="Mutex" rel="Chapter" href="Mutex.html">
<link title="Nativeint" rel="Chapter" href="Nativeint.html">
<link title="Numbers" rel="Chapter" href="Numbers.html">
<link title="Obj" rel="Chapter" href="Obj.html">
<link title="Oo" rel="Chapter" href="Oo.html">
<link title="Parse" rel="Chapter" href="Parse.html">
<link title="Parser" rel="Chapter" href="Parser.html">
<link title="Parsetree" rel="Chapter" href="Parsetree.html">
<link title="Parsing" rel="Chapter" href="Parsing.html">
<link title="Pervasives" rel="Chapter" href="Pervasives.html">
<link title="Pparse" rel="Chapter" href="Pparse.html">
<link title="Pprintast" rel="Chapter" href="Pprintast.html">
<link title="Printast" rel="Chapter" href="Printast.html">
<link title="Printexc" rel="Chapter" href="Printexc.html">
<link title="Printf" rel="Chapter" href="Printf.html">
<link title="Profile" rel="Chapter" href="Profile.html">
<link title="Queue" rel="Chapter" href="Queue.html">
<link title="Random" rel="Chapter" href="Random.html">
<link title="Scanf" rel="Chapter" href="Scanf.html">
<link title="Seq" rel="Chapter" href="Seq.html">
<link title="Set" rel="Chapter" href="Set.html">
<link title="Simplif" rel="Chapter" href="Simplif.html">
<link title="Sort" rel="Chapter" href="Sort.html">
<link title="Spacetime" rel="Chapter" href="Spacetime.html">
<link title="Stack" rel="Chapter" href="Stack.html">
<link title="StdLabels" rel="Chapter" href="StdLabels.html">
<link title="Str" rel="Chapter" href="Str.html">
<link title="Stream" rel="Chapter" href="Stream.html">
<link title="String" rel="Chapter" href="String.html">
<link title="StringLabels" rel="Chapter" href="StringLabels.html">
<link title="Strongly_connected_components" rel="Chapter" href="Strongly_connected_components.html">
<link title="Syntaxerr" rel="Chapter" href="Syntaxerr.html">
<link title="Sys" rel="Chapter" href="Sys.html">
<link title="Targetint" rel="Chapter" href="Targetint.html">
<link title="Tbl" rel="Chapter" href="Tbl.html">
<link title="Terminfo" rel="Chapter" href="Terminfo.html">
<link title="Thread" rel="Chapter" href="Thread.html">
<link title="ThreadUnix" rel="Chapter" href="ThreadUnix.html">
<link title="Typemod" rel="Chapter" href="Typemod.html">
<link title="Uchar" rel="Chapter" href="Uchar.html">
<link title="Unix" rel="Chapter" href="Unix.html">
<link title="UnixLabels" rel="Chapter" href="UnixLabels.html">
<link title="Warnings" rel="Chapter" href="Warnings.html">
<link title="Weak" rel="Chapter" href="Weak.html"><title>Arg_helper</title>
</head>
<body>
<div class="navbar"><a class="pre" href="Arg.html" title="Arg">Previous</a>
<a class="up" href="index.html" title="Index">Up</a>
<a class="post" href="Array.html" title="Array">Next</a>
</div>
<h1>Module <a href="type_Arg_helper.html">Arg_helper</a></h1>
<pre><span id="MODULEArg_helper"><span class="keyword">module</span> Arg_helper</span>: <code class="code"><span class="keyword">sig</span></code> <a href="Arg_helper.html">..</a> <code class="code"><span class="keyword">end</span></code></pre><div class="info module top">
<div class="info-desc">
<p>Decipher command line arguments of the form
<value> | <key>=<value><code class="code">,...</code>
(as used for example for the specification of inlining parameters
varying by simplification round).</p>
</div>
</div>
<hr width="100%">
<pre><span id="MODULEMake"><span class="keyword">module</span> <a href="Arg_helper.Make.html">Make</a></span>: <div class="sig_block"><code class="code"><span class="keyword">functor</span> (</code><code class="code"><span class="constructor">S</span></code><code class="code"> : </code><code class="code"><span class="keyword">sig</span></code></pre><div class="sig_block">
<pre><span id="MODULEKey"><span class="keyword">module</span> <a href="Arg_helper.Make.Key.html">Key</a></span>: <code class="code"><span class="keyword">sig</span></code> <a href="Arg_helper.Make.Key.html">..</a> <code class="code"><span class="keyword">end</span></code></pre>
<pre><span id="MODULEValue"><span class="keyword">module</span> <a href="Arg_helper.Make.Value.html">Value</a></span>: <code class="code"><span class="keyword">sig</span></code> <a href="Arg_helper.Make.Value.html">..</a> <code class="code"><span class="keyword">end</span></code></pre></div><pre><code class="code"><span class="keyword">end</span></code><code class="code">) <span class="keywordsign">-></span> </code><code class="code"><span class="keyword">sig</span></code> <a href="Arg_helper.Make.html">..</a> <code class="code"><span class="keyword">end</span></code></div></pre></body></html>
| {
"pile_set_name": "Github"
} |
# Ubuntu Setup Scripts/Files
## systemd startup with logging to syslog
Either copy/paste the following into `/etc/systemd/system/arbbot.service` or copy the file included in this directory to there.
> Note, you may want to add a user/group below also or change the syslog destination to a file.
###### /etc/systemd/system/arbbot.service
```shell
[Unit]
Description=Arbbot - Arbitrage Trading Bot
After=syslog.target network.target mysql.service
[Service]
ExecStart=/usr/bin/php main.php
WorkingDirectory=/var/www/arbbot
Type=simple
InaccessibleDirectories=/home /root /boot /opt /mnt /media
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=arbbot
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
NoNewPrivileges=true
Restart=always
[Install]
WantedBy=multi-user.target
```
next, enable the service, start it, then check to see if it started.
```shell
sudo systemctl enable arbbot
sudo systemctl start arbbot
sudo systemctl status arbbot
```
## NTP setup
NTP is **vital** to the functionality of this tool. Make sure it works. Here's a copy/paste to make it easy:
###### ntp setup script
```shell
#!/bin/bash
apt update
apt -y install ntp
service ntp stop
ntpdate ntp.ubuntu.com
service ntp start
update-rc.d ntp enable
sleep 5
echo "Checking for Peers"
ntpq -c lpeer
```
| {
"pile_set_name": "Github"
} |
import * as React from "react";
const IconRotate = (size = 24, color = "currentColor", stroke = 2, ...props) => <svg className="icon icon-tabler icon-tabler-rotate" width={size} height={size} viewBox="0 0 24 24" strokeWidth={stroke} stroke={color} fill="none" strokeLinecap="round" strokeLinejoin="round" {...props}><path stroke="none" d="M0 0h24v24H0z" fill="none" /><path d="M19.95 11a8 8 0 1 0 -.5 4m.5 5v-5h-5" /></svg>;
export default IconRotate; | {
"pile_set_name": "Github"
} |
<?php
namespace Metaregistrar\EPP;
/*
<extension>
<keysys:update xmlns:keysys="http://www.key-systems.net/epp/keysys-1.0">
<keysys:domain>
<keysys:renewalmode>AUTOEXPIRE</keysys:renewalmode>
</keysys:domain>
</keysys:update>
</extension>
*/
class rrpproxyEppRenewalmodeRequest extends eppUpdateDomainRequest {
const RRP_RENEWALMODE_DEFAULT = "DEFAULT";
const RRP_RENEWALMODE_AUTORENEW = "AUTORENEW";
const RRP_RENEWALMODE_AUTOEXPIRE = "AUTOEXPIRE";
const RRP_RENEWALMODE_AUTODELETE = "AUTODELETE";
const RRP_RENEWALMODE_RENEWONCE = "RENEWONCE";
const RRP_RENEWALMODE_RENEWONCETHENAUTODELETE = "RENEWONCETHENAUTODELETE";
const RRP_RENEWALMODE_RENEWONCETHENAUTOEXPIRE = "RENEWONCETHENAUTOEXPIRE";
/**
* rrpproxyEppRenewalmodeRequest constructor.
* @param eppDomain $domain
* @param string $renewalmode
* @throws eppException
*/
function __construct(eppDomain $domain, $renewalmode) {
$upd = new eppDomain($domain->getDomainname());
parent::__construct($domain, null, null, $upd);
$this->addRenewalmode($renewalmode);
parent::addSessionId();
}
/**
* @param string $renewalmode
*/
private function addRenewalmode($renewalmode){
$ext = $this->createElement('extension');
$infdata = $this->createElement('keysys:update');
$domdata = $this->createElement('keysys:domain');
$cd = $this->createElement('keysys:renewalmode', $renewalmode);
$domdata->appendChild($cd);
$infdata->appendChild($domdata);
$ext->appendChild($infdata);
$this->getCommand()->appendChild($ext);
}
} | {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<base target="_blank"/>
<style type="text/css">
body, td {
font-family: sans-serif;
background-color: white;
font-size: 12px;
margin: 8px;
}
tt, code, pre {
font-family: 'DejaVu Sans Mono', 'Droid Sans Mono', 'Lucida Console', Consolas, Monaco, monospace;
}
h1 {
font-size:2.2em;
}
h2 {
font-size:1.8em;
}
h3 {
font-size:1.4em;
}
h4 {
font-size:1.0em;
}
h5 {
font-size:0.9em;
}
h6 {
font-size:0.8em;
}
a:visited {
color: rgb(50%, 0%, 50%);
}
pre {
margin-top: 0;
max-width: 95%;
border: 1px solid #ccc;
}
pre code {
display: block; padding: 0.5em;
}
code.r {
background-color: #F8F8F8;
}
table, td, th {
border: none;
}
blockquote {
color:#666666;
margin:0;
padding-left: 1em;
border-left: 0.5em #EEE solid;
}
hr {
height: 0px;
border-bottom: none;
border-top-width: thin;
border-top-style: dotted;
border-top-color: #999999;
}
@media print {
* {
background: transparent !important;
color: black !important;
filter:none !important;
-ms-filter: none !important;
}
body {
font-size:12pt;
max-width:100%;
}
a, a:visited {
text-decoration: underline;
}
hr {
visibility: hidden;
page-break-before: always;
}
pre, blockquote {
padding-right: 1em;
page-break-inside: avoid;
}
tr, img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
@page :left {
margin: 15mm 20mm 15mm 10mm;
}
@page :right {
margin: 15mm 10mm 15mm 20mm;
}
p, h2, h3 {
orphans: 3; widows: 3;
}
h2, h3 {
page-break-after: avoid;
}
}
</style>
</head>
<body>
<p>Optimization algorithms fall into three categories:</p>
<ul>
<li>Function values only</li>
<li>Function values and gradients only</li>
<li>Function values and gradients and Hessians</li>
</ul>
<p>This can be further refined by what the user must supply versus what the algorithm can invent.</p>
<p>Gradient descent</p>
<p>Direction method<br/>
Trust region methods</p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
#import "EXPMatchers+beLessThanOrEqualTo.h"
#import "EXPMatcherHelpers.h"
EXPMatcherImplementationBegin(_beLessThanOrEqualTo, (id expected)) {
match(^BOOL{
if ([actual respondsToSelector:@selector(compare:)]) {
return [actual compare:expected] != NSOrderedDescending;
}
return NO;
});
failureMessageForTo(^NSString *{
return [NSString stringWithFormat:@"expected: %@ to be less than or equal to %@", EXPDescribeObject(actual), EXPDescribeObject(expected)];
});
failureMessageForNotTo(^NSString *{
return [NSString stringWithFormat:@"expected: %@ not to be less than or equal to %@", EXPDescribeObject(actual), EXPDescribeObject(expected)];
});
}
EXPMatcherImplementationEnd | {
"pile_set_name": "Github"
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-input-directive</title>
<script src="../../../angular.min.js"></script>
</head>
<body ng-app="inputExample">
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}]);
</script>
<div ng-controller="ExampleController">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span><br>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
Matrix4i m = Matrix4i::Random();
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Here is m.bottomLeftCorner<2,2>():" << endl;
cout << m.bottomLeftCorner<2,2>() << endl;
m.bottomLeftCorner<2,2>().setZero();
cout << "Now the matrix m is:" << endl << m << endl;
| {
"pile_set_name": "Github"
} |
cstatfs: statfs.cc
g++ -O2 -Wall -std=c++0x $< `pkg-config fuse --cflags --libs` -o $@
| {
"pile_set_name": "Github"
} |
#include "../../../../include/uapi/linux/virtio_config.h"
| {
"pile_set_name": "Github"
} |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the cognito-idp-2016-04-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.CognitoIdentityProvider.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CognitoIdentityProvider.Model.Internal.MarshallTransformations
{
/// <summary>
/// InitiateAuth Request Marshaller
/// </summary>
public class InitiateAuthRequestMarshaller : IMarshaller<IRequest, InitiateAuthRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((InitiateAuthRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(InitiateAuthRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.CognitoIdentityProvider");
string target = "AWSCognitoIdentityProviderService.InitiateAuth";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-04-18";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetAnalyticsMetadata())
{
context.Writer.WritePropertyName("AnalyticsMetadata");
context.Writer.WriteObjectStart();
var marshaller = AnalyticsMetadataTypeMarshaller.Instance;
marshaller.Marshall(publicRequest.AnalyticsMetadata, context);
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetAuthFlow())
{
context.Writer.WritePropertyName("AuthFlow");
context.Writer.Write(publicRequest.AuthFlow);
}
if(publicRequest.IsSetAuthParameters())
{
context.Writer.WritePropertyName("AuthParameters");
context.Writer.WriteObjectStart();
foreach (var publicRequestAuthParametersKvp in publicRequest.AuthParameters)
{
context.Writer.WritePropertyName(publicRequestAuthParametersKvp.Key);
var publicRequestAuthParametersValue = publicRequestAuthParametersKvp.Value;
context.Writer.Write(publicRequestAuthParametersValue);
}
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetClientId())
{
context.Writer.WritePropertyName("ClientId");
context.Writer.Write(publicRequest.ClientId);
}
if(publicRequest.IsSetClientMetadata())
{
context.Writer.WritePropertyName("ClientMetadata");
context.Writer.WriteObjectStart();
foreach (var publicRequestClientMetadataKvp in publicRequest.ClientMetadata)
{
context.Writer.WritePropertyName(publicRequestClientMetadataKvp.Key);
var publicRequestClientMetadataValue = publicRequestClientMetadataKvp.Value;
context.Writer.Write(publicRequestClientMetadataValue);
}
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetUserContextData())
{
context.Writer.WritePropertyName("UserContextData");
context.Writer.WriteObjectStart();
var marshaller = UserContextDataTypeMarshaller.Instance;
marshaller.Marshall(publicRequest.UserContextData, context);
context.Writer.WriteObjectEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static InitiateAuthRequestMarshaller _instance = new InitiateAuthRequestMarshaller();
internal static InitiateAuthRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static InitiateAuthRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | {
"pile_set_name": "Github"
} |
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import React from 'react'
import PropTypes from 'prop-types'
import { View, StyleSheet, Text, ViewPropTypes } from 'react-native'
import V from '../variable'
const styles = StyleSheet.create({
popupHeader: {
flexDirection: 'row',
alignItems: 'center',
borderBottomWidth: StyleSheet.hairlineWidth,
borderColor: '#E5E5E5',
backgroundColor: '#fbf9fe'
},
popupActionLeft: {
flex: 1,
color: '#586C94',
textAlign: 'left',
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 15,
fontSize: V.baseFontSize
},
popupActionRight: {
flex: 1,
color: '#586C94',
textAlign: 'right',
paddingTop: 10,
paddingBottom: 10,
paddingRight: 15,
fontSize: V.baseFontSize
}
})
const PopupHeader = ({ style, left = {}, right = {} }) =>
<View style={[styles.popupHeader, style]}>
<Text
style={[styles.popupActionLeft, left.style]}
onPress={left.onPress}
>{left.label}</Text>
<Text
style={[styles.popupActionRight, right.style]}
onPress={right.onPress}
>{right.label}</Text>
</View>
PopupHeader.propTypes = {
style: ViewPropTypes.style,
left: PropTypes.object,
right: PropTypes.object
}
export default PopupHeader
| {
"pile_set_name": "Github"
} |
<p class="input-field">
<%= label :card, :first_name, 'Card first name' %>
<%= text_field :card, :first_name %>
</p>
<p class="input-field">
<%= label :card, :last_name, 'Card last name' %>
<%= text_field :card, :last_name %>
</p>
<p class="input-field">
<%= label :card, :type, 'Card type' %>
<%= select :card, :type, card_types %>
</p>
<p class="input-field">
<%= label :card, :number %>
<%= text_field :card, :number, :autocomplete => "off" %>
</p>
<p class="input-field inline">
<%= label :card, :month, 'Expiration' %>
<%= select :card, :month, month_names, :selected => Time.now.month %>
<%= select :card, :year, next_fifteen_years %>
</p>
<p class="input-field">
<%= label :card, :verification_value, 'Verification' %>
<%= text_field :card, :verification_value, :style => "width:40px", :autocomplete => "off" %>
</p> | {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <[email protected]>'
__docformat__ = 'restructuredtext en'
from operator import attrgetter
from PyQt5.Qt import (Qt, QAbstractItemModel, QModelIndex, pyqtSignal)
from calibre.db.search import _match, CONTAINS_MATCH, EQUALS_MATCH, REGEXP_MATCH
from calibre.utils.config_base import prefs
from calibre.utils.icu import sort_key
from calibre.utils.search_query_parser import SearchQueryParser
class BooksModel(QAbstractItemModel):
total_changed = pyqtSignal(int)
HEADERS = [_('Title'), _('Author(s)'), _('Format')]
def __init__(self, all_books):
QAbstractItemModel.__init__(self)
self.books = all_books
self.all_books = all_books
self.filter = ''
self.search_filter = SearchFilter(all_books)
self.sort_col = 0
self.sort_order = Qt.AscendingOrder
def get_book(self, index):
row = index.row()
if row < len(self.books):
return self.books[row]
else:
return None
def search(self, filter):
self.filter = filter.strip()
if not self.filter:
self.books = self.all_books
else:
try:
self.books = list(self.search_filter.parse(self.filter))
except:
self.books = self.all_books
self.layoutChanged.emit()
self.sort(self.sort_col, self.sort_order)
self.total_changed.emit(self.rowCount())
def index(self, row, column, parent=QModelIndex()):
return self.createIndex(row, column)
def parent(self, index):
if not index.isValid() or index.internalId() == 0:
return QModelIndex()
return self.createIndex(0, 0)
def rowCount(self, *args):
return len(self.books)
def columnCount(self, *args):
return len(self.HEADERS)
def headerData(self, section, orientation, role):
if role != Qt.DisplayRole:
return None
text = ''
if orientation == Qt.Horizontal:
if section < len(self.HEADERS):
text = self.HEADERS[section]
return (text)
else:
return (section+1)
def data(self, index, role):
row, col = index.row(), index.column()
result = self.books[row]
if role == Qt.DisplayRole:
if col == 0:
return (result.title)
elif col == 1:
return (result.author)
elif col == 2:
return (result.formats)
return None
def data_as_text(self, result, col):
text = ''
if col == 0:
text = result.title
elif col == 1:
text = result.author
elif col == 2:
text = result.formats
return text
def sort(self, col, order, reset=True):
self.sort_col = col
self.sort_order = order
if not self.books:
return
descending = order == Qt.DescendingOrder
self.books.sort(None,
lambda x: sort_key(type(u'')(self.data_as_text(x, col))),
descending)
if reset:
self.beginResetModel(), self.endResetModel()
class SearchFilter(SearchQueryParser):
USABLE_LOCATIONS = [
'all',
'author',
'authors',
'format',
'formats',
'title',
]
def __init__(self, all_books=[]):
SearchQueryParser.__init__(self, locations=self.USABLE_LOCATIONS)
self.srs = set(all_books)
def universal_set(self):
return self.srs
def get_matches(self, location, query):
location = location.lower().strip()
if location == 'authors':
location = 'author'
elif location == 'formats':
location = 'format'
matchkind = CONTAINS_MATCH
if len(query) > 1:
if query.startswith('\\'):
query = query[1:]
elif query.startswith('='):
matchkind = EQUALS_MATCH
query = query[1:]
elif query.startswith('~'):
matchkind = REGEXP_MATCH
query = query[1:]
if matchkind != REGEXP_MATCH: # leave case in regexps because it can be significant e.g. \S \W \D
query = query.lower()
if location not in self.USABLE_LOCATIONS:
return set()
matches = set()
all_locs = set(self.USABLE_LOCATIONS) - {'all'}
locations = all_locs if location == 'all' else [location]
q = {
'author': lambda x: x.author.lower(),
'format': attrgetter('formats'),
'title': lambda x: x.title.lower(),
}
for x in ('author', 'format'):
q[x+'s'] = q[x]
upf = prefs['use_primary_find_in_search']
for sr in self.srs:
for locvalue in locations:
accessor = q[locvalue]
if query == 'true':
if accessor(sr) is not None:
matches.add(sr)
continue
if query == 'false':
if accessor(sr) is None:
matches.add(sr)
continue
try:
# Can't separate authors because comma is used for name sep and author sep
# Exact match might not get what you want. For that reason, turn author
# exactmatch searches into contains searches.
if locvalue == 'author' and matchkind == EQUALS_MATCH:
m = CONTAINS_MATCH
else:
m = matchkind
vals = [accessor(sr)]
if _match(query, vals, m, use_primary_find_in_search=upf):
matches.add(sr)
break
except ValueError: # Unicode errors
import traceback
traceback.print_exc()
return matches
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="format_bar_height">44dp</dimen>
<dimen name="format_bar_height_tablet">49dp</dimen>
<dimen name="format_bar_left_margin">5dp</dimen>
<dimen name="format_bar_right_margin">2dp</dimen>
<dimen name="format_bar_html_button_left_margin">3dp</dimen>
<dimen name="format_bar_scroll_right_margin">-7dp</dimen>
<dimen name="format_bar_button_margin_tablet">@dimen/format_bar_button_margin_tablet_small</dimen>
<dimen name="format_bar_button_margin_tablet_small">0dp</dimen>
<dimen name="format_bar_button_margin_tablet_large">7dp</dimen>
<dimen name="format_bar_button_margin_tablet_extra_large">12dp</dimen>
<dimen name="format_bar_button_group_tablet">@dimen/format_bar_button_group_tablet_small</dimen>
<dimen name="format_bar_button_group_tablet_small">15dp</dimen>
<dimen name="format_bar_button_group_tablet_large">25dp</dimen>
<dimen name="format_bar_button_group_tablet_extra_large">35dp</dimen>
<dimen name="format_bar_horizontal_divider_height">1dp</dimen>
<dimen name="format_bar_vertical_divider_width">0.6dp</dimen>
<dimen name="format_bar_vertical_divider_height">28dp</dimen>
<dimen name="sourceview_side_margin">15dp</dimen>
<dimen name="sourceview_side_margin_large">90dp</dimen>
<dimen name="sourceview_side_margin_extra_large">170dp</dimen>
<dimen name="sourceview_top_margin">15dp</dimen>
<dimen name="sourceview_title_bottom_margin">15dp</dimen>
<dimen name="image_settings_dialog_padding">16dp</dimen>
<dimen name="image_settings_dialog_extra_margin">0dp</dimen>
<dimen name="image_settings_dialog_extra_margin_tablet">84dp</dimen>
<dimen name="image_settings_dialog_label_indent">4dp</dimen>
<dimen name="image_settings_dialog_label_margin_bottom">4dp</dimen>
<dimen name="image_settings_dialog_input_margin_bottom">16dp</dimen>
<dimen name="image_settings_dialog_input_field_start_margin">-4dp</dimen>
<dimen name="image_settings_dialog_top_separator_margin_top">16dp</dimen>
<dimen name="image_settings_dialog_thumbnail_container_margin_bottom">8dp</dimen>
<dimen name="image_settings_dialog_thumbnail_size">100dp</dimen>
<dimen name="image_settings_dialog_thumbnail_progress_size">50dp</dimen>
<dimen name="image_settings_dialog_thumbnail_left_margin">4dp</dimen>
<dimen name="image_settings_dialog_thumbnail_right_margin">8dp</dimen>
<dimen name="image_settings_dialog_filename_margin_left">16dp</dimen>
<dimen name="post_editor_content_side_margin">20dp</dimen>
<dimen name="margin_extra_small">2dp</dimen>
<dimen name="margin_small">4dp</dimen>
<dimen name="margin_medium">8dp</dimen>
<dimen name="margin_large">12dp</dimen>
<dimen name="margin_extra_large">16dp</dimen>
<dimen name="spacing_extra_body">1.3dp</dimen>
<dimen name="spacing_extra_title">0.9dp</dimen>
<item name="spacing_multiplier_body" format="float" type="dimen">1.2</item>
<dimen name="aztec_title_size">24sp</dimen>
</resources>
| {
"pile_set_name": "Github"
} |
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "MOVE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
MOVE \- 重定位一个游标
.SH SYNOPSIS
.sp
.nf
MOVE [ \fIdirection\fR { FROM | IN } ] \fIcursorname\fR
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBMOVE\fR 在不检索数据的情况下重新定位一个游标。 MOVE ALL 把游标移动到结尾。 MOVE 的工作类似于 FETCH 命令, 但只是重定位游标而不返回行。
.PP
请参考
FETCH [\fBfetch\fR(7)]
命令获取语法和参数的详细信息。
.SH "OUTPUTS 输出"
.PP
成功完成时,MOVE 命令返回一个下面形式的命令标签
.sp
.nf
MOVE \fIcount\fR
.sp
.fi
\fIcount\fR 是移动的行数(可能为零)。
.SH "EXAMPLES 例子"
设置和使用一个游标:
.sp
.nf
BEGIN WORK;
DECLARE liahona CURSOR FOR SELECT * FROM films;
-- 忽略开头 5 行:
MOVE FORWARD 5 IN liahona;
MOVE 5
-- 抓取游标 liahona 里的第六行:
FETCH 1 FROM liahona;
code | title | did | date_prod | kind | len
-------+--------+-----+------------+--------+-------
P_303 | 48 Hrs | 103 | 1982-10-22 | Action | 01:37
(1 row)
-- 关闭游标 liahona 并提交工作:
CLOSE liahona;
COMMIT WORK;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
SQL 标准里没有 MOVE 语句。
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <[email protected]>
| {
"pile_set_name": "Github"
} |
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M16.5,12c1.38,0 2.49,-1.12 2.49,-2.5S17.88,7 16.5,7 14,8.12 14,9.5s1.12,2.5 2.5,2.5zM9,11c1.66,0 2.99,-1.34 2.99,-3S10.66,5 9,5 6,6.34 6,8s1.34,3 3,3zM16.5,14c-1.83,0 -5.5,0.92 -5.5,2.75L11,19h11v-2.25c0,-1.83 -3.67,-2.75 -5.5,-2.75zM9,13c-2.33,0 -7,1.17 -7,3.5L2,19h7v-2.25c0,-0.85 0.33,-2.34 2.37,-3.47C10.5,13.1 9.66,13 9,13z"/>
</vector>
| {
"pile_set_name": "Github"
} |
package bugsnag
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type payload struct {
*Event
*Configuration
}
type hash map[string]interface{}
func (p *payload) deliver() error {
if len(p.APIKey) != 32 {
return fmt.Errorf("bugsnag/payload.deliver: invalid api key")
}
buf, err := json.Marshal(p)
if err != nil {
return fmt.Errorf("bugsnag/payload.deliver: %v", err)
}
client := http.Client{
Transport: p.Transport,
}
resp, err := client.Post(p.Endpoint, "application/json", bytes.NewBuffer(buf))
if err != nil {
return fmt.Errorf("bugsnag/payload.deliver: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("bugsnag/payload.deliver: Got HTTP %s\n", resp.Status)
}
return nil
}
func (p *payload) MarshalJSON() ([]byte, error) {
data := hash{
"apiKey": p.APIKey,
"notifier": hash{
"name": "Bugsnag Go",
"url": "https://github.com/bugsnag/bugsnag-go",
"version": VERSION,
},
"events": []hash{
{
"payloadVersion": "2",
"exceptions": []hash{
{
"errorClass": p.ErrorClass,
"message": p.Message,
"stacktrace": p.Stacktrace,
},
},
"severity": p.Severity.String,
"app": hash{
"releaseStage": p.ReleaseStage,
},
"user": p.User,
"metaData": p.MetaData.sanitize(p.ParamsFilters),
},
},
}
event := data["events"].([]hash)[0]
if p.Context != "" {
event["context"] = p.Context
}
if p.GroupingHash != "" {
event["groupingHash"] = p.GroupingHash
}
if p.Hostname != "" {
event["device"] = hash{
"hostname": p.Hostname,
}
}
if p.AppVersion != "" {
event["app"].(hash)["version"] = p.AppVersion
}
return json.Marshal(data)
}
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0
#include <linux/compiler.h>
#include <errno.h>
#include <inttypes.h>
#include <string.h>
#include <sys/wait.h>
#include "tests.h"
#include "evlist.h"
#include "evsel.h"
#include "util.h"
#include "debug.h"
#include "thread_map.h"
#include "target.h"
static int attach__enable_on_exec(struct perf_evlist *evlist)
{
struct perf_evsel *evsel = perf_evlist__last(evlist);
struct target target = {
.uid = UINT_MAX,
};
const char *argv[] = { "true", NULL, };
char sbuf[STRERR_BUFSIZE];
int err;
pr_debug("attaching to spawned child, enable on exec\n");
err = perf_evlist__create_maps(evlist, &target);
if (err < 0) {
pr_debug("Not enough memory to create thread/cpu maps\n");
return err;
}
err = perf_evlist__prepare_workload(evlist, &target, argv, false, NULL);
if (err < 0) {
pr_debug("Couldn't run the workload!\n");
return err;
}
evsel->attr.enable_on_exec = 1;
err = perf_evlist__open(evlist);
if (err < 0) {
pr_debug("perf_evlist__open: %s\n",
str_error_r(errno, sbuf, sizeof(sbuf)));
return err;
}
return perf_evlist__start_workload(evlist) == 1 ? TEST_OK : TEST_FAIL;
}
static int detach__enable_on_exec(struct perf_evlist *evlist)
{
waitpid(evlist->workload.pid, NULL, 0);
return 0;
}
static int attach__current_disabled(struct perf_evlist *evlist)
{
struct perf_evsel *evsel = perf_evlist__last(evlist);
struct thread_map *threads;
int err;
pr_debug("attaching to current thread as disabled\n");
threads = thread_map__new(-1, getpid(), UINT_MAX);
if (threads == NULL) {
pr_debug("thread_map__new\n");
return -1;
}
evsel->attr.disabled = 1;
err = perf_evsel__open_per_thread(evsel, threads);
if (err) {
pr_debug("Failed to open event cpu-clock:u\n");
return err;
}
thread_map__put(threads);
return perf_evsel__enable(evsel) == 0 ? TEST_OK : TEST_FAIL;
}
static int attach__current_enabled(struct perf_evlist *evlist)
{
struct perf_evsel *evsel = perf_evlist__last(evlist);
struct thread_map *threads;
int err;
pr_debug("attaching to current thread as enabled\n");
threads = thread_map__new(-1, getpid(), UINT_MAX);
if (threads == NULL) {
pr_debug("failed to call thread_map__new\n");
return -1;
}
err = perf_evsel__open_per_thread(evsel, threads);
thread_map__put(threads);
return err == 0 ? TEST_OK : TEST_FAIL;
}
static int detach__disable(struct perf_evlist *evlist)
{
struct perf_evsel *evsel = perf_evlist__last(evlist);
return perf_evsel__enable(evsel);
}
static int attach__cpu_disabled(struct perf_evlist *evlist)
{
struct perf_evsel *evsel = perf_evlist__last(evlist);
struct cpu_map *cpus;
int err;
pr_debug("attaching to CPU 0 as enabled\n");
cpus = cpu_map__new("0");
if (cpus == NULL) {
pr_debug("failed to call cpu_map__new\n");
return -1;
}
evsel->attr.disabled = 1;
err = perf_evsel__open_per_cpu(evsel, cpus);
if (err) {
if (err == -EACCES)
return TEST_SKIP;
pr_debug("Failed to open event cpu-clock:u\n");
return err;
}
cpu_map__put(cpus);
return perf_evsel__enable(evsel);
}
static int attach__cpu_enabled(struct perf_evlist *evlist)
{
struct perf_evsel *evsel = perf_evlist__last(evlist);
struct cpu_map *cpus;
int err;
pr_debug("attaching to CPU 0 as enabled\n");
cpus = cpu_map__new("0");
if (cpus == NULL) {
pr_debug("failed to call cpu_map__new\n");
return -1;
}
err = perf_evsel__open_per_cpu(evsel, cpus);
if (err == -EACCES)
return TEST_SKIP;
cpu_map__put(cpus);
return err ? TEST_FAIL : TEST_OK;
}
static int test_times(int (attach)(struct perf_evlist *),
int (detach)(struct perf_evlist *))
{
struct perf_counts_values count;
struct perf_evlist *evlist = NULL;
struct perf_evsel *evsel;
int err = -1, i;
evlist = perf_evlist__new();
if (!evlist) {
pr_debug("failed to create event list\n");
goto out_err;
}
err = parse_events(evlist, "cpu-clock:u", NULL);
if (err) {
pr_debug("failed to parse event cpu-clock:u\n");
goto out_err;
}
evsel = perf_evlist__last(evlist);
evsel->attr.read_format |=
PERF_FORMAT_TOTAL_TIME_ENABLED |
PERF_FORMAT_TOTAL_TIME_RUNNING;
err = attach(evlist);
if (err == TEST_SKIP) {
pr_debug(" SKIP : not enough rights\n");
return err;
}
TEST_ASSERT_VAL("failed to attach", !err);
for (i = 0; i < 100000000; i++) { }
TEST_ASSERT_VAL("failed to detach", !detach(evlist));
perf_evsel__read(evsel, 0, 0, &count);
err = !(count.ena == count.run);
pr_debug(" %s: ena %" PRIu64", run %" PRIu64"\n",
!err ? "OK " : "FAILED",
count.ena, count.run);
out_err:
perf_evlist__delete(evlist);
return !err ? TEST_OK : TEST_FAIL;
}
/*
* This test creates software event 'cpu-clock'
* attaches it in several ways (explained below)
* and checks that enabled and running times
* match.
*/
int test__event_times(struct test *test __maybe_unused, int subtest __maybe_unused)
{
int err, ret = 0;
#define _T(attach, detach) \
err = test_times(attach, detach); \
if (err && (ret == TEST_OK || ret == TEST_SKIP)) \
ret = err;
/* attach on newly spawned process after exec */
_T(attach__enable_on_exec, detach__enable_on_exec)
/* attach on current process as enabled */
_T(attach__current_enabled, detach__disable)
/* attach on current process as disabled */
_T(attach__current_disabled, detach__disable)
/* attach on cpu as disabled */
_T(attach__cpu_disabled, detach__disable)
/* attach on cpu as enabled */
_T(attach__cpu_enabled, detach__disable)
#undef _T
return ret;
}
| {
"pile_set_name": "Github"
} |
var convert = require('./convert'),
func = convert('deburr', require('../deburr'), require('./_falseOptions'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"pile_set_name": "Github"
} |
/* FSBoolean.m Copyright (c) 1998-2009 Philippe Mougin. */
/* This software is open source. See the license. */
#import "build_config.h"
#import <Foundation/Foundation.h>
#import "FSBooleanPrivate.h"
#import "FScriptFunctions.h"
#import "FSBlock.h"
#import "FSNumber.h"
#import "FSMiscTools.h"
FSBoolean *fsTrue = nil;
FSBoolean *fsFalse = nil;
BOOL BooleanSetupTooLate = NO;
// MACROS
#define VERIF_OP_BOOLEAN(METHOD) {if (operand != fsTrue && operand != fsFalse && ![operand isKindOfClass:[FSBoolean class]]) FSArgumentError(operand,1,@"FSBoolean",METHOD);}
@implementation FSBoolean
+ (FSBoolean *) fsFalse {return fsFalse;}
+ (FSBoolean *) fsTrue {return fsTrue;}
+ (FSBoolean *) booleanWithBool:(BOOL)theBool {return theBool ? fsTrue : fsFalse;}
+ (void)initialize
{
static BOOL tooLate = NO;
if ( !tooLate )
{
tooLate = YES;
fsTrue = [[True alloc] init];
fsFalse = [[False alloc] init];
}
}
-(id)autorelease {return self;}
-(id)copy {return self;}
-(id)copyWithZone:(NSZone *)zone {return self;}
-(void)encodeWithCoder:(NSCoder *)coder {}
-(id)initWithCoder:(NSCoder *)coder {self = [super init]; return self;}
-(NSUInteger)hash {return self == fsTrue;}
#if !TARGET_OS_IPHONE
- (id)replacementObjectForPortCoder:(NSPortCoder *)encoder
{
if ([encoder isBycopy]) return self;
return [super replacementObjectForPortCoder:encoder];
}
#endif
-(void)release {}
-(id)retain {return self;}
-(NSUInteger)retainCount {return UINT_MAX;}
////////////////////////////// USER METHODS FOR BOOLEAN //////////////////////
- (FSBoolean *)and:(FSBlock*)operand
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
- (FSBoolean*) clone {return self;}
- (id) ifFalse:(FSBlock *)falseBlock
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
- (id) ifFalse:(FSBlock *)falseBlock ifTrue:(FSBlock *)trueBlock
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
- (id) ifTrue:(FSBlock *)trueBlock
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
- (id) ifTrue:(FSBlock *)trueBlock ifFalse:(FSBlock *)falseBlock
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
- (FSBoolean*)not
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
- (FSBoolean*) operator_ampersand:(FSBoolean*)operand
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
- (FSBoolean*) operator_bar:(FSBoolean*)operand
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
- (FSBoolean *) operator_less:(id)operand
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
-(NSNumber *) operator_plus:(id)operand
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
- (FSBoolean *)operator_equal:(id)operand
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
- (FSBoolean *)operator_tilde_equal:(id)operand
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
- (FSBoolean *)or:(FSBlock*)operand
{ FSExecError(@"You are using an instance of the abstract class FSBoolean. You should use an instance of the True or False classes instead"); }
@end
@implementation True
- awakeAfterUsingCoder:(NSCoder *)aDecoder
{
[self release];
return fsTrue;
}
- (NSString *)description { return @"YES"; }
- (double) doubleValue { return 1; }
- (BOOL) isTrue { return YES; }
///////////////////////////////// USER METHODS FOR TRUE //////////////////////
- (FSBoolean *)and:(FSBlock*)operand
{
id operandValue;
FSVerifClassArgsNoNil(@"and:",1,operand,[FSBlock class]);
operandValue = [operand value];
if (operandValue == fsTrue || operandValue == fsFalse)
return operandValue;
else if ([operandValue isKindOfClass:[FSBoolean class]]) return [operandValue isTrue] ? fsTrue : fsFalse;
else
FSExecError([NSString stringWithFormat:@"argument 1 of method \"and:\" is a block evaluating to %@, it should evaluate to a boolean", descriptionForFSMessage(operandValue)]);
}
- (id) ifFalse:(FSBlock *)falseBlock {FSVerifClassArgsNoNil(@"ifFalse:",1,falseBlock,[FSBlock class]); return nil;}
- (id) ifFalse:(FSBlock *)falseBlock ifTrue:(FSBlock *)trueBlock
{
FSVerifClassArgsNoNil(@"ifFalse:ifTrue:",2,falseBlock,[FSBlock class],trueBlock,[FSBlock class]);
return [trueBlock value];
}
- (id) ifTrue:(FSBlock *)trueBlock
{
FSVerifClassArgsNoNil(@"ifTrue:",1,trueBlock,[FSBlock class]);
return [trueBlock value];
}
- (id) ifTrue:(FSBlock *)trueBlock ifFalse:(FSBlock *)falseBlock
{
FSVerifClassArgsNoNil(@"ifTrue:ifFalse:",2,trueBlock,[FSBlock class],falseBlock,[FSBlock class]);
return [trueBlock value];
}
- (BOOL)isEqual:(id)object
{
return (object == fsTrue || ([object isKindOfClass:[FSBoolean class]] && [object isTrue]));
}
- (FSBoolean*) not { return fsFalse; }
- (FSBoolean*)operator_ampersand:(FSBoolean *)operand
{
if (operand == fsTrue || operand == fsFalse) return operand;
else if ([operand isKindOfClass:[FSBoolean class]]) return [operand isTrue] ? fsTrue : fsFalse;
else FSArgumentError(operand,1,@"FSBoolean",@"&");
}
- (FSBoolean*)operator_bar:(FSBoolean *)operand
{
VERIF_OP_BOOLEAN(@"|")
return fsTrue;
}
- (FSBoolean *) operator_less:(id)operand
{
if (operand == fsTrue || operand == fsFalse || [operand isKindOfClass:[FSBoolean class]]) return fsFalse;
else FSArgumentError(operand,1,@"FSBoolean",@"<");
}
- (NSNumber *)operator_plus:(id)operand
{
VERIF_OP_BOOLEAN(@"+")
return (id)[FSNumber numberWithDouble:1+[operand doubleValue]];
}
- (FSBoolean *)operator_equal:(id)operand
{
return ([self isEqual:operand] ? fsTrue : fsFalse);
}
- (FSBoolean *)operator_tilde_equal:(id)operand
{
return (![self isEqual:operand] ? fsTrue : fsFalse);
}
- (FSBoolean*)or:(FSBlock*)operand
{
FSVerifClassArgsNoNil(@"or:",1,operand,[FSBlock class]);
return fsTrue;
}
@end
@implementation False
- awakeAfterUsingCoder:(NSCoder *)aDecoder
{
[self release];
return fsFalse;
}
- (NSString *)description { return @"NO"; }
- (double) doubleValue { return 0;}
- (BOOL) isTrue { return NO; }
///////////////////////////////// USER METHODS FOR FALSE //////////////////////
- (FSBoolean*)and:(FSBlock*)operand
{
FSVerifClassArgsNoNil(@"and:",1,operand,[FSBlock class]);
return fsFalse;
}
- (id) ifFalse:(FSBlock *)falseBlock
{
FSVerifClassArgsNoNil(@"ifFalse:",1,falseBlock,[FSBlock class]);
return [falseBlock value];
}
- (id) ifFalse:(FSBlock *)falseBlock ifTrue:(FSBlock *)trueBlock
{
FSVerifClassArgsNoNil(@"ifFalse:ifTrue:",2,falseBlock,[FSBlock class],trueBlock,[FSBlock class]);
return [falseBlock value];
}
-(id) ifTrue:(FSBlock *)trueBlock {FSVerifClassArgsNoNil(@"ifTrue:",1,trueBlock,[FSBlock class]); return nil; }
- (id) ifTrue:(FSBlock *)trueBlock ifFalse:(FSBlock *)falseBlock
{
FSVerifClassArgsNoNil(@"ifTrue:ifFalse:",2,trueBlock,[FSBlock class],falseBlock,[FSBlock class]);
return [falseBlock value];
}
- (BOOL)isEqual:(id)object
{
return (object == fsFalse || ([object isKindOfClass:[FSBoolean class]] && ![object isTrue]));
}
- (FSBoolean*) not { return fsTrue; }
- (FSBoolean *)operator_ampersand:(FSBoolean *)operand
{
VERIF_OP_BOOLEAN(@"&")
return fsFalse;
}
- (FSBoolean *)operator_bar:(FSBoolean *)operand
{
if (operand == fsTrue || operand == fsFalse) return operand;
else if ([operand isKindOfClass:[FSBoolean class]]) return [operand isTrue] ? fsTrue : fsFalse;
else FSArgumentError(operand,1,@"FSBoolean",@"|");
}
- (FSBoolean *) operator_less:(id)operand
{
if (operand == fsTrue || operand == fsFalse) return operand;
else if ([operand isKindOfClass:[FSBoolean class]]) return [operand isTrue] ? fsTrue : fsFalse;
else FSArgumentError(operand,1,@"FSBoolean",@"<");
}
- (NSNumber *)operator_plus:(id)operand
{
VERIF_OP_BOOLEAN(@"+")
return (id)[FSNumber numberWithDouble:[operand doubleValue]];
}
- (FSBoolean *)operator_equal:(id)operand
{
return ([self isEqual:operand] ? fsTrue : fsFalse);
}
- (FSBoolean *)operator_tilde_equal:(id)operand
{
return (![self isEqual:operand] ? fsTrue : fsFalse);
}
- (FSBoolean *)or:(FSBlock*)operand
{
id operandValue;
FSVerifClassArgsNoNil(@"or:",1,operand,[FSBlock class]);
operandValue = [operand value];
if (operandValue == fsTrue || operandValue == fsFalse)
return operandValue;
else if ([operandValue isKindOfClass:[FSBoolean class]]) return [operandValue isTrue] ? fsTrue : fsFalse;
else
FSExecError([NSString stringWithFormat:@"argument 1 of method \"or:\" is a block evaluating to %@, it should evaluate to a boolean", descriptionForFSMessage(operandValue)]);
}
@end
| {
"pile_set_name": "Github"
} |
eclipse.preferences.version=1
org.eclipse.rse.systemtype.local.systemType.defaultUserId=Administrator
useridperkey=X6X8-20160714WJ.Local\=Administrator;
| {
"pile_set_name": "Github"
} |
/* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
| {
"pile_set_name": "Github"
} |
/** @jsx h */
import h from '../../hyperscript';
export default (
<document>
<paragraph>
<image alt="Hello" src="test.png" />
</paragraph>
</document>
);
| {
"pile_set_name": "Github"
} |
; RUN: %llc_dwarf -O0 < %s | FileCheck %s
; Do not emit AT_upper_bound for an unbounded array.
; radar 9241695
define i32 @main() nounwind ssp !dbg !0 {
entry:
%retval = alloca i32, align 4
%a = alloca [0 x i32], align 4
store i32 0, i32* %retval
call void @llvm.dbg.declare(metadata [0 x i32]* %a, metadata !6, metadata !DIExpression()), !dbg !11
ret i32 0, !dbg !12
}
declare void @llvm.dbg.declare(metadata, metadata, metadata) nounwind readnone
!llvm.dbg.cu = !{!2}
!llvm.module.flags = !{!16}
!0 = distinct !DISubprogram(name: "main", line: 3, isLocal: false, isDefinition: true, virtualIndex: 6, isOptimized: false, unit: !2, scopeLine: 3, file: !14, scope: !1, type: !3)
!1 = !DIFile(filename: "array.c", directory: "/private/tmp")
!2 = distinct !DICompileUnit(language: DW_LANG_C99, producer: "clang version 3.0 (trunk 129138)", isOptimized: false, emissionKind: FullDebug, file: !14, enums: !15, retainedTypes: !15, imports: null)
!3 = !DISubroutineType(types: !4)
!4 = !{!5}
!5 = !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32, encoding: DW_ATE_signed)
!6 = !DILocalVariable(name: "a", line: 4, scope: !7, file: !1, type: !8)
!7 = distinct !DILexicalBlock(line: 3, column: 12, file: !14, scope: !0)
!8 = !DICompositeType(tag: DW_TAG_array_type, align: 32, file: !14, scope: !2, baseType: !5, elements: !9)
!9 = !{!10}
;CHECK: debug_info,
;CHECK: DW_TAG_subrange_type
;CHECK-NEXT: DW_AT_type
;CHECK-NOT: DW_AT_lower_bound
;CHECK-NOT: DW_AT_upper_bound
;CHECK-NEXT: End Of Children Mark
!10 = !DISubrange(count: -1)
!11 = !DILocation(line: 4, column: 7, scope: !7)
!12 = !DILocation(line: 5, column: 3, scope: !7)
!14 = !DIFile(filename: "array.c", directory: "/private/tmp")
!15 = !{}
!16 = !{i32 1, !"Debug Info Version", i32 3}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.