text
stringlengths 2
99.9k
| meta
dict |
---|---|
[remap]
importer="texture"
type="StreamTexture"
path="res://.import/Begin.png-b298fe1c5c6cd84f4972ff6cf52aa0aa.stex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://Begin.png"
dest_files=[ "res://.import/Begin.png-b298fe1c5c6cd84f4972ff6cf52aa0aa.stex" ]
[params]
compress/mode=0
compress/lossy_quality=0.7
compress/hdr_mode=0
compress/bptc_ldr=0
compress/normal_map=0
flags/repeat=0
flags/filter=true
flags/mipmaps=false
flags/anisotropic=false
flags/srgb=2
process/fix_alpha_border=true
process/premult_alpha=false
process/HDR_as_SRGB=false
process/invert_color=false
stream=false
size_limit=0
detect_3d=true
svg/scale=1.0
| {
"pile_set_name": "Github"
} |
<p>Given a rooted binary tree, return the lowest common ancestor of its deepest leaves.</p>
<p>Recall that:</p>
<ul>
<li>The node of a binary tree is a <em>leaf</em> if and only if it has no children</li>
<li>The <em>depth</em> of the root of the tree is 0, and if the depth of a node is <code>d</code>, the depth of each of its children is <code>d+1</code>.</li>
<li>The <em>lowest common ancestor</em> of a set <code>S</code> of nodes is the node <code>A</code> with the largest depth such that every node in S is in the subtree with root <code>A</code>.</li>
</ul>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> root = [1,2,3]
<strong>Output:</strong> [1,2,3]
<strong>Explanation:</strong>
The deepest leaves are the nodes with values 2 and 3.
The lowest common ancestor of these leaves is the node with value 1.
The answer returned is a TreeNode object (not an array) with serialization "[1,2,3]".
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> root = [1,2,3,4]
<strong>Output:</strong> [4]
</pre>
<p><strong>Example 3:</strong></p>
<pre>
<strong>Input:</strong> root = [1,2,3,4,5]
<strong>Output:</strong> [2,4,5]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The given tree will have between 1 and 1000 nodes.</li>
<li>Each node of the tree will have a distinct value between 1 and 1000.</li>
</ul>
| {
"pile_set_name": "Github"
} |
parallel_jobs
: This option controls how many parallel workers will copy files during a
backup or recovery command. Default 1. Global/Server. For backup purposes,
it works only when `backup_method` is `rsync`.
| {
"pile_set_name": "Github"
} |
好奇心原文链接:[这家创业公司的生意,从改造北京的“地下防空洞”开始_商业_好奇心日报-Emily Feng](https://www.qdaily.com/articles/24308.html)
WebArchive归档链接:[这家创业公司的生意,从改造北京的“地下防空洞”开始_商业_好奇心日报-Emily Feng](http://web.archive.org/web/20160328162233/http://www.qdaily.com:80/articles/24308.html)
 | {
"pile_set_name": "Github"
} |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class SecurityGroupNetworkInterface(Model):
"""Network interface and all its associated security rules.
:param id: ID of the network interface.
:type id: str
:param security_rule_associations:
:type security_rule_associations:
~azure.mgmt.network.v2018_08_01.models.SecurityRuleAssociations
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'security_rule_associations': {'key': 'securityRuleAssociations', 'type': 'SecurityRuleAssociations'},
}
def __init__(self, **kwargs):
super(SecurityGroupNetworkInterface, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.security_rule_associations = kwargs.get('security_rule_associations', None)
| {
"pile_set_name": "Github"
} |
using System;
namespace WebSqlConnectionTest
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}
| {
"pile_set_name": "Github"
} |
libavcodec/allcodecs.o: libavcodec/allcodecs.c config.h \
libavcodec/avcodec.h libavutil/samplefmt.h libavutil/avutil.h \
libavutil/common.h libavutil/attributes.h libavutil/macros.h \
libavutil/version.h libavutil/avconfig.h libavutil/intmath.h \
libavutil/mem.h libavutil/error.h libavutil/internal.h libavutil/timer.h \
libavutil/log.h libavutil/cpu.h libavutil/dict.h libavutil/pixfmt.h \
libavutil/libm.h libavutil/intfloat.h libavutil/mathematics.h \
libavutil/rational.h libavutil/attributes.h libavutil/avutil.h \
libavutil/buffer.h libavutil/cpu.h libavutil/channel_layout.h \
libavutil/dict.h libavutil/frame.h libavutil/buffer.h \
libavutil/samplefmt.h libavutil/log.h libavutil/pixfmt.h \
libavutil/rational.h libavcodec/version.h libavutil/version.h
| {
"pile_set_name": "Github"
} |
{
"yuiGridsUrl": "http://yui.yahooapis.com/3.5.1/build/cssgrids/cssgrids-min.css",
"yuiSeedUrl": "http://yui.yahooapis.com/combo?3.5.1/build/yui/yui-min.js"
}
| {
"pile_set_name": "Github"
} |

# Postman Learning Center
Postman is the collaboration platform for API development. And the [Postman Learning Center](https://learning.postman.com/) has the resources you need to ramp up quickly and extend your skills with Postman. Postman allows you to write API test cases in any format of your choice (JSON/XML/many more) and run them to verify and validate your API. Moreover, Postman provides collections which can improve a developer's workflow. Postman is available for several platforms including windows and Mac OS X. For more information visit [the Postman website](https://www.postman.com/).
## Contribution guidelines
We would love for you to contribute to the Learning Center! To contribute to this project, please read:
* The [Code of Conduct](https://www.postman.com/code-of-conduct)
* The [Contribution Guidelines](CONTRIBUTING.md)
* The [Documentation Style Guide](DOCS_STYLE_GUIDE.md)
**NOTE:** We have added a new Markdown linter with GitHub Actions. When making a pull request, it will run against this linter. Your changed files are required to pass linting before they will be merged. More information on this can be found in the [contribution guidelines](CONTRIBUTING.md).
> To say thank you for your contribution, we’d love to send you exclusive Contributor swag. Fill out the [Contributor Submission form](https://docs.google.com/forms/d/e/1FAIpQLSfbLAcxl-IOiv3NmgEaWw7FleOaXnIyIoIrY_zn6U4JvjQBGA/viewform?usp=send_form) and we’ll send you a token of our gratitude.
## Build the Learning Center locally
```
$ git clone https://github.com/postmanlabs/postman-docs.git
$ cd postman-docs
$ npm install
$ npm install -g gatsby-cli
$ npm run dev
```
**NOTE:** this site was build with node v12.11.0. We recommend installing and using [nvm](https://github.com/nvm-sh/nvm) and setting your node version to v12.11.0.
### Build using Docker
You can build the Learning Center and run it in a Docker container using the following dockerfile.
1. Start by cloning the the repository
`git clone https://github.com/postmanlabs/postman-docs.git`
2. Create a file and name it "dockerfile" with the following contents
```
FROM node:12
EXPOSE 8000
# copy the postman-docs project directory
COPY postman-docs /var/postman-docs
WORKDIR "/var/postman-docs"
RUN npm install -g gatsby-cli
RUN npm install --force
CMD ["yarn", "dev", "-H", "0.0.0.0" ]
```
The dockerfile should be in the same directory as the postman-docs directory
```
# example directory structure
|--[current folder]
|--postman-docs
|--dockerfile
```
3. Build the Docker image with this command:
`$ docker build --tag postman-docs:1.0 .`
4. Start a container using the image
`$ docker run -p 8000:8000 -d postman-docs:1.0`
#### Docker Compose
You can also build with docker-compose using the dockerfile above and this docker-compose.yaml
```
version: '3'
services:
node:
build:
context: ./
ports:
- "8000:8000"
```
The docker-compose.yaml should be in the same directory as the postman-docs directory and dockerfile.
```
# example directory structure
|--[current folder]
|--postman-docs
|--dockerfile
|--docker-compose.yaml
```
Start run the container with this command
`$ docker-compose up`
## Project Structure
The built site will only host the most up-to-date docs. All legacy documentation is stored in github and excluded from build.
### To update the docs
* Posts are maintained under the `/src/pages/docs` folder.
* The folder structure of /docs is the URL structure for posts. For example, `/docs/postman/variables-and-environments/variables.md` is mapped to URL `https://learning.postman.com/docs/postman/variables-and-environments/variables/`.
* Links in the docs should be relative. Example:
```
[Newman](/docs/postman/collection-runs/command-line-integration-with-newman/)
```
## Resources
* [Download Postman](https://www.postman.com/downloads/)
* [Postman Release Notes](https://www.postman.com/downloads/release-notes)
* [Postman Integrations](https://www.postman.com/integrations/)
* [The Postman API](https://docs.api.getpostman.com/)
* [Postman community](https://community.postman.com/) on Discourse
## License
[Apache License 2.0](LICENSE)
| {
"pile_set_name": "Github"
} |
{
"type": "pseudoClass",
"content": [
{
"type": "ident",
"content": "nth-child",
"syntax": "sass",
"start": {
"line": 1,
"column": 2
},
"end": {
"line": 1,
"column": 10
}
},
{
"type": "arguments",
"content": [
{
"type": "interpolation",
"content": [
{
"type": "variable",
"content": [
{
"type": "ident",
"content": "i",
"syntax": "sass",
"start": {
"line": 1,
"column": 15
},
"end": {
"line": 1,
"column": 15
}
}
],
"syntax": "sass",
"start": {
"line": 1,
"column": 14
},
"end": {
"line": 1,
"column": 15
}
}
],
"syntax": "sass",
"start": {
"line": 1,
"column": 12
},
"end": {
"line": 1,
"column": 16
}
},
{
"type": "operator",
"content": "+",
"syntax": "sass",
"start": {
"line": 1,
"column": 17
},
"end": {
"line": 1,
"column": 17
}
},
{
"type": "number",
"content": "1",
"syntax": "sass",
"start": {
"line": 1,
"column": 18
},
"end": {
"line": 1,
"column": 18
}
}
],
"syntax": "sass",
"start": {
"line": 1,
"column": 11
},
"end": {
"line": 1,
"column": 19
}
}
],
"syntax": "sass",
"start": {
"line": 1,
"column": 1
},
"end": {
"line": 1,
"column": 19
}
}
| {
"pile_set_name": "Github"
} |
package com.jeecms.cms.entity.main;
import com.jeecms.cms.entity.main.base.BaseCmsUserSite;
public class CmsUserSite extends BaseCmsUserSite {
private static final long serialVersionUID = 1L;
/* [CONSTRUCTOR MARKER BEGIN] */
public CmsUserSite () {
super();
}
/**
* Constructor for primary key
*/
public CmsUserSite (java.lang.Integer id) {
super(id);
}
/**
* Constructor for required fields
*/
public CmsUserSite (
java.lang.Integer id,
com.jeecms.cms.entity.main.CmsUser user,
com.jeecms.cms.entity.main.CmsSite site,
java.lang.Byte checkStep,
java.lang.Boolean allChannel) {
super (
id,
user,
site,
checkStep,
allChannel);
}
/* [CONSTRUCTOR MARKER END] */
} | {
"pile_set_name": "Github"
} |
/*
* DemoApplication 2016-03-04
* Copyright (c) 2016 hujiang Co.Ltd. All right reserved(http://www.hujiang.com).
*
*/
package com.hujiang.library.demo;
import android.app.Application;
import android.content.Context;
import com.alibaba.android.arouter.launcher.ARouter;
import com.hujiang.library.LibrarySDK;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
//import android.support.multidex.MultiDex;
//import android.support.multidex.MultiDex;
//import com.hujiang.account.AccountRunTime;
//import com.hujiang.framework.app.RunTimeManager;
//import com.hujiang.social.sdk.SocialSDK;
//import com.taobao.android.dexposed.DexposedBridge
//import com.taobao.android.dexposed.XC_MethodHook
/**
* class description here
* @author simon
* *
* @version 1.0.0
* *
* @since 2016-03-04
*/
public class DemoApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LibrarySDK.init();
ImageLoader.getInstance().init(new ImageLoaderConfiguration.Builder(this).build());
ARouter.openLog();
ARouter.openDebug();
ARouter.init(this);
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
}
} | {
"pile_set_name": "Github"
} |
import { TASK_COMPILE_GET_SOURCE_PATHS } from "@nomiclabs/buidler/builtin-tasks/task-names";
import { assert } from "chai";
import * as fs from "fs";
import path from "path";
import { TruffleEnvironmentArtifacts } from "../src/artifacts";
import { TruffleContract, TruffleContractInstance } from "../src/types";
import { useEnvironment } from "./helpers";
function assertIsContract(contract: TruffleContract) {
assert.containsAllKeys(contract, [
"new",
"at",
"defaults",
"detectNetwork",
"deployed",
"link",
]);
}
function assertIsContractInstance(
contractInstance: TruffleContractInstance,
...functionNames: string[]
) {
assert.containsAllKeys(contractInstance, [
"address",
"abi",
...functionNames,
]);
}
function testArtifactsFunctionality() {
beforeEach(async function () {
const version = await this.env.network.provider.send("web3_clientVersion");
// We only run these test on Ganache, see this:
// https://github.com/ethereum/web3.js/issues/935
if (!version.toLowerCase().includes("testrpc")) {
this.skip();
}
});
it("Should load existing contracts successfully", function () {
assertIsContract(this.env.artifacts.require("Greeter"));
assertIsContract(this.env.artifacts.require("Lib"));
assertIsContract(this.env.artifacts.require("UsesLib"));
});
it("Should set a default sender to contract deployments", async function () {
const Greeter = this.env.artifacts.require("Greeter");
const greeter = await Greeter.new();
assertIsContractInstance(greeter, "greet", "setGreeting");
const Lib = this.env.artifacts.require("Lib");
const lib = await Lib.new();
assertIsContractInstance(lib, "addOne");
});
it("Should set a default sender to the contract's functions", async function () {
const Greeter = this.env.artifacts.require("Greeter");
const greeter = await Greeter.new();
assert.equal(await greeter.greet(), "Hi");
await greeter.setGreeting("Hi!!!");
assert.equal(await greeter.greet(), "Hi!!!");
});
it("Should work with Contract.at", async function () {
const Greeter = this.env.artifacts.require("Greeter");
const greeter = await Greeter.new();
const greeterWithAt = Greeter.at(greeter.address);
assertIsContractInstance(greeterWithAt, "greet");
assert.equal(await greeterWithAt.greet(), "Hi");
await greeterWithAt.setGreeting("Hi!!!");
assert.equal(await greeterWithAt.greet(), "Hi!!!");
});
it("Should work with new Contract(addr)", async function () {
const Greeter = this.env.artifacts.require("Greeter");
const greeter = await Greeter.new();
const greeterWithNew = new Greeter(greeter.address);
assertIsContractInstance(greeterWithNew, "greet");
assert.equal(await greeterWithNew.greet(), "Hi");
await greeterWithNew.setGreeting("Hi!!!");
assert.equal(await greeterWithNew.greet(), "Hi!!!");
});
it("Should provison cloned contracts", async function () {
const Greeter = this.env.artifacts.require("Greeter");
const ClonedGreeter = Greeter.clone();
const greeter = await ClonedGreeter.new();
assertIsContractInstance(greeter, "greet");
assert.equal(await greeter.greet(), "Hi");
await greeter.setGreeting("Hi!!!");
assert.equal(await greeter.greet(), "Hi!!!");
});
it("Should fail to deploy an unlinked contract", async function () {
const UsesLib = this.env.artifacts.require("UsesLib");
try {
await UsesLib.new();
assert.fail("UsesLib shouldn't be deployeable if not linked");
} catch (error) {
assert.include(error.message, "UsesLib contains unresolved libraries");
}
});
it("Should deploy linked contracts succesfully", async function () {
const Lib = this.env.artifacts.require("Lib");
const lib = await Lib.new();
assertIsContractInstance(lib, "addOne");
const UsesLib = this.env.artifacts.require("UsesLib");
UsesLib.link(lib);
const usesLib = await UsesLib.new();
assertIsContractInstance(usesLib, "n", "addTwo");
assert.equal((await usesLib.n()).toString(), "0");
await usesLib.addTwo();
assert.equal((await usesLib.n()).toString(), "2");
});
}
describe("BuidlerRuntimeEnvironment extension", function () {
useEnvironment(path.join(__dirname, "buidler-project-solc-0.5"));
it("It should add the artifacts object", function () {
assert.instanceOf(this.env.artifacts, TruffleEnvironmentArtifacts);
});
});
describe("TruffleContracts loading and provisioning", function () {
describe("When compiling with solc 0.5.x", function () {
useEnvironment(path.join(__dirname, "buidler-project-solc-0.5"));
testArtifactsFunctionality();
});
describe("When compiling with solc 0.4.x", function () {
useEnvironment(path.join(__dirname, "buidler-project-solc-0.4"));
testArtifactsFunctionality();
});
describe("When compiling with solc 0.6.x", function () {
useEnvironment(path.join(__dirname, "buidler-project-solc-0.6"));
testArtifactsFunctionality();
});
describe("Without accounts", function () {
function shouldWorkWithoutAccounts() {
it("Should be able to call constant functions", async function () {
const Greeter = this.env.artifacts.require("Greeter");
// We test it this way as actually deploying a contract here, without
// accounts, is difficult.
const greeterWithAt = Greeter.at(
"0x0000000000000000000000000000000000000001"
);
// Shouldn't throw.
await greeterWithAt.greet.estimateGas();
});
}
describe("With solc 0.4.x", function () {
useEnvironment(
path.join(__dirname, "buidler-project-solc-0.4"),
"withoutAccounts"
);
shouldWorkWithoutAccounts();
});
describe("With solc 0.5.x", function () {
useEnvironment(
path.join(__dirname, "buidler-project-solc-0.5"),
"withoutAccounts"
);
shouldWorkWithoutAccounts();
});
describe("With solc 0.6.x", function () {
useEnvironment(
path.join(__dirname, "buidler-project-solc-0.6"),
"withoutAccounts"
);
shouldWorkWithoutAccounts();
});
});
});
describe("Test contracts compilation", function () {
useEnvironment(path.join(__dirname, "buidler-project-with-test-contracts"));
it("Should include sources from sources", async function () {
const sources = await this.env.run(TASK_COMPILE_GET_SOURCE_PATHS);
assert.include(
sources,
fs.realpathSync(
path.join(
__dirname,
"buidler-project-with-test-contracts",
"contracts",
"fromContracts.sol"
)
)
);
});
it("Should include sources from test", async function () {
const sources = await this.env.run(TASK_COMPILE_GET_SOURCE_PATHS);
assert.include(
sources,
fs.realpathSync(
path.join(
__dirname,
"buidler-project-with-test-contracts",
"test",
"fromTest.sol"
)
)
);
});
it("Should ignore non-source files from test", async function () {
const sources = await this.env.run(TASK_COMPILE_GET_SOURCE_PATHS);
assert.notInclude(
sources,
fs.realpathSync(
path.join(
__dirname,
"buidler-project-with-test-contracts",
"test",
"shouldBeIgnored.txt"
)
)
);
});
it("Should include all the files from contracts and test", async function () {
const sources = await this.env.run(TASK_COMPILE_GET_SOURCE_PATHS);
assert.lengthOf(sources, 2);
});
});
| {
"pile_set_name": "Github"
} |
<div data-ui-field="widget" class="ui-overlay-shadow ui-corner-all ui-body-inherit hg-widget-a" style="height:270px;position:relative;z-index:10;background:none">
<div class="ui-body-inherit ui-corner-all" style="position:absolute;opacity:0.8;z-index:-1;left:0;top:0;right:0;bottom:0"></div>
<div class="ui-header" style="padding-left:5px;padding-right:5px;font-weight:normal;border-top:0">
<img data-ui-field="icon" style="height:36px;margin:2px;margin-right:4px" align="left" src="pages/control/widgets/homegenie/generic/images/temperature.png" />
<div data-ui-field="name" style="margin-right:68px;text-overflow:ellipsis;white-space:nowrap;overflow:hidden;font-size:14pt">Name</div>
<div data-ui-field="description" style="margin-right:68px;text-overflow:ellipsis;white-space:nowrap;overflow:hidden;font-size:8pt">loading...</div>
<a data-ui-field="options" data-role="button" data-icon="edit" data-iconshadow="false" data-iconpos="notext" class="ui-btn-right" style="margin-right:40px">Options</a>
<a data-ui-field="settings" data-role="button" data-icon="gear" data-iconshadow="false" data-iconpos="notext" class="ui-btn-right">Features</a>
</div>
<div align="center" style="padding:4px;">
<!-- HEAT -->
<div data-ui-field="heat_field" style="display:table-cell;padding-left:6px;padding-right:6px">
<i data-ui-field="heatset_image" class="fa fa-fire"></i>
<b data-ui-field="heatset_value">21.0</b>
</div>
<!-- COOL -->
<div data-ui-field="cool_field" style="display:table-cell;padding-left:6px;padding-right:6px">
<i class="fa fa-asterisk"></i>
<b data-ui-field="coolset_value">23.0</b>
</div>
<!-- FAN -->
<div data-ui-field="fan_field" style="display:table-cell;padding-left:6px;padding-right:6px">
<i class="fa fa-refresh"></i>
<b data-ui-field="fan_value">AUTO</b>
</div>
</div>
<div align="center" style="padding:4px">
<div data-ui-field="temperature_value" style="width:120px;font-size:30pt; padding:8px; background: rgba(200,200,200,0.1); border:solid 2px rgba(255,255,255,0.2);display:table-cell;-webkit-border-radius: 20px;-moz-border-radius: 20px;border-radius: 20px;">
22.5°
</div>
</div>
<div align="center" data-ui-field="mode_controls">
<!--span data-locale-id="therm_setmode" style="font-size:8pt;text-transform:uppercase">Operating Mode</span-->
<div data-role="controlgroup" data-type="horizontal" data-mini="true">
<a data-ui-field="mode_off" data-locale-id="therm_off" data-role="button" href="">Off</a>
<a data-ui-field="mode_cool" data-locale-id="therm_cool" data-role="button" href="">Cool</a>
<a data-ui-field="mode_heat" data-locale-id="therm_heat" data-role="button" href="">Heat</a>
<a data-ui-field="mode_auto" data-locale-id="therm_auto" data-role="button" href="">Auto</a>
</div>
</div>
<div align="center" data-ui-field="fan_controls">
<span data-locale-id="therm_fanmode" style="font-size:8pt;text-transform:uppercase">Fan Mode</span>
<div data-role="controlgroup" data-type="horizontal" data-mini="true">
<a data-ui-field="fanmode_on" data-locale-id="fan_on" data-role="button" href="">On</a>
<a data-ui-field="fanmode_auto" data-locale-id="fan_auto" data-role="button" href="">Auto</a>
<a data-ui-field="fanmode_circulate" data-locale-id="fan_circulate" data-role="button" href="">Circulate</a>
</div>
</div>
<div data-ui-field="updatetime" style="margin-right:10px;margin-bottom:10px;text-align:right;font-size:10pt"></div>
<div class="ui-footer hg-widget-footer" align="right" style="border-bottom:0">
<b style="font-size:11pt;display: table-cell;"> Status </b>
<div data-ui-field="operating_value" style="font-size:10pt;display: table-cell;">OFF</div>
<b style="font-size:11pt;display: table-cell;"> Mode </b>
<div data-ui-field="mode_value" style="font-size:10pt;display: table-cell;">HEAT</div>
</div>
</div>
<!-- widget popups and other ui elements follow -->
<div class="hg-popup-a" data-ui-field="controlpopup" data-position-to="window" data-transition="pop" data-overlay-theme="b">
<a href="#" data-rel="back" data-role="button" data-icon="delete" data-iconpos="notext" class="ui-btn-right">Close</a>
<div style="margin:10px">
<!-- BEGIN - COMMON UI PART --->
<table width="100%">
<tr>
<td width="56">
<img data-ui-field="icon" height="56" src="pages/control/widgets/homegenie/generic/images/temperature.png" />
</td>
<td>
<div data-ui-field="group" style="margin:0;margin-left:10px;font-family:Georgia;font-size:11pt;color:gray">Group Name</div>
<h4 data-ui-field="name" style="margin:0;margin-left:10px;">Description</h4>
</td>
<td valign="top">
<div data-ui-field="status" style="margin-top:10px;font-size:11pt;color:gray;" align="right"></div>
</td>
</tr>
</table>
<!-- END - COMMON UI PART --->
<!-- BEGIN - MODULE TYPE SPECIFIC DIVS -->
<div align="center">
<input data-ui-field="level_knob" data-role="none" type="text" class="dial"
data-width="170"
data-height="120"
data-min="40"
data-max="100"
data-step="0.5"
data-gradient="bluered"
data-fgcolor="#CCCCCC"
data-bgcolor="#555555"
data-angleoffset=-125
data-anglearc=250
-data-cursor=true
-data-skin="tron"
data-thickness=".4"
-data-linecap=round
data-displayprevious=true>
</div>
<div align="center">
<span data-locale-id="therm_setpoint">Set Point</span>
<div align="center">
<div style="display:table-cell" data-mini="true"><a data-ui-field="cool_setpoint" data-locale-id="therm_cool" data-role="button" href="">Cool</a></div>
<div style="display:table-cell" data-mini="true"><a data-ui-field="heat_setpoint" data-locale-id="therm_heat" data-role="button" href="">Heat</a></div>
</div>
</div>
<!-- END - MODULE TYPE SPECIFIC DIVS -->
<br />
</div>
</div> | {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<!DOCTYPE OpenGLAPI SYSTEM "gl_API.dtd">
<OpenGLAPI>
<category name="GL_KHR_robustness" number="190">
<enum name="GUILTY_CONTEXT_RESET_KHR" value="0x8253"/>
<enum name="INNOCENT_CONTEXT_RESET_KHR" value="0x8254"/>
<enum name="UNKNOWN_CONTEXT_RESET_KHR" value="0x8255"/>
<enum name="RESET_NOTIFICATION_STRATEGY_KHR" count="1" value="0x8256">
<size name="Get" mode="get"/>
</enum>
<enum name="LOSE_CONTEXT_ON_RESET_KHR" value="0x8252"/>
<enum name="NO_RESET_NOTIFICATION_KHR" value="0x8261"/>
<enum name="CONTEXT_FLAG_ROBUST_ACCESS_BIT_KHR" value="0x00000004"/>
<!-- This extension applies to both GL and ES. GL entrypoints have
no suffix, ES entrypoints have the KHR suffix. This file
defines entry points for ES. -->
<function name="GetGraphicsResetStatusKHR"
alias="GetGraphicsResetStatusARB" es2="2.0">
<return type="GLenum"/>
</function>
<function name="ReadnPixelsKHR" alias="ReadnPixelsARB" es2="2.0">
<param name="x" type="GLint"/>
<param name="y" type="GLint"/>
<param name="width" type="GLsizei"/>
<param name="height" type="GLsizei"/>
<param name="format" type="GLenum"/>
<param name="type" type="GLenum"/>
<param name="bufSize" type="GLsizei"/>
<param name="data" type="GLvoid *" output="true"/>
</function>
<function name="GetnUniformfvKHR" alias="GetnUniformfvARB" es2="2.0">
<param name="program" type="GLuint"/>
<param name="location" type="GLint"/>
<param name="bufSize" type="GLsizei"/>
<param name="params" type="GLfloat *" output="true"/>
</function>
<function name="GetnUniformivKHR" alias="GetnUniformivARB" es2="2.0">
<param name="program" type="GLuint"/>
<param name="location" type="GLint"/>
<param name="bufSize" type="GLsizei"/>
<param name="params" type="GLint *" output="true"/>
</function>
<function name="GetnUniformuivKHR" alias="GetnUniformuivARB" es2="2.0">
<param name="program" type="GLuint"/>
<param name="location" type="GLint"/>
<param name="bufSize" type="GLsizei"/>
<param name="params" type="GLuint *" output="true"/>
</function>
</category>
</OpenGLAPI>
| {
"pile_set_name": "Github"
} |
describe Kontena::Workers::Volumes::VolumeManager, :celluloid => true do
include RpcClientMocks
let(:subject) { described_class.new(false) }
let(:node) do
Node.new(
'id' => 'aaaa',
'instance_number' => 2,
'grid' => {}
)
end
before(:each) do
mock_rpc_client
allow(subject.wrapped_object).to receive(:node).and_return(node)
end
describe '#initialize' do
it 'starts to listen volume:update events' do
expect(subject.wrapped_object).to receive(:on_update_notify).once
Celluloid::Notifications.publish('volume:update', 'foo')
sleep 0.1
end
end
describe '#populate_volumes_from_master' do
it 'fails with a warning if no proper response from master' do
expect(rpc_client).to receive(:request).with('/node_volumes/list', [node.id]).and_return(
{
'volumes' => 'foo'
}
)
expect(subject.wrapped_object).to receive(:error).with(/Invalid response from master/)
expect{subject.populate_volumes_from_master}.not_to raise_error
end
it 'calls terminate and ensure with volumes from master' do
expect(subject.wrapped_object).to receive(:terminate_volumes).with(['123', '456'])
expect(rpc_client).to receive(:request).with('/node_volumes/list', [node.id]).and_return(
{
'volumes' => [
{'name' => 'foo', 'volume_instance_id' => '123'},
{'name' => 'bar', 'volume_instance_id' => '456'}
]
}
)
expect(subject.wrapped_object).to receive(:ensure_volume).twice
subject.populate_volumes_from_master
end
end
describe '#populate_volumes_from_docker' do
it 'sends volume info to master' do
expect(Docker::Volume).to receive(:all).and_return(['foo', 'bar'])
expect(subject.wrapped_object).to receive(:sync_volume_to_master).twice
subject.populate_volumes_from_docker
end
end
describe '#ensure_volume' do
let(:volume) do
Kontena::Models::Volume.new(
{
'name' => 'foo',
'driver' => 'local',
'driver_opts' => {},
'labels' => {}
}
)
end
it 'does not create a volume if it already exists' do
expect(subject.wrapped_object).to receive(:volume_exist?).with('foo', 'local').and_return(true)
expect(Docker::Volume).not_to receive(:create)
subject.ensure_volume(volume)
end
it 'does not create a volume if it already exists' do
expect(Docker::Volume).to receive(:get).with('foo').and_raise(Docker::Error::NotFoundError)
expect(Docker::Volume).to receive(:create).with('foo', {
'Driver' => volume.driver,
'DriverOpts' => volume.driver_opts,
'Labels' => volume.labels
}).and_return(double)
expect(subject.wrapped_object).to receive(:sync_volume_to_master)
subject.ensure_volume(volume)
end
it 'does not crash actor if random failure from docker' do
expect(subject.wrapped_object).to receive(:volume_exist?).with('foo', 'local').and_return(false)
expect(Docker::Volume).to receive(:create).and_raise(StandardError)
expect(subject.wrapped_object).not_to receive(:sync_volume_to_master)
subject.ensure_volume(volume)
# The actor should be still alive
expect(subject.alive?).to eq(true)
end
it 'does not crash actor from possible abort in volume_exists?' do
# This will cause the Celluloid::abort to happen
expect(Docker::Volume).to receive(:get).and_raise(StandardError)
expect(subject.wrapped_object).not_to receive(:sync_volume_to_master)
subject.ensure_volume(volume)
# The actor should be still alive
expect(subject.alive?).to eq(true)
end
end
describe '#sync_volume_to_master' do
it 'sends volume data to master' do
expect(rpc_client).to receive(:request).with(
'/node_volumes/set_state',
[node.id, hash_including('name' => 'foo', 'volume_id' => '123', 'volume_instance_id' => '456')]
)
docker_volume = double(:volume, 'id' => 'foo', 'info' => {
'Name' => 'foo',
'Labels' => { 'io.kontena.volume.id' => '123', 'io.kontena.volume_instance.id' => '456'}
})
subject.sync_volume_to_master(docker_volume)
end
it 'does not send volume data to master for un-managed volume' do
expect(rpc_client).not_to receive(:request)
docker_volume = double(:volume, 'id' => 'foo', 'info' => {
'Name' => 'foo',
'Labels' => { }
})
subject.sync_volume_to_master(docker_volume)
end
end
describe '#volume_exist?' do
it 'return true if volume exists' do
expect(Docker::Volume).to receive(:get).with('foo').and_return(double(:volume, :info => {'Driver' => 'local'}))
expect(subject.volume_exist?('foo', 'local')).to be_truthy
end
it 'return false if volume not exists' do
expect(Docker::Volume).to receive(:get).with('foo').and_raise(Docker::Error::NotFoundError)
expect(subject.volume_exist?('foo', 'local')).to be_falsey
end
it 'raises if volume drivers do not match' do
expect(Docker::Volume).to receive(:get).with('foo').and_return(double(:volume, :info => {'Driver' => 'foo'}))
expect {
subject.volume_exist?('foo', 'local')
}.to raise_error(Kontena::Workers::Volumes::VolumeManager::DriverMismatchError)
end
end
describe '#terminate_volumes' do
it 'removes docker volumes that are not supposed to exist' do
volumes = [
double(:volume, 'id' => 'foo', 'info' => {
'Name' => 'foo',
'Labels' => { 'io.kontena.volume_instance.id' => '123'}
}),
double(:volume, 'id' => 'bar', 'info' => {
'Name' => 'bar',
'Labels' => { 'io.kontena.volume_instance.id' => '456'}
})
]
expect(Docker::Volume).to receive(:all).and_return(volumes)
expect(volumes[0]).to receive(:remove)
subject.terminate_volumes(['456'])
end
it 'handles error from volume remove' do
volumes = [
double(:volume, 'id' => 'foo', 'info' => {
'Name' => 'foo',
'Labels' => { 'io.kontena.volume_instance.id' => '123'}
})
]
expect(Docker::Volume).to receive(:all).and_return(volumes)
expect(volumes[0]).to receive(:remove).and_raise("BoomBoom")
subject.terminate_volumes(['456'])
# The actor should be still alive
expect(subject).to be_alive
end
end
end
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.sysds.runtime.instructions.spark.functions.MatrixMatrixBinaryOpFunction (SystemDS 2.0.0-SNAPSHOT API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.sysds.runtime.instructions.spark.functions.MatrixMatrixBinaryOpFunction (SystemDS 2.0.0-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../org/apache/sysds/runtime/instructions/spark/functions/MatrixMatrixBinaryOpFunction.html" title="class in org.apache.sysds.runtime.instructions.spark.functions">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/apache/sysds/runtime/instructions/spark/functions/class-use/MatrixMatrixBinaryOpFunction.html" target="_top">Frames</a></li>
<li><a href="MatrixMatrixBinaryOpFunction.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.sysds.runtime.instructions.spark.functions.MatrixMatrixBinaryOpFunction" class="title">Uses of Class<br>org.apache.sysds.runtime.instructions.spark.functions.MatrixMatrixBinaryOpFunction</h2>
</div>
<div class="classUseContainer">No usage of org.apache.sysds.runtime.instructions.spark.functions.MatrixMatrixBinaryOpFunction</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../org/apache/sysds/runtime/instructions/spark/functions/MatrixMatrixBinaryOpFunction.html" title="class in org.apache.sysds.runtime.instructions.spark.functions">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/apache/sysds/runtime/instructions/spark/functions/class-use/MatrixMatrixBinaryOpFunction.html" target="_top">Frames</a></li>
<li><a href="MatrixMatrixBinaryOpFunction.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2020 <a href="https://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:mml="http://www.w3.org/1998/Math/MathML" manifest="cll.appcache" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>1.4. Disclaimers</title>
<link rel="stylesheet" type="text/css" href="final.css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
<link rel="home" href="index.html" title="The Complete Lojban Language" />
<link rel="up" href="chapter-about.html" title="Chapter 1. Lojban As We Mangle It In Lojbanistan: About This Book" />
<link rel="prev" href="section-conventions.html" title="1.3. What are the typographical conventions of this book?" />
<link rel="next" href="credits.html" title="1.5. Acknowledgements and Credits" />
<script xmlns="" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:docbook="http://docbook.org/ns/docbook" type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=MML_HTMLorMML"></script>
<meta xmlns="" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:docbook="http://docbook.org/ns/docbook" name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div xmlns="" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:docbook="http://docbook.org/ns/docbook" class="navheader">
<table width="100%" summary="Chapter Header">
<tr>
<th colspan="3" align="center">Chapter 1. Lojban As We Mangle It In Lojbanistan: About This Book</th>
</tr>
</table>
<table width="100%" summary="Navigation header">
<tr>
<td width="50%" align="right">
<a accesskey="p" href="section-conventions.html">Prev: Section 1.3</a>
</td>
<td width="50%" align="left">
<a accesskey="n" href="credits.html">Next: Section 1.5</a>
</td>
</tr>
</table>
</div>
<div xmlns="" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:docbook="http://docbook.org/ns/docbook" class="toc-link" align="center">
<a accesskey="h" href="index.html">Table of Contents</a>
</div>
<div xmlns="" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:docbook="http://docbook.org/ns/docbook" class="back-to-info-link" align="center">
<a accesskey="b" href="http://www.lojban.org/cll">Book Info Page</a>
</div>
<hr xmlns="" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:docbook="http://docbook.org/ns/docbook" />
<div class="section">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="section-disclaimers"></a>1.4. <a id="c1s4"></a>Disclaimers</h2>
</div>
</div>
</div>
<p><a id="idm47148580469184" class="indexterm"></a> It is necessary to add, alas, that the examples used in this book do not refer to any existing person, place, or institution, and that any such resemblance is entirely coincidental and unintentional, and not intended to give offense.</p>
<p><a id="idm47148580467792" class="indexterm"></a> When definitions and place structures of gismu, and especially of lujvo, are given in this book, they may differ from those given in the English-Lojban dictionary (which, as of this writing, is not yet published). If so, the information given in the dictionary supersedes whatever is given here.</p>
</div>
<hr xmlns="" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:docbook="http://docbook.org/ns/docbook" />
<div xmlns="" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:docbook="http://docbook.org/ns/docbook" class="navheader">
<table width="100%" summary="Chapter Header">
<tr>
<th colspan="3" align="center">Chapter 1. Lojban As We Mangle It In Lojbanistan: About This Book</th>
</tr>
</table>
<table width="100%" summary="Navigation header">
<tr>
<td width="50%" align="right">
<a accesskey="p" href="section-conventions.html">Prev: Section 1.3</a>
</td>
<td width="50%" align="left">
<a accesskey="n" href="credits.html">Next: Section 1.5</a>
</td>
</tr>
</table>
</div>
<div xmlns="" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:docbook="http://docbook.org/ns/docbook" class="toc-link" align="center">
<a accesskey="h" href="index.html">Table of Contents</a>
</div>
<div xmlns="" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:docbook="http://docbook.org/ns/docbook" class="back-to-info-link" align="center">
<a accesskey="b" href="http://www.lojban.org/cll">Book Info Page</a>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef __NVBIOS_RAMCFG_H__
#define __NVBIOS_RAMCFG_H__
struct nvbios_ramcfg {
unsigned rammap_ver;
unsigned rammap_hdr;
unsigned rammap_min;
unsigned rammap_max;
union {
struct {
unsigned rammap_00_16_20:1;
unsigned rammap_00_16_40:1;
unsigned rammap_00_17_02:1;
};
struct {
unsigned rammap_10_04_02:1;
unsigned rammap_10_04_08:1;
};
struct {
unsigned rammap_11_08_01:1;
unsigned rammap_11_08_0c:2;
unsigned rammap_11_08_10:1;
unsigned rammap_11_09_01ff:9;
unsigned rammap_11_0a_03fe:9;
unsigned rammap_11_0a_0400:1;
unsigned rammap_11_0a_0800:1;
unsigned rammap_11_0b_01f0:5;
unsigned rammap_11_0b_0200:1;
unsigned rammap_11_0b_0400:1;
unsigned rammap_11_0b_0800:1;
unsigned rammap_11_0d:8;
unsigned rammap_11_0e:8;
unsigned rammap_11_0f:8;
unsigned rammap_11_11_0c:2;
};
};
unsigned ramcfg_ver;
unsigned ramcfg_hdr;
unsigned ramcfg_timing;
unsigned ramcfg_DLLoff;
unsigned ramcfg_RON;
unsigned ramcfg_FBVDDQ;
union {
struct {
unsigned ramcfg_00_03_01:1;
unsigned ramcfg_00_03_02:1;
unsigned ramcfg_00_03_08:1;
unsigned ramcfg_00_03_10:1;
unsigned ramcfg_00_04_02:1;
unsigned ramcfg_00_04_04:1;
unsigned ramcfg_00_04_20:1;
unsigned ramcfg_00_05:8;
unsigned ramcfg_00_06:8;
unsigned ramcfg_00_07:8;
unsigned ramcfg_00_08:8;
unsigned ramcfg_00_09:8;
unsigned ramcfg_00_0a_0f:4;
unsigned ramcfg_00_0a_f0:4;
};
struct {
unsigned ramcfg_10_02_01:1;
unsigned ramcfg_10_02_02:1;
unsigned ramcfg_10_02_04:1;
unsigned ramcfg_10_02_08:1;
unsigned ramcfg_10_02_10:1;
unsigned ramcfg_10_02_20:1;
unsigned ramcfg_10_03_0f:4;
unsigned ramcfg_10_04_01:1;
unsigned ramcfg_10_05:8;
unsigned ramcfg_10_06:8;
unsigned ramcfg_10_07:8;
unsigned ramcfg_10_08:8;
unsigned ramcfg_10_09_0f:4;
unsigned ramcfg_10_09_f0:4;
};
struct {
unsigned ramcfg_11_01_01:1;
unsigned ramcfg_11_01_02:1;
unsigned ramcfg_11_01_04:1;
unsigned ramcfg_11_01_08:1;
unsigned ramcfg_11_01_10:1;
unsigned ramcfg_11_01_40:1;
unsigned ramcfg_11_01_80:1;
unsigned ramcfg_11_02_03:2;
unsigned ramcfg_11_02_04:1;
unsigned ramcfg_11_02_08:1;
unsigned ramcfg_11_02_10:1;
unsigned ramcfg_11_02_40:1;
unsigned ramcfg_11_02_80:1;
unsigned ramcfg_11_03_0f:4;
unsigned ramcfg_11_03_30:2;
unsigned ramcfg_11_03_c0:2;
unsigned ramcfg_11_03_f0:4;
unsigned ramcfg_11_04:8;
unsigned ramcfg_11_06:8;
unsigned ramcfg_11_07_02:1;
unsigned ramcfg_11_07_04:1;
unsigned ramcfg_11_07_08:1;
unsigned ramcfg_11_07_10:1;
unsigned ramcfg_11_07_40:1;
unsigned ramcfg_11_07_80:1;
unsigned ramcfg_11_08_01:1;
unsigned ramcfg_11_08_02:1;
unsigned ramcfg_11_08_04:1;
unsigned ramcfg_11_08_08:1;
unsigned ramcfg_11_08_10:1;
unsigned ramcfg_11_08_20:1;
unsigned ramcfg_11_09:8;
};
};
unsigned timing_ver;
unsigned timing_hdr;
unsigned timing[11];
union {
struct {
unsigned timing_10_WR:8;
unsigned timing_10_WTR:8;
unsigned timing_10_CL:8;
unsigned timing_10_RC:8;
/*empty: 4 */
unsigned timing_10_RFC:8; /* Byte 5 */
/*empty: 6 */
unsigned timing_10_RAS:8; /* Byte 7 */
/*empty: 8 */
unsigned timing_10_RP:8; /* Byte 9 */
unsigned timing_10_RCDRD:8;
unsigned timing_10_RCDWR:8;
unsigned timing_10_RRD:8;
unsigned timing_10_13:8;
unsigned timing_10_ODT:3;
/* empty: 15 */
unsigned timing_10_16:8;
/* empty: 17 */
unsigned timing_10_18:8;
unsigned timing_10_CWL:8;
unsigned timing_10_20:8;
unsigned timing_10_21:8;
/* empty: 22, 23 */
unsigned timing_10_24:8;
};
struct {
unsigned timing_20_2e_03:2;
unsigned timing_20_2e_30:2;
unsigned timing_20_2e_c0:2;
unsigned timing_20_2f_03:2;
unsigned timing_20_2c_003f:6;
unsigned timing_20_2c_1fc0:7;
unsigned timing_20_30_f8:5;
unsigned timing_20_30_07:3;
unsigned timing_20_31_0007:3;
unsigned timing_20_31_0078:4;
unsigned timing_20_31_0780:4;
unsigned timing_20_31_0800:1;
unsigned timing_20_31_7000:3;
unsigned timing_20_31_8000:1;
};
};
};
u8 nvbios_ramcfg_count(struct nvkm_bios *);
u8 nvbios_ramcfg_index(struct nvkm_subdev *);
#endif
| {
"pile_set_name": "Github"
} |
/* App
------------------
*/
// DEFINITION
iio.App = function() {
this.App.apply(this, arguments)
}
iio.inherit(iio.App, iio.Drawable);
iio.App.prototype._super = iio.Drawable.prototype;
// CONSTRUCTOR
iio.App.prototype.App = function(view, script, settings) {
this._super.Drawable.call(this);
//set app reference for shared functions
this.app = this;
//set canvas & context
this.canvas = view;
this.ctx = view.getContext('2d');
//prep canvas
this.canvas.parent = this;
iio.canvas.prep_input(this.canvas);
//get width & height from canvas
this.width = view.clientWidth || view.width;
this.height = view.clientHeight || view.height;
//set center
this.center = new iio.Vector(
this.width / 2,
this.height / 2
);
this.update_pos();
//add app to global app array
iio.apps.push(this);
//run js script
/*if (typeof(app) === "string") {
app = iio.scripts[app];
}*/
//app.call(this, this, s);
// run script
this.script = new script(this, settings);
}
// IMPLEMENT ABSTRACT FUNCTIONS
iio.App.prototype.update = function(){
var nuFPS;
if(this.onUpdate)
nuFPS = this.onUpdate(this);
if (this.script.onUpdate) {
var result = this.script.onUpdate(this.script);
if (typeof result !== 'undefined')
nuFPS = result;
}
this.draw();
return nuFPS;
}
iio.App.prototype.trueVs = function() {
// set this.vs with correct values
this.vs = [
new iio.Vector(-this.width/2, -this.height/2),
new iio.Vector(this.width/2, -this.height/2),
new iio.Vector(this.width/2, this.height/2),
new iio.Vector(-this.width/2, this.height/2),
];
// return clone of this.vs
var vs = [];
for(var i=0; i<this.vs.length; i++)
vs[i] = this.vs[i].clone();
return vs;
}
iio.App.prototype.draw = function( noClear ) {
// clear canvas
if( !this.keepDraws )
this.ctx.clearRect(0, 0, this.width, this.height);
// draw background color
if (this.color) {
this.ctx.fillStyle = this.color.rgbaString();
this.ctx.fillRect(0, 0, this.width, this.height);
}
// draw child objects
if (this.objs.length > 0)
for(var i=0; i<this.objs.length; i++)
if (!this.clipObjs
|| (this.objs[i].right() > 0 && this.objs[i].left() < this.width
&& this.objs[i].bottom() > 0 && this.objs[i].top() < this.height))
if (this.objs[i].draw) this.objs[i].draw(this.ctx);
}
// APP FUNCTIONS
iio.App.prototype.eventVector = function(e) {
this.update_pos();
var ex = e.clientX;
var ey = e.clientY;
if (e.touches && e.touches[0]) {
ex = e.touches[0].clientX;
ey = e.touches[0].clientY;
}
return new iio.Vector(
ex - this.pos.x,
ey - this.pos.y
)
}
iio.App.prototype.update_pos = function(){
var offset = this.canvas.getBoundingClientRect();
this.pos = new iio.Vector(
offset.left,
offset.top
);
}
iio.App.prototype.stop = function() {
this.objs.forEach(function(obj) {
if (obj instanceof iio.Sound)
obj.stop();
else iio.cancelLoops(obj);
});
iio.cancelLoops(this);
if (this.mainLoop) iio.cancelLoop(this.mainLoop.id);
this.clear();
return this;
}
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' ?>
<math display="block" xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
<mn>1.3</mn>
<mo>×</mo>
<mn>.2</mn>
</mrow>
</math>
| {
"pile_set_name": "Github"
} |
/**
* MIT License
* <p>
* Copyright (c) 2017 James
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
package me.zbl.mediator;
/**
* 派对成员
*/
public interface PartyMember {
void joinParty(Party party);
void partyActivity(Activity activity);
void act(Activity activity);
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<title>Leaflet debug page</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ==" crossorigin="" />
<script src="https://unpkg.com/[email protected]/dist/leaflet-src.js" integrity="sha512-WXoSHqw/t26DszhdMhOXOkI7qCiv5QWXhH9R7CgvgZMHz1ImlkVQ3uNsiQKu5wwbbxtPzFXd1hK4tzno2VqhpA==" crossorigin=""></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="screen.css" />
<link rel="stylesheet" href="../dist/MarkerCluster.css" />
<link rel="stylesheet" href="../dist/MarkerCluster.Default.css" />
<script src="../dist/leaflet.markercluster-src.js"></script>
<script type="text/javascript" src="geojson-sample.js"></script>
</head>
<body>
<div id="map"></div>
<span>Mouse over a cluster to see the bounds of its children and click a cluster to zoom to those bounds</span>
<script type="text/javascript">
var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}),
latlng = L.latLng(0.78, 102.37);
var map = L.map('map', {center: latlng, zoom: 7, layers: [tiles]});
var geojson = L.geoJson(geojsonSample, {
style: function (feature) {
return {color: feature.properties.color};
},
onEachFeature: function (feature, layer) {
var popupText = 'geometry type: ' + feature.geometry.type;
if (feature.properties.color) {
popupText += '<br/>color: ' + feature.properties.color;
}
layer.bindPopup(popupText);
}
});
geojson.addLayer(new L.Marker(new L.LatLng(2.745530718801952, 105.194091796875)));
var eye1 = new L.Marker(new L.LatLng(-0.7250783020332547, 101.8212890625));
var eye2 = new L.Marker(new L.LatLng(-0.7360637370492077, 103.2275390625));
var nose = new L.Marker(new L.LatLng(-1.3292264529974207, 102.5463867187));
var mouth = new L.Polyline([
new L.LatLng(-1.3841426927920029, 101.7333984375),
new L.LatLng(-1.6037944300589726, 101.964111328125),
new L.LatLng(-1.6806671337507222, 102.249755859375),
new L.LatLng(-1.7355743631421197, 102.67822265625),
new L.LatLng(-1.5928123762763, 103.0078125),
new L.LatLng(-1.3292264529974207, 103.3154296875)
]);
var markers = L.markerClusterGroup();
markers.addLayer(geojson).addLayers([eye1,eye2,nose,mouth]);
map.addLayer(markers);
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
'use strict';
var Mixin = module.exports = function (host) {
var originalMethods = {},
overriddenMethods = this._getOverriddenMethods(this, originalMethods);
Object.keys(overriddenMethods).forEach(function (key) {
if (typeof overriddenMethods[key] === 'function') {
originalMethods[key] = host[key];
host[key] = overriddenMethods[key];
}
});
};
Mixin.prototype._getOverriddenMethods = function () {
throw new Error('Not implemented');
};
| {
"pile_set_name": "Github"
} |
var convert = require('./convert'),
func = convert('mixin', require('../mixin'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"pile_set_name": "Github"
} |
Tag attribute _id_ plays a crucial role in web development as it allows JavaScript to identify a DOM element. That's why class _Component_ provides two dedicated methods to set this attribute. With method _setOutputMarkupId(boolean output)_ we can decide if the _id_ attribute will be rendered or not in the final markup (by default is not rendered). The value of this attribute will be automatically generated by Wicket and it will be unique for the entire page.
If we need to specify this value by hand, we can use method _setMarkupId(String id)_. The value of the id can be retrieved with method _getMarkupId()_.
Wicket generates markup ids using an instance of interface _org.apache.wicket.IMarkupIdGenerator_. The default implementation is _org.apache.wicket.DefaultMarkupIdGenerator_ and it uses a session-scoped counter to generate the final id. A different generator can be set with the markup settings class _org.apache.wicket.settings.MarkupSettings_ available in the application class:
[source,java]
----
@Override
public void init()
{
super.init();
getMarkupSettings().setMarkupIdGenerator(myGenerator);
}
----
| {
"pile_set_name": "Github"
} |
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\rc\cli.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\rc\cli.js" %*
) | {
"pile_set_name": "Github"
} |
/**
* This method returns an empty string.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {string} Returns the empty string.
* @example
*
* _.times(2, _.stubString);
* // => ['', '']
*/
function stubString() {
return '';
}
module.exports = stubString;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The contents of this file are subject to the terms of either the Universal Permissive License
* v 1.0 as shown at http://oss.oracle.com/licenses/upl
*
* or the following license:
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* 3. Neither the name of the copyright holder 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.
*/
package org.openjdk.jmc.console.ui.notification.wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.openjdk.jmc.console.ui.notification.widget.ActionChooser;
import org.openjdk.jmc.rjmx.IConnectionHandle;
import org.openjdk.jmc.rjmx.triggers.TriggerRule;
import org.openjdk.jmc.rjmx.triggers.internal.NotificationRegistry;
import org.openjdk.jmc.ui.misc.IRefreshable;
import org.openjdk.jmc.ui.uibuilder.StandardUIBuilder;
/**
* This is the wizard page for editing trigger conditions .
*/
public class ActionWizardPage extends WizardPage {
public final static String PAGE_NAME = "org.openjdk.jmc.notification.trigger.action"; //$NON-NLS-1$
private final TriggerRule m_notificationRule;
private final IConnectionHandle m_connectionHandle;
private final NotificationRegistry m_notificationModel;
public ActionWizardPage(NotificationRegistry notificationModel, IConnectionHandle handle, TriggerRule rule) {
super(PAGE_NAME, Messages.ActionWizardPage_TITLE, null);
setDescription(Messages.ActionWizardPage_DESCRIPTION);
m_notificationRule = rule;
m_connectionHandle = handle;
m_notificationModel = notificationModel;
}
@Override
public void createControl(Composite parent) {
Composite cp = new Composite(parent, SWT.NONE);
StandardUIBuilder builder = new StandardUIBuilder(cp);
final ActionChooser actionChooser = new ActionChooser(builder, m_notificationRule, m_connectionHandle,
m_notificationModel, cp, true, true, false, null);
actionChooser.createAndAddActionSelectionChangedListener(new IRefreshable() {
@Override
public boolean refresh() {
setPageComplete(m_notificationRule.getAction() != null);
return true;
}
});
setPageComplete(m_notificationRule.getAction() != null);
setControl(cp);
}
}
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0+
/*
* inputbox.c -- implements the input box
*
* ORIGINAL AUTHOR: Savio Lam ([email protected])
* MODIFIED FOR LINUX KERNEL CONFIG BY: William Roadcap ([email protected])
*/
#include "dialog.h"
char dialog_input_result[MAX_LEN + 1];
/*
* Print the termination buttons
*/
static void print_buttons(WINDOW * dialog, int height, int width, int selected)
{
int x = width / 2 - 11;
int y = height - 2;
print_button(dialog, " Ok ", y, x, selected == 0);
print_button(dialog, " Help ", y, x + 14, selected == 1);
wmove(dialog, y, x + 1 + 14 * selected);
wrefresh(dialog);
}
/*
* Display a dialog box for inputing a string
*/
int dialog_inputbox(const char *title, const char *prompt, int height, int width,
const char *init)
{
int i, x, y, box_y, box_x, box_width;
int input_x = 0, key = 0, button = -1;
int show_x, len, pos;
char *instr = dialog_input_result;
WINDOW *dialog;
if (!init)
instr[0] = '\0';
else
strcpy(instr, init);
do_resize:
if (getmaxy(stdscr) <= (height - INPUTBOX_HEIGTH_MIN))
return -ERRDISPLAYTOOSMALL;
if (getmaxx(stdscr) <= (width - INPUTBOX_WIDTH_MIN))
return -ERRDISPLAYTOOSMALL;
/* center dialog box on screen */
x = (getmaxx(stdscr) - width) / 2;
y = (getmaxy(stdscr) - height) / 2;
draw_shadow(stdscr, y, x, height, width);
dialog = newwin(height, width, y, x);
keypad(dialog, TRUE);
draw_box(dialog, 0, 0, height, width,
dlg.dialog.atr, dlg.border.atr);
wattrset(dialog, dlg.border.atr);
mvwaddch(dialog, height - 3, 0, ACS_LTEE);
for (i = 0; i < width - 2; i++)
waddch(dialog, ACS_HLINE);
wattrset(dialog, dlg.dialog.atr);
waddch(dialog, ACS_RTEE);
print_title(dialog, title, width);
wattrset(dialog, dlg.dialog.atr);
print_autowrap(dialog, prompt, width - 2, 1, 3);
/* Draw the input field box */
box_width = width - 6;
getyx(dialog, y, x);
box_y = y + 2;
box_x = (width - box_width) / 2;
draw_box(dialog, y + 1, box_x - 1, 3, box_width + 2,
dlg.dialog.atr, dlg.border.atr);
print_buttons(dialog, height, width, 0);
/* Set up the initial value */
wmove(dialog, box_y, box_x);
wattrset(dialog, dlg.inputbox.atr);
len = strlen(instr);
pos = len;
if (len >= box_width) {
show_x = len - box_width + 1;
input_x = box_width - 1;
for (i = 0; i < box_width - 1; i++)
waddch(dialog, instr[show_x + i]);
} else {
show_x = 0;
input_x = len;
waddstr(dialog, instr);
}
wmove(dialog, box_y, box_x + input_x);
wrefresh(dialog);
while (key != KEY_ESC) {
key = wgetch(dialog);
if (button == -1) { /* Input box selected */
switch (key) {
case TAB:
case KEY_UP:
case KEY_DOWN:
break;
case KEY_BACKSPACE:
case 8: /* ^H */
case 127: /* ^? */
if (pos) {
wattrset(dialog, dlg.inputbox.atr);
if (input_x == 0) {
show_x--;
} else
input_x--;
if (pos < len) {
for (i = pos - 1; i < len; i++) {
instr[i] = instr[i+1];
}
}
pos--;
len--;
instr[len] = '\0';
wmove(dialog, box_y, box_x);
for (i = 0; i < box_width; i++) {
if (!instr[show_x + i]) {
waddch(dialog, ' ');
break;
}
waddch(dialog, instr[show_x + i]);
}
wmove(dialog, box_y, input_x + box_x);
wrefresh(dialog);
}
continue;
case KEY_LEFT:
if (pos > 0) {
if (input_x > 0) {
wmove(dialog, box_y, --input_x + box_x);
} else if (input_x == 0) {
show_x--;
wmove(dialog, box_y, box_x);
for (i = 0; i < box_width; i++) {
if (!instr[show_x + i]) {
waddch(dialog, ' ');
break;
}
waddch(dialog, instr[show_x + i]);
}
wmove(dialog, box_y, box_x);
}
pos--;
}
continue;
case KEY_RIGHT:
if (pos < len) {
if (input_x < box_width - 1) {
wmove(dialog, box_y, ++input_x + box_x);
} else if (input_x == box_width - 1) {
show_x++;
wmove(dialog, box_y, box_x);
for (i = 0; i < box_width; i++) {
if (!instr[show_x + i]) {
waddch(dialog, ' ');
break;
}
waddch(dialog, instr[show_x + i]);
}
wmove(dialog, box_y, input_x + box_x);
}
pos++;
}
continue;
default:
if (key < 0x100 && isprint(key)) {
if (len < MAX_LEN) {
wattrset(dialog, dlg.inputbox.atr);
if (pos < len) {
for (i = len; i > pos; i--)
instr[i] = instr[i-1];
instr[pos] = key;
} else {
instr[len] = key;
}
pos++;
len++;
instr[len] = '\0';
if (input_x == box_width - 1) {
show_x++;
} else {
input_x++;
}
wmove(dialog, box_y, box_x);
for (i = 0; i < box_width; i++) {
if (!instr[show_x + i]) {
waddch(dialog, ' ');
break;
}
waddch(dialog, instr[show_x + i]);
}
wmove(dialog, box_y, input_x + box_x);
wrefresh(dialog);
} else
flash(); /* Alarm user about overflow */
continue;
}
}
}
switch (key) {
case 'O':
case 'o':
delwin(dialog);
return 0;
case 'H':
case 'h':
delwin(dialog);
return 1;
case KEY_UP:
case KEY_LEFT:
switch (button) {
case -1:
button = 1; /* Indicates "Help" button is selected */
print_buttons(dialog, height, width, 1);
break;
case 0:
button = -1; /* Indicates input box is selected */
print_buttons(dialog, height, width, 0);
wmove(dialog, box_y, box_x + input_x);
wrefresh(dialog);
break;
case 1:
button = 0; /* Indicates "OK" button is selected */
print_buttons(dialog, height, width, 0);
break;
}
break;
case TAB:
case KEY_DOWN:
case KEY_RIGHT:
switch (button) {
case -1:
button = 0; /* Indicates "OK" button is selected */
print_buttons(dialog, height, width, 0);
break;
case 0:
button = 1; /* Indicates "Help" button is selected */
print_buttons(dialog, height, width, 1);
break;
case 1:
button = -1; /* Indicates input box is selected */
print_buttons(dialog, height, width, 0);
wmove(dialog, box_y, box_x + input_x);
wrefresh(dialog);
break;
}
break;
case ' ':
case '\n':
delwin(dialog);
return (button == -1 ? 0 : button);
case 'X':
case 'x':
key = KEY_ESC;
break;
case KEY_ESC:
key = on_key_esc(dialog);
break;
case KEY_RESIZE:
delwin(dialog);
on_key_resize();
goto do_resize;
}
}
delwin(dialog);
return KEY_ESC; /* ESC pressed */
}
| {
"pile_set_name": "Github"
} |
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_JACOBIAN_ENTRY_H
#define BT_JACOBIAN_ENTRY_H
#include "LinearMath/btMatrix3x3.h"
//notes:
// Another memory optimization would be to store m_1MinvJt in the remaining 3 w components
// which makes the btJacobianEntry memory layout 16 bytes
// if you only are interested in angular part, just feed massInvA and massInvB zero
/// Jacobian entry is an abstraction that allows to describe constraints
/// it can be used in combination with a constraint solver
/// Can be used to relate the effect of an impulse to the constraint error
ATTRIBUTE_ALIGNED16(class) btJacobianEntry
{
public:
btJacobianEntry() {};
//constraint between two different rigidbodies
btJacobianEntry(
const btMatrix3x3& world2A,
const btMatrix3x3& world2B,
const btVector3& rel_pos1,const btVector3& rel_pos2,
const btVector3& jointAxis,
const btVector3& inertiaInvA,
const btScalar massInvA,
const btVector3& inertiaInvB,
const btScalar massInvB)
:m_linearJointAxis(jointAxis)
{
m_aJ = world2A*(rel_pos1.cross(m_linearJointAxis));
m_bJ = world2B*(rel_pos2.cross(-m_linearJointAxis));
m_0MinvJt = inertiaInvA * m_aJ;
m_1MinvJt = inertiaInvB * m_bJ;
m_Adiag = massInvA + m_0MinvJt.dot(m_aJ) + massInvB + m_1MinvJt.dot(m_bJ);
btAssert(m_Adiag > btScalar(0.0));
}
//angular constraint between two different rigidbodies
btJacobianEntry(const btVector3& jointAxis,
const btMatrix3x3& world2A,
const btMatrix3x3& world2B,
const btVector3& inertiaInvA,
const btVector3& inertiaInvB)
:m_linearJointAxis(btVector3(btScalar(0.),btScalar(0.),btScalar(0.)))
{
m_aJ= world2A*jointAxis;
m_bJ = world2B*-jointAxis;
m_0MinvJt = inertiaInvA * m_aJ;
m_1MinvJt = inertiaInvB * m_bJ;
m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ);
btAssert(m_Adiag > btScalar(0.0));
}
//angular constraint between two different rigidbodies
btJacobianEntry(const btVector3& axisInA,
const btVector3& axisInB,
const btVector3& inertiaInvA,
const btVector3& inertiaInvB)
: m_linearJointAxis(btVector3(btScalar(0.),btScalar(0.),btScalar(0.)))
, m_aJ(axisInA)
, m_bJ(-axisInB)
{
m_0MinvJt = inertiaInvA * m_aJ;
m_1MinvJt = inertiaInvB * m_bJ;
m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ);
btAssert(m_Adiag > btScalar(0.0));
}
//constraint on one rigidbody
btJacobianEntry(
const btMatrix3x3& world2A,
const btVector3& rel_pos1,const btVector3& rel_pos2,
const btVector3& jointAxis,
const btVector3& inertiaInvA,
const btScalar massInvA)
:m_linearJointAxis(jointAxis)
{
m_aJ= world2A*(rel_pos1.cross(jointAxis));
m_bJ = world2A*(rel_pos2.cross(-jointAxis));
m_0MinvJt = inertiaInvA * m_aJ;
m_1MinvJt = btVector3(btScalar(0.),btScalar(0.),btScalar(0.));
m_Adiag = massInvA + m_0MinvJt.dot(m_aJ);
btAssert(m_Adiag > btScalar(0.0));
}
btScalar getDiagonal() const { return m_Adiag; }
// for two constraints on the same rigidbody (for example vehicle friction)
btScalar getNonDiagonal(const btJacobianEntry& jacB, const btScalar massInvA) const
{
const btJacobianEntry& jacA = *this;
btScalar lin = massInvA * jacA.m_linearJointAxis.dot(jacB.m_linearJointAxis);
btScalar ang = jacA.m_0MinvJt.dot(jacB.m_aJ);
return lin + ang;
}
// for two constraints on sharing two same rigidbodies (for example two contact points between two rigidbodies)
btScalar getNonDiagonal(const btJacobianEntry& jacB,const btScalar massInvA,const btScalar massInvB) const
{
const btJacobianEntry& jacA = *this;
btVector3 lin = jacA.m_linearJointAxis * jacB.m_linearJointAxis;
btVector3 ang0 = jacA.m_0MinvJt * jacB.m_aJ;
btVector3 ang1 = jacA.m_1MinvJt * jacB.m_bJ;
btVector3 lin0 = massInvA * lin ;
btVector3 lin1 = massInvB * lin;
btVector3 sum = ang0+ang1+lin0+lin1;
return sum[0]+sum[1]+sum[2];
}
btScalar getRelativeVelocity(const btVector3& linvelA,const btVector3& angvelA,const btVector3& linvelB,const btVector3& angvelB)
{
btVector3 linrel = linvelA - linvelB;
btVector3 angvela = angvelA * m_aJ;
btVector3 angvelb = angvelB * m_bJ;
linrel *= m_linearJointAxis;
angvela += angvelb;
angvela += linrel;
btScalar rel_vel2 = angvela[0]+angvela[1]+angvela[2];
return rel_vel2 + SIMD_EPSILON;
}
//private:
btVector3 m_linearJointAxis;
btVector3 m_aJ;
btVector3 m_bJ;
btVector3 m_0MinvJt;
btVector3 m_1MinvJt;
//Optimization: can be stored in the w/last component of one of the vectors
btScalar m_Adiag;
};
#endif //BT_JACOBIAN_ENTRY_H
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2003-2020 The Music Player Daemon Project
* http://www.musicpd.org
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef PCM_EXPORT_HXX
#define PCM_EXPORT_HXX
#include "SampleFormat.hxx"
#include "Buffer.hxx"
#include "config.h"
#ifdef ENABLE_DSD
#include "Dsd16.hxx"
#include "Dsd32.hxx"
#include "Dop.hxx"
#endif
#include <cstdint>
template<typename T> struct ConstBuffer;
/**
* An object that handles export of PCM samples to some instance
* outside of MPD. It has a few more options to tweak the binary
* representation which are not supported by the #PcmConvert library.
*/
class PcmExport {
/**
* This buffer is used to reorder channels.
*
* @see #alsa_channel_order
*/
PcmBuffer order_buffer;
#ifdef ENABLE_DSD
/**
* @see DsdMode::U16
*/
Dsd16Converter dsd16_converter;
/**
* @see DsdMode::U32
*/
Dsd32Converter dsd32_converter;
/**
* @see DsdMode::DOP
*/
DsdToDopConverter dop_converter;
#endif
/**
* The buffer is used to pack samples, removing padding.
*
* @see #pack24
*/
PcmBuffer pack_buffer;
/**
* The buffer is used to reverse the byte order.
*
* @see #reverse_endian
*/
PcmBuffer reverse_buffer;
size_t silence_size;
uint8_t silence_buffer[64]; /* worst-case size */
/**
* The sample format of input data.
*/
SampleFormat src_sample_format;
/**
* The number of channels.
*/
uint8_t channels;
/**
* Convert the given buffer from FLAC channel order to ALSA
* channel order using ToAlsaChannelOrder()?
*/
bool alsa_channel_order;
#ifdef ENABLE_DSD
public:
enum class DsdMode : uint8_t {
NONE,
/**
* Convert DSD (U8) to DSD_U16?
*/
U16,
/**
* Convert DSD (U8) to DSD_U32?
*/
U32,
/**
* Convert DSD to DSD-over-PCM (DoP)? Input format
* must be SampleFormat::DSD and output format must be
* SampleFormat::S24_P32.
*/
DOP,
};
private:
DsdMode dsd_mode;
#endif
/**
* Convert (padded) 24 bit samples to 32 bit by shifting 8
* bits to the left?
*/
bool shift8;
/**
* Pack 24 bit samples?
*/
bool pack24;
/**
* Export the samples in reverse byte order? A non-zero value
* means the option is enabled and represents the size of each
* sample (2 or bigger).
*/
uint8_t reverse_endian;
public:
struct Params {
bool alsa_channel_order = false;
#ifdef ENABLE_DSD
DsdMode dsd_mode = DsdMode::NONE;
#endif
bool shift8 = false;
bool pack24 = false;
bool reverse_endian = false;
/**
* Calculate the output sample rate, given a specific input
* sample rate. Usually, both are the same; however, with
* DSD_U32, four input bytes (= 4 * 8 bits) are combined to
* one output word (32 bits), dividing the sample rate by 4.
*/
gcc_pure
unsigned CalcOutputSampleRate(unsigned input_sample_rate) const noexcept;
/**
* The inverse of CalcOutputSampleRate().
*/
gcc_pure
unsigned CalcInputSampleRate(unsigned output_sample_rate) const noexcept;
};
/**
* Open the object.
*
* There is no "close" method. This function may be called multiple
* times to reuse the object.
*
* This function cannot fail.
*
* @param channels the number of channels; ignored unless dop is set
*/
void Open(SampleFormat sample_format, unsigned channels,
Params params) noexcept;
/**
* Reset the filter's state, e.g. drop/flush buffers.
*/
void Reset() noexcept;
/**
* Calculate the size of one input frame.
*/
gcc_pure
size_t GetInputFrameSize() const noexcept {
return channels * sample_format_size(src_sample_format);
}
/**
* Calculate the size of one output frame.
*/
gcc_pure
size_t GetOutputFrameSize() const noexcept;
/**
* @return the size of one input block in bytes
*/
gcc_pure
size_t GetInputBlockSize() const noexcept;
/**
* @return the size of one output block in bytes
*/
gcc_pure
size_t GetOutputBlockSize() const noexcept;
/**
* @return one block of silence output; its size is the same
* as GetOutputBlockSize(); the pointer is valid as long as
* this #PcmExport object exists and until the next Open()
* call
*/
ConstBuffer<void> GetSilence() const noexcept;
/**
* Export a PCM buffer.
*
* @param src the source PCM buffer
* @return the destination buffer; may be empty (and may be a
* pointer to the source buffer)
*/
ConstBuffer<void> Export(ConstBuffer<void> src) noexcept;
/**
* Converts the number of consumed bytes from the Export()
* destination buffer to the according number of bytes from the
* pcm_export() source buffer.
*/
gcc_pure
size_t CalcInputSize(size_t dest_size) const noexcept;
};
#endif
| {
"pile_set_name": "Github"
} |
package com.mifos.mifosxdroid.offline.offlinedashbarod;
import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.mifos.mifosxdroid.R;
import com.mifos.mifosxdroid.adapters.OfflineDashboardAdapter;
import com.mifos.mifosxdroid.core.MifosBaseActivity;
import com.mifos.mifosxdroid.core.MifosBaseFragment;
import com.mifos.mifosxdroid.core.RecyclerItemClickListener;
import com.mifos.mifosxdroid.core.util.Toaster;
import com.mifos.mifosxdroid.offline.synccenterpayloads.SyncCenterPayloadActivity;
import com.mifos.mifosxdroid.offline.syncclientpayloads.SyncClientPayloadActivity;
import com.mifos.mifosxdroid.offline.syncgrouppayloads.SyncGroupPayloadsActivity;
import com.mifos.mifosxdroid.offline.syncloanrepaymenttransacition.SyncLoanRepaymentTransactionActivity;
import com.mifos.mifosxdroid.offline.syncsavingsaccounttransaction
.SyncSavingsAccountTransactionActivity;
import com.mifos.objects.accounts.loan.LoanRepaymentRequest;
import com.mifos.objects.accounts.savings.SavingsAccountTransactionRequest;
import com.mifos.objects.client.ClientPayload;
import com.mifos.objects.group.GroupPayload;
import com.mifos.services.data.CenterPayload;
import com.mifos.utils.ItemOffsetDecoration;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* This Fragment is the Dashboard of the Offline sync of Clients, Groups, LoanRepayment etc.
* In which presenter request the DataManager to get the offline created clients or groups or
* LoanRepayment from DatabaseHelper and get the List of Groups, clients and LoanRepayment etc.
*
* if DataManager Response List is not equal to zero then add the Card Name and List Count in
* OfflineDashboardAdapter.showCard(String cardName, String cardCount) and add the Class in
* List<Class> mPayloadClasses, which will open onclick the card.
*
* mPayloadIndex, this is the counter value of the number of request we are making to the
* DataManager to load the Clients, Groups, LoanRepayment etc list from DatabaseHelper
*
* SYNC_CARD_UI_NAMES is array of the card UI names, which contains the all possible name of cards.
* due to this array we have maintain the single method in
* OfflineDashboardAdapter.showCard(String cardName, String cardCount) and update the list.
*
* if DatabaseHelper returns the List size zero for all Clients, Groups, LoanRepayment etc
* then showNoPayloadToShow() and Nothing to Sync.
*
* Created by Rajan Maurya on 20/07/16.
*/
public class OfflineDashboardFragment extends MifosBaseFragment implements
OfflineDashboardMvpView, RecyclerItemClickListener.OnItemClickListener {
public final String LOG_TAG = getClass().getSimpleName();
@BindView(R.id.rv_offline_dashboard)
RecyclerView rv_offline_dashboard;
@BindView(R.id.pb_offline_dashboard)
ProgressBar pb_offline_dashboard;
@BindView(R.id.noPayloadText)
TextView mNoPayloadText;
@BindView(R.id.noPayloadIcon)
ImageView mNoPayloadIcon;
@BindView(R.id.ll_error)
LinearLayout ll_error;
View rootView;
@Inject
OfflineDashboardPresenter mOfflineDashboardPresenter;
@Inject
OfflineDashboardAdapter mOfflineDashboardAdapter;
// update mPayloadIndex to number of request is going to fetch data in Presenter;
private int mPayloadIndex = 5;
private static final int GRID_COUNT = 2;
private List<Class> mPayloadClasses;
public static final int[] SYNC_CARD_UI_NAMES = {R.string.sync_clients,
R.string.sync_groups,
R.string.sync_centers,
R.string.sync_loanrepayments,
R.string.sync_savingsaccounttransactions};
@Override
public void onItemClick(View childView, int position) {
startPayloadActivity(mPayloadClasses.get(position));
}
@Override
public void onItemLongPress(View childView, int position) {
}
public static OfflineDashboardFragment newInstance() {
OfflineDashboardFragment fragment = new OfflineDashboardFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mPayloadClasses = new ArrayList<>();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_offline_dashboard, container, false);
setToolbarTitle(getActivity().getResources().getString(R.string.offline));
((MifosBaseActivity) getActivity()).getActivityComponent().inject(this);
mOfflineDashboardPresenter.attachView(this);
ButterKnife.bind(this, rootView);
LinearLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), GRID_COUNT);
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rv_offline_dashboard.setLayoutManager(mLayoutManager);
rv_offline_dashboard.setHasFixedSize(true);
rv_offline_dashboard.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(),
this));
rv_offline_dashboard.setItemAnimator(new DefaultItemAnimator());
rv_offline_dashboard.addItemDecoration(new ItemOffsetDecoration(getActivity(),
R.dimen.item_offset));
rv_offline_dashboard.setAdapter(mOfflineDashboardAdapter);
return rootView;
}
@Override
public void onStart() {
super.onStart();
mOfflineDashboardAdapter.removeAllCards();
mPayloadClasses.clear();
mPayloadIndex = 5;
mOfflineDashboardPresenter.loadDatabaseClientPayload();
mOfflineDashboardPresenter.loadDatabaseGroupPayload();
mOfflineDashboardPresenter.loadDatabaseCenterPayload();
mOfflineDashboardPresenter.loadDatabaseLoanRepaymentTransactions();
mOfflineDashboardPresenter.loadDatabaseSavingsAccountTransactions();
}
/**
* This method set the response of DataManager from DatabaseHelper that if List<ClientPayload>
* Size is zero the decrease the value of mPayloadIndex by 1 and if size is not equal to zero
* the update the adapter and add the Card UI name and size() of the List to sync.
*
* @param clientPayloads List<ClientPayload> from DatabaseHelperClient
*/
@Override
public void showClients(List<ClientPayload> clientPayloads) {
if (clientPayloads.size() != 0) {
mOfflineDashboardAdapter.showCard(getActivity()
.getResources().getString(R.string.payloads_count) +
clientPayloads.size(), SYNC_CARD_UI_NAMES[0]);
mPayloadClasses.add(SyncClientPayloadActivity.class);
} else {
mPayloadIndex = mPayloadIndex - 1;
showNoPayloadToShow();
}
}
/**
* This method set the response of DataManager from DatabaseHelper that if List<GroupsPayload>
* Size is zero, then decrease the value of mPayloadIndex by 1 and if size is not equal to zero
* the update the adapter and add the Card UI name and size() of the List to sync.
*
* @param groupPayloads List<GroupPayload> from DatabaseHelperGroup
*/
@Override
public void showGroups(List<GroupPayload> groupPayloads) {
if (groupPayloads.size() != 0) {
mOfflineDashboardAdapter.showCard(getActivity()
.getResources().getString(R.string.payloads_count) +
groupPayloads.size(), SYNC_CARD_UI_NAMES[1]);
mPayloadClasses.add(SyncGroupPayloadsActivity.class);
} else {
mPayloadIndex = mPayloadIndex - 1;
showNoPayloadToShow();
}
}
/**
* This method set the response of DataManager from DatabaseHelper that if List<CenterPayload>
* Size is zero, then decrease the value of mPayloadIndex by 1 and if size is not equal to zero
* the update the adapter and add the Card UI name and size() of the List to sync.
*
* @param centerPayloads List<CenterPayload> from DatabaseHelperGroup
*/
@Override
public void showCenters(List<CenterPayload> centerPayloads) {
if (centerPayloads.size() != 0) {
mOfflineDashboardAdapter.showCard(getActivity()
.getResources().getString(R.string.payloads_count) +
centerPayloads.size(), SYNC_CARD_UI_NAMES[2]);
mPayloadClasses.add(SyncCenterPayloadActivity.class);
} else {
mPayloadIndex = mPayloadIndex - 1;
showNoPayloadToShow();
}
}
/**
* This method set the response of DataManager from DatabaseHelper that if
* List<LoanRepaymentRequest> Size is zero, then decrease the value of mPayloadIndex by 1 and
* if size is not equal to zero the update the adapter and add the Card UI name and size() of
* the List to sync.
*
* @param loanRepaymentRequests List<LoanRepaymentRequest> from DatabaseHelperLoan
*/
@Override
public void showLoanRepaymentTransactions(List<LoanRepaymentRequest> loanRepaymentRequests) {
if (loanRepaymentRequests.size() != 0) {
mOfflineDashboardAdapter.showCard(getActivity().getResources()
.getString(R.string.transactions_count) +
loanRepaymentRequests.size(), SYNC_CARD_UI_NAMES[3]);
mPayloadClasses.add(SyncLoanRepaymentTransactionActivity.class);
} else {
mPayloadIndex = mPayloadIndex - 1;
showNoPayloadToShow();
}
}
/**
* This method set the response of DataManager from DatabaseHelper, if
* List<SavingsAccountTransactionRequest> Size is zero, then decrease the value of
* mPayloadIndex by 1 and if size is not equal to zero then update the adapter and add the
* Card UI name and size() of the List to sync.
*
* @param transactions List<SavingsAccountTransaction>
*/
@Override
public void showSavingsAccountTransaction(List<SavingsAccountTransactionRequest> transactions) {
if (transactions.size() != 0) {
mOfflineDashboardAdapter.showCard(getActivity().getResources()
.getString(R.string.transactions_count) +
transactions.size(), SYNC_CARD_UI_NAMES[4]);
mPayloadClasses.add(SyncSavingsAccountTransactionActivity.class);
} else {
mPayloadIndex = mPayloadIndex - 1;
showNoPayloadToShow();
}
}
/**
* This Method setting the main UI RecyclerView.setVisibility(View.GONE) and Set text TO
* TextView that Nothing to Sync when mPayloadIndex = 0. It means there is nothing in the
* Database to sync to the Server.
*/
@Override
public void showNoPayloadToShow() {
if (mPayloadIndex == 0) {
rv_offline_dashboard.setVisibility(View.GONE);
ll_error.setVisibility(View.VISIBLE);
mNoPayloadText.setText(getActivity()
.getResources().getString(R.string.nothing_to_sync));
mNoPayloadIcon.setImageResource(R.drawable.ic_assignment_turned_in_black_24dp);
}
}
@Override
public void showError(int stringId) {
Toaster.show(rootView, getResources().getString(stringId));
}
@Override
public void showProgressbar(boolean b) {
if (b) {
pb_offline_dashboard.setVisibility(View.VISIBLE);
} else {
pb_offline_dashboard.setVisibility(View.GONE);
}
}
/**
* This is the Generic Type method for starting the activity.
* @param t Activity Class that is user wants to start
* @param <T>
*/
public <T> void startPayloadActivity(Class<T> t) {
Intent intent = new Intent(getActivity(), t);
startActivity(intent);
}
@Override
public void onDestroyView() {
super.onDestroyView();
mOfflineDashboardPresenter.detachView();
}
}
| {
"pile_set_name": "Github"
} |
--TEST--
is_soap_fault 1: test against null
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--FILE--
<?php
var_dump(is_soap_fault(null));
$fault = new SoapFault("code", "message");
var_dump(is_soap_fault($fault));
?>
--EXPECT--
bool(false)
bool(true)
| {
"pile_set_name": "Github"
} |
{
"config": {
"abort": {
"already_configured": "La integraci\u00f3 OpenWeatherMap per a aquestes coordenades ja est\u00e0 configurada."
},
"error": {
"auth": "La clau API no \u00e9s correcta.",
"connection": "No s'ha pogut connectar amb l'API d'OWM"
},
"step": {
"user": {
"data": {
"api_key": "Clau API d'OpenWeatherMap",
"language": "Idioma",
"latitude": "Latitud",
"longitude": "Longitud",
"mode": "Mode",
"name": "Nom de la integraci\u00f3"
},
"description": "Configura la integraci\u00f3 OpenWeatherMap. Per generar la clau API, ves a https://openweathermap.org/appid",
"title": "OpenWeatherMap"
}
}
},
"options": {
"step": {
"init": {
"data": {
"language": "Idioma",
"mode": "Mode"
}
}
}
}
} | {
"pile_set_name": "Github"
} |
// +build ignore,OMIT
package main
import (
"encoding/json"
"fmt"
"strings"
)
const blob = `[
{"Title":"Øredev", "URL":"http://oredev.org"},
{"Title":"Strange Loop", "URL":"http://thestrangeloop.com"}
]`
type Item struct {
Title string
URL string
}
func main() {
var items []*Item
json.NewDecoder(strings.NewReader(blob)).Decode(&items)
for _, item := range items {
fmt.Printf("Title: %v URL: %v\n", item.Title, item.URL)
}
}
| {
"pile_set_name": "Github"
} |

### Contents
#### Basics
- [Introduction to VIPER](introduction-to-viper.md)
- [Structure of the VIPER module](module-structure.md)
- [Code generation and module creation automation](code-generation.md)
#### Practice
- Compound VIPER modules
- Transitions between modules
- [The road from MVC to VIPER](mvc-chainsaw-massacre.md)
- VIPER and NSFetchedResultsController
- [UIWebView and VIPER](webview.md)
- VIPER and TDD
#### Other
- Code Style Questions
- Additional Materials by Rambler&Co
- [Other Materials](other-materials.md)
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# Copyright 2012-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
from awscli.testutils import BaseAWSCommandParamsTest
import awscli.clidriver
class TestPurgeQueue(BaseAWSCommandParamsTest):
prefix = 'sqs purge-queue'
def test_simple(self):
url = 'https://foo.bar/queue'
cmdline = self.prefix
cmdline += ' --queue-url %s' % url
result = {'QueueUrl': url}
self.assert_params_for_cmd(cmdline, result)
if __name__ == "__main__":
unittest.main()
| {
"pile_set_name": "Github"
} |
---
title: The Interledger Quoting Protocol (ILQP)
draft: FINAL
deprecated: true
---
# Interledger Quoting Protocol (ILQP)
The Interledger Quoting Protocol is a method of getting quote information from a Connector in preparation for arranging transfers across two ledgers. The quote returned by a Connector is non-binding, but provides a basis for choosing which connectors to use.
There are two consumers of the ILQP: sending clients, and other connectors.
## Background and Terminology
The quoting protocol returns the price of a _hypothetical_ payment through the connector being queried. However, no part of the ILQP initiates or creates an actual payment. All the information in the ILQP is non-binding and advisory. ILQP only calculates and reports the expected cost of a payment.
Accounts ILQP are identified by their ILP Addresses. For a full explanation of ILP Addresses, see [ILP Addresses](../0015-ilp-addresses/0015-ilp-addresses.md).
ILP payments can be as simple as two transfers in different ledgers joined by a single connector. In other cases, they may be longer chains with multiple connectors across three or more ledgers. The response of an ILQP request combines the exchange rates of all links in the chain into one quote.
**Ledgers:**
* The **source ledger** is where the sender and the connector both have accounts.
* The **destination ledger** is where the receiver and the last connector both have accounts.
The source and destination ledger are different ledgers. Otherwise, there should be no reason to use ILQP.
**Parties:**
* The **sender** is the party who would be debited on the source ledger by the hypothetical payment.
* The **receiver** is the party being credited on the destination ledger by the hypothetical payment.
* A **connector** forms the active link between an incoming transfer on one ledger and an outgoing transfer on the next.
In a multiple-hop payment, there are multiple connectors, each of which creates an outgoing transfer in response to an incoming transfer. If the first connector in the chain has full (cached) pricing information, it will respond to the sender's quote request immmediately. If not, it will forward the quote request along the chain, and then relay the response it gets back.
> The following description of ILQP documents the current behaviour of nodes on the live Interledger, the majority of which are running [ILP Kit](https://github.com/interledgerjs/ilp-kit) software.
## Get Quote
Quotes are sent through a request/response mechanism exposed by the ledger plugins or ledger layer.
A quote request's `ilp` property must be a `QuoteLiquidityRequest`, `QuoteBySourceRequest`, or `QuoteByDestinationRequest`. The response's `ilp` property must be a `QuoteLiquidityResponse`, `QuoteBySourceResponse`, or `QuoteByDestinationResponse` respectively. If an error occurs during quoting, `ilp` will be a [`IlpError`](../0003-interledger-protocol/0003-interledger-protocol.md#ilp-error-format) instead.
## ILQP Packets
See [interledgerjs/ilp-packet](https://github.com/interledgerjs/ilp-packet/) for an example implementation of a packet serializer/deserializer.
### QuoteLiquidityRequest
| Field | Type | Short Description |
|:--|:--|:--|
| type | Byte | Always `2` |
| length | Length Determinant | One or more bytes, indicating how many bytes follow in the rest of the packet |
| destinationAccount | Length-prefixed String | Address corresponding to the destination account |
| destinationHoldDuration | UInt32 | How much time the receiver needs to fulfill the payment (in milliseconds) |
| extensions | Length Determinant | Always `0` |
### QuoteLiquidityResponse
| Field | Type | Short Description |
|:--|:--|:--|
| type | Byte | Always `3` |
| length | Length Determinant | One or more bytes, indicating how many bytes follow in the rest of the packet |
| liquidity | LiquidityCurve | Curve describing the liquidity for the quoted route |
| appliesToPrefix | Length-prefixed String | Common prefix of all addresses for which this liquidity curve applies. |
| sourceHoldDuration | UInt32 | How long the sender should put the money on hold (in milliseconds) |
| expiresAt | GeneralizedTime | Maximum time where the connector expects to be able to honor this liquidity curve. This MUST be expressed in the UTC + 0 (Z) timezone. |
| extensions | Length Determinant | Always `0` |
`LiquidityCurve` is encoded as a `SEQUENCE OF SEQUENCE { x UInt64, y UInt64 }`. This is a binary format, so for example the curve `[ [0, 0], [10, 265] ]` is equivalent to the base64-encoded string `"AAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAAAAAAAAkBAAA="`.
See [interledgerjs/ilp-routing.LiquidityCurve](https://github.com/interledgerjs/ilp-routing/blob/master/src/lib/liquidity-curve.js) for an example implementation of a LiquidityCurve serializer/deserializer.
### QuoteBySourceRequest
| Field | Type | Short Description |
|:--|:--|:--|
| type | Byte | Always `4` |
| length | Length Determinant | One or more bytes, indicating how many bytes follow in the rest of the packet |
| destinationAccount | Length-prefixed String | Length-prefixed address corresponding to the destination account |
| sourceAmount | UInt64 | Amount the sender needs to send, denominated in the asset of the source ledger |
| destinationHoldDuration | UInt32 | How much time the receiver needs to fulfill the payment (in milliseconds) |
| extensions | Length Determinant | Always `0` |
### QuoteBySourceResponse
| Field | Type | Short Description |
|:--|:--|:--|
| type | Byte | Always `5` |
| length | Length Determinant | One or more bytes, indicating how many bytes follow in the rest of the packet |
| destinationAmount | UInt64 | Amount that will arrive at the receiver |
| sourceHoldDuration | UInt32 | How long the sender should put money on hold (in milliseconds) |
| extensions | Length Determinant | Always `0` |
### QuoteByDestinationRequest
| Field | Type | Short Description |
|:--|:--|:--|
| type | Byte | Always `6` |
| length | Length Determinant | One or more bytes, indicating how many bytes follow in the rest of the packet |
| destinationAccount | Length-prefixed String | Length-prefixed address corresponding to the destination account |
| destinationAmount | UInt64 | Amount that will arrive at the receiver |
| destinationHoldDuration | UInt32 | How much time the receiver needs to fulfill the payment (in milliseconds) |
| extensions | Length Determinant | Always `0` |
### QuoteByDestinationResponse
| Field | Type | Short Description |
|:--|:--|:--|
| type | Byte | Always `7` |
| length | Length Determinant | One or more bytes, indicating how many bytes follow in the rest of the packet |
| sourceAmount | UInt64 | Amount the sender needs to send, denominated in the asset of the source ledger |
| sourceHoldDuration | UInt32 | How long the sender should put money on hold (in milliseconds) |
| extensions | Length Determinant | Always `0` |
## Next Steps
After getting a quote using ILQP, the client can display the quote to the user and optionally proceed to _Preparing_ (also called _Setting Up_) the payment, for example using the [Simple Payment Setup Protocol](https://github.com/interledger/rfcs/tree/master/0009-simple-payment-setup-protocol). That process actually sets money aside and creates the crypto-conditions that will release the money to the desired parties.
## Appendix A: ASN.1 Module
The [InterledgerQuotingProtocol.asn](../asn1/InterledgerQuotingProtocol.asn) ASN.1 module describes the binary ILQP messages.
| {
"pile_set_name": "Github"
} |
class Keys {
static final String currentLanguageCode = "current_language_code";
static final String currentLanguage = "current_language";
static final String appName = "app_name";
static final String account = "account";
static final String password = "password";
static final String hasLogged = "hasLogged";
static final String area = "area";
static final String contacts = "contacts";
static final String brokenNetwork = "brokenNetwork";
static final String faceUrl = 'faceUrl';
static final String nickName = 'nickName';
static final String gender = 'gender';
}
| {
"pile_set_name": "Github"
} |
module github.com/knative/docs
go 1.14
require (
cloud.google.com/go/storage v1.10.0
github.com/cloudevents/sdk-go/v2 v2.2.0
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/eclipse/paho.mqtt.golang v1.1.1
github.com/golang/protobuf v1.4.2
github.com/google/go-github v17.0.0+incompatible
github.com/kelseyhightower/envconfig v1.4.0
github.com/openzipkin/zipkin-go v0.2.2
github.com/satori/go.uuid v1.2.0
go.opencensus.io v0.22.4
golang.org/x/net v0.0.0-20200707034311-ab3426394381
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
google.golang.org/grpc v1.31.0
gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
gopkg.in/go-playground/webhooks.v3 v3.13.0
gopkg.in/yaml.v2 v2.3.0
knative.dev/test-infra v0.0.0-20200924233740-ac857351ea07
)
replace go.opencensus.io => go.opencensus.io v0.20.2
| {
"pile_set_name": "Github"
} |
#include <QtScript/QScriptEngine>
#include <QtScript/QScriptContext>
#include <QtScript/QScriptValue>
#include <QtCore/QStringList>
#include <QtCore/QDebug>
#include <qmetaobject.h>
#include <__package_shared.h>
#include <qpixmapcache.h>
#include <QVariant>
#include <qpixmap.h>
#include <qpixmapcache.h>
#include "qtscriptshell_QPixmapCache.h"
static const char * const qtscript_QPixmapCache_function_names[] = {
"QPixmapCache"
// static
, "cacheLimit"
, "clear"
, "find"
, "insert"
, "remove"
, "replace"
, "setCacheLimit"
// prototype
, "toString"
};
static const char * const qtscript_QPixmapCache_function_signatures[] = {
""
// static
, ""
, ""
, "QPixmapCache_Key key, QPixmap pixmap\nString key, QPixmap pixmap"
, "QPixmap pixmap\nString key, QPixmap pixmap"
, "QPixmapCache_Key key\nString key"
, "QPixmapCache_Key key, QPixmap pixmap"
, "int arg__1"
// prototype
""
};
static const int qtscript_QPixmapCache_function_lengths[] = {
0
// static
, 0
, 0
, 2
, 2
, 1
, 2
, 1
// prototype
, 0
};
static QScriptValue qtscript_QPixmapCache_throw_ambiguity_error_helper(
QScriptContext *context, const char *functionName, const char *signatures)
{
QStringList lines = QString::fromLatin1(signatures).split(QLatin1Char('\n'));
QStringList fullSignatures;
for (int i = 0; i < lines.size(); ++i)
fullSignatures.append(QString::fromLatin1("%0(%1)").arg(functionName).arg(lines.at(i)));
return context->throwError(QString::fromLatin1("QPixmapCache::%0(): could not find a function match; candidates are:\n%1")
.arg(functionName).arg(fullSignatures.join(QLatin1String("\n"))));
}
Q_DECLARE_METATYPE(QPixmapCache*)
Q_DECLARE_METATYPE(QtScriptShell_QPixmapCache*)
Q_DECLARE_METATYPE(QPixmapCache::Key)
Q_DECLARE_METATYPE(QPixmap*)
//
// QPixmapCache
//
static QScriptValue qtscript_QPixmapCache_prototype_call(QScriptContext *context, QScriptEngine *)
{
#if QT_VERSION > 0x040400
Q_ASSERT(context->callee().isFunction());
uint _id = context->callee().data().toUInt32();
#else
uint _id;
if (context->callee().isFunction())
_id = context->callee().data().toUInt32();
else
_id = 0xBABE0000 + 0;
#endif
Q_ASSERT((_id & 0xFFFF0000) == 0xBABE0000);
_id &= 0x0000FFFF;
QPixmapCache* _q_self = qscriptvalue_cast<QPixmapCache*>(context->thisObject());
if (!_q_self) {
return context->throwError(QScriptContext::TypeError,
QString::fromLatin1("QPixmapCache.%0(): this object is not a QPixmapCache")
.arg(qtscript_QPixmapCache_function_names[_id+8]));
}
switch (_id) {
case 0: {
QString result = QString::fromLatin1("QPixmapCache");
return QScriptValue(context->engine(), result);
}
default:
Q_ASSERT(false);
}
return qtscript_QPixmapCache_throw_ambiguity_error_helper(context,
qtscript_QPixmapCache_function_names[_id+8],
qtscript_QPixmapCache_function_signatures[_id+8]);
}
static QScriptValue qtscript_QPixmapCache_static_call(QScriptContext *context, QScriptEngine *)
{
uint _id = context->callee().data().toUInt32();
Q_ASSERT((_id & 0xFFFF0000) == 0xBABE0000);
_id &= 0x0000FFFF;
switch (_id) {
case 0:
if (context->thisObject().strictlyEquals(context->engine()->globalObject())) {
return context->throwError(QString::fromLatin1("QPixmapCache(): Did you forget to construct with 'new'?"));
}
if (context->argumentCount() == 0) {
QtScriptShell_QPixmapCache* _q_cpp_result = new QtScriptShell_QPixmapCache();
QScriptValue _q_result = context->engine()->newVariant(context->thisObject(), qVariantFromValue((QPixmapCache*)_q_cpp_result));
_q_cpp_result->__qtscript_self = _q_result;
return _q_result;
}
break;
case 1:
if (context->argumentCount() == 0) {
int _q_result = QPixmapCache::cacheLimit();
return QScriptValue(context->engine(), _q_result);
}
break;
case 2:
if (context->argumentCount() == 0) {
QPixmapCache::clear();
return context->engine()->undefinedValue();
}
break;
case 3:
if (context->argumentCount() == 2) {
if ((qMetaTypeId<QPixmapCache::Key>() == context->argument(0).toVariant().userType())
&& qscriptvalue_cast<QPixmap*>(context->argument(1))) {
QPixmapCache::Key _q_arg0 = qscriptvalue_cast<QPixmapCache::Key>(context->argument(0));
QPixmap* _q_arg1 = qscriptvalue_cast<QPixmap*>(context->argument(1));
bool _q_result = QPixmapCache::find(_q_arg0, _q_arg1);
return QScriptValue(context->engine(), _q_result);
} else if (context->argument(0).isString()
&& (qMetaTypeId<QPixmap>() == context->argument(1).toVariant().userType())) {
QString _q_arg0 = context->argument(0).toString();
QPixmap _q_arg1 = qscriptvalue_cast<QPixmap>(context->argument(1));
bool _q_result = QPixmapCache::find(_q_arg0, _q_arg1);
return QScriptValue(context->engine(), _q_result);
}
}
break;
case 4:
if (context->argumentCount() == 1) {
QPixmap _q_arg0 = qscriptvalue_cast<QPixmap>(context->argument(0));
QPixmapCache::Key _q_result = QPixmapCache::insert(_q_arg0);
return qScriptValueFromValue(context->engine(), _q_result);
}
if (context->argumentCount() == 2) {
QString _q_arg0 = context->argument(0).toString();
QPixmap _q_arg1 = qscriptvalue_cast<QPixmap>(context->argument(1));
bool _q_result = QPixmapCache::insert(_q_arg0, _q_arg1);
return QScriptValue(context->engine(), _q_result);
}
break;
case 5:
if (context->argumentCount() == 1) {
if ((qMetaTypeId<QPixmapCache::Key>() == context->argument(0).toVariant().userType())) {
QPixmapCache::Key _q_arg0 = qscriptvalue_cast<QPixmapCache::Key>(context->argument(0));
QPixmapCache::remove(_q_arg0);
return context->engine()->undefinedValue();
} else if (context->argument(0).isString()) {
QString _q_arg0 = context->argument(0).toString();
QPixmapCache::remove(_q_arg0);
return context->engine()->undefinedValue();
}
}
break;
case 6:
if (context->argumentCount() == 2) {
QPixmapCache::Key _q_arg0 = qscriptvalue_cast<QPixmapCache::Key>(context->argument(0));
QPixmap _q_arg1 = qscriptvalue_cast<QPixmap>(context->argument(1));
bool _q_result = QPixmapCache::replace(_q_arg0, _q_arg1);
return QScriptValue(context->engine(), _q_result);
}
break;
case 7:
if (context->argumentCount() == 1) {
int _q_arg0 = context->argument(0).toInt32();
QPixmapCache::setCacheLimit(_q_arg0);
return context->engine()->undefinedValue();
}
break;
default:
Q_ASSERT(false);
}
return qtscript_QPixmapCache_throw_ambiguity_error_helper(context,
qtscript_QPixmapCache_function_names[_id],
qtscript_QPixmapCache_function_signatures[_id]);
}
QScriptValue qtscript_create_QPixmapCache_class(QScriptEngine *engine)
{
engine->setDefaultPrototype(qMetaTypeId<QPixmapCache*>(), QScriptValue());
QScriptValue proto = engine->newVariant(qVariantFromValue((QPixmapCache*)0));
engine->setDefaultPrototype(qMetaTypeId<QPixmapCache*>(), proto);
QScriptValue ctor = engine->newFunction(qtscript_QPixmapCache_static_call, proto, qtscript_QPixmapCache_function_lengths[0]);
ctor.setData(QScriptValue(engine, uint(0xBABE0000 + 0)));
for (int i = 0; i < 7; ++i) {
QScriptValue fun = engine->newFunction(qtscript_QPixmapCache_static_call,
qtscript_QPixmapCache_function_lengths[i+1]);
fun.setData(QScriptValue(engine, uint(0xBABE0000 + i+1)));
ctor.setProperty(QString::fromLatin1(qtscript_QPixmapCache_function_names[i+1]),
fun, QScriptValue::SkipInEnumeration);
}
return ctor;
}
| {
"pile_set_name": "Github"
} |
package db
import (
"cms-srv/entity"
"database/sql"
)
func SelectAllMovieHall(page int64, num int64) ([]*entity.MovieHall, error) {
movieHalls := []*entity.MovieHall{}
err := db.Select(&movieHalls, "SELECT * FROM `movie_hall` ORDER BY `mh_id` DESC LIMIT ?,?", (page-1)*num, page*num)
if err == sql.ErrNoRows {
return nil, nil
}
return movieHalls, err
}
func SelectAllMovieHallBycinemaID(page int64, num int64, cinemaID int64) ([]*entity.MovieHall, error) {
movieHalls := []*entity.MovieHall{}
err := db.Select(&movieHalls, "SELECT * FROM `movie_hall` WHERE `cinema_id` = ? ORDER BY `mh_id` DESC LIMIT ?,?", cinemaID, (page-1)*num, page*num)
if err == sql.ErrNoRows {
return nil, nil
}
return movieHalls, err
}
func SelectAllMovieHallByMHID(mhId int64) (*entity.MovieHall, error) {
movieHall := entity.MovieHall{}
err := db.Get(&movieHall, "SELECT * FROM `movie_hall` WHERE `mh_id` = ? LIMIT 1", mhId)
if err == sql.ErrNoRows {
return nil, nil
}
return &movieHall, err
}
func SelectMovieHallTotalByCinemaID(cinemaID int64) (int64, error) {
var total int64
err := db.Get(&total, "SELECT count(*) FROM `movie_hall` WHERE `cinema_id` = ? ", cinemaID)
if err == sql.ErrNoRows {
return 0, nil
}
return total, err
}
func SelectMovieHallTotal() (int64, error) {
var total int64
err := db.Get(&total, "SELECT count(*) FROM `movie_hall`")
if err == sql.ErrNoRows {
return 0, nil
}
return total, err
}
func AddMovieHall(movieHall *entity.MovieHall) error {
_, err := db.Exec("INSERT INTO `movie_hall`(`mh_name`,`mh_address`,`cinema_id`) VALUES(?,?,?)",
movieHall.MhName, movieHall.MhAddress, movieHall.CinemaId)
if err == sql.ErrNoRows {
return nil
}
return err
}
func DeleteMovieHall(mhID int64) error {
_, err := db.Exec("DELETE FROM `movie_hall` WHERE `mh_id` = ?", mhID)
if err == sql.ErrNoRows {
return nil
}
return err
}
func UpdateMovieHall(movieHall *entity.MovieHall) error {
_, err := db.Exec("UPDATE `movie_hall` SET `mh_name` = ?,`mh_address` = ?,`cinema_id` = ? WHERE `mh_id` = ?",
movieHall.MhName, movieHall.MhAddress, movieHall.CinemaId, movieHall.MhID)
if err == sql.ErrNoRows {
return nil
}
return err
}
func SelectAllMovieHallsBycinemaID(cinemaID int64) ([]*entity.MovieHall, error) {
movieHalls := []*entity.MovieHall{}
err := db.Select(&movieHalls, "SELECT * FROM `movie_hall` WHERE `cinema_id` = ? ORDER BY `mh_id` DESC", cinemaID)
if err == sql.ErrNoRows {
return nil, nil
}
return movieHalls, err
}
func SelectMovieHallHallName(mhID int64) (string, error) {
var hallName string
err := db.Get(&hallName, "SELECT `mh_name` FROM `movie_hall` WHERE `mh_id` = ? ", mhID)
if err == sql.ErrNoRows {
return hallName, nil
}
return hallName, err
}
| {
"pile_set_name": "Github"
} |
package com.therealdanvega;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ConfigpropsApplication.class)
@WebAppConfiguration
public class ConfigpropsApplicationTests {
@Test
public void contextLoads() {
}
}
| {
"pile_set_name": "Github"
} |
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_IO_WKT_DETAIL_PREFIX_HPP
#define BOOST_GEOMETRY_IO_WKT_DETAIL_PREFIX_HPP
namespace boost { namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace wkt
{
struct prefix_null
{
static inline const char* apply() { return ""; }
};
struct prefix_point
{
static inline const char* apply() { return "POINT"; }
};
struct prefix_polygon
{
static inline const char* apply() { return "POLYGON"; }
};
struct prefix_linestring
{
static inline const char* apply() { return "LINESTRING"; }
};
struct prefix_multipoint
{
static inline const char* apply() { return "MULTIPOINT"; }
};
struct prefix_multilinestring
{
static inline const char* apply() { return "MULTILINESTRING"; }
};
struct prefix_multipolygon
{
static inline const char* apply() { return "MULTIPOLYGON"; }
};
}} // namespace wkt::impl
#endif
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_IO_WKT_DETAIL_PREFIX_HPP
| {
"pile_set_name": "Github"
} |
lf
lf
lf
lf
lf
| {
"pile_set_name": "Github"
} |
/*
* fs/cifs/transport.c
*
* Copyright (C) International Business Machines Corp., 2002,2008
* Author(s): Steve French ([email protected])
* Jeremy Allison ([email protected]) 2006.
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/fs.h>
#include <linux/list.h>
#include <linux/gfp.h>
#include <linux/wait.h>
#include <linux/net.h>
#include <linux/delay.h>
#include <linux/freezer.h>
#include <linux/tcp.h>
#include <linux/bvec.h>
#include <linux/highmem.h>
#include <linux/uaccess.h>
#include <asm/processor.h>
#include <linux/mempool.h>
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsproto.h"
#include "cifs_debug.h"
void
cifs_wake_up_task(struct mid_q_entry *mid)
{
wake_up_process(mid->callback_data);
}
struct mid_q_entry *
AllocMidQEntry(const struct smb_hdr *smb_buffer, struct TCP_Server_Info *server)
{
struct mid_q_entry *temp;
if (server == NULL) {
cifs_dbg(VFS, "Null TCP session in AllocMidQEntry\n");
return NULL;
}
temp = mempool_alloc(cifs_mid_poolp, GFP_NOFS);
if (temp == NULL)
return temp;
else {
memset(temp, 0, sizeof(struct mid_q_entry));
temp->mid = get_mid(smb_buffer);
temp->pid = current->pid;
temp->command = cpu_to_le16(smb_buffer->Command);
cifs_dbg(FYI, "For smb_command %d\n", smb_buffer->Command);
/* do_gettimeofday(&temp->when_sent);*/ /* easier to use jiffies */
/* when mid allocated can be before when sent */
temp->when_alloc = jiffies;
temp->server = server;
/*
* The default is for the mid to be synchronous, so the
* default callback just wakes up the current task.
*/
temp->callback = cifs_wake_up_task;
temp->callback_data = current;
}
atomic_inc(&midCount);
temp->mid_state = MID_REQUEST_ALLOCATED;
return temp;
}
void
DeleteMidQEntry(struct mid_q_entry *midEntry)
{
#ifdef CONFIG_CIFS_STATS2
__le16 command = midEntry->server->vals->lock_cmd;
unsigned long now;
#endif
midEntry->mid_state = MID_FREE;
atomic_dec(&midCount);
if (midEntry->large_buf)
cifs_buf_release(midEntry->resp_buf);
else
cifs_small_buf_release(midEntry->resp_buf);
#ifdef CONFIG_CIFS_STATS2
now = jiffies;
/* commands taking longer than one second are indications that
something is wrong, unless it is quite a slow link or server */
if ((now - midEntry->when_alloc) > HZ) {
if ((cifsFYI & CIFS_TIMER) && (midEntry->command != command)) {
pr_debug(" CIFS slow rsp: cmd %d mid %llu",
midEntry->command, midEntry->mid);
pr_info(" A: 0x%lx S: 0x%lx R: 0x%lx\n",
now - midEntry->when_alloc,
now - midEntry->when_sent,
now - midEntry->when_received);
}
}
#endif
mempool_free(midEntry, cifs_mid_poolp);
}
void
cifs_delete_mid(struct mid_q_entry *mid)
{
spin_lock(&GlobalMid_Lock);
list_del(&mid->qhead);
spin_unlock(&GlobalMid_Lock);
DeleteMidQEntry(mid);
}
/*
* smb_send_kvec - send an array of kvecs to the server
* @server: Server to send the data to
* @smb_msg: Message to send
* @sent: amount of data sent on socket is stored here
*
* Our basic "send data to server" function. Should be called with srv_mutex
* held. The caller is responsible for handling the results.
*/
static int
smb_send_kvec(struct TCP_Server_Info *server, struct msghdr *smb_msg,
size_t *sent)
{
int rc = 0;
int retries = 0;
struct socket *ssocket = server->ssocket;
*sent = 0;
smb_msg->msg_name = (struct sockaddr *) &server->dstaddr;
smb_msg->msg_namelen = sizeof(struct sockaddr);
smb_msg->msg_control = NULL;
smb_msg->msg_controllen = 0;
if (server->noblocksnd)
smb_msg->msg_flags = MSG_DONTWAIT + MSG_NOSIGNAL;
else
smb_msg->msg_flags = MSG_NOSIGNAL;
while (msg_data_left(smb_msg)) {
/*
* If blocking send, we try 3 times, since each can block
* for 5 seconds. For nonblocking we have to try more
* but wait increasing amounts of time allowing time for
* socket to clear. The overall time we wait in either
* case to send on the socket is about 15 seconds.
* Similarly we wait for 15 seconds for a response from
* the server in SendReceive[2] for the server to send
* a response back for most types of requests (except
* SMB Write past end of file which can be slow, and
* blocking lock operations). NFS waits slightly longer
* than CIFS, but this can make it take longer for
* nonresponsive servers to be detected and 15 seconds
* is more than enough time for modern networks to
* send a packet. In most cases if we fail to send
* after the retries we will kill the socket and
* reconnect which may clear the network problem.
*/
rc = sock_sendmsg(ssocket, smb_msg);
if (rc == -EAGAIN) {
retries++;
if (retries >= 14 ||
(!server->noblocksnd && (retries > 2))) {
cifs_dbg(VFS, "sends on sock %p stuck for 15 seconds\n",
ssocket);
return -EAGAIN;
}
msleep(1 << retries);
continue;
}
if (rc < 0)
return rc;
if (rc == 0) {
/* should never happen, letting socket clear before
retrying is our only obvious option here */
cifs_dbg(VFS, "tcp sent no data\n");
msleep(500);
continue;
}
/* send was at least partially successful */
*sent += rc;
retries = 0; /* in case we get ENOSPC on the next send */
}
return 0;
}
static unsigned long
rqst_len(struct smb_rqst *rqst)
{
unsigned int i;
struct kvec *iov = rqst->rq_iov;
unsigned long buflen = 0;
/* total up iov array first */
for (i = 0; i < rqst->rq_nvec; i++)
buflen += iov[i].iov_len;
/* add in the page array if there is one */
if (rqst->rq_npages) {
buflen += rqst->rq_pagesz * (rqst->rq_npages - 1);
buflen += rqst->rq_tailsz;
}
return buflen;
}
static int
__smb_send_rqst(struct TCP_Server_Info *server, struct smb_rqst *rqst)
{
int rc;
struct kvec *iov = rqst->rq_iov;
int n_vec = rqst->rq_nvec;
unsigned int smb_buf_length = get_rfc1002_length(iov[0].iov_base);
unsigned long send_length;
unsigned int i;
size_t total_len = 0, sent, size;
struct socket *ssocket = server->ssocket;
struct msghdr smb_msg;
int val = 1;
if (ssocket == NULL)
return -ENOTSOCK;
/* sanity check send length */
send_length = rqst_len(rqst);
if (send_length != smb_buf_length + 4) {
WARN(1, "Send length mismatch(send_length=%lu smb_buf_length=%u)\n",
send_length, smb_buf_length);
return -EIO;
}
if (n_vec < 2)
return -EIO;
cifs_dbg(FYI, "Sending smb: smb_len=%u\n", smb_buf_length);
dump_smb(iov[0].iov_base, iov[0].iov_len);
dump_smb(iov[1].iov_base, iov[1].iov_len);
/* cork the socket */
kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,
(char *)&val, sizeof(val));
size = 0;
for (i = 0; i < n_vec; i++)
size += iov[i].iov_len;
iov_iter_kvec(&smb_msg.msg_iter, WRITE | ITER_KVEC, iov, n_vec, size);
rc = smb_send_kvec(server, &smb_msg, &sent);
if (rc < 0)
goto uncork;
total_len += sent;
/* now walk the page array and send each page in it */
for (i = 0; i < rqst->rq_npages; i++) {
size_t len = i == rqst->rq_npages - 1
? rqst->rq_tailsz
: rqst->rq_pagesz;
struct bio_vec bvec = {
.bv_page = rqst->rq_pages[i],
.bv_len = len
};
iov_iter_bvec(&smb_msg.msg_iter, WRITE | ITER_BVEC,
&bvec, 1, len);
rc = smb_send_kvec(server, &smb_msg, &sent);
if (rc < 0)
break;
total_len += sent;
}
uncork:
/* uncork it */
val = 0;
kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK,
(char *)&val, sizeof(val));
if ((total_len > 0) && (total_len != smb_buf_length + 4)) {
cifs_dbg(FYI, "partial send (wanted=%u sent=%zu): terminating session\n",
smb_buf_length + 4, total_len);
/*
* If we have only sent part of an SMB then the next SMB could
* be taken as the remainder of this one. We need to kill the
* socket so the server throws away the partial SMB
*/
server->tcpStatus = CifsNeedReconnect;
}
if (rc < 0 && rc != -EINTR)
cifs_dbg(VFS, "Error %d sending data on socket to server\n",
rc);
else
rc = 0;
return rc;
}
static int
smb_send_rqst(struct TCP_Server_Info *server, struct smb_rqst *rqst, int flags)
{
struct smb_rqst cur_rqst;
int rc;
if (!(flags & CIFS_TRANSFORM_REQ))
return __smb_send_rqst(server, rqst);
if (!server->ops->init_transform_rq ||
!server->ops->free_transform_rq) {
cifs_dbg(VFS, "Encryption requested but transform callbacks are missed\n");
return -EIO;
}
rc = server->ops->init_transform_rq(server, &cur_rqst, rqst);
if (rc)
return rc;
rc = __smb_send_rqst(server, &cur_rqst);
server->ops->free_transform_rq(&cur_rqst);
return rc;
}
int
smb_send(struct TCP_Server_Info *server, struct smb_hdr *smb_buffer,
unsigned int smb_buf_length)
{
struct kvec iov[2];
struct smb_rqst rqst = { .rq_iov = iov,
.rq_nvec = 2 };
iov[0].iov_base = smb_buffer;
iov[0].iov_len = 4;
iov[1].iov_base = (char *)smb_buffer + 4;
iov[1].iov_len = smb_buf_length;
return __smb_send_rqst(server, &rqst);
}
static int
wait_for_free_credits(struct TCP_Server_Info *server, const int timeout,
int *credits)
{
int rc;
spin_lock(&server->req_lock);
if (timeout == CIFS_ASYNC_OP) {
/* oplock breaks must not be held up */
server->in_flight++;
*credits -= 1;
spin_unlock(&server->req_lock);
return 0;
}
while (1) {
if (*credits <= 0) {
spin_unlock(&server->req_lock);
cifs_num_waiters_inc(server);
rc = wait_event_killable(server->request_q,
has_credits(server, credits));
cifs_num_waiters_dec(server);
if (rc)
return rc;
spin_lock(&server->req_lock);
} else {
if (server->tcpStatus == CifsExiting) {
spin_unlock(&server->req_lock);
return -ENOENT;
}
/*
* Can not count locking commands against total
* as they are allowed to block on server.
*/
/* update # of requests on the wire to server */
if (timeout != CIFS_BLOCKING_OP) {
*credits -= 1;
server->in_flight++;
}
spin_unlock(&server->req_lock);
break;
}
}
return 0;
}
static int
wait_for_free_request(struct TCP_Server_Info *server, const int timeout,
const int optype)
{
int *val;
val = server->ops->get_credits_field(server, optype);
/* Since an echo is already inflight, no need to wait to send another */
if (*val <= 0 && optype == CIFS_ECHO_OP)
return -EAGAIN;
return wait_for_free_credits(server, timeout, val);
}
int
cifs_wait_mtu_credits(struct TCP_Server_Info *server, unsigned int size,
unsigned int *num, unsigned int *credits)
{
*num = size;
*credits = 0;
return 0;
}
static int allocate_mid(struct cifs_ses *ses, struct smb_hdr *in_buf,
struct mid_q_entry **ppmidQ)
{
if (ses->server->tcpStatus == CifsExiting) {
return -ENOENT;
}
if (ses->server->tcpStatus == CifsNeedReconnect) {
cifs_dbg(FYI, "tcp session dead - return to caller to retry\n");
return -EAGAIN;
}
if (ses->status == CifsNew) {
if ((in_buf->Command != SMB_COM_SESSION_SETUP_ANDX) &&
(in_buf->Command != SMB_COM_NEGOTIATE))
return -EAGAIN;
/* else ok - we are setting up session */
}
if (ses->status == CifsExiting) {
/* check if SMB session is bad because we are setting it up */
if (in_buf->Command != SMB_COM_LOGOFF_ANDX)
return -EAGAIN;
/* else ok - we are shutting down session */
}
*ppmidQ = AllocMidQEntry(in_buf, ses->server);
if (*ppmidQ == NULL)
return -ENOMEM;
spin_lock(&GlobalMid_Lock);
list_add_tail(&(*ppmidQ)->qhead, &ses->server->pending_mid_q);
spin_unlock(&GlobalMid_Lock);
return 0;
}
static int
wait_for_response(struct TCP_Server_Info *server, struct mid_q_entry *midQ)
{
int error;
error = wait_event_freezekillable_unsafe(server->response_q,
midQ->mid_state != MID_REQUEST_SUBMITTED);
if (error < 0)
return -ERESTARTSYS;
return 0;
}
struct mid_q_entry *
cifs_setup_async_request(struct TCP_Server_Info *server, struct smb_rqst *rqst)
{
int rc;
struct smb_hdr *hdr = (struct smb_hdr *)rqst->rq_iov[0].iov_base;
struct mid_q_entry *mid;
if (rqst->rq_iov[0].iov_len != 4 ||
rqst->rq_iov[0].iov_base + 4 != rqst->rq_iov[1].iov_base)
return ERR_PTR(-EIO);
/* enable signing if server requires it */
if (server->sign)
hdr->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
mid = AllocMidQEntry(hdr, server);
if (mid == NULL)
return ERR_PTR(-ENOMEM);
rc = cifs_sign_rqst(rqst, server, &mid->sequence_number);
if (rc) {
DeleteMidQEntry(mid);
return ERR_PTR(rc);
}
return mid;
}
/*
* Send a SMB request and set the callback function in the mid to handle
* the result. Caller is responsible for dealing with timeouts.
*/
int
cifs_call_async(struct TCP_Server_Info *server, struct smb_rqst *rqst,
mid_receive_t *receive, mid_callback_t *callback,
mid_handle_t *handle, void *cbdata, const int flags)
{
int rc, timeout, optype;
struct mid_q_entry *mid;
unsigned int credits = 0;
timeout = flags & CIFS_TIMEOUT_MASK;
optype = flags & CIFS_OP_MASK;
if ((flags & CIFS_HAS_CREDITS) == 0) {
rc = wait_for_free_request(server, timeout, optype);
if (rc)
return rc;
credits = 1;
}
mutex_lock(&server->srv_mutex);
mid = server->ops->setup_async_request(server, rqst);
if (IS_ERR(mid)) {
mutex_unlock(&server->srv_mutex);
add_credits_and_wake_if(server, credits, optype);
return PTR_ERR(mid);
}
mid->receive = receive;
mid->callback = callback;
mid->callback_data = cbdata;
mid->handle = handle;
mid->mid_state = MID_REQUEST_SUBMITTED;
/* put it on the pending_mid_q */
spin_lock(&GlobalMid_Lock);
list_add_tail(&mid->qhead, &server->pending_mid_q);
spin_unlock(&GlobalMid_Lock);
cifs_in_send_inc(server);
rc = smb_send_rqst(server, rqst, flags);
cifs_in_send_dec(server);
cifs_save_when_sent(mid);
if (rc < 0) {
server->sequence_number -= 2;
cifs_delete_mid(mid);
}
mutex_unlock(&server->srv_mutex);
if (rc == 0)
return 0;
add_credits_and_wake_if(server, credits, optype);
return rc;
}
/*
*
* Send an SMB Request. No response info (other than return code)
* needs to be parsed.
*
* flags indicate the type of request buffer and how long to wait
* and whether to log NT STATUS code (error) before mapping it to POSIX error
*
*/
int
SendReceiveNoRsp(const unsigned int xid, struct cifs_ses *ses,
char *in_buf, int flags)
{
int rc;
struct kvec iov[1];
struct kvec rsp_iov;
int resp_buf_type;
iov[0].iov_base = in_buf;
iov[0].iov_len = get_rfc1002_length(in_buf) + 4;
flags |= CIFS_NO_RESP;
rc = SendReceive2(xid, ses, iov, 1, &resp_buf_type, flags, &rsp_iov);
cifs_dbg(NOISY, "SendRcvNoRsp flags %d rc %d\n", flags, rc);
return rc;
}
static int
cifs_sync_mid_result(struct mid_q_entry *mid, struct TCP_Server_Info *server)
{
int rc = 0;
cifs_dbg(FYI, "%s: cmd=%d mid=%llu state=%d\n",
__func__, le16_to_cpu(mid->command), mid->mid, mid->mid_state);
spin_lock(&GlobalMid_Lock);
switch (mid->mid_state) {
case MID_RESPONSE_RECEIVED:
spin_unlock(&GlobalMid_Lock);
return rc;
case MID_RETRY_NEEDED:
rc = -EAGAIN;
break;
case MID_RESPONSE_MALFORMED:
rc = -EIO;
break;
case MID_SHUTDOWN:
rc = -EHOSTDOWN;
break;
default:
list_del_init(&mid->qhead);
cifs_dbg(VFS, "%s: invalid mid state mid=%llu state=%d\n",
__func__, mid->mid, mid->mid_state);
rc = -EIO;
}
spin_unlock(&GlobalMid_Lock);
mutex_lock(&server->srv_mutex);
DeleteMidQEntry(mid);
mutex_unlock(&server->srv_mutex);
return rc;
}
static inline int
send_cancel(struct TCP_Server_Info *server, struct smb_rqst *rqst,
struct mid_q_entry *mid)
{
return server->ops->send_cancel ?
server->ops->send_cancel(server, rqst, mid) : 0;
}
int
cifs_check_receive(struct mid_q_entry *mid, struct TCP_Server_Info *server,
bool log_error)
{
unsigned int len = get_rfc1002_length(mid->resp_buf) + 4;
dump_smb(mid->resp_buf, min_t(u32, 92, len));
/* convert the length into a more usable form */
if (server->sign) {
struct kvec iov[2];
int rc = 0;
struct smb_rqst rqst = { .rq_iov = iov,
.rq_nvec = 2 };
iov[0].iov_base = mid->resp_buf;
iov[0].iov_len = 4;
iov[1].iov_base = (char *)mid->resp_buf + 4;
iov[1].iov_len = len - 4;
/* FIXME: add code to kill session */
rc = cifs_verify_signature(&rqst, server,
mid->sequence_number);
if (rc)
cifs_dbg(VFS, "SMB signature verification returned error = %d\n",
rc);
}
/* BB special case reconnect tid and uid here? */
return map_smb_to_linux_error(mid->resp_buf, log_error);
}
struct mid_q_entry *
cifs_setup_request(struct cifs_ses *ses, struct smb_rqst *rqst)
{
int rc;
struct smb_hdr *hdr = (struct smb_hdr *)rqst->rq_iov[0].iov_base;
struct mid_q_entry *mid;
if (rqst->rq_iov[0].iov_len != 4 ||
rqst->rq_iov[0].iov_base + 4 != rqst->rq_iov[1].iov_base)
return ERR_PTR(-EIO);
rc = allocate_mid(ses, hdr, &mid);
if (rc)
return ERR_PTR(rc);
rc = cifs_sign_rqst(rqst, ses->server, &mid->sequence_number);
if (rc) {
cifs_delete_mid(mid);
return ERR_PTR(rc);
}
return mid;
}
int
cifs_send_recv(const unsigned int xid, struct cifs_ses *ses,
struct smb_rqst *rqst, int *resp_buf_type, const int flags,
struct kvec *resp_iov)
{
int rc = 0;
int timeout, optype;
struct mid_q_entry *midQ;
unsigned int credits = 1;
char *buf;
timeout = flags & CIFS_TIMEOUT_MASK;
optype = flags & CIFS_OP_MASK;
*resp_buf_type = CIFS_NO_BUFFER; /* no response buf yet */
if ((ses == NULL) || (ses->server == NULL)) {
cifs_dbg(VFS, "Null session\n");
return -EIO;
}
if (ses->server->tcpStatus == CifsExiting)
return -ENOENT;
/*
* Ensure that we do not send more than 50 overlapping requests
* to the same server. We may make this configurable later or
* use ses->maxReq.
*/
rc = wait_for_free_request(ses->server, timeout, optype);
if (rc)
return rc;
/*
* Make sure that we sign in the same order that we send on this socket
* and avoid races inside tcp sendmsg code that could cause corruption
* of smb data.
*/
mutex_lock(&ses->server->srv_mutex);
midQ = ses->server->ops->setup_request(ses, rqst);
if (IS_ERR(midQ)) {
mutex_unlock(&ses->server->srv_mutex);
/* Update # of requests on wire to server */
add_credits(ses->server, 1, optype);
return PTR_ERR(midQ);
}
midQ->mid_state = MID_REQUEST_SUBMITTED;
cifs_in_send_inc(ses->server);
rc = smb_send_rqst(ses->server, rqst, flags);
cifs_in_send_dec(ses->server);
cifs_save_when_sent(midQ);
if (rc < 0)
ses->server->sequence_number -= 2;
mutex_unlock(&ses->server->srv_mutex);
if (rc < 0)
goto out;
if (timeout == CIFS_ASYNC_OP)
goto out;
rc = wait_for_response(ses->server, midQ);
if (rc != 0) {
cifs_dbg(FYI, "Cancelling wait for mid %llu\n", midQ->mid);
send_cancel(ses->server, rqst, midQ);
spin_lock(&GlobalMid_Lock);
if (midQ->mid_state == MID_REQUEST_SUBMITTED) {
midQ->mid_flags |= MID_WAIT_CANCELLED;
midQ->callback = DeleteMidQEntry;
spin_unlock(&GlobalMid_Lock);
add_credits(ses->server, 1, optype);
return rc;
}
spin_unlock(&GlobalMid_Lock);
}
rc = cifs_sync_mid_result(midQ, ses->server);
if (rc != 0) {
add_credits(ses->server, 1, optype);
return rc;
}
if (!midQ->resp_buf || midQ->mid_state != MID_RESPONSE_RECEIVED) {
rc = -EIO;
cifs_dbg(FYI, "Bad MID state?\n");
goto out;
}
buf = (char *)midQ->resp_buf;
resp_iov->iov_base = buf;
resp_iov->iov_len = get_rfc1002_length(buf) + 4;
if (midQ->large_buf)
*resp_buf_type = CIFS_LARGE_BUFFER;
else
*resp_buf_type = CIFS_SMALL_BUFFER;
credits = ses->server->ops->get_credits(midQ);
rc = ses->server->ops->check_receive(midQ, ses->server,
flags & CIFS_LOG_ERROR);
/* mark it so buf will not be freed by cifs_delete_mid */
if ((flags & CIFS_NO_RESP) == 0)
midQ->resp_buf = NULL;
out:
cifs_delete_mid(midQ);
add_credits(ses->server, credits, optype);
return rc;
}
int
SendReceive2(const unsigned int xid, struct cifs_ses *ses,
struct kvec *iov, int n_vec, int *resp_buf_type /* ret */,
const int flags, struct kvec *resp_iov)
{
struct smb_rqst rqst;
struct kvec *new_iov;
int rc;
new_iov = kmalloc(sizeof(struct kvec) * (n_vec + 1), GFP_KERNEL);
if (!new_iov)
return -ENOMEM;
/* 1st iov is a RFC1001 length followed by the rest of the packet */
memcpy(new_iov + 1, iov, (sizeof(struct kvec) * n_vec));
new_iov[0].iov_base = new_iov[1].iov_base;
new_iov[0].iov_len = 4;
new_iov[1].iov_base += 4;
new_iov[1].iov_len -= 4;
memset(&rqst, 0, sizeof(struct smb_rqst));
rqst.rq_iov = new_iov;
rqst.rq_nvec = n_vec + 1;
rc = cifs_send_recv(xid, ses, &rqst, resp_buf_type, flags, resp_iov);
kfree(new_iov);
return rc;
}
int
SendReceive(const unsigned int xid, struct cifs_ses *ses,
struct smb_hdr *in_buf, struct smb_hdr *out_buf,
int *pbytes_returned, const int timeout)
{
int rc = 0;
struct mid_q_entry *midQ;
unsigned int len = be32_to_cpu(in_buf->smb_buf_length);
struct kvec iov = { .iov_base = in_buf, .iov_len = len };
struct smb_rqst rqst = { .rq_iov = &iov, .rq_nvec = 1 };
if (ses == NULL) {
cifs_dbg(VFS, "Null smb session\n");
return -EIO;
}
if (ses->server == NULL) {
cifs_dbg(VFS, "Null tcp session\n");
return -EIO;
}
if (ses->server->tcpStatus == CifsExiting)
return -ENOENT;
/* Ensure that we do not send more than 50 overlapping requests
to the same server. We may make this configurable later or
use ses->maxReq */
if (len > CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4) {
cifs_dbg(VFS, "Illegal length, greater than maximum frame, %d\n",
len);
return -EIO;
}
rc = wait_for_free_request(ses->server, timeout, 0);
if (rc)
return rc;
/* make sure that we sign in the same order that we send on this socket
and avoid races inside tcp sendmsg code that could cause corruption
of smb data */
mutex_lock(&ses->server->srv_mutex);
rc = allocate_mid(ses, in_buf, &midQ);
if (rc) {
mutex_unlock(&ses->server->srv_mutex);
/* Update # of requests on wire to server */
add_credits(ses->server, 1, 0);
return rc;
}
rc = cifs_sign_smb(in_buf, ses->server, &midQ->sequence_number);
if (rc) {
mutex_unlock(&ses->server->srv_mutex);
goto out;
}
midQ->mid_state = MID_REQUEST_SUBMITTED;
cifs_in_send_inc(ses->server);
rc = smb_send(ses->server, in_buf, len);
cifs_in_send_dec(ses->server);
cifs_save_when_sent(midQ);
if (rc < 0)
ses->server->sequence_number -= 2;
mutex_unlock(&ses->server->srv_mutex);
if (rc < 0)
goto out;
if (timeout == CIFS_ASYNC_OP)
goto out;
rc = wait_for_response(ses->server, midQ);
if (rc != 0) {
send_cancel(ses->server, &rqst, midQ);
spin_lock(&GlobalMid_Lock);
if (midQ->mid_state == MID_REQUEST_SUBMITTED) {
/* no longer considered to be "in-flight" */
midQ->callback = DeleteMidQEntry;
spin_unlock(&GlobalMid_Lock);
add_credits(ses->server, 1, 0);
return rc;
}
spin_unlock(&GlobalMid_Lock);
}
rc = cifs_sync_mid_result(midQ, ses->server);
if (rc != 0) {
add_credits(ses->server, 1, 0);
return rc;
}
if (!midQ->resp_buf || !out_buf ||
midQ->mid_state != MID_RESPONSE_RECEIVED) {
rc = -EIO;
cifs_dbg(VFS, "Bad MID state?\n");
goto out;
}
*pbytes_returned = get_rfc1002_length(midQ->resp_buf);
memcpy(out_buf, midQ->resp_buf, *pbytes_returned + 4);
rc = cifs_check_receive(midQ, ses->server, 0);
out:
cifs_delete_mid(midQ);
add_credits(ses->server, 1, 0);
return rc;
}
/* We send a LOCKINGX_CANCEL_LOCK to cause the Windows
blocking lock to return. */
static int
send_lock_cancel(const unsigned int xid, struct cifs_tcon *tcon,
struct smb_hdr *in_buf,
struct smb_hdr *out_buf)
{
int bytes_returned;
struct cifs_ses *ses = tcon->ses;
LOCK_REQ *pSMB = (LOCK_REQ *)in_buf;
/* We just modify the current in_buf to change
the type of lock from LOCKING_ANDX_SHARED_LOCK
or LOCKING_ANDX_EXCLUSIVE_LOCK to
LOCKING_ANDX_CANCEL_LOCK. */
pSMB->LockType = LOCKING_ANDX_CANCEL_LOCK|LOCKING_ANDX_LARGE_FILES;
pSMB->Timeout = 0;
pSMB->hdr.Mid = get_next_mid(ses->server);
return SendReceive(xid, ses, in_buf, out_buf,
&bytes_returned, 0);
}
int
SendReceiveBlockingLock(const unsigned int xid, struct cifs_tcon *tcon,
struct smb_hdr *in_buf, struct smb_hdr *out_buf,
int *pbytes_returned)
{
int rc = 0;
int rstart = 0;
struct mid_q_entry *midQ;
struct cifs_ses *ses;
unsigned int len = be32_to_cpu(in_buf->smb_buf_length);
struct kvec iov = { .iov_base = in_buf, .iov_len = len };
struct smb_rqst rqst = { .rq_iov = &iov, .rq_nvec = 1 };
if (tcon == NULL || tcon->ses == NULL) {
cifs_dbg(VFS, "Null smb session\n");
return -EIO;
}
ses = tcon->ses;
if (ses->server == NULL) {
cifs_dbg(VFS, "Null tcp session\n");
return -EIO;
}
if (ses->server->tcpStatus == CifsExiting)
return -ENOENT;
/* Ensure that we do not send more than 50 overlapping requests
to the same server. We may make this configurable later or
use ses->maxReq */
if (len > CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4) {
cifs_dbg(VFS, "Illegal length, greater than maximum frame, %d\n",
len);
return -EIO;
}
rc = wait_for_free_request(ses->server, CIFS_BLOCKING_OP, 0);
if (rc)
return rc;
/* make sure that we sign in the same order that we send on this socket
and avoid races inside tcp sendmsg code that could cause corruption
of smb data */
mutex_lock(&ses->server->srv_mutex);
rc = allocate_mid(ses, in_buf, &midQ);
if (rc) {
mutex_unlock(&ses->server->srv_mutex);
return rc;
}
rc = cifs_sign_smb(in_buf, ses->server, &midQ->sequence_number);
if (rc) {
cifs_delete_mid(midQ);
mutex_unlock(&ses->server->srv_mutex);
return rc;
}
midQ->mid_state = MID_REQUEST_SUBMITTED;
cifs_in_send_inc(ses->server);
rc = smb_send(ses->server, in_buf, len);
cifs_in_send_dec(ses->server);
cifs_save_when_sent(midQ);
if (rc < 0)
ses->server->sequence_number -= 2;
mutex_unlock(&ses->server->srv_mutex);
if (rc < 0) {
cifs_delete_mid(midQ);
return rc;
}
/* Wait for a reply - allow signals to interrupt. */
rc = wait_event_interruptible(ses->server->response_q,
(!(midQ->mid_state == MID_REQUEST_SUBMITTED)) ||
((ses->server->tcpStatus != CifsGood) &&
(ses->server->tcpStatus != CifsNew)));
/* Were we interrupted by a signal ? */
if ((rc == -ERESTARTSYS) &&
(midQ->mid_state == MID_REQUEST_SUBMITTED) &&
((ses->server->tcpStatus == CifsGood) ||
(ses->server->tcpStatus == CifsNew))) {
if (in_buf->Command == SMB_COM_TRANSACTION2) {
/* POSIX lock. We send a NT_CANCEL SMB to cause the
blocking lock to return. */
rc = send_cancel(ses->server, &rqst, midQ);
if (rc) {
cifs_delete_mid(midQ);
return rc;
}
} else {
/* Windows lock. We send a LOCKINGX_CANCEL_LOCK
to cause the blocking lock to return. */
rc = send_lock_cancel(xid, tcon, in_buf, out_buf);
/* If we get -ENOLCK back the lock may have
already been removed. Don't exit in this case. */
if (rc && rc != -ENOLCK) {
cifs_delete_mid(midQ);
return rc;
}
}
rc = wait_for_response(ses->server, midQ);
if (rc) {
send_cancel(ses->server, &rqst, midQ);
spin_lock(&GlobalMid_Lock);
if (midQ->mid_state == MID_REQUEST_SUBMITTED) {
/* no longer considered to be "in-flight" */
midQ->callback = DeleteMidQEntry;
spin_unlock(&GlobalMid_Lock);
return rc;
}
spin_unlock(&GlobalMid_Lock);
}
/* We got the response - restart system call. */
rstart = 1;
}
rc = cifs_sync_mid_result(midQ, ses->server);
if (rc != 0)
return rc;
/* rcvd frame is ok */
if (out_buf == NULL || midQ->mid_state != MID_RESPONSE_RECEIVED) {
rc = -EIO;
cifs_dbg(VFS, "Bad MID state?\n");
goto out;
}
*pbytes_returned = get_rfc1002_length(midQ->resp_buf);
memcpy(out_buf, midQ->resp_buf, *pbytes_returned + 4);
rc = cifs_check_receive(midQ, ses->server, 0);
out:
cifs_delete_mid(midQ);
if (rstart && rc == -EACCES)
return -ERESTARTSYS;
return rc;
}
| {
"pile_set_name": "Github"
} |
import pkg
__import__('pkg.a')
__import__('pkg.b')
print pkg.b | {
"pile_set_name": "Github"
} |
/* prmip.c (write MIP solution in printable format) */
/***********************************************************************
* This code is part of GLPK (GNU Linear Programming Kit).
*
* Copyright (C) 2009-2016 Andrew Makhorin, Department for Applied
* Informatics, Moscow Aviation Institute, Moscow, Russia. All rights
* reserved. E-mail: <[email protected]>.
*
* GLPK is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GLPK 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 GLPK. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/
#include "env.h"
#include "prob.h"
#define xfprintf glp_format
int glp_print_mip(glp_prob *P, const char *fname)
{ /* write MIP solution in printable format */
glp_file *fp;
GLPROW *row;
GLPCOL *col;
int i, j, t, ae_ind, re_ind, ret;
double ae_max, re_max;
xprintf("Writing MIP solution to '%s'...\n", fname);
fp = glp_open(fname, "w");
if (fp == NULL)
{ xprintf("Unable to create '%s' - %s\n", fname, get_err_msg());
ret = 1;
goto done;
}
xfprintf(fp, "%-12s%s\n", "Problem:",
P->name == NULL ? "" : P->name);
xfprintf(fp, "%-12s%d\n", "Rows:", P->m);
xfprintf(fp, "%-12s%d (%d integer, %d binary)\n", "Columns:",
P->n, glp_get_num_int(P), glp_get_num_bin(P));
xfprintf(fp, "%-12s%d\n", "Non-zeros:", P->nnz);
t = glp_mip_status(P);
xfprintf(fp, "%-12s%s\n", "Status:",
t == GLP_OPT ? "INTEGER OPTIMAL" :
t == GLP_FEAS ? "INTEGER NON-OPTIMAL" :
t == GLP_NOFEAS ? "INTEGER EMPTY" :
t == GLP_UNDEF ? "INTEGER UNDEFINED" : "???");
xfprintf(fp, "%-12s%s%s%.10g (%s)\n", "Objective:",
P->obj == NULL ? "" : P->obj,
P->obj == NULL ? "" : " = ", P->mip_obj,
P->dir == GLP_MIN ? "MINimum" :
P->dir == GLP_MAX ? "MAXimum" : "???");
xfprintf(fp, "\n");
xfprintf(fp, " No. Row name Activity Lower bound "
" Upper bound\n");
xfprintf(fp, "------ ------------ ------------- ------------- "
"-------------\n");
for (i = 1; i <= P->m; i++)
{ row = P->row[i];
xfprintf(fp, "%6d ", i);
if (row->name == NULL || strlen(row->name) <= 12)
xfprintf(fp, "%-12s ", row->name == NULL ? "" : row->name);
else
xfprintf(fp, "%s\n%20s", row->name, "");
xfprintf(fp, "%3s", "");
xfprintf(fp, "%13.6g ",
fabs(row->mipx) <= 1e-9 ? 0.0 : row->mipx);
if (row->type == GLP_LO || row->type == GLP_DB ||
row->type == GLP_FX)
xfprintf(fp, "%13.6g ", row->lb);
else
xfprintf(fp, "%13s ", "");
if (row->type == GLP_UP || row->type == GLP_DB)
xfprintf(fp, "%13.6g ", row->ub);
else
xfprintf(fp, "%13s ", row->type == GLP_FX ? "=" : "");
xfprintf(fp, "\n");
}
xfprintf(fp, "\n");
xfprintf(fp, " No. Column name Activity Lower bound "
" Upper bound\n");
xfprintf(fp, "------ ------------ ------------- ------------- "
"-------------\n");
for (j = 1; j <= P->n; j++)
{ col = P->col[j];
xfprintf(fp, "%6d ", j);
if (col->name == NULL || strlen(col->name) <= 12)
xfprintf(fp, "%-12s ", col->name == NULL ? "" : col->name);
else
xfprintf(fp, "%s\n%20s", col->name, "");
xfprintf(fp, "%s ",
col->kind == GLP_CV ? " " :
col->kind == GLP_IV ? "*" : "?");
xfprintf(fp, "%13.6g ",
fabs(col->mipx) <= 1e-9 ? 0.0 : col->mipx);
if (col->type == GLP_LO || col->type == GLP_DB ||
col->type == GLP_FX)
xfprintf(fp, "%13.6g ", col->lb);
else
xfprintf(fp, "%13s ", "");
if (col->type == GLP_UP || col->type == GLP_DB)
xfprintf(fp, "%13.6g ", col->ub);
else
xfprintf(fp, "%13s ", col->type == GLP_FX ? "=" : "");
xfprintf(fp, "\n");
}
xfprintf(fp, "\n");
xfprintf(fp, "Integer feasibility conditions:\n");
xfprintf(fp, "\n");
glp_check_kkt(P, GLP_MIP, GLP_KKT_PE, &ae_max, &ae_ind, &re_max,
&re_ind);
xfprintf(fp, "KKT.PE: max.abs.err = %.2e on row %d\n",
ae_max, ae_ind);
xfprintf(fp, " max.rel.err = %.2e on row %d\n",
re_max, re_ind);
xfprintf(fp, "%8s%s\n", "",
re_max <= 1e-9 ? "High quality" :
re_max <= 1e-6 ? "Medium quality" :
re_max <= 1e-3 ? "Low quality" : "SOLUTION IS WRONG");
xfprintf(fp, "\n");
glp_check_kkt(P, GLP_MIP, GLP_KKT_PB, &ae_max, &ae_ind, &re_max,
&re_ind);
xfprintf(fp, "KKT.PB: max.abs.err = %.2e on %s %d\n",
ae_max, ae_ind <= P->m ? "row" : "column",
ae_ind <= P->m ? ae_ind : ae_ind - P->m);
xfprintf(fp, " max.rel.err = %.2e on %s %d\n",
re_max, re_ind <= P->m ? "row" : "column",
re_ind <= P->m ? re_ind : re_ind - P->m);
xfprintf(fp, "%8s%s\n", "",
re_max <= 1e-9 ? "High quality" :
re_max <= 1e-6 ? "Medium quality" :
re_max <= 1e-3 ? "Low quality" : "SOLUTION IS INFEASIBLE");
xfprintf(fp, "\n");
xfprintf(fp, "End of output\n");
#if 0 /* FIXME */
xfflush(fp);
#endif
if (glp_ioerr(fp))
{ xprintf("Write error on '%s' - %s\n", fname, get_err_msg());
ret = 1;
goto done;
}
ret = 0;
done: if (fp != NULL) glp_close(fp);
return ret;
}
/* eof */
| {
"pile_set_name": "Github"
} |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M20.49 3.51c-.56-.56-2.15-.97-4.16-.97-3.08 0-7.15.96-9.98 3.79-4.69 4.7-4.25 12.74-2.84 14.16.56.56 2.15.97 4.16.97 3.08 0 7.15-.96 9.98-3.79 4.69-4.7 4.25-12.74 2.84-14.16zM7.76 7.76c2.64-2.64 6.35-3.12 8.03-3.19-2.05.94-4.46 2.45-6.61 4.61-2.16 2.16-3.67 4.58-4.61 6.63.09-2.48.87-5.74 3.19-8.05zm8.48 8.48c-2.64 2.64-6.35 3.12-8.03 3.19 2.05-.94 4.46-2.45 6.61-4.61 2.16-2.16 3.67-4.58 4.62-6.63-.1 2.48-.88 5.74-3.2 8.05z" />
, 'SportsRugbySharp');
| {
"pile_set_name": "Github"
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// An exception for task cancellations.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System.Threading.Tasks
{
/// <summary>
/// Represents an exception used to communicate task cancellation.
/// </summary>
[Serializable]
#if !MONO
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
#endif
public class TaskCanceledException : OperationCanceledException
{
[NonSerialized]
private readonly Task _canceledTask; // The task which has been canceled.
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskCanceledException"/> class.
/// </summary>
// TODO: SR
//public TaskCanceledException() : base(SR.TaskCanceledException_ctor_DefaultMessage)
public TaskCanceledException() : base("A task was canceled.")
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskCanceledException"/>
/// class with a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public TaskCanceledException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskCanceledException"/>
/// class with a specified error message and a reference to the inner exception that is the cause of
/// this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception.</param>
public TaskCanceledException(string message, Exception innerException) : base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskCanceledException"/> class
/// with a reference to the <see cref="T:System.Threading.Tasks.Task"/> that has been canceled.
/// </summary>
/// <param name="task">A task that has been canceled.</param>
// TODO: NotSupported
public TaskCanceledException(Task task) :
base("A task was canceled.", task != null ? new CancellationToken() : new CancellationToken())
// TODO: NotSupported
//base(SR.TaskCanceledException_ctor_DefaultMessage, task != null ? task.CancellationToken : new CancellationToken())
{
_canceledTask = task;
}
///// <summary>
///// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskCanceledException"/>
///// class with serialized data.
///// </summary>
///// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
///// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination. </param>
// TODO: NotSupported
//protected TaskCanceledException(SerializationInfo info, StreamingContext context) : base(info, context)
//{
//}
/// <summary>
/// Gets the task associated with this exception.
/// </summary>
/// <remarks>
/// It is permissible for no Task to be associated with a
/// <see cref="T:System.Threading.Tasks.TaskCanceledException"/>, in which case
/// this property will return null.
/// </remarks>
public Task Task => _canceledTask;
}
}
| {
"pile_set_name": "Github"
} |
#pragma once
#include <functional>
#include <memory>
#include <queue>
#include <unordered_map>
#include <vector>
#include "abstract_expression.hpp"
#include "logical_query_plan/lqp_utils.hpp"
namespace opossum {
class AbstractLQPNode;
enum class LogicalOperator;
class LQPColumnExpression;
class TransactionContext;
/**
* Utility to check whether two vectors of Expressions are equal according to AbstractExpression::operator==()
* Note that this function also pays respect to the order of elements.
*/
bool expressions_equal(const std::vector<std::shared_ptr<AbstractExpression>>& expressions_a,
const std::vector<std::shared_ptr<AbstractExpression>>& expressions_b);
/**
* Utility to compare vectors of Expressions from different LQPs
*/
bool expressions_equal_to_expressions_in_different_lqp(
const std::vector<std::shared_ptr<AbstractExpression>>& expressions_left,
const std::vector<std::shared_ptr<AbstractExpression>>& expressions_right, const LQPNodeMapping& node_mapping);
/**
* Utility to compare two Expressions from different LQPs
*/
bool expression_equal_to_expression_in_different_lqp(const AbstractExpression& expression_left,
const AbstractExpression& expression_right,
const LQPNodeMapping& node_mapping);
/**
* Utility to AbstractExpression::deep_copy() a vector of expressions
*/
std::vector<std::shared_ptr<AbstractExpression>> expressions_deep_copy(
const std::vector<std::shared_ptr<AbstractExpression>>& expressions);
/**
* Recurse through the expression and replace them according to @param mapping, where applicable
*/
void expression_deep_replace(std::shared_ptr<AbstractExpression>& expression,
const ExpressionUnorderedMap<std::shared_ptr<AbstractExpression>>& mapping);
/**
* Utility to AbstractExpression::deep_copy() a vector of expressions while adjusting LQPColumnExpressions according to
* the node_mapping
*/
std::vector<std::shared_ptr<AbstractExpression>> expressions_copy_and_adapt_to_different_lqp(
const std::vector<std::shared_ptr<AbstractExpression>>& expressions, const LQPNodeMapping& node_mapping);
/**
* Utility to AbstractExpression::deep_copy() a single expression while adjusting LQPColumnExpressions according to the
* node_mapping
*/
std::shared_ptr<AbstractExpression> expression_copy_and_adapt_to_different_lqp(const AbstractExpression& expression,
const LQPNodeMapping& node_mapping);
/**
* Makes all LQPColumnExpressions point to their equivalent in a copied LQP
*/
void expression_adapt_to_different_lqp(std::shared_ptr<AbstractExpression>& expression,
const LQPNodeMapping& node_mapping);
std::shared_ptr<LQPColumnExpression> expression_adapt_to_different_lqp(const LQPColumnExpression& lqp_column_expression,
const LQPNodeMapping& node_mapping);
/**
* Create a comma separated string with the AbstractExpression::description(mode) of each expression
*/
std::string expression_descriptions(const std::vector<std::shared_ptr<AbstractExpression>>& expressions,
const AbstractExpression::DescriptionMode mode);
enum class ExpressionVisitation { VisitArguments, DoNotVisitArguments };
/**
* Calls the passed @param visitor on each sub-expression of the @param expression.
* The visitor returns `ExpressionVisitation`, indicating whether the current expression's arguments should be visited
* as well.
*
* @tparam Expression Either `std::shared_ptr<AbstractExpression>` or `const std::shared_ptr<AbstractExpression>`
* @tparam Visitor Functor called with every sub expression as a param.
* Return `ExpressionVisitation`
*/
template <typename Expression, typename Visitor>
void visit_expression(Expression& expression, Visitor visitor) {
// The reference wrapper bit is important so we can manipulate the Expression even by replacing sub expression
std::queue<std::reference_wrapper<Expression>> expression_queue;
expression_queue.push(expression);
while (!expression_queue.empty()) {
auto expression_reference = expression_queue.front();
expression_queue.pop();
if (visitor(expression_reference.get()) == ExpressionVisitation::VisitArguments) {
for (auto& argument : expression_reference.get()->arguments) {
expression_queue.push(argument);
}
}
}
}
/**
* @return The result DataType of a non-boolean binary expression where the operands have the specified types.
* E.g., `<float> + <long> => <double>`, `(<float>, <int>, <int>) => <float>`
* Division of integer types will return an integer type, see #1799.
*/
DataType expression_common_type(const DataType lhs, const DataType rhs);
/**
* @return Checks whether the expression can be evaluated on top of a specified LQP (i.e., all required
* LQPColumnExpressions are available from this LQP). This does not mean that all expressions are already
* readily available as a column. It might be necessary to add a Projection or an Aggregate.
* To check if an expression is available in a form ready to be used by a scan/join,
* use `Operator*Predicate::from_expression(...)`.
*/
bool expression_evaluable_on_lqp(const std::shared_ptr<AbstractExpression>& expression, const AbstractLQPNode& lqp);
/**
* Convert "(a AND b) AND c" to [a,b,c] where a,b,c can be arbitrarily complex expressions
*/
std::vector<std::shared_ptr<AbstractExpression>> flatten_logical_expressions(
const std::shared_ptr<AbstractExpression>& expression, const LogicalOperator logical_operator);
/**
* Convert ([a,b,c], AND) into "(a AND b) AND c"
*/
std::shared_ptr<AbstractExpression> inflate_logical_expressions(
const std::vector<std::shared_ptr<AbstractExpression>>& expressions, const LogicalOperator logical_operator);
/**
* Traverse the expression(s) for ParameterExpressions and set them to the requested values
*/
void expression_set_parameters(const std::shared_ptr<AbstractExpression>& expression,
const std::unordered_map<ParameterID, AllTypeVariant>& parameters);
void expressions_set_parameters(const std::vector<std::shared_ptr<AbstractExpression>>& expressions,
const std::unordered_map<ParameterID, AllTypeVariant>& parameters);
/**
* Traverse the expression(s) for subqueries and set the transaction context in them
*/
void expression_set_transaction_context(const std::shared_ptr<AbstractExpression>& expression,
const std::weak_ptr<TransactionContext>& transaction_context);
void expressions_set_transaction_context(const std::vector<std::shared_ptr<AbstractExpression>>& expressions,
const std::weak_ptr<TransactionContext>& transaction_context);
bool expression_contains_placeholder(const std::shared_ptr<AbstractExpression>& expression);
bool expression_contains_correlated_parameter(const std::shared_ptr<AbstractExpression>& expression);
/**
* @return The value of a CorrelatedParameterExpression or ValueExpression
* std::nullopt for other expression types
*/
std::optional<AllTypeVariant> expression_get_value_or_parameter(const AbstractExpression& expression);
} // namespace opossum
| {
"pile_set_name": "Github"
} |
rule n3e9_4c346a49c4000b14
{
meta:
copyright="Copyright (c) 2014-2018 Support Intelligence Inc, All Rights Reserved."
engine="saphire/1.3.1 divinorum/0.998 icewater/0.4"
viz_url="http://icewater.io/en/cluster/query?h64=n3e9.4c346a49c4000b14"
cluster="n3e9.4c346a49c4000b14"
cluster_size="556"
filetype = "application/x-dosexec"
tlp = "amber"
version = "icewater snowflake"
author = "Rick Wesson (@wessorh) [email protected]"
date = "20171111"
license = "RIL-1.0 [Rick's Internet License] "
family="malicious riskware fsojcj"
md5_hashes="['00a698615c87e3607a26ad14df3836fc','0185a4e3ec67e1664048f024c0b50633','0878ca5a681cb646ff38f5cc9510d7cf']"
strings:
$hex_string = { d97009feda710affda710affd97009feda710affd97009feda710affdf730afef7800afff5810e4bdd7c1d22dc7a1aebdb7715eddb7715eddb7715eddb7715ed }
condition:
filesize > 262144 and filesize < 1048576
and $hex_string
}
| {
"pile_set_name": "Github"
} |
define(['exports', 'module', './visitor'], function (exports, module, _visitor) {
'use strict';
// istanbul ignore next
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _Visitor = _interopRequireDefault(_visitor);
function WhitespaceControl() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
this.options = options;
}
WhitespaceControl.prototype = new _Visitor['default']();
WhitespaceControl.prototype.Program = function (program) {
var doStandalone = !this.options.ignoreStandalone;
var isRoot = !this.isRootSeen;
this.isRootSeen = true;
var body = program.body;
for (var i = 0, l = body.length; i < l; i++) {
var current = body[i],
strip = this.accept(current);
if (!strip) {
continue;
}
var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
_isNextWhitespace = isNextWhitespace(body, i, isRoot),
openStandalone = strip.openStandalone && _isPrevWhitespace,
closeStandalone = strip.closeStandalone && _isNextWhitespace,
inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
if (strip.close) {
omitRight(body, i, true);
}
if (strip.open) {
omitLeft(body, i, true);
}
if (doStandalone && inlineStandalone) {
omitRight(body, i);
if (omitLeft(body, i)) {
// If we are on a standalone node, save the indent info for partials
if (current.type === 'PartialStatement') {
// Pull out the whitespace from the final line
current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
}
}
}
if (doStandalone && openStandalone) {
omitRight((current.program || current.inverse).body);
// Strip out the previous content node if it's whitespace only
omitLeft(body, i);
}
if (doStandalone && closeStandalone) {
// Always strip the next node
omitRight(body, i);
omitLeft((current.inverse || current.program).body);
}
}
return program;
};
WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
this.accept(block.program);
this.accept(block.inverse);
// Find the inverse program that is involed with whitespace stripping.
var program = block.program || block.inverse,
inverse = block.program && block.inverse,
firstInverse = inverse,
lastInverse = inverse;
if (inverse && inverse.chained) {
firstInverse = inverse.body[0].program;
// Walk the inverse chain to find the last inverse that is actually in the chain.
while (lastInverse.chained) {
lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
}
}
var strip = {
open: block.openStrip.open,
close: block.closeStrip.close,
// Determine the standalone candiacy. Basically flag our content as being possibly standalone
// so our parent can determine if we actually are standalone
openStandalone: isNextWhitespace(program.body),
closeStandalone: isPrevWhitespace((firstInverse || program).body)
};
if (block.openStrip.close) {
omitRight(program.body, null, true);
}
if (inverse) {
var inverseStrip = block.inverseStrip;
if (inverseStrip.open) {
omitLeft(program.body, null, true);
}
if (inverseStrip.close) {
omitRight(firstInverse.body, null, true);
}
if (block.closeStrip.open) {
omitLeft(lastInverse.body, null, true);
}
// Find standalone else statments
if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
omitLeft(program.body);
omitRight(firstInverse.body);
}
} else if (block.closeStrip.open) {
omitLeft(program.body, null, true);
}
return strip;
};
WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
return mustache.strip;
};
WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
/* istanbul ignore next */
var strip = node.strip || {};
return {
inlineStandalone: true,
open: strip.open,
close: strip.close
};
};
function isPrevWhitespace(body, i, isRoot) {
if (i === undefined) {
i = body.length;
}
// Nodes that end with newlines are considered whitespace (but are special
// cased for strip operations)
var prev = body[i - 1],
sibling = body[i - 2];
if (!prev) {
return isRoot;
}
if (prev.type === 'ContentStatement') {
return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
}
}
function isNextWhitespace(body, i, isRoot) {
if (i === undefined) {
i = -1;
}
var next = body[i + 1],
sibling = body[i + 2];
if (!next) {
return isRoot;
}
if (next.type === 'ContentStatement') {
return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
}
}
// Marks the node to the right of the position as omitted.
// I.e. {{foo}}' ' will mark the ' ' node as omitted.
//
// If i is undefined, then the first child will be marked as such.
//
// If mulitple is truthy then all whitespace will be stripped out until non-whitespace
// content is met.
function omitRight(body, i, multiple) {
var current = body[i == null ? 0 : i + 1];
if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
return;
}
var original = current.value;
current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
current.rightStripped = current.value !== original;
}
// Marks the node to the left of the position as omitted.
// I.e. ' '{{foo}} will mark the ' ' node as omitted.
//
// If i is undefined then the last child will be marked as such.
//
// If mulitple is truthy then all whitespace will be stripped out until non-whitespace
// content is met.
function omitLeft(body, i, multiple) {
var current = body[i == null ? body.length - 1 : i - 1];
if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
return;
}
// We omit the last node if it's whitespace only and not preceeded by a non-content node.
var original = current.value;
current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
current.leftStripped = current.value !== original;
return current.leftStripped;
}
module.exports = WhitespaceControl;
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL2xpYi9oYW5kbGViYXJzL2NvbXBpbGVyL3doaXRlc3BhY2UtY29udHJvbC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7QUFFQSxXQUFTLGlCQUFpQixHQUFlO1FBQWQsT0FBTyx5REFBRyxFQUFFOztBQUNyQyxRQUFJLENBQUMsT0FBTyxHQUFHLE9BQU8sQ0FBQztHQUN4QjtBQUNELG1CQUFpQixDQUFDLFNBQVMsR0FBRyx5QkFBYSxDQUFDOztBQUU1QyxtQkFBaUIsQ0FBQyxTQUFTLENBQUMsT0FBTyxHQUFHLFVBQVMsT0FBTyxFQUFFO0FBQ3RELFFBQU0sWUFBWSxHQUFHLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxnQkFBZ0IsQ0FBQzs7QUFFcEQsUUFBSSxNQUFNLEdBQUcsQ0FBQyxJQUFJLENBQUMsVUFBVSxDQUFDO0FBQzlCLFFBQUksQ0FBQyxVQUFVLEdBQUcsSUFBSSxDQUFDOztBQUV2QixRQUFJLElBQUksR0FBRyxPQUFPLENBQUMsSUFBSSxDQUFDO0FBQ3hCLFNBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxJQUFJLENBQUMsTUFBTSxFQUFFLENBQUMsR0FBRyxDQUFDLEVBQUUsQ0FBQyxFQUFFLEVBQUU7QUFDM0MsVUFBSSxPQUFPLEdBQUcsSUFBSSxDQUFDLENBQUMsQ0FBQztVQUNqQixLQUFLLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxPQUFPLENBQUMsQ0FBQzs7QUFFakMsVUFBSSxDQUFDLEtBQUssRUFBRTtBQUNWLGlCQUFTO09BQ1Y7O0FBRUQsVUFBSSxpQkFBaUIsR0FBRyxnQkFBZ0IsQ0FBQyxJQUFJLEVBQUUsQ0FBQyxFQUFFLE1BQU0sQ0FBQztVQUNyRCxpQkFBaUIsR0FBRyxnQkFBZ0IsQ0FBQyxJQUFJLEVBQUUsQ0FBQyxFQUFFLE1BQU0sQ0FBQztVQUVyRCxjQUFjLEdBQUcsS0FBSyxDQUFDLGNBQWMsSUFBSSxpQkFBaUI7VUFDMUQsZUFBZSxHQUFHLEtBQUssQ0FBQyxlQUFlLElBQUksaUJBQWlCO1VBQzVELGdCQUFnQixHQUFHLEtBQUssQ0FBQyxnQkFBZ0IsSUFBSSxpQkFBaUIsSUFBSSxpQkFBaUIsQ0FBQzs7QUFFeEYsVUFBSSxLQUFLLENBQUMsS0FBSyxFQUFFO0FBQ2YsaUJBQVMsQ0FBQyxJQUFJLEVBQUUsQ0FBQyxFQUFFLElBQUksQ0FBQyxDQUFDO09BQzFCO0FBQ0QsVUFBSSxLQUFLLENBQUMsSUFBSSxFQUFFO0FBQ2QsZ0JBQVEsQ0FBQyxJQUFJLEVBQUUsQ0FBQyxFQUFFLElBQUksQ0FBQyxDQUFDO09BQ3pCOztBQUVELFVBQUksWUFBWSxJQUFJLGdCQUFnQixFQUFFO0FBQ3BDLGlCQUFTLENBQUMsSUFBSSxFQUFFLENBQUMsQ0FBQyxDQUFDOztBQUVuQixZQUFJLFFBQVEsQ0FBQyxJQUFJLEVBQUUsQ0FBQyxDQUFDLEVBQUU7O0FBRXJCLGNBQUksT0FBTyxDQUFDLElBQUksS0FBSyxrQkFBa0IsRUFBRTs7QUFFdkMsbUJBQU8sQ0FBQyxNQUFNLEdBQUcsQUFBQyxXQUFXLENBQUUsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsUUFBUSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7V0FDOUQ7U0FDRjtPQUNGO0FBQ0QsVUFBSSxZQUFZLElBQUksY0FBYyxFQUFFO0FBQ2xDLGlCQUFTLENBQUMsQ0FBQyxPQUFPLENBQUMsT0FBTyxJQUFJLE9BQU8sQ0FBQyxPQUFPLENBQUEsQ0FBRSxJQUFJLENBQUMsQ0FBQzs7O0FBR3JELGdCQUFRLENBQUMsSUFBSSxFQUFFLENBQUMsQ0FBQyxDQUFDO09BQ25CO0FBQ0QsVUFBSSxZQUFZLElBQUksZUFBZSxFQUFFOztBQUVuQyxpQkFBUyxDQUFDLElBQUksRUFBRSxDQUFDLENBQUMsQ0FBQzs7QUFFbkIsZ0JBQVEsQ0FBQyxDQUFDLE9BQU8sQ0FBQyxPQUFPLElBQUksT0FBTyxDQUFDLE9BQU8sQ0FBQSxDQUFFLElBQUksQ0FBQyxDQUFDO09BQ3JEO0tBQ0Y7O0FBRUQsV0FBTyxPQUFPLENBQUM7R0FDaEIsQ0FBQzs7QUFFRixtQkFBaUIsQ0FBQyxTQUFTLENBQUMsY0FBYyxHQUMxQyxpQkFBaUIsQ0FBQyxTQUFTLENBQUMsY0FBYyxHQUMxQyxpQkFBaUIsQ0FBQyxTQUFTLENBQUMscUJBQXFCLEdBQUcsVUFBUyxLQUFLLEVBQUU7QUFDbEUsUUFBSSxDQUFDLE1BQU0sQ0FBQyxLQUFLLENBQUMsT0FBTyxDQUFDLENBQUM7QUFDM0IsUUFBSSxDQUFDLE1BQU0sQ0FBQyxLQUFLLENBQUMsT0FBTyxDQUFDLENBQUM7OztBQUczQixRQUFJLE9BQU8sR0FBRyxLQUFLLENBQUMsT0FBTyxJQUFJLEtBQUssQ0FBQyxPQUFPO1FBQ3hDLE9BQU8sR0FBRyxLQUFLLENBQUMsT0FBTyxJQUFJLEtBQUssQ0FBQyxPQUFPO1FBQ3hDLFlBQVksR0FBRyxPQUFPO1FBQ3RCLFdBQVcsR0FBRyxPQUFPLENBQUM7O0FBRTFCLFFBQUksT0FBTyxJQUFJLE9BQU8sQ0FBQyxPQUFPLEVBQUU7QUFDOUIsa0JBQVksR0FBRyxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDLE9BQU8sQ0FBQzs7O0FBR3ZDLGFBQU8sV0FBVyxDQUFDLE9BQU8sRUFBRTtBQUMxQixtQkFBVyxHQUFHLFdBQVcsQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFDLElBQUksQ0FBQyxNQUFNLEdBQUcsQ0FBQyxDQUFDLENBQUMsT0FBTyxDQUFDO09BQ3JFO0tBQ0Y7O0FBRUQsUUFBSSxLQUFLLEdBQUc7QUFDVixVQUFJLEVBQUUsS0FBSyxDQUFDLFNBQVMsQ0FBQyxJQUFJO0FBQzFCLFdBQUssRUFBRSxLQUFLLENBQUMsVUFBVSxDQUFDLEtBQUs7Ozs7QUFJN0Isb0JBQWMsRUFBRSxnQkFBZ0IsQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDO0FBQzlDLHFCQUFlLEVBQUUsZ0JBQWdCLENBQUMsQ0FBQyxZQUFZLElBQUksT0FBTyxDQUFBLENBQUUsSUFBSSxDQUFDO0tBQ2xFLENBQUM7O0FBRUYsUUFBSSxLQUFLLENBQUMsU0FBUyxDQUFDLEtBQUssRUFBRTtBQUN6QixlQUFTLENBQUMsT0FBTyxDQUFDLElBQUksRUFBRSxJQUFJLEVBQUUsSUFBSSxDQUFDLENBQUM7S0FDckM7O0FBRUQsUUFBSSxPQUFPLEVBQUU7QUFDWCxVQUFJLFlBQVksR0FBRyxLQUFLLENBQUMsWUFBWSxDQUFDOztBQUV0QyxVQUFJLFlBQVksQ0FBQyxJQUFJLEVBQUU7QUFDckIsZ0JBQVEsQ0FBQyxPQUFPLENBQUMsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLENBQUMsQ0FBQztPQUNwQzs7QUFFRCxVQUFJLFlBQVksQ0FBQyxLQUFLLEVBQUU7QUFDdEIsaUJBQVMsQ0FBQyxZQUFZLENBQUMsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLENBQUMsQ0FBQztPQUMxQztBQUNELFVBQUksS0FBSyxDQUFDLFVBQVUsQ0FBQyxJQUFJLEVBQUU7QUFDekIsZ0JBQVEsQ0FBQyxXQUFXLENBQUMsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLENBQUMsQ0FBQztPQUN4Qzs7O0FBR0QsVUFBSSxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUMsZ0JBQWdCLElBQzNCLGdCQUFnQixDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsSUFDOUIsZ0JBQWdCLENBQUMsWUFBWSxDQUFDLElBQUksQ0FBQyxFQUFFO0FBQzFDLGdCQUFRLENBQUMsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQ3ZCLGlCQUFTLENBQUMsWUFBWSxDQUFDLElBQUksQ0FBQyxDQUFDO09BQzlCO0tBQ0YsTUFBTSxJQUFJLEtBQUssQ0FBQyxVQUFVLENBQUMsSUFBSSxFQUFFO0FBQ2hDLGNBQVEsQ0FBQyxPQUFPLENBQUMsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLENBQUMsQ0FBQztLQUNwQzs7QUFFRCxXQUFPLEtBQUssQ0FBQztHQUNkLENBQUM7O0FBRUYsbUJBQWlCLENBQUMsU0FBUyxDQUFDLFNBQVMsR0FDckMsaUJBQWlCLENBQUMsU0FBUyxDQUFDLGlCQUFpQixHQUFHLFVBQVMsUUFBUSxFQUFFO0FBQ2pFLFdBQU8sUUFBUSxDQUFDLEtBQUssQ0FBQztHQUN2QixDQUFDOztBQUVGLG1CQUFpQixDQUFDLFNBQVMsQ0FBQyxnQkFBZ0IsR0FDeEMsaUJBQWlCLENBQUMsU0FBUyxDQUFDLGdCQUFnQixHQUFHLFVBQVMsSUFBSSxFQUFFOztBQUVoRSxRQUFJLEtBQUssR0FBRyxJQUFJLENBQUMsS0FBSyxJQUFJLEVBQUUsQ0FBQztBQUM3QixXQUFPO0FBQ0wsc0JBQWdCLEVBQUUsSUFBSTtBQUN0QixVQUFJLEVBQUUsS0FBSyxDQUFDLElBQUk7QUFDaEIsV0FBSyxFQUFFLEtBQUssQ0FBQyxLQUFLO0tBQ25CLENBQUM7R0FDSCxDQUFDOztBQUdGLFdBQVMsZ0JBQWdCLENBQUMsSUFBSSxFQUFFLENBQUMsRUFBRSxNQUFNLEVBQUU7QUFDekMsUUFBSSxDQUFDLEtBQUssU0FBUyxFQUFFO0FBQ25CLE9BQUMsR0FBRyxJQUFJLENBQUMsTUFBTSxDQUFDO0tBQ2pCOzs7O0FBSUQsUUFBSSxJQUFJLEdBQUcsSUFBSSxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUM7UUFDbEIsT0FBTyxHQUFHLElBQUksQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7QUFDMUIsUUFBSSxDQUFDLElBQUksRUFBRTtBQUNULGFBQU8sTUFBTSxDQUFDO0tBQ2Y7O0FBRUQsUUFBSSxJQUFJLENBQUMsSUFBSSxLQUFLLGtCQUFrQixFQUFFO0FBQ3BDLGFBQU8sQ0FBQyxPQUFPLElBQUksQ0FBQyxNQUFNLEdBQUksWUFBWSxHQUFLLGdCQUFnQixDQUFDLENBQUUsSUFBSSxDQUFDLElBQUksQ0FBQyxRQUFRLENBQUMsQ0FBQztLQUN2RjtHQUNGO0FBQ0QsV0FBUyxnQkFBZ0IsQ0FBQyxJQUFJLEVBQUUsQ0FBQyxFQUFFLE1BQU0sRUFBRTtBQUN6QyxRQUFJLENBQUMsS0FBSyxTQUFTLEVBQUU7QUFDbkIsT0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDO0tBQ1I7O0FBRUQsUUFBSSxJQUFJLEdBQUcsSUFBSSxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUM7UUFDbEIsT0FBTyxHQUFHLElBQUksQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7QUFDMUIsUUFBSSxDQUFDLElBQUksRUFBRTtBQUNULGFBQU8sTUFBTSxDQUFDO0tBQ2Y7O0FBRUQsUUFBSSxJQUFJLENBQUMsSUFBSSxLQUFLLGtCQUFrQixFQUFFO0FBQ3BDLGFBQU8sQ0FBQyxPQUFPLElBQUksQ0FBQyxNQUFNLEdBQUksWUFBWSxHQUFLLGdCQUFnQixDQUFDLENBQUUsSUFBSSxDQUFDLElBQUksQ0FBQyxRQUFRLENBQUMsQ0FBQztLQUN2RjtHQUNGOzs7Ozs7Ozs7QUFTRCxXQUFTLFNBQVMsQ0FBQyxJQUFJLEVBQUUsQ0FBQyxFQUFFLFFBQVEsRUFBRTtBQUNwQyxRQUFJLE9BQU8sR0FBRyxJQUFJLENBQUMsQ0FBQyxJQUFJLElBQUksR0FBRyxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDO0FBQzFDLFFBQUksQ0FBQyxPQUFPLElBQUksT0FBTyxDQUFDLElBQUksS0FBSyxrQkFBa0IsSUFBSyxDQUFDLFFBQVEsSUFBSSxPQUFPLENBQUMsYUFBYSxBQUFDLEVBQUU7QUFDM0YsYUFBTztLQUNSOztBQUVELFFBQUksUUFBUSxHQUFHLE9BQU8sQ0FBQyxLQUFLLENBQUM7QUFDN0IsV0FBTyxDQUFDLEtBQUssR0FBRyxPQUFPLENBQUMsS0FBSyxDQUFDLE9BQU8sQ0FBQyxRQUFRLEdBQUksTUFBTSxHQUFLLGVBQWUsQUFBQyxFQUFFLEVBQUUsQ0FBQyxDQUFDO0FBQ25GLFdBQU8sQ0FBQyxhQUFhLEdBQUcsT0FBTyxDQUFDLEtBQUssS0FBSyxRQUFRLENBQUM7R0FDcEQ7Ozs7Ozs7OztBQVNELFdBQVMsUUFBUSxDQUFDLElBQUksRUFBRSxDQUFDLEVBQUUsUUFBUSxFQUFFO0FBQ25DLFFBQUksT0FBTyxHQUFHLElBQUksQ0FBQyxDQUFDLElBQUksSUFBSSxHQUFHLElBQUksQ0FBQyxNQUFNLEdBQUcsQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQztBQUN4RCxRQUFJLENBQUMsT0FBTyxJQUFJLE9BQU8sQ0FBQyxJQUFJLEtBQUssa0JBQWtCLElBQUssQ0FBQyxRQUFRLElBQUksT0FBTyxDQUFDLFlBQVksQUFBQyxFQUFFO0FBQzFGLGFBQU87S0FDUjs7O0FBR0QsUUFBSSxRQUFRLEdBQUcsT0FBTyxDQUFDLEtBQUssQ0FBQztBQUM3QixXQUFPLENBQUMsS0FBSyxHQUFHLE9BQU8sQ0FBQyxLQUFLLENBQUMsT0FBTyxDQUFDLFFBQVEsR0FBSSxNQUFNLEdBQUssU0FBUyxBQUFDLEVBQUUsRUFBRSxDQUFDLENBQUM7QUFDN0UsV0FBTyxDQUFDLFlBQVksR0FBRyxPQUFPLENBQUMsS0FBSyxLQUFLLFFBQVEsQ0FBQztBQUNsRCxXQUFPLE9BQU8sQ0FBQyxZQUFZLENBQUM7R0FDN0I7O21CQUVjLGlCQUFpQiIsImZpbGUiOiJ3aGl0ZXNwYWNlLWNvbnRyb2wuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgVmlzaXRvciBmcm9tICcuL3Zpc2l0b3InO1xuXG5mdW5jdGlvbiBXaGl0ZXNwYWNlQ29udHJvbChvcHRpb25zID0ge30pIHtcbiAgdGhpcy5vcHRpb25zID0gb3B0aW9ucztcbn1cbldoaXRlc3BhY2VDb250cm9sLnByb3RvdHlwZSA9IG5ldyBWaXNpdG9yKCk7XG5cbldoaXRlc3BhY2VDb250cm9sLnByb3RvdHlwZS5Qcm9ncmFtID0gZnVuY3Rpb24ocHJvZ3JhbSkge1xuICBjb25zdCBkb1N0YW5kYWxvbmUgPSAhdGhpcy5vcHRpb25zLmlnbm9yZVN0YW5kYWxvbmU7XG5cbiAgbGV0IGlzUm9vdCA9ICF0aGlzLmlzUm9vdFNlZW47XG4gIHRoaXMuaXNSb290U2VlbiA9IHRydWU7XG5cbiAgbGV0IGJvZHkgPSBwcm9ncmFtLmJvZHk7XG4gIGZvciAobGV0IGkgPSAwLCBsID0gYm9keS5sZW5ndGg7IGkgPCBsOyBpKyspIHtcbiAgICBsZXQgY3VycmVudCA9IGJvZHlbaV0sXG4gICAgICAgIHN0cmlwID0gdGhpcy5hY2NlcHQoY3VycmVudCk7XG5cbiAgICBpZiAoIXN0cmlwKSB7XG4gICAgICBjb250aW51ZTtcbiAgICB9XG5cbiAgICBsZXQgX2lzUHJldldoaXRlc3BhY2UgPSBpc1ByZXZXaGl0ZXNwYWNlKGJvZHksIGksIGlzUm9vdCksXG4gICAgICAgIF9pc05leHRXaGl0ZXNwYWNlID0gaXNOZXh0V2hpdGVzcGFjZShib2R5LCBpLCBpc1Jvb3QpLFxuXG4gICAgICAgIG9wZW5TdGFuZGFsb25lID0gc3RyaXAub3BlblN0YW5kYWxvbmUgJiYgX2lzUHJldldoaXRlc3BhY2UsXG4gICAgICAgIGNsb3NlU3RhbmRhbG9uZSA9IHN0cmlwLmNsb3NlU3RhbmRhbG9uZSAmJiBfaXNOZXh0V2hpdGVzcGFjZSxcbiAgICAgICAgaW5saW5lU3RhbmRhbG9uZSA9IHN0cmlwLmlubGluZVN0YW5kYWxvbmUgJiYgX2lzUHJldldoaXRlc3BhY2UgJiYgX2lzTmV4dFdoaXRlc3BhY2U7XG5cbiAgICBpZiAoc3RyaXAuY2xvc2UpIHtcbiAgICAgIG9taXRSaWdodChib2R5LCBpLCB0cnVlKTtcbiAgICB9XG4gICAgaWYgKHN0cmlwLm9wZW4pIHtcbiAgICAgIG9taXRMZWZ0KGJvZHksIGksIHRydWUpO1xuICAgIH1cblxuICAgIGlmIChkb1N0YW5kYWxvbmUgJiYgaW5saW5lU3RhbmRhbG9uZSkge1xuICAgICAgb21pdFJpZ2h0KGJvZHksIGkpO1xuXG4gICAgICBpZiAob21pdExlZnQoYm9keSwgaSkpIHtcbiAgICAgICAgLy8gSWYgd2UgYXJlIG9uIGEgc3RhbmRhbG9uZSBub2RlLCBzYXZlIHRoZSBpbmRlbnQgaW5mbyBmb3IgcGFydGlhbHNcbiAgICAgICAgaWYgKGN1cnJlbnQudHlwZSA9PT0gJ1BhcnRpYWxTdGF0ZW1lbnQnKSB7XG4gICAgICAgICAgLy8gUHVsbCBvdXQgdGhlIHdoaXRlc3BhY2UgZnJvbSB0aGUgZmluYWwgbGluZVxuICAgICAgICAgIGN1cnJlbnQuaW5kZW50ID0gKC8oWyBcXHRdKyQpLykuZXhlYyhib2R5W2kgLSAxXS5vcmlnaW5hbClbMV07XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICB9XG4gICAgaWYgKGRvU3RhbmRhbG9uZSAmJiBvcGVuU3RhbmRhbG9uZSkge1xuICAgICAgb21pdFJpZ2h0KChjdXJyZW50LnByb2dyYW0gfHwgY3VycmVudC5pbnZlcnNlKS5ib2R5KTtcblxuICAgICAgLy8gU3RyaXAgb3V0IHRoZSBwcmV2aW91cyBjb250ZW50IG5vZGUgaWYgaXQncyB3aGl0ZXNwYWNlIG9ubHlcbiAgICAgIG9taXRMZWZ0KGJvZHksIGkpO1xuICAgIH1cbiAgICBpZiAoZG9TdGFuZGFsb25lICYmIGNsb3NlU3RhbmRhbG9uZSkge1xuICAgICAgLy8gQWx3YXlzIHN0cmlwIHRoZSBuZXh0IG5vZGVcbiAgICAgIG9taXRSaWdodChib2R5LCBpKTtcblxuICAgICAgb21pdExlZnQoKGN1cnJlbnQuaW52ZXJzZSB8fCBjdXJyZW50LnByb2dyYW0pLmJvZHkpO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiBwcm9ncmFtO1xufTtcblxuV2hpdGVzcGFjZUNvbnRyb2wucHJvdG90eXBlLkJsb2NrU3RhdGVtZW50ID1cbldoaXRlc3BhY2VDb250cm9sLnByb3RvdHlwZS5EZWNvcmF0b3JCbG9jayA9XG5XaGl0ZXNwYWNlQ29udHJvbC5wcm90b3R5cGUuUGFydGlhbEJsb2NrU3RhdGVtZW50ID0gZnVuY3Rpb24oYmxvY2spIHtcbiAgdGhpcy5hY2NlcHQoYmxvY2sucHJvZ3JhbSk7XG4gIHRoaXMuYWNjZXB0KGJsb2NrLmludmVyc2UpO1xuXG4gIC8vIEZpbmQgdGhlIGludmVyc2UgcHJvZ3JhbSB0aGF0IGlzIGludm9sZWQgd2l0aCB3aGl0ZXNwYWNlIHN0cmlwcGluZy5cbiAgbGV0IHByb2dyYW0gPSBibG9jay5wcm9ncmFtIHx8IGJsb2NrLmludmVyc2UsXG4gICAgICBpbnZlcnNlID0gYmxvY2sucHJvZ3JhbSAmJiBibG9jay5pbnZlcnNlLFxuICAgICAgZmlyc3RJbnZlcnNlID0gaW52ZXJzZSxcbiAgICAgIGxhc3RJbnZlcnNlID0gaW52ZXJzZTtcblxuICBpZiAoaW52ZXJzZSAmJiBpbnZlcnNlLmNoYWluZWQpIHtcbiAgICBmaXJzdEludmVyc2UgPSBpbnZlcnNlLmJvZHlbMF0ucHJvZ3JhbTtcblxuICAgIC8vIFdhbGsgdGhlIGludmVyc2UgY2hhaW4gdG8gZmluZCB0aGUgbGFzdCBpbnZlcnNlIHRoYXQgaXMgYWN0dWFsbHkgaW4gdGhlIGNoYWluLlxuICAgIHdoaWxlIChsYXN0SW52ZXJzZS5jaGFpbmVkKSB7XG4gICAgICBsYXN0SW52ZXJzZSA9IGxhc3RJbnZlcnNlLmJvZHlbbGFzdEludmVyc2UuYm9keS5sZW5ndGggLSAxXS5wcm9ncmFtO1xuICAgIH1cbiAgfVxuXG4gIGxldCBzdHJpcCA9IHtcbiAgICBvcGVuOiBibG9jay5vcGVuU3RyaXAub3BlbixcbiAgICBjbG9zZTogYmxvY2suY2xvc2VTdHJpcC5jbG9zZSxcblxuICAgIC8vIERldGVybWluZSB0aGUgc3RhbmRhbG9uZSBjYW5kaWFjeS4gQmFzaWNhbGx5IGZsYWcgb3VyIGNvbnRlbnQgYXMgYmVpbmcgcG9zc2libHkgc3RhbmRhbG9uZVxuICAgIC8vIHNvIG91ciBwYXJlbnQgY2FuIGRldGVybWluZSBpZiB3ZSBhY3R1YWxseSBhcmUgc3RhbmRhbG9uZVxuICAgIG9wZW5TdGFuZGFsb25lOiBpc05leHRXaGl0ZXNwYWNlKHByb2dyYW0uYm9keSksXG4gICAgY2xvc2VTdGFuZGFsb25lOiBpc1ByZXZXaGl0ZXNwYWNlKChmaXJzdEludmVyc2UgfHwgcHJvZ3JhbSkuYm9keSlcbiAgfTtcblxuICBpZiAoYmxvY2sub3BlblN0cmlwLmNsb3NlKSB7XG4gICAgb21pdFJpZ2h0KHByb2dyYW0uYm9keSwgbnVsbCwgdHJ1ZSk7XG4gIH1cblxuICBpZiAoaW52ZXJzZSkge1xuICAgIGxldCBpbnZlcnNlU3RyaXAgPSBibG9jay5pbnZlcnNlU3RyaXA7XG5cbiAgICBpZiAoaW52ZXJzZVN0cmlwLm9wZW4pIHtcbiAgICAgIG9taXRMZWZ0KHByb2dyYW0uYm9keSwgbnVsbCwgdHJ1ZSk7XG4gICAgfVxuXG4gICAgaWYgKGludmVyc2VTdHJpcC5jbG9zZSkge1xuICAgICAgb21pdFJpZ2h0KGZpcnN0SW52ZXJzZS5ib2R5LCBudWxsLCB0cnVlKTtcbiAgICB9XG4gICAgaWYgKGJsb2NrLmNsb3NlU3RyaXAub3Blbikge1xuICAgICAgb21pdExlZnQobGFzdEludmVyc2UuYm9keSwgbnVsbCwgdHJ1ZSk7XG4gICAgfVxuXG4gICAgLy8gRmluZCBzdGFuZGFsb25lIGVsc2Ugc3RhdG1lbnRzXG4gICAgaWYgKCF0aGlzLm9wdGlvbnMuaWdub3JlU3RhbmRhbG9uZVxuICAgICAgICAmJiBpc1ByZXZXaGl0ZXNwYWNlKHByb2dyYW0uYm9keSlcbiAgICAgICAgJiYgaXNOZXh0V2hpdGVzcGFjZShmaXJzdEludmVyc2UuYm9keSkpIHtcbiAgICAgIG9taXRMZWZ0KHByb2dyYW0uYm9keSk7XG4gICAgICBvbWl0UmlnaHQoZmlyc3RJbnZlcnNlLmJvZHkpO1xuICAgIH1cbiAgfSBlbHNlIGlmIChibG9jay5jbG9zZVN0cmlwLm9wZW4pIHtcbiAgICBvbWl0TGVmdChwcm9ncmFtLmJvZHksIG51bGwsIHRydWUpO1xuICB9XG5cbiAgcmV0dXJuIHN0cmlwO1xufTtcblxuV2hpdGVzcGFjZUNvbnRyb2wucHJvdG90eXBlLkRlY29yYXRvciA9XG5XaGl0ZXNwYWNlQ29udHJvbC5wcm90b3R5cGUuTXVzdGFjaGVTdGF0ZW1lbnQgPSBmdW5jdGlvbihtdXN0YWNoZSkge1xuICByZXR1cm4gbXVzdGFjaGUuc3RyaXA7XG59O1xuXG5XaGl0ZXNwYWNlQ29udHJvbC5wcm90b3R5cGUuUGFydGlhbFN0YXRlbWVudCA9XG4gICAgV2hpdGVzcGFjZUNvbnRyb2wucHJvdG90eXBlLkNvbW1lbnRTdGF0ZW1lbnQgPSBmdW5jdGlvbihub2RlKSB7XG4gIC8qIGlzdGFuYnVsIGlnbm9yZSBuZXh0ICovXG4gIGxldCBzdHJpcCA9IG5vZGUuc3RyaXAgfHwge307XG4gIHJldHVybiB7XG4gICAgaW5saW5lU3RhbmRhbG9uZTogdHJ1ZSxcbiAgICBvcGVuOiBzdHJpcC5vcGVuLFxuICAgIGNsb3NlOiBzdHJpcC5jbG9zZVxuICB9O1xufTtcblxuXG5mdW5jdGlvbiBpc1ByZXZXaGl0ZXNwYWNlKGJvZHksIGksIGlzUm9vdCkge1xuICBpZiAoaSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgaSA9IGJvZHkubGVuZ3RoO1xuICB9XG5cbiAgLy8gTm9kZXMgdGhhdCBlbmQgd2l0aCBuZXdsaW5lcyBhcmUgY29uc2lkZXJlZCB3aGl0ZXNwYWNlIChidXQgYXJlIHNwZWNpYWxcbiAgLy8gY2FzZWQgZm9yIHN0cmlwIG9wZXJhdGlvbnMpXG4gIGxldCBwcmV2ID0gYm9keVtpIC0gMV0sXG4gICAgICBzaWJsaW5nID0gYm9keVtpIC0gMl07XG4gIGlmICghcHJldikge1xuICAgIHJldHVybiBpc1Jvb3Q7XG4gIH1cblxuICBpZiAocHJldi50eXBlID09PSAnQ29udGVudFN0YXRlbWVudCcpIHtcbiAgICByZXR1cm4gKHNpYmxpbmcgfHwgIWlzUm9vdCA/ICgvXFxyP1xcblxccyo/JC8pIDogKC8oXnxcXHI/XFxuKVxccyo/JC8pKS50ZXN0KHByZXYub3JpZ2luYWwpO1xuICB9XG59XG5mdW5jdGlvbiBpc05leHRXaGl0ZXNwYWNlKGJvZHksIGksIGlzUm9vdCkge1xuICBpZiAoaSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgaSA9IC0xO1xuICB9XG5cbiAgbGV0IG5leHQgPSBib2R5W2kgKyAxXSxcbiAgICAgIHNpYmxpbmcgPSBib2R5W2kgKyAyXTtcbiAgaWYgKCFuZXh0KSB7XG4gICAgcmV0dXJuIGlzUm9vdDtcbiAgfVxuXG4gIGlmIChuZXh0LnR5cGUgPT09ICdDb250ZW50U3RhdGVtZW50Jykge1xuICAgIHJldHVybiAoc2libGluZyB8fCAhaXNSb290ID8gKC9eXFxzKj9cXHI/XFxuLykgOiAoL15cXHMqPyhcXHI/XFxufCQpLykpLnRlc3QobmV4dC5vcmlnaW5hbCk7XG4gIH1cbn1cblxuLy8gTWFya3MgdGhlIG5vZGUgdG8gdGhlIHJpZ2h0IG9mIHRoZSBwb3NpdGlvbiBhcyBvbWl0dGVkLlxuLy8gSS5lLiB7e2Zvb319JyAnIHdpbGwgbWFyayB0aGUgJyAnIG5vZGUgYXMgb21pdHRlZC5cbi8vXG4vLyBJZiBpIGlzIHVuZGVmaW5lZCwgdGhlbiB0aGUgZmlyc3QgY2hpbGQgd2lsbCBiZSBtYXJrZWQgYXMgc3VjaC5cbi8vXG4vLyBJZiBtdWxpdHBsZSBpcyB0cnV0aHkgdGhlbiBhbGwgd2hpdGVzcGFjZSB3aWxsIGJlIHN0cmlwcGVkIG91dCB1bnRpbCBub24td2hpdGVzcGFjZVxuLy8gY29udGVudCBpcyBtZXQuXG5mdW5jdGlvbiBvbWl0UmlnaHQoYm9keSwgaSwgbXVsdGlwbGUpIHtcbiAgbGV0IGN1cnJlbnQgPSBib2R5W2kgPT0gbnVsbCA/IDAgOiBpICsgMV07XG4gIGlmICghY3VycmVudCB8fCBjdXJyZW50LnR5cGUgIT09ICdDb250ZW50U3RhdGVtZW50JyB8fCAoIW11bHRpcGxlICYmIGN1cnJlbnQucmlnaHRTdHJpcHBlZCkpIHtcbiAgICByZXR1cm47XG4gIH1cblxuICBsZXQgb3JpZ2luYWwgPSBjdXJyZW50LnZhbHVlO1xuICBjdXJyZW50LnZhbHVlID0gY3VycmVudC52YWx1ZS5yZXBsYWNlKG11bHRpcGxlID8gKC9eXFxzKy8pIDogKC9eWyBcXHRdKlxccj9cXG4/LyksICcnKTtcbiAgY3VycmVudC5yaWdodFN0cmlwcGVkID0gY3VycmVudC52YWx1ZSAhPT0gb3JpZ2luYWw7XG59XG5cbi8vIE1hcmtzIHRoZSBub2RlIHRvIHRoZSBsZWZ0IG9mIHRoZSBwb3NpdGlvbiBhcyBvbWl0dGVkLlxuLy8gSS5lLiAnICd7e2Zvb319IHdpbGwgbWFyayB0aGUgJyAnIG5vZGUgYXMgb21pdHRlZC5cbi8vXG4vLyBJZiBpIGlzIHVuZGVmaW5lZCB0aGVuIHRoZSBsYXN0IGNoaWxkIHdpbGwgYmUgbWFya2VkIGFzIHN1Y2guXG4vL1xuLy8gSWYgbXVsaXRwbGUgaXMgdHJ1dGh5IHRoZW4gYWxsIHdoaXRlc3BhY2Ugd2lsbCBiZSBzdHJpcHBlZCBvdXQgdW50aWwgbm9uLXdoaXRlc3BhY2Vcbi8vIGNvbnRlbnQgaXMgbWV0LlxuZnVuY3Rpb24gb21pdExlZnQoYm9keSwgaSwgbXVsdGlwbGUpIHtcbiAgbGV0IGN1cnJlbnQgPSBib2R5W2kgPT0gbnVsbCA/IGJvZHkubGVuZ3RoIC0gMSA6IGkgLSAxXTtcbiAgaWYgKCFjdXJyZW50IHx8IGN1cnJlbnQudHlwZSAhPT0gJ0NvbnRlbnRTdGF0ZW1lbnQnIHx8ICghbXVsdGlwbGUgJiYgY3VycmVudC5sZWZ0U3RyaXBwZWQpKSB7XG4gICAgcmV0dXJuO1xuICB9XG5cbiAgLy8gV2Ugb21pdCB0aGUgbGFzdCBub2RlIGlmIGl0J3Mgd2hpdGVzcGFjZSBvbmx5IGFuZCBub3QgcHJlY2VlZGVkIGJ5IGEgbm9uLWNvbnRlbnQgbm9kZS5cbiAgbGV0IG9yaWdpbmFsID0gY3VycmVudC52YWx1ZTtcbiAgY3VycmVudC52YWx1ZSA9IGN1cnJlbnQudmFsdWUucmVwbGFjZShtdWx0aXBsZSA/ICgvXFxzKyQvKSA6ICgvWyBcXHRdKyQvKSwgJycpO1xuICBjdXJyZW50LmxlZnRTdHJpcHBlZCA9IGN1cnJlbnQudmFsdWUgIT09IG9yaWdpbmFsO1xuICByZXR1cm4gY3VycmVudC5sZWZ0U3RyaXBwZWQ7XG59XG5cbmV4cG9ydCBkZWZhdWx0IFdoaXRlc3BhY2VDb250cm9sO1xuIl19
| {
"pile_set_name": "Github"
} |
/*
* This file is part of Cleanflight.
*
* Cleanflight is free software. You can redistribute
* this software and/or modify this software under the terms of the
* GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* Cleanflight is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software.
*
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include <stdbool.h>
#include "platform.h"
#ifdef USE_TARGET_CONFIG
#include "pg/sdcard.h"
#include "telemetry/telemetry.h"
void targetConfiguration(void)
{
sdcardConfigMutable()->useDma = true;
telemetryConfigMutable()->halfDuplex = 0;
}
#endif
| {
"pile_set_name": "Github"
} |
load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library")
rn_android_library(
name = "toast",
srcs = glob(["**/*.java"]),
visibility = [
"PUBLIC",
],
deps = [
react_native_dep("third-party/java/infer-annotations:infer-annotations"),
react_native_dep("third-party/java/jsr-305:jsr-305"),
react_native_target("java/com/facebook/react/bridge:bridge"),
react_native_target("java/com/facebook/react/common:common"),
react_native_target("java/com/facebook/react/module/annotations:annotations"),
],
exported_deps = [react_native_target("java/com/facebook/fbreact/specs:FBReactNativeSpec")],
)
| {
"pile_set_name": "Github"
} |
#! /bin/bash
set -e
if [ $# != 1 ]; then exit 1; fi
LCOV_DIR=$1
SRC_NAME_LENGTH=28
DIR_NAME_LENGTH=16
COVERAGE_HIGH=90
COVERAGE_MID=75
echo ""
echo "Processing [${LCOV_DIR}] for Coverage Brief"
echo ""
#
# sdk-example / example.c : [100.00%] (7/7) [100.00%] (1/1)
#
[ "$(uname)" != "Darwin" ] && echo -ne "\e[1;36m"
printf "%${DIR_NAME_LENGTH}s %-${SRC_NAME_LENGTH}s: %-24s %-20s\n\n" \
"Directory" \
"Source File" \
"Line Coverage" \
"Function Coverage"
[ "$(uname)" != "Darwin" ] && echo -ne "\e[0m"
REPORT_LIST=$(find ${LCOV_DIR} -mindepth 2 -name "index.html")
for R in ${REPORT_LIST}; do
SOURCE_LIST=$(grep "coverFile" ${R} | awk -F '<' '{ print $3 }' | cut -d'>' -f2)
for S in ${SOURCE_LIST}; do
STATS=$(grep -A 7 "${S}</a>" ${R} | sed -n '6p;8p'|grep -o [0-9]*)
DIR_NAME=$(expr substr $(dirname ${R}|xargs basename) 1 15)
SRC_NAME=$(expr substr ${S} 1 $(( SRC_NAME_LENGTH -1 )))
COVER_LINE=$(echo ${STATS}|cut -d' ' -f1)
TOTAL_LINE=$(echo ${STATS}|cut -d' ' -f2)
COVER_FUNC=$(echo ${STATS}|cut -d' ' -f3)
TOTAL_FUNC=$(echo ${STATS}|cut -d' ' -f4)
LINE_PERCENT="$(echo "scale=2; ${COVER_LINE} * 100 / ${TOTAL_LINE}"|bc -l)%"
FUNC_PERCENT="$(echo "scale=2; ${COVER_FUNC} * 100 / ${TOTAL_FUNC}"|bc -l)%"
printf \
"%-8s %${DIR_NAME_LENGTH}s / %-${SRC_NAME_LENGTH}s: [ %s ] (%s/%s) \t [ %s ] (%s/%s)\n" \
${LINE_PERCENT} \
${DIR_NAME} \
${SRC_NAME} \
${LINE_PERCENT} \
${COVER_LINE} \
${TOTAL_LINE} \
${FUNC_PERCENT} \
${COVER_FUNC} \
${TOTAL_FUNC}
done
done \
| sort -nr \
| cut -d' ' -f2- \
| awk -v SRC_LEN=${SRC_NAME_LENGTH} -v DIR_LEN=${DIR_NAME_LENGTH} \
-v HIGH=${COVERAGE_HIGH} -v MID=${COVERAGE_MID} \
'{
split($6, arr, ".");
if (arr[1] > HIGH)
printf("\033[1;32m");
else if (arr[1] > MID)
printf("\033[1;35m");
else
printf("\033[1;31m");
printf("%" DIR_LEN "s / %-" SRC_LEN "s: [ %-8s] %-12s [ %-8s] %-12s\n",
$1, $3, $6, $8, $10, $12);
printf("\033[0m");
}'
#
# 1 2 3 4 5 6 7 8 9 10 11 12
# sdk-example / example.c : [ 100.00% ] (7/7) [ 100.00% ] (1/1)
#
echo ""
exit 0
| {
"pile_set_name": "Github"
} |
import React, { cloneElement, Component } from 'react';
import PropTypes from 'prop-types';
import arrayTreeFilter from 'array-tree-filter';
import isEqual from 'lodash/isEqual';
import Trigger from '../trigger';
import Icon from '../../icon';
import Menus from './Menus';
import MenusSingle from './MenusSingle';
import KeyCode from '../../_util/KeyCode';
import Locale from './locale/en_US';
const BUILT_IN_PLACEMENTS = {
bottomLeft: {
points: ['tl', 'bl'],
offset: [0, 4],
overflow: {
adjustX: 1,
adjustY: 1,
},
},
topLeft: {
points: ['bl', 'tl'],
offset: [0, -4],
overflow: {
adjustX: 1,
adjustY: 1,
},
},
bottomRight: {
points: ['tr', 'br'],
offset: [0, 4],
overflow: {
adjustX: 1,
adjustY: 1,
},
},
topRight: {
points: ['br', 'tr'],
offset: [0, -4],
overflow: {
adjustX: 1,
adjustY: 1,
},
},
};
export default class Cascader extends Component {
static defaultProps = {
options: [],
onChange() {},
onPopupVisibleChange() {},
disabled: false,
transitionName: '',
prefixCls: 'rc-cascader',
popupClassName: '',
popupPlacement: 'bottomLeft',
builtinPlacements: BUILT_IN_PLACEMENTS,
expandTrigger: 'click',
expandIcon: <Icon type="navigate_next" />,
menuMode:'multiple',
locale:Locale,
};
static propTypes = {
value: PropTypes.array,
defaultValue: PropTypes.array,
options: PropTypes.array.isRequired,
onChange: PropTypes.func,
onPopupVisibleChange: PropTypes.func,
popupVisible: PropTypes.bool,
disabled: PropTypes.bool,
transitionName: PropTypes.string,
popupClassName: PropTypes.string,
popupPlacement: PropTypes.string,
prefixCls: PropTypes.string,
dropdownMenuColumnStyle: PropTypes.object,
builtinPlacements: PropTypes.object,
loadData: PropTypes.func,
changeOnSelect: PropTypes.bool,
children: PropTypes.node,
onKeyDown: PropTypes.func,
expandTrigger: PropTypes.string,
expandIcon: PropTypes.node,
menuMode: PropTypes.string,
locale: PropTypes.object,
singleMenuStyle: PropTypes.object,
singleMenuItemStyle: PropTypes.object,
singlePleaseRender: PropTypes.func,
singleMenuItemRender: PropTypes.func,
};
constructor(props) {
super(props);
let initialValue = [];
if ('value' in props) {
initialValue = props.value || [];
} else if ('defaultValue' in props) {
initialValue = props.defaultValue || [];
}
this.state = {
popupVisible: props.popupVisible,
activeValue: initialValue,
value: initialValue,
isTabSelected: false,
};
}
componentWillReceiveProps(nextProps) {
if ('value' in nextProps && !isEqual(this.props.value, nextProps.value)) {
const newValues = {
value: nextProps.value || [],
activeValue: nextProps.value || [],
};
// allow activeValue diff from value
if ('loadData' in nextProps) {
delete newValues.activeValue;
}
this.setState(newValues);
}
if ('popupVisible' in nextProps) {
this.setState({
popupVisible: nextProps.popupVisible,
});
}
}
getPopupDOMNode() {
return this.trigger.getPopupDomNode();
}
getCurrentLevelOptions() {
const { options } = this.props;
const { activeValue = [] } = this.state;
const result = arrayTreeFilter(options, (o, level) => o.value === activeValue[level]);
if (result[result.length - 2]) {
return result[result.length - 2].children;
}
return [...options].filter(o => !o.disabled);
}
getActiveOptions(activeValue) {
return arrayTreeFilter(this.props.options, (o, level) => o.value === activeValue[level]);
}
setPopupVisible = popupVisible => {
if (!('popupVisible' in this.props)) {
this.setState({ popupVisible });
}
// sync activeValue with value when panel open
if (popupVisible && !this.state.visible) {
this.setState({
activeValue: this.state.value,
});
}
this.props.onPopupVisibleChange(popupVisible);
};
handleChange = (options, setProps, e) => {
if (e.type !== 'keydown' || e.keyCode === KeyCode.ENTER) {
this.props.onChange(options.map(o => o.value), options);
this.setPopupVisible(setProps.visible);
}
};
handlePopupVisibleChange = popupVisible => {
this.setPopupVisible(popupVisible);
};
handleMenuSelect = (targetOption, menuIndex,isTabSelected = false,e) => {
// Keep focused state for keyboard support
const triggerNode = this.trigger.getRootDomNode();
if (triggerNode && triggerNode.focus) {
triggerNode.focus();
}
const { changeOnSelect, loadData, expandTrigger } = this.props;
if (!targetOption || targetOption.disabled) {
return;
}
let { activeValue } = this.state;
activeValue = activeValue.slice(0, menuIndex + 1);
activeValue[menuIndex] = targetOption.value;
const activeOptions = this.getActiveOptions(activeValue);
if (targetOption.isLeaf === false && !targetOption.children && loadData) {
if (changeOnSelect) {
this.handleChange(activeOptions, { visible: true }, e);
}
this.setState({ activeValue,isTabSelected });
loadData(activeOptions);
return;
}
const newState = {};
if (!targetOption.children || !targetOption.children.length) {
this.handleChange(activeOptions, { visible: false }, e);
// set value to activeValue when select leaf option
newState.value = activeValue;
// add e.type judgement to prevent `onChange` being triggered by mouseEnter
} else if (changeOnSelect && (e.type === 'click' || e.type === 'keydown')) {
if (expandTrigger === 'hover') {
this.handleChange(activeOptions, { visible: false }, e);
} else {
this.handleChange(activeOptions, { visible: true }, e);
}
// set value to activeValue on every select
newState.value = activeValue;
}
newState.activeValue = activeValue;
// not change the value by keyboard
if ('value' in this.props || (e.type === 'keydown' && e.keyCode !== KeyCode.ENTER)) {
delete newState.value;
}
newState.isTabSelected = isTabSelected
this.setState(newState);
};
handleKeyDown = e => {
const { children } = this.props;
// Don't bind keyboard support when children specify the onKeyDown
if (children && children.props.onKeyDown) {
children.props.onKeyDown(e);
return;
}
const activeValue = [...this.state.activeValue];
const currentLevel = activeValue.length - 1 < 0 ? 0 : activeValue.length - 1;
const currentOptions = this.getCurrentLevelOptions();
const currentIndex = currentOptions.map(o => o.value).indexOf(activeValue[currentLevel]);
if (
e.keyCode !== KeyCode.DOWN &&
e.keyCode !== KeyCode.UP &&
e.keyCode !== KeyCode.LEFT &&
e.keyCode !== KeyCode.RIGHT &&
e.keyCode !== KeyCode.ENTER &&
e.keyCode !== KeyCode.BACKSPACE &&
e.keyCode !== KeyCode.ESC
) {
return;
}
// Press any keys above to reopen menu
if (
!this.state.popupVisible &&
e.keyCode !== KeyCode.BACKSPACE &&
e.keyCode !== KeyCode.LEFT &&
e.keyCode !== KeyCode.RIGHT &&
e.keyCode !== KeyCode.ESC
) {
this.setPopupVisible(true);
return;
}
if (e.keyCode === KeyCode.DOWN || e.keyCode === KeyCode.UP) {
let nextIndex = currentIndex;
if (nextIndex !== -1) {
if (e.keyCode === KeyCode.DOWN) {
nextIndex += 1;
nextIndex = nextIndex >= currentOptions.length ? 0 : nextIndex;
} else {
nextIndex -= 1;
nextIndex = nextIndex < 0 ? currentOptions.length - 1 : nextIndex;
}
} else {
nextIndex = 0;
}
activeValue[currentLevel] = currentOptions[nextIndex].value;
} else if (e.keyCode === KeyCode.LEFT || e.keyCode === KeyCode.BACKSPACE) {
activeValue.splice(activeValue.length - 1, 1);
} else if (e.keyCode === KeyCode.RIGHT) {
if (currentOptions[currentIndex] && currentOptions[currentIndex].children) {
activeValue.push(currentOptions[currentIndex].children[0].value);
}
} else if (e.keyCode === KeyCode.ESC) {
this.setPopupVisible(false);
return;
}
if (!activeValue || activeValue.length === 0) {
this.setPopupVisible(false);
}
const activeOptions = this.getActiveOptions(activeValue);
const targetOption = activeOptions[activeOptions.length - 1];
this.handleMenuSelect(targetOption, activeOptions.length - 1, false , e);
if (this.props.onKeyDown) {
this.props.onKeyDown(e);
}
};
saveTrigger = node => {
this.trigger = node;
};
render() {
const {
prefixCls,
transitionName,
popupClassName,
options,
disabled,
builtinPlacements,
popupPlacement,
children,
locale,
menuMode,
singleMenuStyle,
singleMenuItemStyle,
...restProps
} = this.props;
// Did not show popup when there is no options
let menus = <div />;
let emptyMenuClassName = '';
if (options && options.length > 0) {
if( menuMode === "multiple") {
menus = (
<Menus
{...this.props}
value={this.state.value}
activeValue={this.state.activeValue}
onSelect={this.handleMenuSelect}
visible={this.state.popupVisible}
/>)
}else if (menuMode === "single" ){
menus = (
<MenusSingle
{...this.props}
isTabSelected={this.state.isTabSelected}
value={this.state.value}
activeValue={this.state.activeValue}
onSelect={this.handleMenuSelect}
visible={this.state.popupVisible}
locale={locale}
singleMenuStyle={singleMenuStyle}
singleMenuItemStyle={singleMenuItemStyle}
/>)
} else {
throw new Error('please use correct mode for menu ex "single" and "multiple"')
}
} else {
emptyMenuClassName = ` ${prefixCls}-menus-empty`;
}
return (
<Trigger
ref={this.saveTrigger}
{...restProps}
options={options}
disabled={disabled}
popupPlacement={popupPlacement}
builtinPlacements={builtinPlacements}
popupTransitionName={transitionName}
action={disabled ? [] : ['click']}
popupVisible={disabled ? false : this.state.popupVisible}
onPopupVisibleChange={this.handlePopupVisibleChange}
prefixCls={`${prefixCls}-menus`}
popupClassName={popupClassName + emptyMenuClassName}
popup={menus}
>
{cloneElement(children, {
onKeyDown: this.handleKeyDown,
tabIndex: disabled ? undefined : 0,
})}
</Trigger>
);
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: a950cf5ed15c8b943b03296567b51781
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
| {
"pile_set_name": "Github"
} |
/*!
* \brief Tests for the class Commands.
*
* \copyright Copyright (c) 2018-2020 Governikus GmbH & Co. KG, Germany
*/
#include "EABuilder.h"
#include "GABuilder.h"
#include "PSOBuilder.h"
#include <QtTest>
using namespace governikus;
class test_Commands
: public QObject
{
Q_OBJECT
private Q_SLOTS:
void test_SetCertificateBody_PSOBuilder()
{
PSOBuilder builder(PSOBuilder::P1::VERIFY, PSOBuilder::P2::CERTIFICATE);
const QByteArray data("data");
builder.setCertificateBody(data);
QCOMPARE(builder.mCertificateBody, data);
}
void test_SetSignature_PSOBuilder()
{
PSOBuilder builder(PSOBuilder::P1::VERIFY, PSOBuilder::P2::CERTIFICATE);
const QByteArray data("data");
builder.setSignature(data);
QCOMPARE(builder.mSignature, data);
}
void test_Build_PSOBuilder()
{
PSOBuilder builder(PSOBuilder::P1::VERIFY, PSOBuilder::P2::CERTIFICATE);
CommandApdu apdu = builder.build();
QCOMPARE(apdu.getINS(), 0x2a);
QCOMPARE(apdu.getP1(), 0x00);
QCOMPARE(apdu.getP2(), '\xbe');
QCOMPARE(apdu.getData(), QByteArray());
}
void test_SetSignatureEABuilder()
{
EABuilder builder;
const QByteArray data("data");
builder.setSignature(data);
QCOMPARE(builder.mSignature, data);
}
void test_Build_EABuilder()
{
EABuilder builder;
const QByteArray data("data");
builder.setSignature(data);
CommandApdu apdu = builder.build();
QCOMPARE(apdu.getINS(), char(0x82));
QCOMPARE(apdu.getP1(), 0);
QCOMPARE(apdu.getP2(), 0);
QCOMPARE(apdu.getData(), data);
}
void test_SetCaEphemeralPublicKey_GABuilder()
{
GABuilder builder;
const QByteArray data("");
builder.setCaEphemeralPublicKey(data);
QCOMPARE(builder.mCaEphemeralPublicKey, QByteArray::fromHex("8000"));
}
void test_SetPaceMappingData_GABuilder()
{
GABuilder builder;
const QByteArray data("");
builder.setPaceMappingData(data);
QCOMPARE(builder.mPaceMappingData, QByteArray::fromHex("8100"));
}
void test_SetPaceEphemeralPublicKey_GABuilder()
{
GABuilder builder;
const QByteArray data("");
builder.setPaceEphemeralPublicKey(data);
QCOMPARE(builder.mPaceEphemeralPublicKey, QByteArray::fromHex("8300"));
}
void test_SetPaceAuthenticationToken_GABuilder()
{
GABuilder builder;
const QByteArray data("");
builder.setPaceAuthenticationToken(data);
QCOMPARE(builder.mPaceAuthenticationToken, QByteArray::fromHex("8500"));
}
};
QTEST_GUILESS_MAIN(test_Commands)
#include "test_Commands.moc"
| {
"pile_set_name": "Github"
} |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build sparc64,linux
package unix
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64
//sys Dup2(oldfd int, newfd int) (err error)
//sys Fchown(fd int, uid int, gid int) (err error)
//sys Fstat(fd int, stat *Stat_t) (err error)
//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64
//sys Fstatfs(fd int, buf *Statfs_t) (err error)
//sys Ftruncate(fd int, length int64) (err error)
//sysnb Getegid() (egid int)
//sysnb Geteuid() (euid int)
//sysnb Getgid() (gid int)
//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Getuid() (uid int)
//sysnb InotifyInit() (fd int, err error)
//sys Lchown(path string, uid int, gid int) (err error)
//sys Listen(s int, n int) (err error)
//sys Lstat(path string, stat *Stat_t) (err error)
//sys Pause() (err error)
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
//sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys Setfsgid(gid int) (err error)
//sys Setfsuid(uid int) (err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
//sys Stat(path string, stat *Stat_t) (err error)
//sys Statfs(path string, buf *Statfs_t) (err error)
//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
//sys Truncate(path string, length int64) (err error)
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb getgroups(n int, list *_Gid_t) (nn int, err error)
//sysnb setgroups(n int, list *_Gid_t) (err error)
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error)
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
func Ioperm(from int, num int, on int) (err error) {
return ENOSYS
}
func Iopl(level int) (err error) {
return ENOSYS
}
//sys futimesat(dirfd int, path string, times *[2]Timeval) (err error)
//sysnb Gettimeofday(tv *Timeval) (err error)
func Time(t *Time_t) (tt Time_t, err error) {
var tv Timeval
err = Gettimeofday(&tv)
if err != nil {
return 0, err
}
if t != nil {
*t = Time_t(tv.Sec)
}
return Time_t(tv.Sec), nil
}
//sys Utime(path string, buf *Utimbuf) (err error)
//sys utimes(path string, times *[2]Timeval) (err error)
func setTimespec(sec, nsec int64) Timespec {
return Timespec{Sec: sec, Nsec: nsec}
}
func setTimeval(sec, usec int64) Timeval {
return Timeval{Sec: sec, Usec: int32(usec)}
}
func (r *PtraceRegs) PC() uint64 { return r.Tpc }
func (r *PtraceRegs) SetPC(pc uint64) { r.Tpc = pc }
func (iov *Iovec) SetLen(length int) {
iov.Len = uint64(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint64(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint64(length)
}
//sysnb pipe(p *[2]_C_int) (err error)
func Pipe(p []int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe(&pp)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
func Pipe2(p []int, flags int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe2(&pp, flags)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
func Poll(fds []PollFd, timeout int) (n int, err error) {
if len(fds) == 0 {
return poll(nil, 0, timeout)
}
return poll(&fds[0], len(fds), timeout)
}
| {
"pile_set_name": "Github"
} |
---
dependencies: []
galaxy_info:
role_name: phpredisadmin
author: Manala
company: Manala
description: Handle phpredisadmin
license: MIT
min_ansible_version: 2.4.0
issue_tracker_url: https://github.com/manala/ansible-roles/issues
platforms:
- name: Debian
versions:
- jessie
- stretch
galaxy_tags:
- development
- phpredisadmin
| {
"pile_set_name": "Github"
} |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chromoting;
import android.app.Application;
import org.chromium.chromoting.accountswitcher.AccountSwitcherFactory;
import org.chromium.chromoting.help.HelpAndFeedbackBasic;
import org.chromium.chromoting.help.HelpSingleton;
import org.chromium.chromoting.jni.JniInterface;
/** Main context for the application. */
public class RemotingApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
JniInterface.loadLibrary(this);
AccountSwitcherFactory.setInstance(new AccountSwitcherFactory());
HelpSingleton.setInstance(new HelpAndFeedbackBasic());
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2012-2017 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* 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.
*/
#pragma once
#if ENABLE(C_LOOP)
#include "CLoopStack.h"
#include "CallFrame.h"
#include "CodeBlock.h"
#include "VM.h"
namespace JSC {
inline bool CLoopStack::ensureCapacityFor(Register* newTopOfStack)
{
if (newTopOfStack >= m_end)
return true;
return grow(newTopOfStack);
}
inline void* CLoopStack::currentStackPointer()
{
// One might be tempted to assert that m_currentStackPointer <= m_topCallFrame->topOfFrame()
// here. That assertion would be incorrect because this function may be called from function
// prologues (e.g. during a stack check) where m_currentStackPointer may be higher than
// m_topCallFrame->topOfFrame() because the stack pointer has not been initialized to point
// to frame top yet.
return m_currentStackPointer;
}
inline void CLoopStack::setCLoopStackLimit(Register* newTopOfStack)
{
m_end = newTopOfStack;
m_vm.setCLoopStackLimit(newTopOfStack);
}
} // namespace JSC
#endif // ENABLE(C_LOOP)
| {
"pile_set_name": "Github"
} |
package com.example.pluginhelloworld;
import android.net.http.AndroidHttpClient;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
/**
* 独立插件测试demo
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.test_close_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.this.finish();
}
});
testUseLibray();
}
private void testUseLibray() {
AndroidHttpClient androidHttpClient = AndroidHttpClient.newInstance("test/test", getApplicationContext());
ClassLoader classloader = androidHttpClient.getClass().getClassLoader();
Log.e("MainActivity", "testUseLibray, classloader=" + classloader);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_welcome, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| {
"pile_set_name": "Github"
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use caseless::compatibility_caseless_match_str;
use dom::activation::{Activatable, ActivationSource, synthetic_click_activation};
use dom::attr::Attr;
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::FileListBinding::FileListMethods;
use dom::bindings::codegen::Bindings::HTMLInputElementBinding;
use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
use dom::bindings::codegen::Bindings::KeyboardEventBinding::KeyboardEventMethods;
use dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::error::{Error, ErrorResult};
use dom::bindings::inheritance::Castable;
use dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, RootedReference};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element, LayoutElementHelpers, RawLayoutElementHelpers};
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget;
use dom::file::File;
use dom::filelist::FileList;
use dom::globalscope::GlobalScope;
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlformelement::{FormControl, FormDatum, FormDatumValue, FormSubmitter, HTMLFormElement};
use dom::htmlformelement::{ResetFrom, SubmittedFrom};
use dom::keyboardevent::KeyboardEvent;
use dom::mouseevent::MouseEvent;
use dom::node::{Node, NodeDamage, UnbindContext};
use dom::node::{document_from_node, window_from_node};
use dom::nodelist::NodeList;
use dom::validation::Validatable;
use dom::validitystate::ValidationFlags;
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use ipc_channel::ipc::channel;
use mime_guess;
use net_traits::{CoreResourceMsg, IpcSend};
use net_traits::blob_url_store::get_blob_origin;
use net_traits::filemanager_thread::{FileManagerThreadMsg, FilterPattern};
use script_layout_interface::rpc::TextIndexResponse;
use script_traits::ScriptToConstellationChan;
use servo_atoms::Atom;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ops::Range;
use style::attr::AttrValue;
use style::element_state::*;
use style::str::split_commas;
use textinput::{SelectionDirection, TextInput};
use textinput::KeyReaction::{DispatchInput, Nothing, RedrawSelection, TriggerDefaultAction};
use textinput::Lines::Single;
const DEFAULT_SUBMIT_VALUE: &'static str = "Submit";
const DEFAULT_RESET_VALUE: &'static str = "Reset";
const PASSWORD_REPLACEMENT_CHAR: char = '●';
#[derive(Clone, Copy, JSTraceable, PartialEq)]
#[allow(dead_code)]
#[derive(HeapSizeOf)]
enum InputType {
InputSubmit,
InputReset,
InputButton,
InputText,
InputFile,
InputImage,
InputCheckbox,
InputRadio,
InputPassword
}
#[derive(Debug, PartialEq)]
enum ValueMode {
Value,
Default,
DefaultOn,
Filename,
}
#[dom_struct]
pub struct HTMLInputElement {
htmlelement: HTMLElement,
input_type: Cell<InputType>,
checked_changed: Cell<bool>,
placeholder: DomRefCell<DOMString>,
value_changed: Cell<bool>,
size: Cell<u32>,
maxlength: Cell<i32>,
minlength: Cell<i32>,
#[ignore_heap_size_of = "#7193"]
textinput: DomRefCell<TextInput<ScriptToConstellationChan>>,
activation_state: DomRefCell<InputActivationState>,
// https://html.spec.whatwg.org/multipage/#concept-input-value-dirty-flag
value_dirty: Cell<bool>,
filelist: MutNullableDom<FileList>,
form_owner: MutNullableDom<HTMLFormElement>,
}
#[derive(JSTraceable)]
#[must_root]
#[derive(HeapSizeOf)]
struct InputActivationState {
indeterminate: bool,
checked: bool,
checked_changed: bool,
checked_radio: Option<Dom<HTMLInputElement>>,
// In case mutability changed
was_mutable: bool,
// In case the type changed
old_type: InputType,
}
impl InputActivationState {
fn new() -> InputActivationState {
InputActivationState {
indeterminate: false,
checked: false,
checked_changed: false,
checked_radio: None,
was_mutable: false,
old_type: InputType::InputText
}
}
}
static DEFAULT_INPUT_SIZE: u32 = 20;
static DEFAULT_MAX_LENGTH: i32 = -1;
static DEFAULT_MIN_LENGTH: i32 = -1;
impl HTMLInputElement {
fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLInputElement {
let chan = document.window().upcast::<GlobalScope>().script_to_constellation_chan().clone();
HTMLInputElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE | IN_READ_WRITE_STATE,
local_name, prefix, document),
input_type: Cell::new(InputType::InputText),
placeholder: DomRefCell::new(DOMString::new()),
checked_changed: Cell::new(false),
value_changed: Cell::new(false),
maxlength: Cell::new(DEFAULT_MAX_LENGTH),
minlength: Cell::new(DEFAULT_MIN_LENGTH),
size: Cell::new(DEFAULT_INPUT_SIZE),
textinput: DomRefCell::new(TextInput::new(Single,
DOMString::new(),
chan,
None,
None,
SelectionDirection::None)),
activation_state: DomRefCell::new(InputActivationState::new()),
value_dirty: Cell::new(false),
filelist: MutNullableDom::new(None),
form_owner: Default::default(),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> DomRoot<HTMLInputElement> {
Node::reflect_node(box HTMLInputElement::new_inherited(local_name, prefix, document),
document,
HTMLInputElementBinding::Wrap)
}
pub fn type_(&self) -> Atom {
self.upcast::<Element>()
.get_attribute(&ns!(), &local_name!("type"))
.map_or_else(|| atom!(""), |a| a.value().as_atom().to_owned())
}
// https://html.spec.whatwg.org/multipage/#input-type-attr-summary
fn value_mode(&self) -> ValueMode {
match self.input_type.get() {
InputType::InputSubmit |
InputType::InputReset |
InputType::InputButton |
InputType::InputImage => ValueMode::Default,
InputType::InputCheckbox |
InputType::InputRadio => ValueMode::DefaultOn,
InputType::InputPassword |
InputType::InputText => ValueMode::Value,
InputType::InputFile => ValueMode::Filename,
}
}
}
pub trait LayoutHTMLInputElementHelpers {
#[allow(unsafe_code)]
unsafe fn value_for_layout(self) -> String;
#[allow(unsafe_code)]
unsafe fn size_for_layout(self) -> u32;
#[allow(unsafe_code)]
unsafe fn selection_for_layout(self) -> Option<Range<usize>>;
#[allow(unsafe_code)]
unsafe fn checked_state_for_layout(self) -> bool;
#[allow(unsafe_code)]
unsafe fn indeterminate_state_for_layout(self) -> bool;
}
#[allow(unsafe_code)]
unsafe fn get_raw_textinput_value(input: LayoutDom<HTMLInputElement>) -> DOMString {
(*input.unsafe_get()).textinput.borrow_for_layout().get_content()
}
impl LayoutHTMLInputElementHelpers for LayoutDom<HTMLInputElement> {
#[allow(unsafe_code)]
unsafe fn value_for_layout(self) -> String {
#[allow(unsafe_code)]
unsafe fn get_raw_attr_value(input: LayoutDom<HTMLInputElement>, default: &str) -> String {
let elem = input.upcast::<Element>();
let value = (*elem.unsafe_get())
.get_attr_val_for_layout(&ns!(), &local_name!("value"))
.unwrap_or(default);
String::from(value)
}
match (*self.unsafe_get()).input_type.get() {
InputType::InputCheckbox | InputType::InputRadio => String::new(),
InputType::InputFile | InputType::InputImage => String::new(),
InputType::InputButton => get_raw_attr_value(self, ""),
InputType::InputSubmit => get_raw_attr_value(self, DEFAULT_SUBMIT_VALUE),
InputType::InputReset => get_raw_attr_value(self, DEFAULT_RESET_VALUE),
InputType::InputPassword => {
let text = get_raw_textinput_value(self);
if !text.is_empty() {
text.chars().map(|_| PASSWORD_REPLACEMENT_CHAR).collect()
} else {
String::from((*self.unsafe_get()).placeholder.borrow_for_layout().clone())
}
},
_ => {
let text = get_raw_textinput_value(self);
if !text.is_empty() {
String::from(text)
} else {
String::from((*self.unsafe_get()).placeholder.borrow_for_layout().clone())
}
},
}
}
#[allow(unrooted_must_root)]
#[allow(unsafe_code)]
unsafe fn size_for_layout(self) -> u32 {
(*self.unsafe_get()).size.get()
}
#[allow(unrooted_must_root)]
#[allow(unsafe_code)]
unsafe fn selection_for_layout(self) -> Option<Range<usize>> {
if !(*self.unsafe_get()).upcast::<Element>().focus_state() {
return None;
}
let textinput = (*self.unsafe_get()).textinput.borrow_for_layout();
match (*self.unsafe_get()).input_type.get() {
InputType::InputPassword => {
let text = get_raw_textinput_value(self);
let sel = textinput.get_absolute_selection_range();
// Translate indices from the raw value to indices in the replacement value.
let char_start = text[.. sel.start].chars().count();
let char_end = char_start + text[sel].chars().count();
let bytes_per_char = PASSWORD_REPLACEMENT_CHAR.len_utf8();
Some(char_start * bytes_per_char .. char_end * bytes_per_char)
}
InputType::InputText => Some(textinput.get_absolute_selection_range()),
_ => None
}
}
#[allow(unrooted_must_root)]
#[allow(unsafe_code)]
unsafe fn checked_state_for_layout(self) -> bool {
self.upcast::<Element>().get_state_for_layout().contains(IN_CHECKED_STATE)
}
#[allow(unrooted_must_root)]
#[allow(unsafe_code)]
unsafe fn indeterminate_state_for_layout(self) -> bool {
self.upcast::<Element>().get_state_for_layout().contains(IN_INDETERMINATE_STATE)
}
}
impl HTMLInputElementMethods for HTMLInputElement {
// https://html.spec.whatwg.org/multipage/#dom-input-accept
make_getter!(Accept, "accept");
// https://html.spec.whatwg.org/multipage/#dom-input-accept
make_setter!(SetAccept, "accept");
// https://html.spec.whatwg.org/multipage/#dom-input-alt
make_getter!(Alt, "alt");
// https://html.spec.whatwg.org/multipage/#dom-input-alt
make_setter!(SetAlt, "alt");
// https://html.spec.whatwg.org/multipage/#dom-input-dirName
make_getter!(DirName, "dirname");
// https://html.spec.whatwg.org/multipage/#dom-input-dirName
make_setter!(SetDirName, "dirname");
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
self.form_owner()
}
// https://html.spec.whatwg.org/multipage/#dom-input-files
fn GetFiles(&self) -> Option<DomRoot<FileList>> {
match self.filelist.get() {
Some(ref fl) => Some(fl.clone()),
None => None,
}
}
// https://html.spec.whatwg.org/multipage/#dom-input-defaultchecked
make_bool_getter!(DefaultChecked, "checked");
// https://html.spec.whatwg.org/multipage/#dom-input-defaultchecked
make_bool_setter!(SetDefaultChecked, "checked");
// https://html.spec.whatwg.org/multipage/#dom-input-checked
fn Checked(&self) -> bool {
self.upcast::<Element>().state().contains(IN_CHECKED_STATE)
}
// https://html.spec.whatwg.org/multipage/#dom-input-checked
fn SetChecked(&self, checked: bool) {
self.update_checked_state(checked, true);
}
// https://html.spec.whatwg.org/multipage/#dom-input-readonly
make_bool_getter!(ReadOnly, "readonly");
// https://html.spec.whatwg.org/multipage/#dom-input-readonly
make_bool_setter!(SetReadOnly, "readonly");
// https://html.spec.whatwg.org/multipage/#dom-input-size
make_uint_getter!(Size, "size", DEFAULT_INPUT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-input-size
make_limited_uint_setter!(SetSize, "size", DEFAULT_INPUT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-input-type
make_enumerated_getter!(Type,
"type",
"text",
"hidden" | "search" | "tel" |
"url" | "email" | "password" |
"datetime" | "date" | "month" |
"week" | "time" | "datetime-local" |
"number" | "range" | "color" |
"checkbox" | "radio" | "file" |
"submit" | "image" | "reset" | "button");
// https://html.spec.whatwg.org/multipage/#dom-input-type
make_atomic_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-input-value
fn Value(&self) -> DOMString {
match self.value_mode() {
ValueMode::Value => self.textinput.borrow().get_content(),
ValueMode::Default => {
self.upcast::<Element>()
.get_attribute(&ns!(), &local_name!("value"))
.map_or(DOMString::from(""),
|a| DOMString::from(a.summarize().value))
}
ValueMode::DefaultOn => {
self.upcast::<Element>()
.get_attribute(&ns!(), &local_name!("value"))
.map_or(DOMString::from("on"),
|a| DOMString::from(a.summarize().value))
}
ValueMode::Filename => {
let mut path = DOMString::from("");
match self.filelist.get() {
Some(ref fl) => match fl.Item(0) {
Some(ref f) => {
path.push_str("C:\\fakepath\\");
path.push_str(f.name());
path
}
None => path,
},
None => path,
}
}
}
}
// https://html.spec.whatwg.org/multipage/#dom-input-value
fn SetValue(&self, value: DOMString) -> ErrorResult {
match self.value_mode() {
ValueMode::Value => {
self.textinput.borrow_mut().set_content(value);
self.value_dirty.set(true);
}
ValueMode::Default |
ValueMode::DefaultOn => {
self.upcast::<Element>().set_string_attribute(&local_name!("value"), value);
}
ValueMode::Filename => {
if value.is_empty() {
let window = window_from_node(self);
let fl = FileList::new(&window, vec![]);
self.filelist.set(Some(&fl));
} else {
return Err(Error::InvalidState);
}
}
}
self.value_changed.set(true);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-input-defaultvalue
make_getter!(DefaultValue, "value");
// https://html.spec.whatwg.org/multipage/#dom-input-defaultvalue
make_setter!(SetDefaultValue, "value");
// https://html.spec.whatwg.org/multipage/#attr-fe-name
make_getter!(Name, "name");
// https://html.spec.whatwg.org/multipage/#attr-fe-name
make_atomic_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-input-placeholder
make_getter!(Placeholder, "placeholder");
// https://html.spec.whatwg.org/multipage/#dom-input-placeholder
make_setter!(SetPlaceholder, "placeholder");
// https://html.spec.whatwg.org/multipage/#dom-input-formaction
make_url_or_base_getter!(FormAction, "formaction");
// https://html.spec.whatwg.org/multipage/#dom-input-formaction
make_setter!(SetFormAction, "formaction");
// https://html.spec.whatwg.org/multipage/#dom-input-formenctype
make_enumerated_getter!(FormEnctype,
"formenctype",
"application/x-www-form-urlencoded",
"text/plain" | "multipart/form-data");
// https://html.spec.whatwg.org/multipage/#dom-input-formenctype
make_setter!(SetFormEnctype, "formenctype");
// https://html.spec.whatwg.org/multipage/#dom-input-formmethod
make_enumerated_getter!(FormMethod, "formmethod", "get", "post" | "dialog");
// https://html.spec.whatwg.org/multipage/#dom-input-formmethod
make_setter!(SetFormMethod, "formmethod");
// https://html.spec.whatwg.org/multipage/#dom-input-formtarget
make_getter!(FormTarget, "formtarget");
// https://html.spec.whatwg.org/multipage/#dom-input-formtarget
make_setter!(SetFormTarget, "formtarget");
// https://html.spec.whatwg.org/multipage/#attr-fs-formnovalidate
make_bool_getter!(FormNoValidate, "formnovalidate");
// https://html.spec.whatwg.org/multipage/#attr-fs-formnovalidate
make_bool_setter!(SetFormNoValidate, "formnovalidate");
// https://html.spec.whatwg.org/multipage/#dom-input-max
make_getter!(Max, "max");
// https://html.spec.whatwg.org/multipage/#dom-input-max
make_setter!(SetMax, "max");
// https://html.spec.whatwg.org/multipage/#dom-input-maxlength
make_int_getter!(MaxLength, "maxlength", DEFAULT_MAX_LENGTH);
// https://html.spec.whatwg.org/multipage/#dom-input-maxlength
make_limited_int_setter!(SetMaxLength, "maxlength", DEFAULT_MAX_LENGTH);
// https://html.spec.whatwg.org/multipage/#dom-input-minlength
make_int_getter!(MinLength, "minlength", DEFAULT_MIN_LENGTH);
// https://html.spec.whatwg.org/multipage/#dom-input-minlength
make_limited_int_setter!(SetMinLength, "minlength", DEFAULT_MIN_LENGTH);
// https://html.spec.whatwg.org/multipage/#dom-input-min
make_getter!(Min, "min");
// https://html.spec.whatwg.org/multipage/#dom-input-min
make_setter!(SetMin, "min");
// https://html.spec.whatwg.org/multipage/#dom-input-multiple
make_bool_getter!(Multiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-input-multiple
make_bool_setter!(SetMultiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-input-pattern
make_getter!(Pattern, "pattern");
// https://html.spec.whatwg.org/multipage/#dom-input-pattern
make_setter!(SetPattern, "pattern");
// https://html.spec.whatwg.org/multipage/#dom-input-required
make_bool_getter!(Required, "required");
// https://html.spec.whatwg.org/multipage/#dom-input-required
make_bool_setter!(SetRequired, "required");
// https://html.spec.whatwg.org/multipage/#dom-input-src
make_url_getter!(Src, "src");
// https://html.spec.whatwg.org/multipage/#dom-input-src
make_url_setter!(SetSrc, "src");
// https://html.spec.whatwg.org/multipage/#dom-input-step
make_getter!(Step, "step");
// https://html.spec.whatwg.org/multipage/#dom-input-step
make_setter!(SetStep, "step");
// https://html.spec.whatwg.org/multipage/#dom-input-indeterminate
fn Indeterminate(&self) -> bool {
self.upcast::<Element>().state().contains(IN_INDETERMINATE_STATE)
}
// https://html.spec.whatwg.org/multipage/#dom-input-indeterminate
fn SetIndeterminate(&self, val: bool) {
self.upcast::<Element>().set_state(IN_INDETERMINATE_STATE, val)
}
// https://html.spec.whatwg.org/multipage/#dom-lfe-labels
fn Labels(&self) -> DomRoot<NodeList> {
if self.type_() == atom!("hidden") {
let window = window_from_node(self);
NodeList::empty(&window)
} else {
self.upcast::<HTMLElement>().labels()
}
}
// https://html.spec.whatwg.org/multipage/#dom-input-selectionstart
fn SelectionStart(&self) -> u32 {
self.textinput.borrow().get_selection_start()
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionstart
fn SetSelectionStart(&self, start: u32) {
let selection_end = self.SelectionEnd();
self.textinput.borrow_mut().set_selection_range(start, selection_end);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionend
fn SelectionEnd(&self) -> u32 {
self.textinput.borrow().get_absolute_insertion_point() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionend
fn SetSelectionEnd(&self, end: u32) {
let selection_start = self.SelectionStart();
self.textinput.borrow_mut().set_selection_range(selection_start, end);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectiondirection
fn SelectionDirection(&self) -> DOMString {
DOMString::from(self.textinput.borrow().selection_direction)
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectiondirection
fn SetSelectionDirection(&self, direction: DOMString) {
self.textinput.borrow_mut().selection_direction = SelectionDirection::from(direction);
}
// https://html.spec.whatwg.org/multipage/#dom-textarea/input-setselectionrange
fn SetSelectionRange(&self, start: u32, end: u32, direction: Option<DOMString>) {
let direction = direction.map_or(SelectionDirection::None, |d| SelectionDirection::from(d));
self.textinput.borrow_mut().selection_direction = direction;
self.textinput.borrow_mut().set_selection_range(start, end);
let window = window_from_node(self);
let _ = window.user_interaction_task_source().queue_event(
&self.upcast(),
atom!("select"),
EventBubbles::Bubbles,
EventCancelable::NotCancelable,
&window);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
// Select the files based on filepaths passed in,
// enabled by dom.htmlinputelement.select_files.enabled,
// used for test purpose.
// check-tidy: no specs after this line
fn SelectFiles(&self, paths: Vec<DOMString>) {
if self.input_type.get() == InputType::InputFile {
self.select_files(Some(paths));
}
}
}
#[allow(unsafe_code)]
fn broadcast_radio_checked(broadcaster: &HTMLInputElement, group: Option<&Atom>) {
match group {
None | Some(&atom!("")) => {
// Radio input elements with a missing or empty name are alone in their
// own group.
return;
},
_ => {},
}
//TODO: if not in document, use root ancestor instead of document
let owner = broadcaster.form_owner();
let doc = document_from_node(broadcaster);
// This function is a workaround for lifetime constraint difficulties.
fn do_broadcast(doc_node: &Node, broadcaster: &HTMLInputElement,
owner: Option<&HTMLFormElement>, group: Option<&Atom>) {
let iter = doc_node.query_selector_iter(DOMString::from("input[type=radio]")).unwrap()
.filter_map(DomRoot::downcast::<HTMLInputElement>)
.filter(|r| in_same_group(&r, owner, group) && broadcaster != &**r);
for ref r in iter {
if r.Checked() {
r.SetChecked(false);
}
}
}
do_broadcast(doc.upcast(), broadcaster, owner.r(), group)
}
// https://html.spec.whatwg.org/multipage/#radio-button-group
fn in_same_group(other: &HTMLInputElement, owner: Option<&HTMLFormElement>,
group: Option<&Atom>) -> bool {
other.input_type.get() == InputType::InputRadio &&
// TODO Both a and b are in the same home subtree.
other.form_owner().r() == owner &&
match (other.radio_group_name(), group) {
(Some(ref s1), Some(s2)) => compatibility_caseless_match_str(s1, s2) && s2 != &atom!(""),
_ => false
}
}
impl HTMLInputElement {
fn radio_group_updated(&self, group: Option<&Atom>) {
if self.Checked() {
broadcast_radio_checked(self, group);
}
}
/// https://html.spec.whatwg.org/multipage/#constructing-the-form-data-set
/// Steps range from 3.1 to 3.7 (specific to HTMLInputElement)
pub fn form_datums(&self, submitter: Option<FormSubmitter>) -> Vec<FormDatum> {
// 3.1: disabled state check is in get_unclean_dataset
// Step 3.2
let ty = self.type_();
// Step 3.4
let name = self.Name();
let is_submitter = match submitter {
Some(FormSubmitter::InputElement(s)) => {
self == s
},
_ => false
};
match ty {
// Step 3.1: it's a button but it is not submitter.
atom!("submit") | atom!("button") | atom!("reset") if !is_submitter => return vec![],
// Step 3.1: it's the "Checkbox" or "Radio Button" and whose checkedness is false.
atom!("radio") | atom!("checkbox") => if !self.Checked() || name.is_empty() {
return vec![];
},
atom!("file") => {
let mut datums = vec![];
// Step 3.2-3.7
let name = self.Name();
let type_ = self.Type();
match self.GetFiles() {
Some(fl) => {
for f in fl.iter_files() {
datums.push(FormDatum {
ty: type_.clone(),
name: name.clone(),
value: FormDatumValue::File(DomRoot::from_ref(&f)),
});
}
}
None => {
datums.push(FormDatum {
// XXX(izgzhen): Spec says 'application/octet-stream' as the type,
// but this is _type_ of element rather than content right?
ty: type_.clone(),
name: name.clone(),
value: FormDatumValue::String(DOMString::from("")),
})
}
}
return datums;
}
atom!("image") => return vec![], // Unimplemented
// Step 3.1: it's not the "Image Button" and doesn't have a name attribute.
_ => if name.is_empty() {
return vec![];
}
}
// Step 3.9
vec![FormDatum {
ty: DOMString::from(&*ty), // FIXME(ajeffrey): Convert directly from Atoms to DOMStrings
name: name,
value: FormDatumValue::String(self.Value())
}]
}
// https://html.spec.whatwg.org/multipage/#radio-button-group
fn radio_group_name(&self) -> Option<Atom> {
//TODO: determine form owner
self.upcast::<Element>()
.get_attribute(&ns!(), &local_name!("name"))
.map(|name| name.value().as_atom().clone())
}
fn update_checked_state(&self, checked: bool, dirty: bool) {
self.upcast::<Element>().set_state(IN_CHECKED_STATE, checked);
if dirty {
self.checked_changed.set(true);
}
if self.input_type.get() == InputType::InputRadio && checked {
broadcast_radio_checked(self,
self.radio_group_name().as_ref());
}
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
//TODO: dispatch change event
}
// https://html.spec.whatwg.org/multipage/#concept-fe-mutable
fn is_mutable(&self) -> bool {
// https://html.spec.whatwg.org/multipage/#the-input-element:concept-fe-mutable
// https://html.spec.whatwg.org/multipage/#the-readonly-attribute:concept-fe-mutable
!(self.upcast::<Element>().disabled_state() || self.ReadOnly())
}
// https://html.spec.whatwg.org/multipage/#the-input-element:concept-form-reset-control
pub fn reset(&self) {
match self.input_type.get() {
InputType::InputRadio | InputType::InputCheckbox => {
self.update_checked_state(self.DefaultChecked(), false);
self.checked_changed.set(false);
},
InputType::InputImage => (),
_ => ()
}
self.SetValue(self.DefaultValue())
.expect("Failed to reset input value to default.");
self.value_dirty.set(false);
self.value_changed.set(false);
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
}
fn update_placeholder_shown_state(&self) {
match self.input_type.get() {
InputType::InputText | InputType::InputPassword => {},
_ => return,
}
let has_placeholder = !self.placeholder.borrow().is_empty();
let has_value = !self.textinput.borrow().is_empty();
let el = self.upcast::<Element>();
el.set_placeholder_shown_state(has_placeholder && !has_value);
}
// https://html.spec.whatwg.org/multipage/#file-upload-state-(type=file)
// Select files by invoking UI or by passed in argument
fn select_files(&self, opt_test_paths: Option<Vec<DOMString>>) {
let window = window_from_node(self);
let origin = get_blob_origin(&window.get_url());
let resource_threads = window.upcast::<GlobalScope>().resource_threads();
let mut files: Vec<DomRoot<File>> = vec![];
let mut error = None;
let filter = filter_from_accept(&self.Accept());
let target = self.upcast::<EventTarget>();
if self.Multiple() {
let opt_test_paths = opt_test_paths.map(|paths| paths.iter().map(|p| p.to_string()).collect());
let (chan, recv) = channel().expect("Error initializing channel");
let msg = FileManagerThreadMsg::SelectFiles(filter, chan, origin, opt_test_paths);
let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)).unwrap();
match recv.recv().expect("IpcSender side error") {
Ok(selected_files) => {
for selected in selected_files {
files.push(File::new_from_selected(&window, selected));
}
},
Err(err) => error = Some(err),
};
} else {
let opt_test_path = match opt_test_paths {
Some(paths) => {
if paths.len() == 0 {
return;
} else {
Some(paths[0].to_string()) // neglect other paths
}
}
None => None,
};
let (chan, recv) = channel().expect("Error initializing channel");
let msg = FileManagerThreadMsg::SelectFile(filter, chan, origin, opt_test_path);
let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)).unwrap();
match recv.recv().expect("IpcSender side error") {
Ok(selected) => {
files.push(File::new_from_selected(&window, selected));
},
Err(err) => error = Some(err),
};
}
if let Some(err) = error {
debug!("Input file select error: {:?}", err);
} else {
let filelist = FileList::new(&window, files);
self.filelist.set(Some(&filelist));
target.fire_bubbling_event(atom!("input"));
target.fire_bubbling_event(atom!("change"));
}
}
}
impl VirtualMethods for HTMLInputElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&local_name!("disabled") => {
let disabled_state = match mutation {
AttributeMutation::Set(None) => true,
AttributeMutation::Set(Some(_)) => {
// Input was already disabled before.
return;
},
AttributeMutation::Removed => false,
};
let el = self.upcast::<Element>();
el.set_disabled_state(disabled_state);
el.set_enabled_state(!disabled_state);
el.check_ancestors_disabled_state_for_form_control();
if self.input_type.get() == InputType::InputText {
let read_write = !(self.ReadOnly() || el.disabled_state());
el.set_read_write_state(read_write);
}
},
&local_name!("checked") if !self.checked_changed.get() => {
let checked_state = match mutation {
AttributeMutation::Set(None) => true,
AttributeMutation::Set(Some(_)) => {
// Input was already checked before.
return;
},
AttributeMutation::Removed => false,
};
self.update_checked_state(checked_state, false);
},
&local_name!("size") => {
let size = mutation.new_value(attr).map(|value| {
value.as_uint()
});
self.size.set(size.unwrap_or(DEFAULT_INPUT_SIZE));
}
&local_name!("type") => {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
let new_type = match attr.value().as_atom() {
&atom!("button") => InputType::InputButton,
&atom!("submit") => InputType::InputSubmit,
&atom!("reset") => InputType::InputReset,
&atom!("file") => InputType::InputFile,
&atom!("radio") => InputType::InputRadio,
&atom!("checkbox") => InputType::InputCheckbox,
&atom!("password") => InputType::InputPassword,
_ => InputType::InputText,
};
// https://html.spec.whatwg.org/multipage/#input-type-change
let (old_value_mode, old_idl_value) = (self.value_mode(), self.Value());
self.input_type.set(new_type);
if new_type == InputType::InputText {
let read_write = !(self.ReadOnly() || el.disabled_state());
el.set_read_write_state(read_write);
} else {
el.set_read_write_state(false);
}
if new_type == InputType::InputFile {
let window = window_from_node(self);
let filelist = FileList::new(&window, vec![]);
self.filelist.set(Some(&filelist));
}
let new_value_mode = self.value_mode();
match (&old_value_mode, old_idl_value.is_empty(), new_value_mode) {
// Step 1
(&ValueMode::Value, false, ValueMode::Default) |
(&ValueMode::Value, false, ValueMode::DefaultOn) => {
self.SetValue(old_idl_value)
.expect("Failed to set input value on type change to a default ValueMode.");
}
// Step 2
(_, _, ValueMode::Value) if old_value_mode != ValueMode::Value => {
self.SetValue(self.upcast::<Element>()
.get_attribute(&ns!(), &local_name!("value"))
.map_or(DOMString::from(""),
|a| DOMString::from(a.summarize().value)))
.expect("Failed to set input value on type change to ValueMode::Value.");
self.value_dirty.set(false);
}
// Step 3
(_, _, ValueMode::Filename) if old_value_mode != ValueMode::Filename => {
self.SetValue(DOMString::from(""))
.expect("Failed to set input value on type change to ValueMode::Filename.");
}
_ => {}
}
// Step 5
if new_type == InputType::InputRadio {
self.radio_group_updated(
self.radio_group_name().as_ref());
}
// TODO: Step 6 - value sanitization
},
AttributeMutation::Removed => {
if self.input_type.get() == InputType::InputRadio {
broadcast_radio_checked(
self,
self.radio_group_name().as_ref());
}
self.input_type.set(InputType::InputText);
let el = self.upcast::<Element>();
let read_write = !(self.ReadOnly() || el.disabled_state());
el.set_read_write_state(read_write);
}
}
self.update_placeholder_shown_state();
},
&local_name!("value") if !self.value_changed.get() => {
let value = mutation.new_value(attr).map(|value| (**value).to_owned());
self.textinput.borrow_mut().set_content(
value.map_or(DOMString::new(), DOMString::from));
self.update_placeholder_shown_state();
},
&local_name!("name") if self.input_type.get() == InputType::InputRadio => {
self.radio_group_updated(
mutation.new_value(attr).as_ref().map(|name| name.as_atom()));
},
&local_name!("maxlength") => {
match *attr.value() {
AttrValue::Int(_, value) => {
if value < 0 {
self.textinput.borrow_mut().max_length = None
} else {
self.textinput.borrow_mut().max_length = Some(value as usize)
}
},
_ => panic!("Expected an AttrValue::Int"),
}
},
&local_name!("minlength") => {
match *attr.value() {
AttrValue::Int(_, value) => {
if value < 0 {
self.textinput.borrow_mut().min_length = None
} else {
self.textinput.borrow_mut().min_length = Some(value as usize)
}
},
_ => panic!("Expected an AttrValue::Int"),
}
},
&local_name!("placeholder") => {
{
let mut placeholder = self.placeholder.borrow_mut();
placeholder.clear();
if let AttributeMutation::Set(_) = mutation {
placeholder.extend(
attr.value().chars().filter(|&c| c != '\n' && c != '\r'));
}
}
self.update_placeholder_shown_state();
},
&local_name!("readonly") if self.input_type.get() == InputType::InputText => {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
el.set_read_write_state(false);
},
AttributeMutation::Removed => {
el.set_read_write_state(!el.disabled_state());
}
}
},
&local_name!("form") => {
self.form_attribute_mutated(mutation);
},
_ => {},
}
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("accept") => AttrValue::from_comma_separated_tokenlist(value.into()),
&local_name!("name") => AttrValue::from_atomic(value.into()),
&local_name!("size") => AttrValue::from_limited_u32(value.into(), DEFAULT_INPUT_SIZE),
&local_name!("type") => AttrValue::from_atomic(value.into()),
&local_name!("maxlength") => AttrValue::from_limited_i32(value.into(), DEFAULT_MAX_LENGTH),
&local_name!("minlength") => AttrValue::from_limited_i32(value.into(), DEFAULT_MIN_LENGTH),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, context: &UnbindContext) {
self.super_type().unwrap().unbind_from_tree(context);
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) {
el.check_ancestors_disabled_state_for_form_control();
} else {
el.check_disabled_attribute();
}
}
fn handle_event(&self, event: &Event) {
if let Some(s) = self.super_type() {
s.handle_event(event);
}
if event.type_() == atom!("click") && !event.DefaultPrevented() {
// TODO: Dispatch events for non activatable inputs
// https://html.spec.whatwg.org/multipage/#common-input-element-events
//TODO: set the editing position for text inputs
document_from_node(self).request_focus(self.upcast());
if (self.input_type.get() == InputType::InputText ||
self.input_type.get() == InputType::InputPassword) &&
// Check if we display a placeholder. Layout doesn't know about this.
!self.textinput.borrow().is_empty() {
if let Some(mouse_event) = event.downcast::<MouseEvent>() {
// dispatch_key_event (document.rs) triggers a click event when releasing
// the space key. There's no nice way to catch this so let's use this for
// now.
if !(mouse_event.ScreenX() == 0 && mouse_event.ScreenY() == 0 &&
mouse_event.GetRelatedTarget().is_none()) {
let window = window_from_node(self);
let translated_x = mouse_event.ClientX() + window.PageXOffset();
let translated_y = mouse_event.ClientY() + window.PageYOffset();
let TextIndexResponse(index) = window.text_index_query(
self.upcast::<Node>().to_trusted_node_address(),
translated_x,
translated_y
);
if let Some(i) = index {
self.textinput.borrow_mut().set_edit_point_index(i as usize);
// trigger redraw
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
event.PreventDefault();
}
}
}
}
} else if event.type_() == atom!("keydown") && !event.DefaultPrevented() &&
(self.input_type.get() == InputType::InputText ||
self.input_type.get() == InputType::InputPassword) {
if let Some(keyevent) = event.downcast::<KeyboardEvent>() {
// This can't be inlined, as holding on to textinput.borrow_mut()
// during self.implicit_submission will cause a panic.
let action = self.textinput.borrow_mut().handle_keydown(keyevent);
match action {
TriggerDefaultAction => {
self.implicit_submission(keyevent.CtrlKey(),
keyevent.ShiftKey(),
keyevent.AltKey(),
keyevent.MetaKey());
},
DispatchInput => {
self.value_changed.set(true);
self.update_placeholder_shown_state();
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
event.mark_as_handled();
}
RedrawSelection => {
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
event.mark_as_handled();
}
Nothing => (),
}
}
} else if event.type_() == atom!("keypress") && !event.DefaultPrevented() &&
(self.input_type.get() == InputType::InputText ||
self.input_type.get() == InputType::InputPassword) {
if event.IsTrusted() {
let window = window_from_node(self);
let _ = window.user_interaction_task_source()
.queue_event(&self.upcast(),
atom!("input"),
EventBubbles::Bubbles,
EventCancelable::NotCancelable,
&window);
}
}
}
}
impl FormControl for HTMLInputElement {
fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
self.form_owner.get()
}
fn set_form_owner(&self, form: Option<&HTMLFormElement>) {
self.form_owner.set(form);
}
fn to_element<'a>(&'a self) -> &'a Element {
self.upcast::<Element>()
}
}
impl Validatable for HTMLInputElement {
fn is_instance_validatable(&self) -> bool {
// https://html.spec.whatwg.org/multipage/#candidate-for-constraint-validation
true
}
fn validate(&self, _validate_flags: ValidationFlags) -> bool {
// call stub methods defined in validityState.rs file here according to the flags set in validate_flags
true
}
}
impl Activatable for HTMLInputElement {
fn as_element(&self) -> &Element {
self.upcast()
}
fn is_instance_activatable(&self) -> bool {
match self.input_type.get() {
// https://html.spec.whatwg.org/multipage/#submit-button-state-%28type=submit%29:activation-behaviour-2
// https://html.spec.whatwg.org/multipage/#reset-button-state-%28type=reset%29:activation-behaviour-2
// https://html.spec.whatwg.org/multipage/#checkbox-state-%28type=checkbox%29:activation-behaviour-2
// https://html.spec.whatwg.org/multipage/#radio-button-state-%28type=radio%29:activation-behaviour-2
InputType::InputSubmit | InputType::InputReset | InputType::InputFile
| InputType::InputCheckbox | InputType::InputRadio => self.is_mutable(),
_ => false
}
}
// https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps
#[allow(unsafe_code)]
fn pre_click_activation(&self) {
let mut cache = self.activation_state.borrow_mut();
let ty = self.input_type.get();
cache.old_type = ty;
cache.was_mutable = self.is_mutable();
if cache.was_mutable {
match ty {
// https://html.spec.whatwg.org/multipage/#submit-button-state-(type=submit):activation-behavior
// InputType::InputSubmit => (), // No behavior defined
// https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset):activation-behavior
// InputType::InputSubmit => (), // No behavior defined
InputType::InputCheckbox => {
/*
https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox):pre-click-activation-steps
cache current values of `checked` and `indeterminate`
we may need to restore them later
*/
cache.indeterminate = self.Indeterminate();
cache.checked = self.Checked();
cache.checked_changed = self.checked_changed.get();
self.SetIndeterminate(false);
self.SetChecked(!cache.checked);
},
// https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):pre-click-activation-steps
InputType::InputRadio => {
//TODO: if not in document, use root ancestor instead of document
let owner = self.form_owner();
let doc = document_from_node(self);
let doc_node = doc.upcast::<Node>();
let group = self.radio_group_name();;
// Safe since we only manipulate the DOM tree after finding an element
let checked_member = doc_node.query_selector_iter(DOMString::from("input[type=radio]"))
.unwrap()
.filter_map(DomRoot::downcast::<HTMLInputElement>)
.find(|r| {
in_same_group(&*r, owner.r(), group.as_ref()) &&
r.Checked()
});
cache.checked_radio = checked_member.r().map(Dom::from_ref);
cache.checked_changed = self.checked_changed.get();
self.SetChecked(true);
}
_ => ()
}
}
}
// https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
fn canceled_activation(&self) {
let cache = self.activation_state.borrow();
let ty = self.input_type.get();
if cache.old_type != ty {
// Type changed, abandon ship
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=27414
return;
}
match ty {
// https://html.spec.whatwg.org/multipage/#submit-button-state-(type=submit):activation-behavior
// InputType::InputSubmit => (), // No behavior defined
// https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset):activation-behavior
// InputType::InputReset => (), // No behavior defined
// https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox):canceled-activation-steps
InputType::InputCheckbox => {
// We want to restore state only if the element had been changed in the first place
if cache.was_mutable {
self.SetIndeterminate(cache.indeterminate);
self.SetChecked(cache.checked);
self.checked_changed.set(cache.checked_changed);
}
},
// https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):canceled-activation-steps
InputType::InputRadio => {
// We want to restore state only if the element had been changed in the first place
if cache.was_mutable {
match cache.checked_radio.r() {
Some(o) => {
// Avoiding iterating through the whole tree here, instead
// we can check if the conditions for radio group siblings apply
if in_same_group(&o, self.form_owner().r(), self.radio_group_name().as_ref()) {
o.SetChecked(true);
} else {
self.SetChecked(false);
}
},
None => self.SetChecked(false)
};
self.checked_changed.set(cache.checked_changed);
}
}
_ => ()
}
}
// https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
let ty = self.input_type.get();
if self.activation_state.borrow().old_type != ty || !self.is_mutable() {
// Type changed or input is immutable, abandon ship
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=27414
return;
}
match ty {
InputType::InputSubmit => {
// https://html.spec.whatwg.org/multipage/#submit-button-state-(type=submit):activation-behavior
// FIXME (Manishearth): support document owners (needs ability to get parent browsing context)
// Check if document owner is fully active
self.form_owner().map(|o| {
o.submit(SubmittedFrom::NotFromForm,
FormSubmitter::InputElement(self.clone()))
});
},
InputType::InputReset => {
// https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset):activation-behavior
// FIXME (Manishearth): support document owners (needs ability to get parent browsing context)
// Check if document owner is fully active
self.form_owner().map(|o| {
o.reset(ResetFrom::NotFromForm)
});
},
InputType::InputCheckbox | InputType::InputRadio => {
// https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox):activation-behavior
// https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):activation-behavior
// Check if document owner is fully active
let target = self.upcast::<EventTarget>();
target.fire_bubbling_event(atom!("input"));
target.fire_bubbling_event(atom!("change"));
},
InputType::InputFile => self.select_files(None),
_ => ()
}
}
// https://html.spec.whatwg.org/multipage/#implicit-submission
#[allow(unsafe_code)]
fn implicit_submission(&self, ctrl_key: bool, shift_key: bool, alt_key: bool, meta_key: bool) {
let doc = document_from_node(self);
let node = doc.upcast::<Node>();
let owner = self.form_owner();
let form = match owner {
None => return,
Some(ref f) => f
};
if self.upcast::<Element>().click_in_progress() {
return;
}
let submit_button;
submit_button = node.query_selector_iter(DOMString::from("input[type=submit]")).unwrap()
.filter_map(DomRoot::downcast::<HTMLInputElement>)
.find(|r| r.form_owner() == owner);
match submit_button {
Some(ref button) => {
if button.is_instance_activatable() {
synthetic_click_activation(button.as_element(),
ctrl_key,
shift_key,
alt_key,
meta_key,
ActivationSource::NotFromClick)
}
}
None => {
let inputs = node.query_selector_iter(DOMString::from("input")).unwrap()
.filter_map(DomRoot::downcast::<HTMLInputElement>)
.filter(|input| {
input.form_owner() == owner && match input.type_() {
atom!("text") | atom!("search") | atom!("url") | atom!("tel") |
atom!("email") | atom!("password") | atom!("datetime") |
atom!("date") | atom!("month") | atom!("week") | atom!("time") |
atom!("datetime-local") | atom!("number")
=> true,
_ => false
}
});
if inputs.skip(1).next().is_some() {
// lazily test for > 1 submission-blocking inputs
return;
}
form.submit(SubmittedFrom::NotFromForm,
FormSubmitter::FormElement(&form));
}
}
}
}
// https://html.spec.whatwg.org/multipage/#attr-input-accept
fn filter_from_accept(s: &DOMString) -> Vec<FilterPattern> {
let mut filter = vec![];
for p in split_commas(s) {
if let Some('.') = p.chars().nth(0) {
filter.push(FilterPattern(p[1..].to_string()));
} else {
if let Some(exts) = mime_guess::get_mime_extensions_str(p) {
for ext in exts {
filter.push(FilterPattern(ext.to_string()));
}
}
}
}
filter
}
| {
"pile_set_name": "Github"
} |
# Copyright 2016-17 Eficent Business and IT Consulting Services S.L.
# (http://www.eficent.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from . import models
| {
"pile_set_name": "Github"
} |
<p>Step 8: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.</p> | {
"pile_set_name": "Github"
} |
/* Copyright 2016 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.
==============================================================================*/
#ifndef TENSORFLOW_CONTRIB_FRAMEWORK_KERNELS_ZERO_INITIALIZER_OP_H_
#define TENSORFLOW_CONTRIB_FRAMEWORK_KERNELS_ZERO_INITIALIZER_OP_H_
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor_types.h"
namespace tensorflow {
namespace functor {
template <typename Device, typename T>
struct TensorSetZero {
void operator()(const Device& d, typename TTypes<T>::Flat t) {
t.device(d) = t.constant(T(0));
}
};
} // namespace functor
} // end namespace tensorflow
#endif // TENSORFLOW_CONTRIB_FRAMEWORK_KERNELS_ZERO_INITIALIZER_OP_H_
| {
"pile_set_name": "Github"
} |
//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2015-2016 KONDO Takatoshi
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef MSGPACK_V2_CPP03_DEFINE_MAP_DECL_HPP
#define MSGPACK_V2_CPP03_DEFINE_MAP_DECL_HPP
#include "msgpack/v1/adaptor/detail/cpp03_define_map_decl.hpp"
namespace msgpack {
/// @cond
MSGPACK_API_VERSION_NAMESPACE(v2) {
/// @endcond
namespace type {
using v1::type::define_map;
using v1::type::make_define_map;
} // namespace type
/// @cond
} // MSGPACK_API_VERSION_NAMESPACE(v2)
/// @endcond
} // namespace msgpack
#endif // MSGPACK_V2_CPP03_DEFINE_MAP_DECL_HPP
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2013-2015 Alex Lin.
*
* 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.opoo.press;
import java.util.List;
/**
* @author Alex Lin
*/
public interface MetaTag {
String getSlug();
String getName();
boolean isNameOrSlug(String nameOrSlug);
List<Page> getPages();
/**
* The generated page of this tag.
* @return the generated page of this tag.
*/
Page getPage();
Config getConfig();
void setPage(Page page);
}
| {
"pile_set_name": "Github"
} |
var Tokenizer = require('./tokenizer');
var TAB = 9;
var N = 10;
var F = 12;
var R = 13;
var SPACE = 32;
var EXCLAMATIONMARK = 33; // !
var NUMBERSIGN = 35; // #
var AMPERSAND = 38; // &
var APOSTROPHE = 39; // '
var LEFTPARENTHESIS = 40; // (
var RIGHTPARENTHESIS = 41; // )
var ASTERISK = 42; // *
var PLUSSIGN = 43; // +
var COMMA = 44; // ,
var HYPERMINUS = 45; // -
var LESSTHANSIGN = 60; // <
var GREATERTHANSIGN = 62; // >
var QUESTIONMARK = 63; // ?
var COMMERCIALAT = 64; // @
var LEFTSQUAREBRACKET = 91; // [
var RIGHTSQUAREBRACKET = 93; // ]
var LEFTCURLYBRACKET = 123; // {
var VERTICALLINE = 124; // |
var RIGHTCURLYBRACKET = 125; // }
var INFINITY = 8734; // ∞
var NAME_CHAR = createCharMap(function(ch) {
return /[a-zA-Z0-9\-]/.test(ch);
});
var COMBINATOR_PRECEDENCE = {
' ': 1,
'&&': 2,
'||': 3,
'|': 4
};
function createCharMap(fn) {
var array = typeof Uint32Array === 'function' ? new Uint32Array(128) : new Array(128);
for (var i = 0; i < 128; i++) {
array[i] = fn(String.fromCharCode(i)) ? 1 : 0;
}
return array;
}
function scanSpaces(tokenizer) {
return tokenizer.substringToPos(
tokenizer.findWsEnd(tokenizer.pos)
);
}
function scanWord(tokenizer) {
var end = tokenizer.pos;
for (; end < tokenizer.str.length; end++) {
var code = tokenizer.str.charCodeAt(end);
if (code >= 128 || NAME_CHAR[code] === 0) {
break;
}
}
if (tokenizer.pos === end) {
tokenizer.error('Expect a keyword');
}
return tokenizer.substringToPos(end);
}
function scanNumber(tokenizer) {
var end = tokenizer.pos;
for (; end < tokenizer.str.length; end++) {
var code = tokenizer.str.charCodeAt(end);
if (code < 48 || code > 57) {
break;
}
}
if (tokenizer.pos === end) {
tokenizer.error('Expect a number');
}
return tokenizer.substringToPos(end);
}
function scanString(tokenizer) {
var end = tokenizer.str.indexOf('\'', tokenizer.pos + 1);
if (end === -1) {
tokenizer.pos = tokenizer.str.length;
tokenizer.error('Expect an apostrophe');
}
return tokenizer.substringToPos(end + 1);
}
function readMultiplierRange(tokenizer) {
var min = null;
var max = null;
tokenizer.eat(LEFTCURLYBRACKET);
min = scanNumber(tokenizer);
if (tokenizer.charCode() === COMMA) {
tokenizer.pos++;
if (tokenizer.charCode() !== RIGHTCURLYBRACKET) {
max = scanNumber(tokenizer);
}
} else {
max = min;
}
tokenizer.eat(RIGHTCURLYBRACKET);
return {
min: Number(min),
max: max ? Number(max) : 0
};
}
function readMultiplier(tokenizer) {
var range = null;
var comma = false;
switch (tokenizer.charCode()) {
case ASTERISK:
tokenizer.pos++;
range = {
min: 0,
max: 0
};
break;
case PLUSSIGN:
tokenizer.pos++;
range = {
min: 1,
max: 0
};
break;
case QUESTIONMARK:
tokenizer.pos++;
range = {
min: 0,
max: 1
};
break;
case NUMBERSIGN:
tokenizer.pos++;
comma = true;
if (tokenizer.charCode() === LEFTCURLYBRACKET) {
range = readMultiplierRange(tokenizer);
} else {
range = {
min: 1,
max: 0
};
}
break;
case LEFTCURLYBRACKET:
range = readMultiplierRange(tokenizer);
break;
default:
return null;
}
return {
type: 'Multiplier',
comma: comma,
min: range.min,
max: range.max,
term: null
};
}
function maybeMultiplied(tokenizer, node) {
var multiplier = readMultiplier(tokenizer);
if (multiplier !== null) {
multiplier.term = node;
return multiplier;
}
return node;
}
function maybeToken(tokenizer) {
var ch = tokenizer.peek();
if (ch === '') {
return null;
}
return {
type: 'Token',
value: ch
};
}
function readProperty(tokenizer) {
var name;
tokenizer.eat(LESSTHANSIGN);
tokenizer.eat(APOSTROPHE);
name = scanWord(tokenizer);
tokenizer.eat(APOSTROPHE);
tokenizer.eat(GREATERTHANSIGN);
return maybeMultiplied(tokenizer, {
type: 'Property',
name: name
});
}
// https://drafts.csswg.org/css-values-3/#numeric-ranges
// 4.1. Range Restrictions and Range Definition Notation
//
// Range restrictions can be annotated in the numeric type notation using CSS bracketed
// range notation—[min,max]—within the angle brackets, after the identifying keyword,
// indicating a closed range between (and including) min and max.
// For example, <integer [0, 10]> indicates an integer between 0 and 10, inclusive.
function readTypeRange(tokenizer) {
// use null for Infinity to make AST format JSON serializable/deserializable
var min = null; // -Infinity
var max = null; // Infinity
var sign = 1;
tokenizer.eat(LEFTSQUAREBRACKET);
if (tokenizer.charCode() === HYPERMINUS) {
tokenizer.peek();
sign = -1;
}
if (sign == -1 && tokenizer.charCode() === INFINITY) {
tokenizer.peek();
} else {
min = sign * Number(scanNumber(tokenizer));
}
scanSpaces(tokenizer);
tokenizer.eat(COMMA);
scanSpaces(tokenizer);
if (tokenizer.charCode() === INFINITY) {
tokenizer.peek();
} else {
sign = 1;
if (tokenizer.charCode() === HYPERMINUS) {
tokenizer.peek();
sign = -1;
}
max = sign * Number(scanNumber(tokenizer));
}
tokenizer.eat(RIGHTSQUAREBRACKET);
// If no range is indicated, either by using the bracketed range notation
// or in the property description, then [−∞,∞] is assumed.
if (min === null && max === null) {
return null;
}
return {
type: 'Range',
min: min,
max: max
};
}
function readType(tokenizer) {
var name;
var opts = null;
tokenizer.eat(LESSTHANSIGN);
name = scanWord(tokenizer);
if (tokenizer.charCode() === LEFTPARENTHESIS &&
tokenizer.nextCharCode() === RIGHTPARENTHESIS) {
tokenizer.pos += 2;
name += '()';
}
if (tokenizer.charCodeAt(tokenizer.findWsEnd(tokenizer.pos)) === LEFTSQUAREBRACKET) {
scanSpaces(tokenizer);
opts = readTypeRange(tokenizer);
}
tokenizer.eat(GREATERTHANSIGN);
return maybeMultiplied(tokenizer, {
type: 'Type',
name: name,
opts: opts
});
}
function readKeywordOrFunction(tokenizer) {
var name;
name = scanWord(tokenizer);
if (tokenizer.charCode() === LEFTPARENTHESIS) {
tokenizer.pos++;
return {
type: 'Function',
name: name
};
}
return maybeMultiplied(tokenizer, {
type: 'Keyword',
name: name
});
}
function regroupTerms(terms, combinators) {
function createGroup(terms, combinator) {
return {
type: 'Group',
terms: terms,
combinator: combinator,
disallowEmpty: false,
explicit: false
};
}
combinators = Object.keys(combinators).sort(function(a, b) {
return COMBINATOR_PRECEDENCE[a] - COMBINATOR_PRECEDENCE[b];
});
while (combinators.length > 0) {
var combinator = combinators.shift();
for (var i = 0, subgroupStart = 0; i < terms.length; i++) {
var term = terms[i];
if (term.type === 'Combinator') {
if (term.value === combinator) {
if (subgroupStart === -1) {
subgroupStart = i - 1;
}
terms.splice(i, 1);
i--;
} else {
if (subgroupStart !== -1 && i - subgroupStart > 1) {
terms.splice(
subgroupStart,
i - subgroupStart,
createGroup(terms.slice(subgroupStart, i), combinator)
);
i = subgroupStart + 1;
}
subgroupStart = -1;
}
}
}
if (subgroupStart !== -1 && combinators.length) {
terms.splice(
subgroupStart,
i - subgroupStart,
createGroup(terms.slice(subgroupStart, i), combinator)
);
}
}
return combinator;
}
function readImplicitGroup(tokenizer) {
var terms = [];
var combinators = {};
var token;
var prevToken = null;
var prevTokenPos = tokenizer.pos;
while (token = peek(tokenizer)) {
if (token.type !== 'Spaces') {
if (token.type === 'Combinator') {
// check for combinator in group beginning and double combinator sequence
if (prevToken === null || prevToken.type === 'Combinator') {
tokenizer.pos = prevTokenPos;
tokenizer.error('Unexpected combinator');
}
combinators[token.value] = true;
} else if (prevToken !== null && prevToken.type !== 'Combinator') {
combinators[' '] = true; // a b
terms.push({
type: 'Combinator',
value: ' '
});
}
terms.push(token);
prevToken = token;
prevTokenPos = tokenizer.pos;
}
}
// check for combinator in group ending
if (prevToken !== null && prevToken.type === 'Combinator') {
tokenizer.pos -= prevTokenPos;
tokenizer.error('Unexpected combinator');
}
return {
type: 'Group',
terms: terms,
combinator: regroupTerms(terms, combinators) || ' ',
disallowEmpty: false,
explicit: false
};
}
function readGroup(tokenizer) {
var result;
tokenizer.eat(LEFTSQUAREBRACKET);
result = readImplicitGroup(tokenizer);
tokenizer.eat(RIGHTSQUAREBRACKET);
result.explicit = true;
if (tokenizer.charCode() === EXCLAMATIONMARK) {
tokenizer.pos++;
result.disallowEmpty = true;
}
return result;
}
function peek(tokenizer) {
var code = tokenizer.charCode();
if (code < 128 && NAME_CHAR[code] === 1) {
return readKeywordOrFunction(tokenizer);
}
switch (code) {
case RIGHTSQUAREBRACKET:
// don't eat, stop scan a group
break;
case LEFTSQUAREBRACKET:
return maybeMultiplied(tokenizer, readGroup(tokenizer));
case LESSTHANSIGN:
return tokenizer.nextCharCode() === APOSTROPHE
? readProperty(tokenizer)
: readType(tokenizer);
case VERTICALLINE:
return {
type: 'Combinator',
value: tokenizer.substringToPos(
tokenizer.nextCharCode() === VERTICALLINE
? tokenizer.pos + 2
: tokenizer.pos + 1
)
};
case AMPERSAND:
tokenizer.pos++;
tokenizer.eat(AMPERSAND);
return {
type: 'Combinator',
value: '&&'
};
case COMMA:
tokenizer.pos++;
return {
type: 'Comma'
};
case APOSTROPHE:
return maybeMultiplied(tokenizer, {
type: 'String',
value: scanString(tokenizer)
});
case SPACE:
case TAB:
case N:
case R:
case F:
return {
type: 'Spaces',
value: scanSpaces(tokenizer)
};
case COMMERCIALAT:
code = tokenizer.nextCharCode();
if (code < 128 && NAME_CHAR[code] === 1) {
tokenizer.pos++;
return {
type: 'AtKeyword',
name: scanWord(tokenizer)
};
}
return maybeToken(tokenizer);
case ASTERISK:
case PLUSSIGN:
case QUESTIONMARK:
case NUMBERSIGN:
case EXCLAMATIONMARK:
// prohibited tokens (used as a multiplier start)
break;
case LEFTCURLYBRACKET:
// LEFTCURLYBRACKET is allowed since mdn/data uses it w/o quoting
// check next char isn't a number, because it's likely a disjoined multiplier
code = tokenizer.nextCharCode();
if (code < 48 || code > 57) {
return maybeToken(tokenizer);
}
break;
default:
return maybeToken(tokenizer);
}
}
function parse(source) {
var tokenizer = new Tokenizer(source);
var result = readImplicitGroup(tokenizer);
if (tokenizer.pos !== source.length) {
tokenizer.error('Unexpected input');
}
// reduce redundant groups with single group term
if (result.terms.length === 1 && result.terms[0].type === 'Group') {
result = result.terms[0];
}
return result;
}
// warm up parse to elimitate code branches that never execute
// fix soft deoptimizations (insufficient type feedback)
parse('[a&&<b>#|<\'c\'>*||e() f{2} /,(% g#{1,2} h{2,})]!');
module.exports = parse;
| {
"pile_set_name": "Github"
} |
<?php
namespace Dotenv\Exception;
use InvalidArgumentException;
/**
* This is the invalid file exception class.
*/
class InvalidFileException extends InvalidArgumentException implements ExceptionInterface
{
//
}
| {
"pile_set_name": "Github"
} |
function Music() {
this.init();
}
(function () {
var pages = [],
panels = [],
selectedItem = null;
Music.prototype = {
total:70,
pageSize:10,
dataUrl:"http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.common",
playerUrl:"http://box.baidu.com/widget/flash/bdspacesong.swf",
init:function () {
var me = this;
domUtils.on($G("J_searchName"), "keyup", function (event) {
var e = window.event || event;
if (e.keyCode == 13) {
me.dosearch();
}
});
domUtils.on($G("J_searchBtn"), "click", function () {
me.dosearch();
});
},
callback:function (data) {
var me = this;
me.data = data.song_list;
setTimeout(function () {
$G('J_resultBar').innerHTML = me._renderTemplate(data.song_list);
}, 300);
},
dosearch:function () {
var me = this;
selectedItem = null;
var key = $G('J_searchName').value;
if (utils.trim(key) == "")return false;
key = encodeURIComponent(key);
me._sent(key);
},
doselect:function (i) {
var me = this;
if (typeof i == 'object') {
selectedItem = i;
} else if (typeof i == 'number') {
selectedItem = me.data[i];
}
},
onpageclick:function (id) {
var me = this;
for (var i = 0; i < pages.length; i++) {
$G(pages[i]).className = 'pageoff';
$G(panels[i]).className = 'paneloff';
}
$G('page' + id).className = 'pageon';
$G('panel' + id).className = 'panelon';
},
listenTest:function (elem) {
var me = this,
view = $G('J_preview'),
is_play_action = (elem.className == 'm-try'),
old_trying = me._getTryingElem();
if (old_trying) {
old_trying.className = 'm-try';
view.innerHTML = '';
}
if (is_play_action) {
elem.className = 'm-trying';
view.innerHTML = me._buildMusicHtml(me._getUrl(true));
}
},
_sent:function (param) {
var me = this;
$G('J_resultBar').innerHTML = '<div class="loading"></div>';
utils.loadFile(document, {
src:me.dataUrl + '&query=' + param + '&page_size=' + me.total + '&callback=music.callback&.r=' + Math.random(),
tag:"script",
type:"text/javascript",
defer:"defer"
});
},
_removeHtml:function (str) {
var reg = /<\s*\/?\s*[^>]*\s*>/gi;
return str.replace(reg, "");
},
_getUrl:function (isTryListen) {
var me = this;
var param = 'from=tiebasongwidget&url=&name=' + encodeURIComponent(me._removeHtml(selectedItem.title)) + '&artist='
+ encodeURIComponent(me._removeHtml(selectedItem.author)) + '&extra='
+ encodeURIComponent(me._removeHtml(selectedItem.album_title))
+ '&autoPlay='+isTryListen+'' + '&loop=true';
return me.playerUrl + "?" + param;
},
_getTryingElem:function () {
var s = $G('J_listPanel').getElementsByTagName('span');
for (var i = 0; i < s.length; i++) {
if (s[i].className == 'm-trying')
return s[i];
}
return null;
},
_buildMusicHtml:function (playerUrl) {
var html = '<embed class="BDE_try_Music" allowfullscreen="false" pluginspage="http://www.macromedia.com/go/getflashplayer"';
html += ' src="' + playerUrl + '"';
html += ' width="1" height="1" style="position:absolute;left:-2000px;"';
html += ' type="application/x-shockwave-flash" wmode="transparent" play="true" loop="false"';
html += ' menu="false" allowscriptaccess="never" scale="noborder">';
return html;
},
_byteLength:function (str) {
return str.replace(/[^\u0000-\u007f]/g, "\u0061\u0061").length;
},
_getMaxText:function (s) {
var me = this;
s = me._removeHtml(s);
if (me._byteLength(s) > 12)
return s.substring(0, 5) + '...';
if (!s) s = " ";
return s;
},
_rebuildData:function (data) {
var me = this,
newData = [],
d = me.pageSize,
itembox;
for (var i = 0; i < data.length; i++) {
if ((i + d) % d == 0) {
itembox = [];
newData.push(itembox)
}
itembox.push(data[i]);
}
return newData;
},
_renderTemplate:function (data) {
var me = this;
if (data.length == 0)return '<div class="empty">' + lang.emptyTxt + '</div>';
data = me._rebuildData(data);
var s = [], p = [], t = [];
s.push('<div id="J_listPanel" class="listPanel">');
p.push('<div class="page">');
for (var i = 0, tmpList; tmpList = data[i++];) {
panels.push('panel' + i);
pages.push('page' + i);
if (i == 1) {
s.push('<div id="panel' + i + '" class="panelon">');
if (data.length != 1) {
t.push('<div id="page' + i + '" onclick="music.onpageclick(' + i + ')" class="pageon">' + (i ) + '</div>');
}
} else {
s.push('<div id="panel' + i + '" class="paneloff">');
t.push('<div id="page' + i + '" onclick="music.onpageclick(' + i + ')" class="pageoff">' + (i ) + '</div>');
}
s.push('<div class="m-box">');
s.push('<div class="m-h"><span class="m-t">' + lang.chapter + '</span><span class="m-s">' + lang.singer
+ '</span><span class="m-z">' + lang.special + '</span><span class="m-try-t">' + lang.listenTest + '</span></div>');
for (var j = 0, tmpObj; tmpObj = tmpList[j++];) {
s.push('<label for="radio-' + i + '-' + j + '" class="m-m">');
s.push('<input type="radio" id="radio-' + i + '-' + j + '" name="musicId" class="m-l" onclick="music.doselect(' + (me.pageSize * (i-1) + (j-1)) + ')"/>');
s.push('<span class="m-t">' + me._getMaxText(tmpObj.title) + '</span>');
s.push('<span class="m-s">' + me._getMaxText(tmpObj.author) + '</span>');
s.push('<span class="m-z">' + me._getMaxText(tmpObj.album_title) + '</span>');
s.push('<span class="m-try" onclick="music.doselect(' + (me.pageSize * (i-1) + (j-1)) + ');music.listenTest(this)"></span>');
s.push('</label>');
}
s.push('</div>');
s.push('</div>');
}
t.reverse();
p.push(t.join(''));
s.push('</div>');
p.push('</div>');
return s.join('') + p.join('');
},
exec:function () {
var me = this;
if (selectedItem == null) return;
$G('J_preview').innerHTML = "";
editor.execCommand('music', {
url:me._getUrl(false),
width:400,
height:95
});
}
};
})();
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<material>
<albedo color="0.491905123 1 0.178867504 1"/>
<metalness value="0.2"/>
<glossiness value="0.461538494"/>
</material>
| {
"pile_set_name": "Github"
} |
<?php
/**
* @package FrameworkOnFramework
* @subpackage utils
* @copyright Copyright (C) 2010 - 2015 Nicholas K. Dionysopoulos / Akeeba Ltd. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('FOF_INCLUDED') or die;
/**
* Class to handle dispatching of events.
*
* This is the Observable part of the Observer design pattern
* for the event architecture.
*
* This class is based on JEventDispatcher as found in Joomla! 3.2.0
*/
class FOFUtilsObservableDispatcher extends FOFUtilsObject
{
/**
* An array of Observer objects to notify
*
* @var array
*/
protected $_observers = array();
/**
* The state of the observable object
*
* @var mixed
*/
protected $_state = null;
/**
* A multi dimensional array of [function][] = key for observers
*
* @var array
*/
protected $_methods = array();
/**
* Stores the singleton instance of the dispatcher.
*
* @var FOFUtilsObservableDispatcher
*/
protected static $instance = null;
/**
* Returns the global Event Dispatcher object, only creating it
* if it doesn't already exist.
*
* @return FOFUtilsObservableDispatcher The EventDispatcher object.
*/
public static function getInstance()
{
if (self::$instance === null)
{
self::$instance = new static;
}
return self::$instance;
}
/**
* Get the state of the FOFUtilsObservableDispatcher object
*
* @return mixed The state of the object.
*/
public function getState()
{
return $this->_state;
}
/**
* Registers an event handler to the event dispatcher
*
* @param string $event Name of the event to register handler for
* @param string $handler Name of the event handler
*
* @return void
*
* @throws InvalidArgumentException
*/
public function register($event, $handler)
{
// Are we dealing with a class or callback type handler?
if (is_callable($handler))
{
// Ok, function type event handler... let's attach it.
$method = array('event' => $event, 'handler' => $handler);
$this->attach($method);
}
elseif (class_exists($handler))
{
// Ok, class type event handler... let's instantiate and attach it.
$this->attach(new $handler($this));
}
else
{
throw new InvalidArgumentException('Invalid event handler.');
}
}
/**
* Triggers an event by dispatching arguments to all observers that handle
* the event and returning their return values.
*
* @param string $event The event to trigger.
* @param array $args An array of arguments.
*
* @return array An array of results from each function call.
*/
public function trigger($event, $args = array())
{
$result = array();
/*
* If no arguments were passed, we still need to pass an empty array to
* the call_user_func_array function.
*/
$args = (array) $args;
$event = strtolower($event);
// Check if any plugins are attached to the event.
if (!isset($this->_methods[$event]) || empty($this->_methods[$event]))
{
// No Plugins Associated To Event!
return $result;
}
// Loop through all plugins having a method matching our event
foreach ($this->_methods[$event] as $key)
{
// Check if the plugin is present.
if (!isset($this->_observers[$key]))
{
continue;
}
// Fire the event for an object based observer.
if (is_object($this->_observers[$key]))
{
$args['event'] = $event;
$value = $this->_observers[$key]->update($args);
}
// Fire the event for a function based observer.
elseif (is_array($this->_observers[$key]))
{
$value = call_user_func_array($this->_observers[$key]['handler'], $args);
}
if (isset($value))
{
$result[] = $value;
}
}
return $result;
}
/**
* Attach an observer object
*
* @param object $observer An observer object to attach
*
* @return void
*/
public function attach($observer)
{
if (is_array($observer))
{
if (!isset($observer['handler']) || !isset($observer['event']) || !is_callable($observer['handler']))
{
return;
}
// Make sure we haven't already attached this array as an observer
foreach ($this->_observers as $check)
{
if (is_array($check) && $check['event'] == $observer['event'] && $check['handler'] == $observer['handler'])
{
return;
}
}
$this->_observers[] = $observer;
end($this->_observers);
$methods = array($observer['event']);
}
else
{
if (!($observer instanceof FOFUtilsObservableEvent))
{
return;
}
// Make sure we haven't already attached this object as an observer
$class = get_class($observer);
foreach ($this->_observers as $check)
{
if ($check instanceof $class)
{
return;
}
}
$this->_observers[] = $observer;
$methods = array();
foreach(get_class_methods($observer) as $obs_method)
{
// Magic methods are not allowed
if(strpos('__', $obs_method) === 0)
{
continue;
}
$methods[] = $obs_method;
}
//$methods = get_class_methods($observer);
}
$key = key($this->_observers);
foreach ($methods as $method)
{
$method = strtolower($method);
if (!isset($this->_methods[$method]))
{
$this->_methods[$method] = array();
}
$this->_methods[$method][] = $key;
}
}
/**
* Detach an observer object
*
* @param object $observer An observer object to detach.
*
* @return boolean True if the observer object was detached.
*/
public function detach($observer)
{
$retval = false;
$key = array_search($observer, $this->_observers);
if ($key !== false)
{
unset($this->_observers[$key]);
$retval = true;
foreach ($this->_methods as &$method)
{
$k = array_search($key, $method);
if ($k !== false)
{
unset($method[$k]);
}
}
}
return $retval;
}
}
| {
"pile_set_name": "Github"
} |
package com.karntrehan.posts.core.di
import android.content.Context
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.google.gson.Gson
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import com.karntrehan.posts.core.BuildConfig
import com.karntrehan.posts.core.constants.Constants
import dagger.Module
import dagger.Provides
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
class NetworkModule {
@Provides
@Singleton
fun providesRetrofit(
gsonConverterFactory: GsonConverterFactory,
rxJava2CallAdapterFactory: RxJava2CallAdapterFactory,
okHttpClient: OkHttpClient
): Retrofit {
return Retrofit.Builder().baseUrl(Constants.API_URL)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJava2CallAdapterFactory)
.client(okHttpClient)
.build()
}
@Provides
@Singleton
fun providesOkHttpClient(cache: Cache): OkHttpClient {
val client = OkHttpClient.Builder()
.cache(cache)
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
if (BuildConfig.DEBUG)
client.addNetworkInterceptor(StethoInterceptor())
return client.build()
}
@Provides
@Singleton
fun providesOkhttpCache(context: Context): Cache {
val cacheSize = 10 * 1024 * 1024 // 10 MB
return Cache(context.cacheDir, cacheSize.toLong())
}
@Provides
@Singleton
fun providesGson(): Gson {
return Gson()
}
@Provides
@Singleton
fun providesGsonConverterFactory(): GsonConverterFactory {
return GsonConverterFactory.create()
}
@Provides
@Singleton
fun providesRxJavaCallAdapterFactory(): RxJava2CallAdapterFactory {
return RxJava2CallAdapterFactory.create()
}
} | {
"pile_set_name": "Github"
} |
---
title: PayRates Property, Project [vbapj.chm132494]
keywords: vbapj.chm132494
f1_keywords:
- vbapj.chm132494
ms.prod: office
ms.assetid: 7b85c618-0d0c-4796-9035-4314568d0b45
ms.date: 06/08/2017
localization_priority: Normal
---
# PayRates Property, Project [vbapj.chm132494]
Hi there! You have landed on one of our F1 Help redirector pages. Please select the topic you were looking for below.
[CostRateTable.PayRates Property (Project)](https://msdn.microsoft.com/library/260d9e77-9fce-5169-687f-027995c73273%28Office.15%29.aspx)
[Resource.PayRates Property (Project)](https://msdn.microsoft.com/library/bd01dd18-bbf4-52d5-bc37-d525603fcb8e%28Office.15%29.aspx)
[Project.ReceiveNotifications Property (Project)](https://msdn.microsoft.com/library/16ac7115-ff63-7d49-eeb0-ef416a087959%28Office.15%29.aspx)
[!include[Support and feedback](~/includes/feedback-boilerplate.md)] | {
"pile_set_name": "Github"
} |
// Microsoft version of 'inline'
#define inline __inline
// Visual Studio support alloca(), but it always align variables to 16-bit
// boundary, while SSE need 128-bit alignment. So we disable alloca() when
// SSE is enabled.
#ifndef _USE_SSE
# define USE_ALLOCA
#endif
/* Default to floating point */
#ifndef FIXED_POINT
# define FLOATING_POINT
# define USE_SMALLFT
#else
# define USE_KISS_FFT
#endif
/* We don't support visibility on Win32 */
#define EXPORT
| {
"pile_set_name": "Github"
} |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build 386,netbsd
package unix
func setTimespec(sec, nsec int64) Timespec {
return Timespec{Sec: sec, Nsec: int32(nsec)}
}
func setTimeval(sec, usec int64) Timeval {
return Timeval{Sec: sec, Usec: int32(usec)}
}
func SetKevent(k *Kevent_t, fd, mode, flags int) {
k.Ident = uint32(fd)
k.Filter = uint32(mode)
k.Flags = uint32(flags)
}
func (iov *Iovec) SetLen(length int) {
iov.Len = uint32(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint32(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint32(length)
}
| {
"pile_set_name": "Github"
} |
Release Process and Rules
=========================
.. image:: https://farm5.staticflickr.com/4215/34450901614_b74ae720db_k_d.jpg
.. versionadded:: v2.6.2
Starting with the version to be released after ``v2.6.2``, the following rules
will govern and describe how the Requests core team produces a new release.
Major Releases
--------------
A major release will include breaking changes. When it is versioned, it will
be versioned as ``vX.0.0``. For example, if the previous release was
``v10.2.7`` the next version will be ``v11.0.0``.
Breaking changes are changes that break backwards compatibility with prior
versions. If the project were to change the ``text`` attribute on a
``Response`` object to a method, that would only happen in a Major release.
Major releases may also include miscellaneous bug fixes. The core developers of
Requests are committed to providing a good user experience. This means we're
also committed to preserving backwards compatibility as much as possible. Major
releases will be infrequent and will need strong justifications before they are
considered.
Minor Releases
--------------
A minor release will not include breaking changes but may include miscellaneous
bug fixes. If the previous version of Requests released was ``v10.2.7`` a minor
release would be versioned as ``v10.3.0``.
Minor releases will be backwards compatible with releases that have the same
major version number. In other words, all versions that would start with
``v10.`` should be compatible with each other.
Hotfix Releases
---------------
A hotfix release will only include bug fixes that were missed when the project
released the previous version. If the previous version of Requests released
``v10.2.7`` the hotfix release would be versioned as ``v10.2.8``.
Hotfixes will **not** include upgrades to vendored dependencies after
``v2.6.2``
Reasoning
---------
In the 2.5 and 2.6 release series, the Requests core team upgraded vendored
dependencies and caused a great deal of headaches for both users and the core
team. To reduce this pain, we're forming a concrete set of procedures so
expectations will be properly set.
| {
"pile_set_name": "Github"
} |
[General]
Version=DrumSynth v2.0
Comment=Remember to send any good .ds files to [email protected]
Tuning=0
Stretch=100
Level=-6
Filter=1
HighPass=1
Resonance=38
FilterEnv=0,7 3880,23 444000,100 444000,0
[Tone]
On=1
Level=181
F1=500
F2=120
Droop=32
Phase=0
Envelope=0,100 1750,20 6112,0
[Noise]
On=0
Level=128
Slope=0
Envelope=0,100 500,20 1500,0
FixedSeq=1
[Overtones]
On=0
Level=128
F1=315
Wave1=0
Track1=0
F2=630
Wave2=0
Track2=0
Method=0
Param=0
Envelope1=0,100 1250,20 3750,0
Envelope2=0,100 1000,20 3000,0
Filter=0
[NoiseBand]
On=0
Level=128
F=1200
dF=40
Envelope=0,100 750,20 2250,0
[NoiseBand2]
On=0
Level=128
F=3100
dF=40
Envelope=0,100 1500,20 4500,0
[Distortion]
On=1
Clipping=31
Bits=0
Rate=0
| {
"pile_set_name": "Github"
} |
7800: Ideograph brilhantemente colorido pedra com padrões de veias nele CJK : dong6 : dàng
7801: Número de ideografia, numerais; jarda; símbolo CJK : maa5 : mǎ
7802: Areia ideográfica; seixos, cascalho; CJK gritty : saa1 : shā
7803:
7804:
7805:
7806: Ideografia 1/2 pr stone CJK : fu1 : fū
7807: Ideograph uma pedra parecida com jade, alabastro CJK : min
7808:
7809:
780A:
780B:
780C: Ideograph para construir, empilhar; degraus de pedra, tijolo andar CJK : cai3 : qì
780D: Ideograph hack, chop, cut, caiu CJK : ham2 : ken
780E:
780F:
7810: Ideograph (Cant.) Para acenar com a cabeça; agitar, balançar CJK : ngap6 : è
7811: Ideograph para moer, para calender, para polir; para rolar com um rolo de pedra CJK : ngaa6 : ya
7812: Arsênico ideograma CJK : pei1 : pī
7813:
7814: Ideograph moer, esfregue; estudo, pesquisa CJK : jin4 jin6 ngaan4 : yán
7815: Ideograph quebra, quebra; quebrado, preso CJK : sui
7816: Telha ideografia, tijolo CJK : zyun1 : zhuān
7817: Ideograph molusco gigante, tridacna gigas CJK : ce1 : chē
7818: Ideograph uma espécie de ferramenta agrícola CJK : deon6 : dùn
7819:
781A: Tinta de ideografia CJK : jin6 : yan
781B:
781C: Ideograph um composto orgânico CJK : fung1 : fang
781D: Pesos de equilíbrio ideográfico CJK : faat3 fat3 : fá
781E: Ideograph para esmagar o rock CJK : mut6 : mò
781F: Tabuleiro de pedra ideográfico; monumento CJK : zaa1 zaa2 zok3 zok6 : zhǎ
7820: Ideograph rochoso, montanhoso, desigual CJK : zeoi1 zo2 : jū
7821:
7822: Pilha ideográfica de pedras CJK : lo2 : kē
7823: Ideograph um rolo de pedra; uma pedra pesada, um peso, um prumo CJK : to4 : tuó
7824:
7825: Ideograph uma pedra de amolar; para polir CJK : dai1 dai2 zi2 : dǐ
7826: Stockade Ideograph, forte, posto avançado militar; bordel CJK : zaai6 : zhài
7827: Bigorna ideográfica; pedra plana; exe CJK : zam1 : zhēn
7828:
7829:
782A:
782B:
782C: Ideograph grande pedra CJK : laa1 laap6 : lá
782D: Sonda de pedra ideográfica; perfurar; advogado CJK : bin1 : biān
782E: Ponta de seta Ideograph CJK : nou5 : nǔ
782F: Ideograph para fazer um som alto CJK : pīng
7830: Som ideográfico de pedras batendo, estrondo! CJK : ping1 : png
7831:
7832: Arma Ideograph, canhão CJK : baau3 paau3 paau4 : pào
7833: Ideograph rocky CJK : laak6 lak6 : eu
7834: Ideograph break, ruin, destroy; derrotar CJK : po3 : pò
7835: Ideograph (Cant.) Port (Eng. Empréstimo-word), 西 矺 um sideboard (Eng. Loan-word) CJK : mas3 : bō
7836:
7837: Arsênico ideograma CJK : san1 : shin
7838: Ideograph quebra, esmaga, quebra; libra, mash CJK : zaap3 : zá
7839: Ideógrafo astatine CJK : aai6 ngaai6 : ài
783A: Ideograph whetstone; afiar CJK : lai6 : lì
783B: Ideograph moer, aguçar; moinho CJK : lung4 : longo
783C: Concreto ideográfico CJK : tung4 : língua
783D:
783E: Ideograph cascalho, seixos CJK : nik1 : lì
783F: Ideograma mina; mineral, minério CJK : kuang
7840: Ideograph pedra de fundação, plinto CJK : co2 : chǔ
7841: Ideograph o som de pedras batendo juntos CJK : hang1 : kang
7842:
7843: Ideograph uma toupeira vermelha; cinábrio CJK : zyu1 : zhū
7844:
7845: Ideograph silício CJK : gwai1 : gui
7846:
7847: Ideograph uma espécie de mineral CJK : laau4 lou5 naau4 : náo
7848:
7849: Ossos ideográficos de um cavalo magro CJK : leot6 : Lu
784A:
784B:
784C:
784D: Ideograph strike CJK : gan1 : xiàn
784E: Ideograph whetstone CJK : jing4 : xing
784F: Moagem ideográfica CJK : yán
7850: Variante ideográfica de U + 6D1E 洞, caverna; câmara; poço CJK : dung6 : dong
7851:
7852: Ideografia Selênio CJK : sai1 : XI
7853:
7854:
7855: Ideografia grande, eminente; grande, grande CJK : sek6 : shuò
7856: Cidade ideográfica (arcaica) na província de Hebei CJK : haap6 : xiá
7857: Terra estéril ideográfica; solo arenoso CJK : haau1 : qiāo
7858:
7859: Moinho de pedra de ideografia; moer; desmembrar CJK : wui1 : com
785A:
785B:
785C: Ideograph o som de pedras batendo juntos CJK : hang1 : kang
785D: Salitria ideográfica, niter; bronzear CJK : siu1 : xiāo
785E:
785F: Ideograph (Cant.) Para escorregar; trabalhar e polir pedras preciosas CJK : sin3 : chàn
7860:
7861:
7862:
7863:
7864: Cidade ideográfica (arcaica) na província de Hebei CJK : gip3 haap6 : xiá
7865:
7866:
7867: Ideograph um rebolo; (o mesmo que U + 7850 硐) uma caverna, caverna CJK : yang
7868: Molusco gigante ideográfico, Tridacna gigas CJK : ce1 : chē
7869:
786A:
786B: Ideógrafo enxofre CJK : lau4 : liú
786C: Ideografia dura, firme, forte; obstinado CJK : ngaang6 : yng
786D: Ideograph um salitre bruto CJK : mong4 : máng
786E: Ideógrafo com certeza, certo; verdadeiro, verdadeiro CJK : kok3 : That
786F: Tinta de ideografia CJK : jin6 : yan
7870:
7871:
7872:
7873:
7874:
7875:
7876:
7877: Ideografia alcalina, alcalina, soda cáustica, sal CJK : gaan2 : jiǎn
7878: Ideograma de lábios grossos; um rebolo CJK : nüè
7879:
787A:
787B:
787C: Ideógrafo bórax, boro CJK : paang4 pang4 : péng
787D:
787E: Peso ideograma CJK : zeoi6 : zhuì
787F:
7880:
7881: Ideograph xadrez; qualquer jogo semelhante ao xadrez CJK : kei4 : qi
7882:
7883:
7884:
7885:
7886: Ponta de seta Ideograph CJK : bo1 : bō
7887: Âncora de ideografia CJK : ding3 : dng
7888:
7889: Sala ideográfica de pedra; torre de vigia CJK : diu1 : diāo
788A:
788B:
788C: Ideografia áspera, irregular, rochosa; CJK mediocre : luk1 : Lu
788D: Ideograph obstruir, impedir, bloquear, dissuadir CJK : ngoi6 : ài
788E: Ideograph quebra, quebra; quebrado, preso CJK : seoi3 : sui
788F: Ideograph colorido CJK : coek3 zoek3 : That
7890:
7891: Tabuleiro de pedra ideográfico; lápide CJK : bei1 : bēi
7892:
7893: Ideograph PJ CJK : deoi3 : duì
7894: Ideografia 1/2 pr stone CJK : mou5 : w
7895: Ideograph uma capa, cuspir, promontório CJK : kei4 : qi
7896:
7897: Tigela ideográfica, pequeno prato CJK : wun2 : quando
7898: Iodógrafo iodo CJK : din2 : diǎn
7899:
789A: Ideograph subúrbio CJK : pui5 : bèi
789B: Ideograph areia e cascalho CJK : zaak3 zik1 : qì
789C: Ideograma gritty CJK : cam2 : chěn
789D:
789E: Sala ideográfica de pedra; torre de vigia CJK : ngaam4 : yán
789F: Prato pequeno ideograma, placa CJK : dip6 : morrer
78A0:
78A1: Rolo de pedra ideográfico usado para nivelar campos CJK : duk6 : de
78A2:
78A3: Placa de pedra para ideografia CJK : kit3 : jié
78A4:
78A5:
78A6:
78A7: Ideograma jade; verde, azul CJK : bik1 : bi
78A8:
78A9: Ideografia grande, eminente; grande, grande CJK : sek6 : shuò
78AA: Laje de pedra ideográfica usada para lavar roupas; uma bigorna CJK : caa4 zam1 : zhēn
78AB:
78AC: Ideograph whetstone CJK : xiá
78AD: Ideograph brilhantemente colorido pedra com padrões de veias nele CJK : dong6 : dàng
78AE:
78AF: Ágata ideográfica, cornalina CJK : nou5 : nǎo
78B0: Ideograph colidir, topar com o CJK : pung3 : pèng
78B1: Ideografia alcalina, alcalina, soda cáustica, sal CJK : gaan2 : jiǎn
78B2: Ideógrafo telúrio CJK : dai3 : dì
78B3: Carbono ideográfico CJK : taan3 : bronzeado
78B4: Borda chipada ideográfica de um recipiente CJK : caa4 zaa1 : chá
78B5:
78B6: Ideograph um portal de inundação, um portão de água CJK : kai3 : qì
78B7:
78B8: Ideograph um composto orgânico CJK : fung1 : fang
78B9:
78BA: Ideógrafo com certeza, certo; verdadeiro, verdadeiro CJK : kok3 : That
78BB: Ideograph solid CJK : kok3 : That
78BC: Número de ideografia, numerais; jarda; símbolo CJK : maa5 : mǎ
78BD:
78BE: Rolo ideográfico, esmagamento; rolo CJK : nin5 : niǎn
78BF:
78C0:
78C1: Ideograma magnético; magnetismo; porcelana CJK : ci4 : ci
78C2:
78C3:
78C4:
78C5: Libra ideográfica; pesar CJK : bong2 bong2 : beng
78C6:
78C7: Arsênico ideograma CJK : pai1 : pī
78C8:
78C9: Ideograph a base de pedra ou plinto de um pilar CJK : song2 : sang
78CA: Pilha ideográfica de pedras ou pedras; ótimo CJK : leoi5 : lěi
78CB: Ideografia polonês, lustre; escrutinar CJK : co1 : cuō
78CC:
78CD:
78CE: Ideograph córrego da montanha, riacho CJK : kai1 : XI
78CF:
78D0: Ideograph grande rocha, pedregulho; firma CJK : pun4 : pán
78D1: Moinho de pedra de ideografia; moer; desmembrar CJK : hoi2 wui1 : com
78D2: Ideograph para cair de ou em CJK : wan6 : você
78D3: Ideograph para jogar (uma pedra) CJK : deoi1 zeoi6 : dui
78D4: Ideograph para desmembrar, rasgar; curso para baixo inclinado direito CJK : zaak6 : zhé
78D5: Hit de ideografia; colidir, bater em; som CJK : hap6 : kē
78D6:
78D7:
78D8:
78D9: Rolo Ideograph CJK : gn
78DA: Telha ideografia, tijolo CJK : zyun1 : zhuān
78DB: Penhasco Ideograph CJK : caam4 : chán
78DC:
78DD:
78DE:
78DF: Ideografia medíocre; ocupado; ocupado; rolo CJK : luk1 luk6 : liù
78E0: Ideografo sal amoníaco; areia; seixo CJK : lou5 : l
78E1: Ideograph cliff, borda, banco; passo CJK : ham3 : kàn
78E2: Ideograph (Cant.) Para moer; um rolo CJK : coeng2 cong2 saang2 : chuǎng
78E3: Ideograma gritty CJK : cam2 : chěn
78E4:
78E5: Ideografia um montão de pedras; pedregulhos CJK : leoi5 : lěi
78E6:
78E7: Ideografia de areia e cascalho; rochas expostas na maré baixa; esmagar CJK : zaak3 zik1 : qì
78E8: Moagem ideográfica; polonês; esfregar; desgastar; uma pedra de moinho CJK : mo4 mo6 : mó
78E9:
78EA: Ideograph uma montanha alta; CJK precipitada : ceoi1 : cuī
78EB:
78EC: Instrumento musical ideográfico; pedra musical CJK : hing3 : qng
78ED:
78EE:
78EF: Cais de ideografia; rocha submersa; eddy CJK : gei1 : ji
78F0:
78F1:
78F2:
78F3:
78F4: Etapas do ideógrafo na borda, no penhasco ou na colina CJK : dang3 : dong
78F5: Ideograph brook, córrego da montanha CJK : gaan3 : jiàn
78F6:
78F7: Fosde ideograma; água correndo entre CJK : leon4 leon6 : em linha
78F8:
78F9:
78FA: Ideógrafo enxofre; brimstone CJK : wong4 : Huang
78FB: Ideograph um afluente do rio Wei em Shanxi CJK : pun4 : pán
78FC:
78FD: Terra estéril ideográfica; solo arenoso CJK : haau1 : qiāo
78FE:
78FF:
| {
"pile_set_name": "Github"
} |
"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, unicode_literals, absolute_import
from collections import OrderedDict
from atomic_reactor.plugin import PreBuildPluginsRunner, PluginFailedException
from atomic_reactor.plugins.pre_add_labels_in_df import AddLabelsPlugin
from atomic_reactor.plugins.pre_reactor_config import (ReactorConfigPlugin,
WORKSPACE_CONF_KEY,
ReactorConfig)
from atomic_reactor.util import df_parser, DockerfileImages
from atomic_reactor.source import VcsInfo
from atomic_reactor.constants import INSPECT_CONFIG
from atomic_reactor import start_time as atomic_reactor_start_time
import datetime
import re
import json
import logging
import pytest
from copy import deepcopy
from flexmock import flexmock
from tests.constants import DOCKERFILE_GIT, DOCKERFILE_SHA1, MOCK
if MOCK:
from tests.docker_mock import mock_docker
class MockSource(object):
dockerfile_path = None
path = None
def __init__(self, release_env=None):
self.config = flexmock()
setattr(self.config, 'release_env_var', release_env)
def get_vcs_info(self):
return VcsInfo(vcs_type="git", vcs_url=DOCKERFILE_GIT, vcs_ref=DOCKERFILE_SHA1)
class X(object):
def __init__(self, release_env=None, parent_images=()):
self.image_id = "xxx"
self.source = MockSource(release_env)
self.dockerfile_images = DockerfileImages(parent_images)
DF_CONTENT = """\
FROM fedora
RUN yum install -y python-django
CMD blabla"""
DF_CONTENT_WITH_LABELS = '''\
FROM fedora
RUN yum install -y python-django
CMD blabla
LABEL "build-date" = "docker value"
LABEL "architecture" = "docker value"
LABEL "vcs-type" = "docker value"
LABEL "vcs-url" = "docker value"
LABEL "vcs-ref" = "docker value"
LABEL "com.redhat.build-host" = "docker value"
LABEL "Build_Host" = "docker value"'''
DF_CONTENT_SINGLE_LINE = """\
FROM fedora"""
DF_CONTENT_LABEL = '''\
FROM fedora
LABEL "label2"="df value"'''
DF_CONTENT_LABELS = '''\
FROM fedora
LABEL "label1"="label1_value"
LABEL "label2"="label2_value"
LABEL "Authoritative_Registry"="authoritative-source-url_value"
LABEL "BZComponent"="com.redhat.component_value"
LABEL "Build_Host"="com.redhat.build-host_value"
LABEL "Version"="version_value"'''
LABELS_CONF_WITH_LABELS = {INSPECT_CONFIG: {"Labels": {
"build-date": "base value",
"architecture": "base value",
"vcs-type": "base value",
"vcs-url": "base value",
"vcs-ref": "base value",
"com.redhat.build-host": "base value",
"Build_Host": "base value"}}}
LABELS_CONF_BASE = {INSPECT_CONFIG: {"Labels": {"label1": "base value"}}}
LABELS_CONF_BASE_EXPLICIT = {INSPECT_CONFIG: {"Labels": {"version": "x", "release": "1"}}}
LABELS_CONF_BASE_NONE = {INSPECT_CONFIG: {"Labels": None}}
LABELS_CONF = OrderedDict({'label1': 'value 1', 'label2': 'long value'})
LABELS_CONF_ONE = {'label2': 'long value'}
LABELS_CONF_WRONG = [('label1', 'value1'), ('label2', 'value2')]
LABELS_CONF_EXPLICIT = {"version": "x", "release": "1"}
LABELS_BLANK = {}
# Can't be sure of the order of the labels, expect either
EXPECTED_OUTPUT = ["""FROM fedora
RUN yum install -y python-django
CMD blabla
LABEL "label1"="value 1" "label2"="long value"
""", """\
FROM fedora
RUN yum install -y python-django
CMD blabla
LABEL "label2"="long value" "label1"="value 1"
"""]
EXPECTED_OUTPUT2 = [r"""FROM fedora
RUN yum install -y python-django
CMD blabla
LABEL "label2"="long value"
"""]
EXPECTED_OUTPUT3 = [DF_CONTENT]
EXPECTED_OUTPUT4 = [r"""FROM fedora
LABEL "label2"="long value"
"""]
EXPECTED_OUTPUT5 = [r"""FROM fedora
LABEL "labelnew"="base value"
"""]
EXPECTED_OUTPUT6 = [r"""FROM fedora
LABEL "labelnew"="long value" "label2"="long value"
""", r"""FROM fedora
LABEL "label2"="long value" "labelnew"="long value"
"""]
EXPECTED_OUTPUT7 = [r"""FROM fedora
LABEL "label2"="df value"
LABEL "labelnew"="df value"
"""]
EXPECTED_OUTPUT8 = [r"""FROM fedora
LABEL "label1"="df value"
LABEL "label2"="df value"
""", r"""FROM fedora
LABEL "label2"="df value"
LABEL "label1"="df value"
"""]
# Label order seems to be set randomly, so both possible options are added
EXPECTED_OUTPUT9 = [r"""FROM fedora
RUN yum install -y python-django
CMD blabla
LABEL "release"="1" "version"="x"
""", r"""FROM fedora
RUN yum install -y python-django
CMD blabla
LABEL "version"="x" "release"="1"
"""]
def make_and_store_reactor_config_map(workflow, additional=None):
workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
reactor_map = {
'version': 1
}
if additional:
reactor_map.update(additional)
workflow.plugin_workspace[ReactorConfigPlugin.key] = {
WORKSPACE_CONF_KEY: ReactorConfig(reactor_map)
}
@pytest.mark.parametrize('df_content, labels_conf_base, labels_conf, eq_conf, dont_overwrite,' # noqa
'aliases, expected_output', [ # noqa
(DF_CONTENT, LABELS_CONF_BASE, LABELS_CONF, [], [], {}, EXPECTED_OUTPUT),
(DF_CONTENT, LABELS_CONF_BASE, json.dumps(LABELS_CONF), [], [], {}, EXPECTED_OUTPUT),
(DF_CONTENT, LABELS_CONF_BASE, LABELS_CONF_WRONG, [], [], {}, RuntimeError()),
(DF_CONTENT, LABELS_CONF_BASE, LABELS_CONF, {'key': 'val'}, [], {}, RuntimeError()),
(DF_CONTENT, LABELS_CONF_BASE, LABELS_CONF, [], ["label1", ], {}, EXPECTED_OUTPUT2),
(DF_CONTENT, LABELS_CONF_BASE, LABELS_BLANK, [], ["label1", ], {}, EXPECTED_OUTPUT3),
(DF_CONTENT_SINGLE_LINE, LABELS_CONF_BASE, LABELS_CONF, [], ["label1", ], {},
EXPECTED_OUTPUT4),
(DF_CONTENT, LABELS_CONF_BASE, LABELS_CONF, [], [], {"not": "present"}, EXPECTED_OUTPUT),
(DF_CONTENT_SINGLE_LINE, LABELS_CONF_BASE, LABELS_BLANK, [], [], {"label1": "labelnew"},
EXPECTED_OUTPUT5),
(DF_CONTENT_SINGLE_LINE, LABELS_CONF_BASE, LABELS_CONF_ONE, [], [], {"label2": "labelnew"},
EXPECTED_OUTPUT6),
(DF_CONTENT_LABEL, LABELS_CONF_BASE, LABELS_BLANK, [], [], {"label2": "labelnew"},
EXPECTED_OUTPUT7),
(DF_CONTENT_LABEL, LABELS_CONF_BASE, LABELS_BLANK, [], [], {"label2": "labelnew", "x": "y"},
EXPECTED_OUTPUT7),
(DF_CONTENT_LABEL, LABELS_CONF_BASE_NONE, LABELS_BLANK, [], [], {"label2": "labelnew"},
EXPECTED_OUTPUT7),
(DF_CONTENT_LABEL, LABELS_CONF_BASE, LABELS_BLANK, [], [], {"label2": "label1"},
EXPECTED_OUTPUT8),
(DF_CONTENT, LABELS_CONF_BASE_EXPLICIT, LABELS_CONF_EXPLICIT, [], [], {}, EXPECTED_OUTPUT9),
])
def test_add_labels_plugin(tmpdir, docker_tasker, workflow,
df_content, labels_conf_base, labels_conf, eq_conf,
dont_overwrite, aliases, expected_output, caplog,
reactor_config_map):
df = df_parser(str(tmpdir))
df.content = df_content
if MOCK:
mock_docker()
setattr(workflow, 'builder', X(parent_images=df.parent_images))
setattr(workflow.builder, 'df_path', df.dockerfile_path)
setattr(workflow.builder, 'base_image_inspect', labels_conf_base)
flexmock(workflow, source=MockSource())
if reactor_config_map:
# reactor_config should not return json
if isinstance(labels_conf, str):
image_labels = json.loads(labels_conf)
else:
image_labels = deepcopy(labels_conf)
make_and_store_reactor_config_map(workflow, {
'image_labels': image_labels,
'image_equal_labels': eq_conf,
})
runner = PreBuildPluginsRunner(
docker_tasker,
workflow,
[{
'name': AddLabelsPlugin.key,
'args': {
'labels': labels_conf,
'dont_overwrite': dont_overwrite,
'auto_labels': [],
'aliases': aliases,
'equal_labels': eq_conf,
}
}]
)
if isinstance(expected_output, RuntimeError):
with pytest.raises(PluginFailedException):
runner.run()
assert "plugin 'add_labels_in_dockerfile' raised an exception: RuntimeError" \
in caplog.text
else:
runner.run()
assert AddLabelsPlugin.key is not None
assert df.content in expected_output
@pytest.mark.parametrize('use_reactor', [True, False]) # noqa
@pytest.mark.parametrize('release', [None, 'test'])
def test_add_labels_arrangement6(tmpdir, docker_tasker, workflow, release, use_reactor):
# explicitly test arrangement 6's handling of reactor config
df = df_parser(str(tmpdir))
df.content = DF_CONTENT
if MOCK:
mock_docker()
setattr(workflow, 'builder', X(parent_images=df.parent_images))
setattr(workflow.builder, 'base_image_inspect', LABELS_CONF_BASE)
setattr(workflow.builder, 'df_path', df.dockerfile_path)
flexmock(workflow, source=MockSource())
if use_reactor:
make_and_store_reactor_config_map(workflow, {'image_labels': LABELS_CONF})
if release is not None:
labels = {'release': release}
else:
labels = None
else:
labels = LABELS_CONF
if release is not None:
labels.update({'release': release})
runner = PreBuildPluginsRunner(
docker_tasker,
workflow,
[{
'name': AddLabelsPlugin.key,
'args': {
'labels': labels,
'dont_overwrite': [],
'auto_labels': [],
'aliases': [],
'equal_labels': [],
}
}]
)
runner.run()
assert AddLabelsPlugin.key is not None
assert 'label1' in df.content
if release:
assert 'release' in df.content
assert release in df.content
else:
assert 'release' not in df.content
@pytest.mark.parametrize('auto_label, value_re_part', [ # noqa
('build-date', r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?'),
('architecture', 'x86_64'),
('vcs-type', 'git'),
('vcs-url', DOCKERFILE_GIT),
('vcs-ref', DOCKERFILE_SHA1),
('com.redhat.build-host', 'the-build-host'),
('wrong_label', None)
])
def test_add_labels_plugin_generated(tmpdir, docker_tasker, workflow,
auto_label, value_re_part,
reactor_config_map):
df = df_parser(str(tmpdir))
df.content = DF_CONTENT
if MOCK:
mock_docker()
setattr(workflow, 'builder', X(parent_images=df.parent_images))
setattr(workflow.builder, 'df_path', df.dockerfile_path)
setattr(workflow.builder, 'base_image_inspect', LABELS_CONF_BASE)
flexmock(workflow, source=MockSource())
if reactor_config_map:
make_and_store_reactor_config_map(workflow, {'image_labels': {}})
runner = PreBuildPluginsRunner(
docker_tasker,
workflow,
[{
'name': AddLabelsPlugin.key,
'args': {'labels': {}, "dont_overwrite": [], "auto_labels": [auto_label],
'aliases': {'Build_Host': 'com.redhat.build-host'}}
}]
)
runner.run()
if value_re_part:
assert re.match(value_re_part, df.labels[auto_label])
if auto_label == "build-date":
utc_dt = datetime.datetime.utcfromtimestamp(atomic_reactor_start_time).isoformat()
assert df.labels[auto_label] == utc_dt
@pytest.mark.parametrize('df_old_as_plugin_arg', [True, False]) # noqa
@pytest.mark.parametrize('df_new_as_plugin_arg', [True, False])
@pytest.mark.parametrize('base_old, base_new, df_old, df_new, exp_old, exp_new, exp_log', [
(None, None, None, None, None, None, None),
(None, None, None, 'A', None, 'A', None),
(None, None, 'A', None, 'A', 'A', 'as an alias for label'),
(None, None, 'A', 'A', 'A', 'A', 'already exists'),
(None, None, 'A', 'B', 'B', 'B', 'as an alias for label'),
(None, 'A', None, None, None, 'A', None),
(None, 'A', None, 'A', None, 'A', None),
(None, 'A', None, 'B', None, 'B', None),
(None, 'A', 'A', None, 'A', 'A', 'already exists'),
(None, 'A', 'B', None, 'B', 'B', 'as an alias for label'),
(None, 'A', 'A', 'A', 'A', 'A', 'already exists'),
(None, 'A', 'A', 'B', 'B', 'B', 'as an alias for label'),
(None, 'A', 'B', 'A', 'A', 'A', 'as an alias for label'),
(None, 'A', 'B', 'B', 'B', 'B', 'already exists'),
(None, 'A', 'B', 'C', 'C', 'C', 'as an alias for label'),
('A', None, None, None, 'A', 'A', 'as an alias for label'),
('A', None, None, 'A', 'A', 'A', 'already exists'),
('A', None, None, 'B', 'B', 'B', 'as an alias for label'),
('A', None, 'A', None, 'A', 'A', 'as an alias for label'),
('A', None, 'B', None, 'B', 'B', 'as an alias for label'),
('A', None, 'A', 'A', 'A', 'A', 'already exists'),
('A', None, 'A', 'B', 'B', 'B', 'as an alias for label'),
('A', None, 'B', 'A', 'A', 'A', 'as an alias for label'),
('A', None, 'B', 'B', 'B', 'B', 'already exists'),
('A', None, 'B', 'C', 'C', 'C', 'as an alias for label'),
('A', 'A', None, None, 'A', 'A', 'already exists'),
('A', 'A', None, 'A', 'A', 'A', 'already exists'),
('A', 'A', None, 'B', 'B', 'B', 'as an alias for label'),
('A', 'A', 'A', None, 'A', 'A', 'already exists'),
('A', 'A', 'B', None, 'B', 'B', 'as an alias for label'),
('A', 'A', 'A', 'A', 'A', 'A', 'already exists'),
('A', 'A', 'A', 'B', 'B', 'B', 'as an alias for label'),
('A', 'A', 'B', 'A', 'A', 'A', 'as an alias for label'),
('A', 'A', 'B', 'B', 'B', 'B', 'already exists'),
('A', 'A', 'B', 'C', 'C', 'C', 'as an alias for label'),
('A', 'B', None, None, 'B', 'B', 'as an alias for label'),
('A', 'B', None, 'A', 'A', 'A', 'already exists'),
('A', 'B', None, 'B', 'B', 'B', 'as an alias for label'),
('A', 'B', None, 'C', 'C', 'C', 'as an alias for label'),
('A', 'B', 'A', None, 'A', 'A', 'as an alias for label'),
('A', 'B', 'B', None, 'B', 'B', 'already exists'),
('A', 'B', 'C', None, 'C', 'C', 'as an alias for label'),
('A', 'B', 'A', 'A', 'A', 'A', 'already exists'),
('A', 'B', 'A', 'B', 'B', 'B', 'as an alias for label'),
('A', 'B', 'A', 'C', 'C', 'C', 'as an alias for label'),
('A', 'B', 'B', 'A', 'A', 'A', 'as an alias for label'),
('A', 'B', 'B', 'B', 'B', 'B', 'already exists'),
('A', 'B', 'B', 'C', 'C', 'C', 'as an alias for label'),
('A', 'B', 'C', 'A', 'A', 'A', 'as an alias for label'),
('A', 'B', 'C', 'B', 'B', 'B', 'as an alias for label'),
('A', 'B', 'C', 'C', 'C', 'C', 'already exists'),
('A', 'B', 'C', 'D', 'D', 'D', 'as an alias for label'),
])
def test_add_labels_aliases(tmpdir, docker_tasker, workflow, caplog,
df_old_as_plugin_arg, df_new_as_plugin_arg,
base_old, base_new, df_old, df_new, exp_old, exp_new, exp_log,
reactor_config_map):
if MOCK:
mock_docker()
df_content = "FROM fedora\n"
plugin_labels = {}
if df_old:
if df_old_as_plugin_arg:
plugin_labels["label_old"] = df_old
else:
df_content += 'LABEL label_old="{0}"\n'.format(df_old)
if df_new:
if df_new_as_plugin_arg:
plugin_labels["label_new"] = df_new
else:
df_content += 'LABEL label_new="{0}"\n'.format(df_new)
base_labels = {INSPECT_CONFIG: {"Labels": {}}}
if base_old:
base_labels[INSPECT_CONFIG]["Labels"]["label_old"] = base_old
if base_new:
base_labels[INSPECT_CONFIG]["Labels"]["label_new"] = base_new
df = df_parser(str(tmpdir))
df.content = df_content
setattr(workflow, 'builder', X(parent_images=df.parent_images))
setattr(workflow.builder, 'df_path', df.dockerfile_path)
setattr(workflow.builder, 'base_image_inspect', base_labels)
flexmock(workflow, source=MockSource())
if reactor_config_map:
make_and_store_reactor_config_map(workflow, {'image_labels': plugin_labels})
runner = PreBuildPluginsRunner(
docker_tasker,
workflow,
[{
'name': AddLabelsPlugin.key,
'args': {
'labels': plugin_labels,
'dont_overwrite': [],
'auto_labels': [],
'aliases': {"label_old": "label_new"},
}
}]
)
runner.run()
assert AddLabelsPlugin.key is not None
result_old = df.labels.get("label_old") or \
base_labels[INSPECT_CONFIG]["Labels"].get("label_old")
result_new = df.labels.get("label_new") or \
base_labels[INSPECT_CONFIG]["Labels"].get("label_new")
assert result_old == exp_old
assert result_new == exp_new
if exp_log:
assert exp_log in caplog.text
@pytest.mark.parametrize('base_l, df_l, expected, expected_log', [ # noqa
((None, None), (None, None), (None, None), None),
((None, None), (None, 'A'), ('A', 'A'), 'adding equal label'),
((None, None), ('A', None), ('A', 'A'), 'adding equal label'),
(('A', None), (None, None), ('A', 'A'), 'adding equal label'),
((None, 'A'), (None, None), ('A', 'A'), 'adding equal label'),
(('A', 'B'), (None, None), ('A', 'B'), None),
((None, None), ('A', 'B'), ('A', 'B'), None),
(('A', 'A'), (None, None), ('A', 'A'), None),
(('A', None), ('A', None), ('A', 'A'), 'adding equal label'),
((None, 'A'), (None, 'A'), ('A', 'A'), 'adding equal label'),
(('A', None), ('B', None), ('B', 'B'), 'adding equal label'),
((None, 'A'), (None, 'B'), ('B', 'B'), 'adding equal label'),
(('A', 'C'), ('B', None), ('B', 'B'), 'adding equal label'),
(('A', 'C'), (None, 'B'), ('B', 'B'), 'adding equal label'),
(('A', 'C'), ('B', 'B'), ('B', 'B'), None),
((None, 'A'), ('B', 'B'), ('B', 'B'), None),
(('A', None), ('B', 'B'), ('B', 'B'), None),
(('A', 'A'), (None, None), ('A', 'A'), None),
(('A', None), (None, 'A'), ('A', 'A'), 'skipping label'),
((None, 'A'), ('A', None), ('A', 'A'), 'skipping label'),
])
def test_add_labels_equal_aliases(tmpdir, docker_tasker, workflow, caplog,
base_l, df_l, expected, expected_log,
reactor_config_map):
if MOCK:
mock_docker()
df_content = "FROM fedora\n"
plugin_labels = {}
if df_l[0]:
df_content += 'LABEL description="{0}"\n'.format(df_l[0])
if df_l[1]:
df_content += 'LABEL io.k8s.description="{0}"\n'.format(df_l[1])
base_labels = {INSPECT_CONFIG: {"Labels": {}}}
if base_l[0]:
base_labels[INSPECT_CONFIG]["Labels"]["description"] = base_l[0]
if base_l[1]:
base_labels[INSPECT_CONFIG]["Labels"]["io.k8s.description"] = base_l[1]
df = df_parser(str(tmpdir))
df.content = df_content
setattr(workflow, 'builder', X(parent_images=df.parent_images))
setattr(workflow.builder, 'df_path', df.dockerfile_path)
setattr(workflow.builder, 'base_image_inspect', base_labels)
flexmock(workflow, source=MockSource())
if reactor_config_map:
make_and_store_reactor_config_map(
workflow,
{
'image_labels': plugin_labels,
'image_equal_labels': [['description', 'io.k8s.description']]})
runner = PreBuildPluginsRunner(
docker_tasker,
workflow,
[{
'name': AddLabelsPlugin.key,
'args': {
'labels': plugin_labels,
'dont_overwrite': [],
'auto_labels': [],
'aliases': {},
'equal_labels': [['description', 'io.k8s.description']]
}
}]
)
runner.run()
assert AddLabelsPlugin.key is not None
result_fst = df.labels.get("description") or \
base_labels[INSPECT_CONFIG]["Labels"].get("description")
result_snd = df.labels.get("io.k8s.description") or \
base_labels[INSPECT_CONFIG]["Labels"].get("io.k8s.description")
assert result_fst == expected[0]
assert result_snd == expected[1]
if expected_log:
assert expected_log in caplog.text
@pytest.mark.parametrize('base_l, df_l, expected, expected_log', [ # noqa
((None, None, None), (None, None, None), (None, None, None), None),
((None, None, None), (None, None, 'A'), ('A', 'A', 'A'), 'adding equal label'),
(('A', 'B', 'B'), (None, None, None), ('A', 'B', 'B'), None),
((None, None, None), ('A', 'B', 'B'), ('A', 'B', 'B'), None),
(('A', 'A', 'A'), (None, None, None), ('A', 'A', 'A'), None),
(('A', None, 'A'), ('A', None, 'A'), ('A', 'A', 'A'), 'adding equal label'),
(('A', None, None), (None, 'A', 'A'), ('A', 'A', 'A'), 'skipping label'),
((None, 'A', 'A'), ('A', 'A', None), ('A', 'A', 'A'), 'skipping label'),
(('A', 'A', 'A'), ('B', 'C', None), ('B', 'C', 'B'), 'adding equal label'),
(('A', 'A', 'A'), (None, 'C', 'D'), ('C', 'C', 'D'), 'adding equal label'),
(('A', 'A', 'A'), ('B', None, 'D'), ('B', 'B', 'D'), 'adding equal label'),
])
def test_add_labels_equal_aliases2(tmpdir, docker_tasker, workflow, caplog, base_l,
df_l, expected, expected_log, reactor_config_map):
"""
test with 3 equal labels
"""
if MOCK:
mock_docker()
df_content = "FROM fedora\n"
plugin_labels = {}
if df_l[0]:
df_content += 'LABEL description="{0}"\n'.format(df_l[0])
if df_l[1]:
df_content += 'LABEL io.k8s.description="{0}"\n'.format(df_l[1])
if df_l[2]:
df_content += 'LABEL description_third="{0}"\n'.format(df_l[2])
base_labels = {INSPECT_CONFIG: {"Labels": {}}}
if base_l[0]:
base_labels[INSPECT_CONFIG]["Labels"]["description"] = base_l[0]
if base_l[1]:
base_labels[INSPECT_CONFIG]["Labels"]["io.k8s.description"] = base_l[1]
if base_l[2]:
base_labels[INSPECT_CONFIG]["Labels"]["description_third"] = base_l[2]
df = df_parser(str(tmpdir))
df.content = df_content
setattr(workflow, 'builder', X(parent_images=df.parent_images))
setattr(workflow.builder, 'df_path', df.dockerfile_path)
setattr(workflow.builder, 'base_image_inspect', base_labels)
flexmock(workflow, source=MockSource())
if reactor_config_map:
make_and_store_reactor_config_map(
workflow,
{
'image_labels': plugin_labels,
'image_equal_labels': [['description',
'io.k8s.description',
'description_third']]})
runner = PreBuildPluginsRunner(
docker_tasker,
workflow,
[{
'name': AddLabelsPlugin.key,
'args': {
'labels': plugin_labels,
'dont_overwrite': [],
'auto_labels': [],
'aliases': {},
'equal_labels': [['description', 'io.k8s.description', 'description_third']]
}
}]
)
if isinstance(expected_log, RuntimeError):
with pytest.raises(PluginFailedException):
runner.run()
else:
runner.run()
assert AddLabelsPlugin.key is not None
result_fst = df.labels.get("description") or \
base_labels[INSPECT_CONFIG]["Labels"].get("description")
result_snd = df.labels.get("io.k8s.description") or \
base_labels[INSPECT_CONFIG]["Labels"].get("io.k8s.description")
result_trd = df.labels.get("description_third") or \
base_labels[INSPECT_CONFIG]["Labels"].get("description_third")
assert result_fst == expected[0]
assert result_snd == expected[1]
assert result_trd == expected[2]
if expected_log:
assert expected_log in caplog.text
@pytest.mark.parametrize("label_names", [ # noqa
("distribution-scope", ),
("com.redhat.license_terms", ),
("distribution-scope", "com.redhat.license_terms"),
])
@pytest.mark.parametrize("dont_overwrite", [True, False])
@pytest.mark.parametrize("parent_val, docker_val, result_val", [
(None, None, "default_value"),
("parent_value", "docker_value", "docker_value"),
("parent_value", None, "default_value"),
(None, "docker_value", "docker_value"),
("parent_value", "parent_value", "parent_value"),
])
def test_dont_overwrite_if_in_dockerfile(tmpdir, docker_tasker, workflow,
label_names, dont_overwrite,
parent_val, docker_val, result_val, reactor_config_map):
default_value = 'default_value'
df_content = "FROM fedora\n"
if docker_val:
for label_name in label_names:
df_content += 'LABEL {0}="{1}"\n'.format(label_name, docker_val)
if parent_val:
labels_conf_base = {INSPECT_CONFIG: {"Labels": {}}}
for label_name in label_names:
labels_conf_base[INSPECT_CONFIG]["Labels"][label_name] = parent_val
else:
labels_conf_base = {INSPECT_CONFIG: {"Labels": {}}}
df = df_parser(str(tmpdir))
df.content = df_content
if MOCK:
mock_docker()
setattr(workflow, 'builder', X(parent_images=df.parent_images))
setattr(workflow.builder, 'df_path', df.dockerfile_path)
setattr(workflow.builder, 'base_image_inspect', labels_conf_base)
flexmock(workflow, source=MockSource())
image_labels = {}
for label_name in label_names:
image_labels[label_name] = default_value
wf_args = {
'labels': image_labels,
'auto_labels': [],
'aliases': {},
}
if dont_overwrite:
wf_args["dont_overwrite_if_in_dockerfile"] = label_names
if reactor_config_map:
make_and_store_reactor_config_map(workflow, {'image_labels': image_labels})
runner = PreBuildPluginsRunner(
docker_tasker,
workflow,
[{
'name': AddLabelsPlugin.key,
'args': wf_args
}]
)
runner.run()
for label_name in label_names:
result = df.labels.get(label_name)
assert result == result_val
@pytest.mark.parametrize('url_format, info_url', [ # noqa
('url_pre {label1} {label2} url_post', 'url_pre label1_value label2_value url_post'),
('url_pre url_post', 'url_pre url_post'),
('url_pre {label1} {label2} {label3_non_existent} url_post', None),
('url_pre {label1} {label2} {version} url_post', 'url_pre label1_value label2_value '
'version_value url_post'),
('url_pre {authoritative-source-url} {com.redhat.component} {com.redhat.build-host} url_post',
'url_pre authoritative-source-url_value com.redhat.component_value '
'com.redhat.build-host_value url_post'),
])
def test_url_label(tmpdir, docker_tasker, workflow, url_format, info_url, reactor_config_map):
if MOCK:
mock_docker()
plugin_labels = {}
base_labels = {INSPECT_CONFIG: {"Labels": {}}}
df = df_parser(str(tmpdir))
df.content = DF_CONTENT_LABELS
setattr(workflow, 'builder', X(parent_images=df.parent_images))
setattr(workflow.builder, 'df_path', df.dockerfile_path)
setattr(workflow.builder, 'base_image_inspect', base_labels)
flexmock(workflow, source=MockSource())
if reactor_config_map:
make_and_store_reactor_config_map(workflow, {
'image_labels': plugin_labels,
'image_label_info_url_format': url_format,
})
runner = PreBuildPluginsRunner(
docker_tasker,
workflow,
[{
'name': AddLabelsPlugin.key,
'args': {
'labels': plugin_labels,
'dont_overwrite': [],
'auto_labels': [],
'info_url_format': url_format
}
}]
)
if info_url is not None:
runner.run()
assert df.labels.get("url") == info_url
else:
with pytest.raises(PluginFailedException):
runner.run()
assert AddLabelsPlugin.key is not None
@pytest.mark.parametrize('auto_label', [ # noqa
'build-date',
'architecture',
'vcs-type',
'vcs-url',
'vcs-ref',
'com.redhat.build-host',
])
@pytest.mark.parametrize('labels_docker', [
DF_CONTENT,
DF_CONTENT_WITH_LABELS,
])
@pytest.mark.parametrize('labels_base', [
LABELS_CONF_BASE_NONE,
LABELS_CONF_WITH_LABELS,
])
def test_add_labels_plugin_explicit(tmpdir, docker_tasker, workflow,
auto_label, labels_docker,
labels_base, reactor_config_map):
df = df_parser(str(tmpdir))
df.content = labels_docker
if MOCK:
mock_docker()
setattr(workflow, 'builder', X(parent_images=df.parent_images))
setattr(workflow.builder, 'df_path', df.dockerfile_path)
setattr(workflow.builder, 'base_image_inspect', labels_base)
flexmock(workflow, source=MockSource())
prov_labels = {}
prov_labels[auto_label] = 'explicit_value'
if reactor_config_map:
make_and_store_reactor_config_map(workflow, {'image_labels': prov_labels})
runner = PreBuildPluginsRunner(
docker_tasker,
workflow,
[{
'name': AddLabelsPlugin.key,
'args': {'labels': prov_labels, "dont_overwrite": [], "auto_labels": [auto_label],
'aliases': {'Build_Host': 'com.redhat.build-host'}}
}]
)
runner.run()
assert df.labels[auto_label] != 'explicit_value'
@pytest.mark.parametrize('parent, should_fail', [ # noqa
('koji/image-build', False),
('scratch', False),
('fedora', True),
])
def test_add_labels_base_image(tmpdir, docker_tasker, workflow,
parent, should_fail,
caplog, reactor_config_map):
df = df_parser(str(tmpdir))
df.content = "FROM {}\n".format(parent)
if MOCK:
mock_docker()
setattr(workflow, 'builder', X(parent_images=df.parent_images))
setattr(workflow.builder, 'tasker', docker_tasker)
setattr(workflow.builder, 'df_path', df.dockerfile_path)
setattr(workflow.builder, 'base_image_inspect', {})
flexmock(workflow, source=MockSource())
# When a 'release' label is provided by parameter and used to
# configure the plugin, it should be set in the Dockerfile even
# when processing base images.
prov_labels = {'release': '5'}
if reactor_config_map:
make_and_store_reactor_config_map(workflow, {'image_labels': prov_labels})
runner = PreBuildPluginsRunner(
docker_tasker,
workflow,
[{
'name': AddLabelsPlugin.key,
'args': {'labels': prov_labels, "dont_overwrite": [],
'aliases': {'Build_Host': 'com.redhat.build-host'}}
}]
)
if should_fail:
with caplog.at_level(logging.ERROR):
with pytest.raises(PluginFailedException):
runner.run()
msg = "base image was not inspected"
assert msg in [x.message for x in caplog.records]
else:
runner.run()
assert df.labels['release'] == '5'
@pytest.mark.parametrize('base_new, df_new, plugin_new, expected_in_df, expected_log', [ # noqa
(None, None, None, None, None),
(None, 'A', 'A', 'A', None),
(None, 'B', 'A', 'A', 'setting label'),
(None, 'A', 'B', 'B', None),
(None, None, 'A', 'A', 'setting label'),
(None, 'A', None, 'A', None),
('A', None, 'A', 'A', 'setting label'),
('B', None, 'A', 'A', 'setting label'),
('A', None, 'B', 'B', 'setting label'),
('A', 'A', None, 'A', None),
('A', 'B', None, 'B', None),
('B', 'A', None, 'A', None),
('A', 'A', 'A', 'A', None),
('A', 'B', 'A', 'A', 'setting label'),
('B', 'A', 'A', 'A', None),
('A', 'A', 'B', 'B', 'setting label'),
('A', 'B', 'B', 'B', None),
('B', 'B', 'A', 'A', 'setting label'),
('B', 'A', 'B', 'B', 'setting label'),
('A', 'B', 'C', 'C', 'setting label'),
])
@pytest.mark.parametrize('release_env', ['TEST_RELEASE_VAR', None])
def test_release_label(tmpdir, docker_tasker, workflow, caplog,
base_new, df_new, plugin_new,
expected_in_df, expected_log, release_env, reactor_config_map):
if MOCK:
mock_docker()
df_content = "FROM fedora\n"
plugin_labels = {}
if df_new:
df_content += 'LABEL release="{0}"\n'.format(df_new)
if plugin_new:
plugin_labels["release"] = plugin_new
base_labels = {INSPECT_CONFIG: {"Labels": {}}}
if base_new:
base_labels[INSPECT_CONFIG]["Labels"]["release"] = base_new
df = df_parser(str(tmpdir))
df.content = df_content
setattr(workflow, 'builder', X(release_env, parent_images=df.parent_images))
setattr(workflow.builder, 'df_path', df.dockerfile_path)
setattr(workflow.builder, 'base_image_inspect', base_labels)
flexmock(workflow, source=MockSource(release_env))
if reactor_config_map:
make_and_store_reactor_config_map(workflow, {'image_labels': plugin_labels})
runner = PreBuildPluginsRunner(
docker_tasker,
workflow,
[{
'name': AddLabelsPlugin.key,
'args': {
'labels': plugin_labels,
'dont_overwrite': [],
'auto_labels': [],
'aliases': {}
}
}]
)
runner.run()
assert AddLabelsPlugin.key is not None
result_new = df.labels.get("release")
assert result_new == expected_in_df
if release_env and expected_in_df:
expected = "ENV {}={}\n".format(release_env, expected_in_df)
assert expected in df.lines
if expected_log:
assert expected_log in caplog.text
| {
"pile_set_name": "Github"
} |
772,249,6,15
771,249,6,15
771,250,6,15
770,250,6,15
770,250,6,15
769,251,6,15
769,251,6,15
768,251,6,15
767,252,6,15
766,252,6,15
765,252,6,15
765,253,6,15
764,253,6,15
763,253,6,15
763,254,7,14
762,254,7,14
761,254,7,14
760,255,6,13
759,255,6,13
758,255,7,14
758,255,8,14
757,255,9,15
756,255,9,15
755,256,8,15
754,256,8,15
754,256,7,15
754,256,7,14
754,256,6,14
753,256,6,15
753,256,7,15
752,256,7,16
751,256,7,16
751,257,8,16
750,257,8,16
750,258,8,15
749,258,7,14
749,259,7,13
748,259,7,13
747,259,8,14
746,259,8,14
746,258,8,16
745,258,7,17
745,257,7,19
744,259,7,18
744,260,7,16
743,262,7,15
742,262,7,15
742,262,7,16
741,262,7,16
740,262,8,16
740,263,8,16
739,263,9,16
738,264,8,15
738,265,8,14
737,266,7,13
736,266,7,13
736,265,7,14
735,265,7,14
734,266,7,14
734,266,7,13
733,267,7,13
732,267,7,14
732,267,7,15
731,267,7,16
731,267,7,15
730,267,8,15
730,267,8,14
729,267,8,14
728,268,7,15
727,268,7,15
727,268,7,15
726,269,8,16
726,269,8,16
725,269,8,16
725,269,7,16
724,269,7,16
723,269,7,16
723,270,7,16
722,270,7,16
721,270,7,16
721,269,8,17
720,269,8,17
719,270,9,17
718,272,9,16
717,273,10,16
716,273,9,16
716,273,9,16
715,273,8,16
715,273,8,16
714,274,7,15
714,274,7,15
713,274,7,16
713,274,7,16
712,274,7,17
711,275,7,16
711,275,7,16
710,276,7,15
709,276,8,15
708,277,8,16
707,277,9,16
706,277,9,16
706,277,9,16
705,277,9,16
704,277,9,16
704,277,9,16
703,277,9,16
703,277,8,16
702,278,8,17
702,278,7,17
701,279,7,16
701,279,7,16
700,280,7,15
699,280,7,16
699,281,8,16
698,281,8,17
697,281,8,17
697,281,9,17
696,281,9,17
695,281,9,17
694,281,9,18
693,281,9,18
692,281,9,18
692,282,9,19
691,282,9,19
691,282,9,19
691,281,8,19
691,281,8,19
690,282,9,19
689,284,9,18
688,285,10,18
688,285,10,18
688,285,9,19
688,285,9,19
687,285,9,19
687,285,9,20
686,285,9,20
686,286,9,19
686,287,8,18
686,288,8,17
686,288,8,17
686,288,7,17
686,288,7,17
685,288,8,18
683,288,9,18
682,288,10,19
682,288,9,18
682,289,9,18
682,289,8,17
682,290,9,17
682,290,9,18
682,291,10,18
682,291,10,18
682,292,9,18
682,292,9,18
682,292,9,18
681,292,8,17
681,292,8,17
682,292,8,17
682,293,8,18
683,293,8,18
683,293,8,18
683,294,8,17
683,294,8,17
684,294,8,17
685,295,7,17
686,295,7,17
687,295,7,17
687,295,6,18
688,295,6,18
689,295,6,18
689,295,5,18
690,295,5,18
691,296,4,18
693,296,4,17
694,297,3,17
695,297,3,17
696,298,4,17
697,298,4,17
697,298,5,18
698,297,6,19
698,297,7,20
699,297,7,20
699,298,8,19
700,298,8,19
701,298,7,20
703,299,7,20
704,299,6,21
706,300,6,21
707,300,6,20
709,301,6,20
710,301,7,20
712,300,7,21
713,300,8,21
715,300,8,21
716,301,8,22
718,301,8,22
719,302,8,21
720,303,9,21
721,304,9,20
723,304,9,20
724,304,8,21
726,304,8,21
728,304,8,21
729,305,8,22
731,305,8,22
733,305,8,22
734,305,8,22
736,305,8,22
738,305,8,22
739,306,9,22
741,306,9,22
742,306,9,23
744,306,9,23
745,306,9,24
747,307,9,24
749,307,8,23
751,308,8,23
753,308,8,23
756,308,8,23
758,308,8,23
759,309,9,23
761,309,9,24
762,310,10,24
765,311,10,23
768,311,9,22
771,312,9,21
773,312,9,21
774,313,8,22
776,313,8,22
778,313,7,23
781,313,7,23
783,313,6,24
786,314,7,23
788,314,8,23
791,315,9,22
793,315,8,22
795,314,8,23
797,314,7,23
800,315,7,22
803,316,8,21
806,317,8,20
808,317,8,20
809,317,9,21
811,317,9,21
813,317,9,22
814,318,10,24
816,318,10,25
820,319,9,24
823,320,8,24
827,321,7,23
829,321,7,24
830,321,8,25
832,321,8,26
834,321,8,26
836,322,8,26
838,322,8,26
842,322,8,26
845,323,8,26
849,323,8,26
851,323,8,26
853,324,8,26
855,324,8,26
858,325,9,26
860,325,9,26
863,326,10,26
866,326,9,26
868,326,9,27
871,326,8,27
873,326,8,27
874,327,9,27
876,327,9,27
880,328,9,27
883,328,8,28
887,329,8,28
890,330,8,28
892,330,8,27
895,331,8,27
898,332,8,27
902,332,8,27
905,333,8,27
907,333,8,27
910,333,9,28
912,333,9,28
914,333,9,28
917,334,8,28
919,334,8,28
922,335,8,28
926,336,9,28
929,337,9,28
931,337,9,28
934,338,10,29
936,338,10,29
939,339,10,29
943,340,10,28
946,341,10,28
948,341,11,28
950,342,12,29
952,342,13,29
954,343,13,29
956,343,13,29
958,344,13,29
961,345,13,29
964,345,13,30
967,346,13,30
969,346,13,31
972,347,12,31
974,347,12,32
977,348,12,32
980,349,12,31
983,350,12,31
985,351,12,31
987,351,12,31
989,352,12,31
991,353,12,31
993,353,13,32
995,354,13,32
998,355,13,32
1002,355,13,32
1005,356,13,32
1007,357,13,32
1009,357,13,32
1011,358,13,32
1014,359,13,32
1017,359,13,33
1020,360,13,33
1022,360,13,34
1024,361,14,34
1026,361,14,35
1028,362,14,34
1030,363,14,34
1032,364,14,33
1035,365,14,33
1038,366,13,34
1041,367,13,34
1043,368,13,34
1044,368,14,34
1046,369,14,34
1049,370,14,34
1052,371,15,34
1055,372,15,34
1057,373,15,34
1058,373,15,35
1060,374,15,35
1062,375,15,35
1064,375,15,34
1066,376,15,34
1069,377,15,34
1073,377,14,35
1076,378,14,35
1078,379,14,35
1080,380,14,36
1082,381,14,36
1085,382,14,36
1088,383,14,36
1091,384,14,36
1093,384,14,37
1095,385,15,37
1097,385,15,38
1099,386,15,38
1101,387,14,37
1103,388,14,37
1105,389,14,37
1108,391,15,37
1110,392,15,37
1112,393,15,38
1113,393,16,38
1115,394,16,39
1118,395,15,39
1121,397,15,39
1124,398,14,39
1126,399,15,39
1127,399,15,39
1129,400,16,39
1131,401,16,39
1132,401,15,38
1134,402,15,38
1136,403,15,33
1139,405,15,27
1141,406,15,22
1142,407,15,21
1144,408,16,20
1145,409,16,19
1147,410,16,19
1150,411,17,18
1152,412,17,18
1153,413,16,18
1155,414,16,19
1156,415,15,19
1157,416,16,19
1158,416,16,19
1159,417,17,19
1161,418,17,20
1163,420,17,20
1165,421,17,21
1166,422,17,21
1168,423,16,20
1169,424,16,20
1171,425,16,21
1172,426,17,21
1174,427,17,22
1175,428,17,22
1176,430,18,23
1177,431,18,23
1178,432,18,23
1180,432,18,23
1181,433,18,23
1182,435,18,26
1184,436,19,30
1185,438,19,33
1186,439,19,32
1187,440,19,32
1188,441,19,31
1189,443,19,32
1191,444,20,33
1192,446,20,34
1193,447,20,35
1193,448,21,36
1194,449,21,37
1195,450,21,37
1196,451,20,38
1197,452,20,38
1198,454,20,41
1199,456,21,44
1200,458,21,47
1201,460,21,47
1203,461,20,47
1204,463,20,47
1205,465,20,49
1205,467,21,50
1206,469,21,52
1206,470,21,52
1207,472,22,53
1207,473,22,53
1207,474,22,54
1208,475,23,54
1208,476,23,55
1209,478,22,55
1210,479,22,55
1211,481,21,55
1211,482,21,56
1212,484,22,56
1212,485,22,57
1212,487,23,57
1213,489,23,58
1213,491,24,58
1213,493,24,58
1214,494,23,58
1214,496,23,58
1214,497,24,59
1214,498,24,59
1214,499,25,60
1214,501,24,60
1215,504,24,60
1215,506,23,60
1215,507,24,60
1215,508,24,60
1215,509,25,60
1215,512,25,61
1214,514,24,61
1214,517,24,62
1213,518,25,63
1213,519,25,64
1212,520,26,65
1211,521,26,65
1210,523,26,64
1209,524,26,64
1208,526,27,65
1207,528,27,65
1206,530,28,66
1205,532,27,65
1205,533,27,63
1204,535,26,62
1202,537,26,64
1200,538,26,65
1198,540,26,67
1196,541,27,67
1195,542,27,68
1193,543,28,68
1192,545,27,68
1191,546,26,67
1190,548,25,67
1187,550,26,68
1184,551,26,68
1181,553,27,69
1179,554,27,69
1178,556,27,68
1176,557,27,68
| {
"pile_set_name": "Github"
} |
package name.kropp.intellij.makefile.stub
import com.intellij.psi.stubs.NamedStubBase
import com.intellij.psi.stubs.StubElement
import name.kropp.intellij.makefile.psi.MakefileTarget
class MakefileTargetStubElementImpl(parent: StubElement<*>?, name: String?) : NamedStubBase<MakefileTarget>(parent, MakefileTargetStubElementType, name), MakefileTargetStubElement | {
"pile_set_name": "Github"
} |
/**
* This file was generated by Apache newt version: 1.8.0-dev
*/
#ifndef H_MYNEWT_SYSCFG_
#define H_MYNEWT_SYSCFG_
/**
* This macro exists to ensure code includes this header when needed. If code
* checks the existence of a setting directly via ifdef without including this
* header, the setting macro will silently evaluate to 0. In contrast, an
* attempt to use these macros without including this header will result in a
* compiler error.
*/
#define MYNEWT_VAL(_name) MYNEWT_VAL_ ## _name
#define MYNEWT_VAL_CHOICE(_name, _val) MYNEWT_VAL_ ## _name ## __ ## _val
/*** @apache-mynewt-core/crypto/tinycrypt */
#ifndef MYNEWT_VAL_TINYCRYPT_SYSINIT_STAGE
#define MYNEWT_VAL_TINYCRYPT_SYSINIT_STAGE (200)
#endif
#ifndef MYNEWT_VAL_TINYCRYPT_UECC_RNG_TRNG_DEV_NAME
#define MYNEWT_VAL_TINYCRYPT_UECC_RNG_TRNG_DEV_NAME ("trng")
#endif
#ifndef MYNEWT_VAL_TINYCRYPT_UECC_RNG_USE_TRNG
#define MYNEWT_VAL_TINYCRYPT_UECC_RNG_USE_TRNG (0)
#endif
/*** @apache-mynewt-core/hw/hal */
#ifndef MYNEWT_VAL_HAL_ENABLE_SOFTWARE_BREAKPOINTS
#define MYNEWT_VAL_HAL_ENABLE_SOFTWARE_BREAKPOINTS (1)
#endif
#ifndef MYNEWT_VAL_HAL_FLASH_VERIFY_BUF_SZ
#define MYNEWT_VAL_HAL_FLASH_VERIFY_BUF_SZ (16)
#endif
#ifndef MYNEWT_VAL_HAL_FLASH_VERIFY_ERASES
#define MYNEWT_VAL_HAL_FLASH_VERIFY_ERASES (0)
#endif
#ifndef MYNEWT_VAL_HAL_FLASH_VERIFY_WRITES
#define MYNEWT_VAL_HAL_FLASH_VERIFY_WRITES (0)
#endif
#ifndef MYNEWT_VAL_HAL_SYSTEM_RESET_CB
#define MYNEWT_VAL_HAL_SYSTEM_RESET_CB (0)
#endif
/*** @apache-mynewt-core/kernel/os */
#ifndef MYNEWT_VAL_FLOAT_USER
#define MYNEWT_VAL_FLOAT_USER (0)
#endif
#ifndef MYNEWT_VAL_MSYS_1_BLOCK_COUNT
#define MYNEWT_VAL_MSYS_1_BLOCK_COUNT (12)
#endif
#ifndef MYNEWT_VAL_MSYS_1_BLOCK_SIZE
#define MYNEWT_VAL_MSYS_1_BLOCK_SIZE (292)
#endif
#ifndef MYNEWT_VAL_MSYS_1_SANITY_MIN_COUNT
#define MYNEWT_VAL_MSYS_1_SANITY_MIN_COUNT (0)
#endif
#ifndef MYNEWT_VAL_MSYS_2_BLOCK_COUNT
#define MYNEWT_VAL_MSYS_2_BLOCK_COUNT (0)
#endif
#ifndef MYNEWT_VAL_MSYS_2_BLOCK_SIZE
#define MYNEWT_VAL_MSYS_2_BLOCK_SIZE (0)
#endif
#ifndef MYNEWT_VAL_MSYS_2_SANITY_MIN_COUNT
#define MYNEWT_VAL_MSYS_2_SANITY_MIN_COUNT (0)
#endif
#ifndef MYNEWT_VAL_MSYS_SANITY_TIMEOUT
#define MYNEWT_VAL_MSYS_SANITY_TIMEOUT (60000)
#endif
#ifndef MYNEWT_VAL_OS_ASSERT_CB
#define MYNEWT_VAL_OS_ASSERT_CB (0)
#endif
#ifndef MYNEWT_VAL_OS_CLI
#define MYNEWT_VAL_OS_CLI (0)
#endif
#ifndef MYNEWT_VAL_OS_COREDUMP
#define MYNEWT_VAL_OS_COREDUMP (0)
#endif
#ifndef MYNEWT_VAL_OS_CPUTIME_FREQ
#define MYNEWT_VAL_OS_CPUTIME_FREQ (1000000)
#endif
#ifndef MYNEWT_VAL_OS_CPUTIME_TIMER_NUM
#define MYNEWT_VAL_OS_CPUTIME_TIMER_NUM (0)
#endif
#ifndef MYNEWT_VAL_OS_CRASH_FILE_LINE
#define MYNEWT_VAL_OS_CRASH_FILE_LINE (0)
#endif
#ifndef MYNEWT_VAL_OS_CRASH_LOG
#define MYNEWT_VAL_OS_CRASH_LOG (0)
#endif
#ifndef MYNEWT_VAL_OS_CRASH_RESTORE_REGS
#define MYNEWT_VAL_OS_CRASH_RESTORE_REGS (0)
#endif
#ifndef MYNEWT_VAL_OS_CRASH_STACKTRACE
#define MYNEWT_VAL_OS_CRASH_STACKTRACE (0)
#endif
#ifndef MYNEWT_VAL_OS_CTX_SW_STACK_CHECK
#define MYNEWT_VAL_OS_CTX_SW_STACK_CHECK (0)
#endif
#ifndef MYNEWT_VAL_OS_CTX_SW_STACK_GUARD
#define MYNEWT_VAL_OS_CTX_SW_STACK_GUARD (4)
#endif
#ifndef MYNEWT_VAL_OS_DEBUG_MODE
#define MYNEWT_VAL_OS_DEBUG_MODE (0)
#endif
#ifndef MYNEWT_VAL_OS_EVENTQ_DEBUG
#define MYNEWT_VAL_OS_EVENTQ_DEBUG (0)
#endif
#ifndef MYNEWT_VAL_OS_EVENTQ_MONITOR
#define MYNEWT_VAL_OS_EVENTQ_MONITOR (0)
#endif
#ifndef MYNEWT_VAL_OS_IDLE_TICKLESS_MS_MAX
#define MYNEWT_VAL_OS_IDLE_TICKLESS_MS_MAX (600000)
#endif
#ifndef MYNEWT_VAL_OS_IDLE_TICKLESS_MS_MIN
#define MYNEWT_VAL_OS_IDLE_TICKLESS_MS_MIN (100)
#endif
#ifndef MYNEWT_VAL_OS_MAIN_STACK_SIZE
#define MYNEWT_VAL_OS_MAIN_STACK_SIZE (1024)
#endif
#ifndef MYNEWT_VAL_OS_MAIN_TASK_PRIO
#define MYNEWT_VAL_OS_MAIN_TASK_PRIO (127)
#endif
#ifndef MYNEWT_VAL_OS_MAIN_TASK_SANITY_ITVL_MS
#define MYNEWT_VAL_OS_MAIN_TASK_SANITY_ITVL_MS (0)
#endif
#ifndef MYNEWT_VAL_OS_MEMPOOL_CHECK
#define MYNEWT_VAL_OS_MEMPOOL_CHECK (0)
#endif
#ifndef MYNEWT_VAL_OS_MEMPOOL_GUARD
#define MYNEWT_VAL_OS_MEMPOOL_GUARD (0)
#endif
#ifndef MYNEWT_VAL_OS_MEMPOOL_POISON
#define MYNEWT_VAL_OS_MEMPOOL_POISON (0)
#endif
#ifndef MYNEWT_VAL_OS_SCHEDULING
#define MYNEWT_VAL_OS_SCHEDULING (1)
#endif
#ifndef MYNEWT_VAL_OS_SYSINIT_STAGE
#define MYNEWT_VAL_OS_SYSINIT_STAGE (0)
#endif
#ifndef MYNEWT_VAL_OS_SYSVIEW
#define MYNEWT_VAL_OS_SYSVIEW (0)
#endif
#ifndef MYNEWT_VAL_OS_SYSVIEW_TRACE_CALLOUT
#define MYNEWT_VAL_OS_SYSVIEW_TRACE_CALLOUT (1)
#endif
#ifndef MYNEWT_VAL_OS_SYSVIEW_TRACE_EVENTQ
#define MYNEWT_VAL_OS_SYSVIEW_TRACE_EVENTQ (1)
#endif
#ifndef MYNEWT_VAL_OS_SYSVIEW_TRACE_MBUF
#define MYNEWT_VAL_OS_SYSVIEW_TRACE_MBUF (0)
#endif
#ifndef MYNEWT_VAL_OS_SYSVIEW_TRACE_MEMPOOL
#define MYNEWT_VAL_OS_SYSVIEW_TRACE_MEMPOOL (0)
#endif
#ifndef MYNEWT_VAL_OS_SYSVIEW_TRACE_MUTEX
#define MYNEWT_VAL_OS_SYSVIEW_TRACE_MUTEX (1)
#endif
#ifndef MYNEWT_VAL_OS_SYSVIEW_TRACE_SEM
#define MYNEWT_VAL_OS_SYSVIEW_TRACE_SEM (1)
#endif
#ifndef MYNEWT_VAL_OS_TASK_RUN_TIME_CPUTIME
#define MYNEWT_VAL_OS_TASK_RUN_TIME_CPUTIME (0)
#endif
#ifndef MYNEWT_VAL_OS_TIME_DEBUG
#define MYNEWT_VAL_OS_TIME_DEBUG (0)
#endif
#ifndef MYNEWT_VAL_OS_WATCHDOG_MONITOR
#define MYNEWT_VAL_OS_WATCHDOG_MONITOR (0)
#endif
#ifndef MYNEWT_VAL_SANITY_INTERVAL
#define MYNEWT_VAL_SANITY_INTERVAL (15000)
#endif
#ifndef MYNEWT_VAL_WATCHDOG_INTERVAL
#define MYNEWT_VAL_WATCHDOG_INTERVAL (30000)
#endif
/*** @apache-mynewt-core/sys/console/stub */
#ifndef MYNEWT_VAL_CONSOLE_UART_BAUD
#define MYNEWT_VAL_CONSOLE_UART_BAUD (115200)
#endif
#ifndef MYNEWT_VAL_CONSOLE_UART_DEV
#define MYNEWT_VAL_CONSOLE_UART_DEV ("uart0")
#endif
#ifndef MYNEWT_VAL_CONSOLE_UART_FLOW_CONTROL
#define MYNEWT_VAL_CONSOLE_UART_FLOW_CONTROL (UART_FLOW_CTL_NONE)
#endif
/*** @apache-mynewt-core/sys/flash_map */
#ifndef MYNEWT_VAL_FLASH_MAP_MAX_AREAS
#define MYNEWT_VAL_FLASH_MAP_MAX_AREAS (10)
#endif
#ifndef MYNEWT_VAL_FLASH_MAP_SYSINIT_STAGE
#define MYNEWT_VAL_FLASH_MAP_SYSINIT_STAGE (2)
#endif
/*** @apache-mynewt-core/sys/log/common */
#ifndef MYNEWT_VAL_DFLT_LOG_LVL
#define MYNEWT_VAL_DFLT_LOG_LVL (1)
#endif
#ifndef MYNEWT_VAL_DFLT_LOG_MOD
#define MYNEWT_VAL_DFLT_LOG_MOD (0)
#endif
#ifndef MYNEWT_VAL_LOG_GLOBAL_IDX
#define MYNEWT_VAL_LOG_GLOBAL_IDX (1)
#endif
/*** @apache-mynewt-core/sys/log/modlog */
#ifndef MYNEWT_VAL_MODLOG_CONSOLE_DFLT
#define MYNEWT_VAL_MODLOG_CONSOLE_DFLT (1)
#endif
#ifndef MYNEWT_VAL_MODLOG_LOG_MACROS
#define MYNEWT_VAL_MODLOG_LOG_MACROS (0)
#endif
#ifndef MYNEWT_VAL_MODLOG_MAX_MAPPINGS
#define MYNEWT_VAL_MODLOG_MAX_MAPPINGS (16)
#endif
#ifndef MYNEWT_VAL_MODLOG_MAX_PRINTF_LEN
#define MYNEWT_VAL_MODLOG_MAX_PRINTF_LEN (128)
#endif
#ifndef MYNEWT_VAL_MODLOG_SYSINIT_STAGE
#define MYNEWT_VAL_MODLOG_SYSINIT_STAGE (100)
#endif
/*** @apache-mynewt-core/sys/log/stub */
#ifndef MYNEWT_VAL_LOG_CONSOLE
#define MYNEWT_VAL_LOG_CONSOLE (1)
#endif
#ifndef MYNEWT_VAL_LOG_FCB
#define MYNEWT_VAL_LOG_FCB (0)
#endif
#ifndef MYNEWT_VAL_LOG_FCB_SLOT1
#define MYNEWT_VAL_LOG_FCB_SLOT1 (0)
#endif
/* Overridden by @apache-mynewt-nimble/targets/linux (defined by @apache-mynewt-core/sys/log/stub) */
#ifndef MYNEWT_VAL_LOG_LEVEL
#define MYNEWT_VAL_LOG_LEVEL (0)
#endif
/*** @apache-mynewt-core/sys/mfg */
#ifndef MYNEWT_VAL_MFG_LOG_LVL
#define MYNEWT_VAL_MFG_LOG_LVL (15)
#endif
#ifndef MYNEWT_VAL_MFG_LOG_MODULE
#define MYNEWT_VAL_MFG_LOG_MODULE (128)
#endif
#ifndef MYNEWT_VAL_MFG_MAX_MMRS
#define MYNEWT_VAL_MFG_MAX_MMRS (2)
#endif
#ifndef MYNEWT_VAL_MFG_SYSINIT_STAGE
#define MYNEWT_VAL_MFG_SYSINIT_STAGE (100)
#endif
/*** @apache-mynewt-core/sys/sys */
#ifndef MYNEWT_VAL_DEBUG_PANIC_ENABLED
#define MYNEWT_VAL_DEBUG_PANIC_ENABLED (1)
#endif
/*** @apache-mynewt-core/sys/sysdown */
#ifndef MYNEWT_VAL_SYSDOWN_CONSTRAIN_DOWN
#define MYNEWT_VAL_SYSDOWN_CONSTRAIN_DOWN (1)
#endif
#ifndef MYNEWT_VAL_SYSDOWN_PANIC_FILE_LINE
#define MYNEWT_VAL_SYSDOWN_PANIC_FILE_LINE (0)
#endif
#ifndef MYNEWT_VAL_SYSDOWN_PANIC_MESSAGE
#define MYNEWT_VAL_SYSDOWN_PANIC_MESSAGE (0)
#endif
#ifndef MYNEWT_VAL_SYSDOWN_TIMEOUT_MS
#define MYNEWT_VAL_SYSDOWN_TIMEOUT_MS (10000)
#endif
/*** @apache-mynewt-core/sys/sysinit */
#ifndef MYNEWT_VAL_SYSINIT_CONSTRAIN_INIT
#define MYNEWT_VAL_SYSINIT_CONSTRAIN_INIT (1)
#endif
#ifndef MYNEWT_VAL_SYSINIT_PANIC_FILE_LINE
#define MYNEWT_VAL_SYSINIT_PANIC_FILE_LINE (0)
#endif
#ifndef MYNEWT_VAL_SYSINIT_PANIC_MESSAGE
#define MYNEWT_VAL_SYSINIT_PANIC_MESSAGE (0)
#endif
/*** @apache-mynewt-core/util/rwlock */
#ifndef MYNEWT_VAL_RWLOCK_DEBUG
#define MYNEWT_VAL_RWLOCK_DEBUG (0)
#endif
/*** @apache-mynewt-nimble/nimble */
#ifndef MYNEWT_VAL_BLE_EXT_ADV
#define MYNEWT_VAL_BLE_EXT_ADV (0)
#endif
#ifndef MYNEWT_VAL_BLE_EXT_ADV_MAX_SIZE
#define MYNEWT_VAL_BLE_EXT_ADV_MAX_SIZE (31)
#endif
#ifndef MYNEWT_VAL_BLE_MAX_CONNECTIONS
#define MYNEWT_VAL_BLE_MAX_CONNECTIONS (1)
#endif
#ifndef MYNEWT_VAL_BLE_MAX_PERIODIC_SYNCS
#define MYNEWT_VAL_BLE_MAX_PERIODIC_SYNCS (1)
#endif
#ifndef MYNEWT_VAL_BLE_MULTI_ADV_INSTANCES
#define MYNEWT_VAL_BLE_MULTI_ADV_INSTANCES (0)
#endif
#ifndef MYNEWT_VAL_BLE_PERIODIC_ADV
#define MYNEWT_VAL_BLE_PERIODIC_ADV (0)
#endif
#ifndef MYNEWT_VAL_BLE_PERIODIC_ADV_SYNC_TRANSFER
#define MYNEWT_VAL_BLE_PERIODIC_ADV_SYNC_TRANSFER (0)
#endif
#ifndef MYNEWT_VAL_BLE_ROLE_BROADCASTER
#define MYNEWT_VAL_BLE_ROLE_BROADCASTER (1)
#endif
#ifndef MYNEWT_VAL_BLE_ROLE_CENTRAL
#define MYNEWT_VAL_BLE_ROLE_CENTRAL (1)
#endif
#ifndef MYNEWT_VAL_BLE_ROLE_OBSERVER
#define MYNEWT_VAL_BLE_ROLE_OBSERVER (1)
#endif
#ifndef MYNEWT_VAL_BLE_ROLE_PERIPHERAL
#define MYNEWT_VAL_BLE_ROLE_PERIPHERAL (1)
#endif
#ifndef MYNEWT_VAL_BLE_VERSION
#define MYNEWT_VAL_BLE_VERSION (50)
#endif
#ifndef MYNEWT_VAL_BLE_WHITELIST
#define MYNEWT_VAL_BLE_WHITELIST (1)
#endif
/*** @apache-mynewt-nimble/nimble/host */
#ifndef MYNEWT_VAL_BLE_ATT_PREFERRED_MTU
#define MYNEWT_VAL_BLE_ATT_PREFERRED_MTU (256)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_FIND_INFO
#define MYNEWT_VAL_BLE_ATT_SVR_FIND_INFO (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_FIND_TYPE
#define MYNEWT_VAL_BLE_ATT_SVR_FIND_TYPE (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_INDICATE
#define MYNEWT_VAL_BLE_ATT_SVR_INDICATE (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_MAX_PREP_ENTRIES
#define MYNEWT_VAL_BLE_ATT_SVR_MAX_PREP_ENTRIES (64)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_NOTIFY
#define MYNEWT_VAL_BLE_ATT_SVR_NOTIFY (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_QUEUED_WRITE
#define MYNEWT_VAL_BLE_ATT_SVR_QUEUED_WRITE (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_QUEUED_WRITE_TMO
#define MYNEWT_VAL_BLE_ATT_SVR_QUEUED_WRITE_TMO (30000)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_READ
#define MYNEWT_VAL_BLE_ATT_SVR_READ (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_READ_BLOB
#define MYNEWT_VAL_BLE_ATT_SVR_READ_BLOB (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_READ_GROUP_TYPE
#define MYNEWT_VAL_BLE_ATT_SVR_READ_GROUP_TYPE (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_READ_MULT
#define MYNEWT_VAL_BLE_ATT_SVR_READ_MULT (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_READ_TYPE
#define MYNEWT_VAL_BLE_ATT_SVR_READ_TYPE (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_SIGNED_WRITE
#define MYNEWT_VAL_BLE_ATT_SVR_SIGNED_WRITE (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_WRITE
#define MYNEWT_VAL_BLE_ATT_SVR_WRITE (1)
#endif
#ifndef MYNEWT_VAL_BLE_ATT_SVR_WRITE_NO_RSP
#define MYNEWT_VAL_BLE_ATT_SVR_WRITE_NO_RSP (1)
#endif
#ifndef MYNEWT_VAL_BLE_GAP_MAX_PENDING_CONN_PARAM_UPDATE
#define MYNEWT_VAL_BLE_GAP_MAX_PENDING_CONN_PARAM_UPDATE (1)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_DISC_ALL_CHRS
#define MYNEWT_VAL_BLE_GATT_DISC_ALL_CHRS (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_DISC_ALL_DSCS
#define MYNEWT_VAL_BLE_GATT_DISC_ALL_DSCS (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_DISC_ALL_SVCS
#define MYNEWT_VAL_BLE_GATT_DISC_ALL_SVCS (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_DISC_CHR_UUID
#define MYNEWT_VAL_BLE_GATT_DISC_CHR_UUID (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_DISC_SVC_UUID
#define MYNEWT_VAL_BLE_GATT_DISC_SVC_UUID (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_FIND_INC_SVCS
#define MYNEWT_VAL_BLE_GATT_FIND_INC_SVCS (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_INDICATE
#define MYNEWT_VAL_BLE_GATT_INDICATE (1)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_MAX_PROCS
#define MYNEWT_VAL_BLE_GATT_MAX_PROCS (4)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_NOTIFY
#define MYNEWT_VAL_BLE_GATT_NOTIFY (1)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_READ
#define MYNEWT_VAL_BLE_GATT_READ (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_READ_LONG
#define MYNEWT_VAL_BLE_GATT_READ_LONG (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_READ_MAX_ATTRS
#define MYNEWT_VAL_BLE_GATT_READ_MAX_ATTRS (8)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_READ_MULT
#define MYNEWT_VAL_BLE_GATT_READ_MULT (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_READ_UUID
#define MYNEWT_VAL_BLE_GATT_READ_UUID (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_RESUME_RATE
#define MYNEWT_VAL_BLE_GATT_RESUME_RATE (1000)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_SIGNED_WRITE
#define MYNEWT_VAL_BLE_GATT_SIGNED_WRITE (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_WRITE
#define MYNEWT_VAL_BLE_GATT_WRITE (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_WRITE_LONG
#define MYNEWT_VAL_BLE_GATT_WRITE_LONG (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_WRITE_MAX_ATTRS
#define MYNEWT_VAL_BLE_GATT_WRITE_MAX_ATTRS (4)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_WRITE_NO_RSP
#define MYNEWT_VAL_BLE_GATT_WRITE_NO_RSP (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_GATT_WRITE_RELIABLE
#define MYNEWT_VAL_BLE_GATT_WRITE_RELIABLE (MYNEWT_VAL_BLE_ROLE_CENTRAL)
#endif
#ifndef MYNEWT_VAL_BLE_HOST
#define MYNEWT_VAL_BLE_HOST (1)
#endif
#ifndef MYNEWT_VAL_BLE_HS_AUTO_START
#define MYNEWT_VAL_BLE_HS_AUTO_START (1)
#endif
#ifndef MYNEWT_VAL_BLE_HS_DEBUG
#define MYNEWT_VAL_BLE_HS_DEBUG (0)
#endif
#ifndef MYNEWT_VAL_BLE_HS_FLOW_CTRL
#define MYNEWT_VAL_BLE_HS_FLOW_CTRL (0)
#endif
#ifndef MYNEWT_VAL_BLE_HS_FLOW_CTRL_ITVL
#define MYNEWT_VAL_BLE_HS_FLOW_CTRL_ITVL (1000)
#endif
#ifndef MYNEWT_VAL_BLE_HS_FLOW_CTRL_THRESH
#define MYNEWT_VAL_BLE_HS_FLOW_CTRL_THRESH (2)
#endif
#ifndef MYNEWT_VAL_BLE_HS_FLOW_CTRL_TX_ON_DISCONNECT
#define MYNEWT_VAL_BLE_HS_FLOW_CTRL_TX_ON_DISCONNECT (0)
#endif
#ifndef MYNEWT_VAL_BLE_HS_LOG_LVL
#define MYNEWT_VAL_BLE_HS_LOG_LVL (1)
#endif
#ifndef MYNEWT_VAL_BLE_HS_LOG_MOD
#define MYNEWT_VAL_BLE_HS_LOG_MOD (4)
#endif
#ifndef MYNEWT_VAL_BLE_HS_PHONY_HCI_ACKS
#define MYNEWT_VAL_BLE_HS_PHONY_HCI_ACKS (0)
#endif
#ifndef MYNEWT_VAL_BLE_HS_REQUIRE_OS
#define MYNEWT_VAL_BLE_HS_REQUIRE_OS (1)
#endif
#ifndef MYNEWT_VAL_BLE_HS_STOP_ON_SHUTDOWN
#define MYNEWT_VAL_BLE_HS_STOP_ON_SHUTDOWN (1)
#endif
#ifndef MYNEWT_VAL_BLE_HS_STOP_ON_SHUTDOWN_TIMEOUT
#define MYNEWT_VAL_BLE_HS_STOP_ON_SHUTDOWN_TIMEOUT (2000)
#endif
#ifndef MYNEWT_VAL_BLE_HS_SYSINIT_STAGE
#define MYNEWT_VAL_BLE_HS_SYSINIT_STAGE (200)
#endif
#ifndef MYNEWT_VAL_BLE_L2CAP_COC_MAX_NUM
#define MYNEWT_VAL_BLE_L2CAP_COC_MAX_NUM (0)
#endif
#ifndef MYNEWT_VAL_BLE_L2CAP_COC_MPS
#define MYNEWT_VAL_BLE_L2CAP_COC_MPS (MYNEWT_VAL_MSYS_1_BLOCK_SIZE-8)
#endif
#ifndef MYNEWT_VAL_BLE_L2CAP_ENHANCED_COC
#define MYNEWT_VAL_BLE_L2CAP_ENHANCED_COC (0)
#endif
#ifndef MYNEWT_VAL_BLE_L2CAP_JOIN_RX_FRAGS
#define MYNEWT_VAL_BLE_L2CAP_JOIN_RX_FRAGS (1)
#endif
#ifndef MYNEWT_VAL_BLE_L2CAP_MAX_CHANS
#define MYNEWT_VAL_BLE_L2CAP_MAX_CHANS (3*MYNEWT_VAL_BLE_MAX_CONNECTIONS)
#endif
#ifndef MYNEWT_VAL_BLE_L2CAP_RX_FRAG_TIMEOUT
#define MYNEWT_VAL_BLE_L2CAP_RX_FRAG_TIMEOUT (30000)
#endif
#ifndef MYNEWT_VAL_BLE_L2CAP_SIG_MAX_PROCS
#define MYNEWT_VAL_BLE_L2CAP_SIG_MAX_PROCS (1)
#endif
#ifndef MYNEWT_VAL_BLE_MESH
#define MYNEWT_VAL_BLE_MESH (0)
#endif
#ifndef MYNEWT_VAL_BLE_MONITOR_CONSOLE_BUFFER_SIZE
#define MYNEWT_VAL_BLE_MONITOR_CONSOLE_BUFFER_SIZE (128)
#endif
#ifndef MYNEWT_VAL_BLE_MONITOR_RTT
#define MYNEWT_VAL_BLE_MONITOR_RTT (0)
#endif
#ifndef MYNEWT_VAL_BLE_MONITOR_RTT_BUFFERED
#define MYNEWT_VAL_BLE_MONITOR_RTT_BUFFERED (1)
#endif
#ifndef MYNEWT_VAL_BLE_MONITOR_RTT_BUFFER_NAME
#define MYNEWT_VAL_BLE_MONITOR_RTT_BUFFER_NAME ("btmonitor")
#endif
#ifndef MYNEWT_VAL_BLE_MONITOR_RTT_BUFFER_SIZE
#define MYNEWT_VAL_BLE_MONITOR_RTT_BUFFER_SIZE (256)
#endif
#ifndef MYNEWT_VAL_BLE_MONITOR_UART
#define MYNEWT_VAL_BLE_MONITOR_UART (0)
#endif
#ifndef MYNEWT_VAL_BLE_MONITOR_UART_BAUDRATE
#define MYNEWT_VAL_BLE_MONITOR_UART_BAUDRATE (1000000)
#endif
#ifndef MYNEWT_VAL_BLE_MONITOR_UART_BUFFER_SIZE
#define MYNEWT_VAL_BLE_MONITOR_UART_BUFFER_SIZE (64)
#endif
#ifndef MYNEWT_VAL_BLE_MONITOR_UART_DEV
#define MYNEWT_VAL_BLE_MONITOR_UART_DEV ("uart0")
#endif
#ifndef MYNEWT_VAL_BLE_RPA_TIMEOUT
#define MYNEWT_VAL_BLE_RPA_TIMEOUT (300)
#endif
#ifndef MYNEWT_VAL_BLE_SM_BONDING
#define MYNEWT_VAL_BLE_SM_BONDING (0)
#endif
#ifndef MYNEWT_VAL_BLE_SM_IO_CAP
#define MYNEWT_VAL_BLE_SM_IO_CAP (BLE_HS_IO_NO_INPUT_OUTPUT)
#endif
#ifndef MYNEWT_VAL_BLE_SM_KEYPRESS
#define MYNEWT_VAL_BLE_SM_KEYPRESS (0)
#endif
#ifndef MYNEWT_VAL_BLE_SM_LEGACY
#define MYNEWT_VAL_BLE_SM_LEGACY (1)
#endif
#ifndef MYNEWT_VAL_BLE_SM_MAX_PROCS
#define MYNEWT_VAL_BLE_SM_MAX_PROCS (1)
#endif
#ifndef MYNEWT_VAL_BLE_SM_MITM
#define MYNEWT_VAL_BLE_SM_MITM (0)
#endif
#ifndef MYNEWT_VAL_BLE_SM_OOB_DATA_FLAG
#define MYNEWT_VAL_BLE_SM_OOB_DATA_FLAG (0)
#endif
#ifndef MYNEWT_VAL_BLE_SM_OUR_KEY_DIST
#define MYNEWT_VAL_BLE_SM_OUR_KEY_DIST (0)
#endif
#ifndef MYNEWT_VAL_BLE_SM_SC
#define MYNEWT_VAL_BLE_SM_SC (0)
#endif
#ifndef MYNEWT_VAL_BLE_SM_SC_DEBUG_KEYS
#define MYNEWT_VAL_BLE_SM_SC_DEBUG_KEYS (0)
#endif
#ifndef MYNEWT_VAL_BLE_SM_THEIR_KEY_DIST
#define MYNEWT_VAL_BLE_SM_THEIR_KEY_DIST (0)
#endif
#ifndef MYNEWT_VAL_BLE_STORE_MAX_BONDS
#define MYNEWT_VAL_BLE_STORE_MAX_BONDS (3)
#endif
#ifndef MYNEWT_VAL_BLE_STORE_MAX_CCCDS
#define MYNEWT_VAL_BLE_STORE_MAX_CCCDS (8)
#endif
/*** @apache-mynewt-nimble/nimble/host/services/ans */
#ifndef MYNEWT_VAL_BLE_SVC_ANS_NEW_ALERT_CAT
#define MYNEWT_VAL_BLE_SVC_ANS_NEW_ALERT_CAT (0)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_ANS_SYSINIT_STAGE
#define MYNEWT_VAL_BLE_SVC_ANS_SYSINIT_STAGE (303)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_ANS_UNR_ALERT_CAT
#define MYNEWT_VAL_BLE_SVC_ANS_UNR_ALERT_CAT (0)
#endif
/*** @apache-mynewt-nimble/nimble/host/services/bas */
#ifndef MYNEWT_VAL_BLE_SVC_BAS_BATTERY_LEVEL_NOTIFY_ENABLE
#define MYNEWT_VAL_BLE_SVC_BAS_BATTERY_LEVEL_NOTIFY_ENABLE (1)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_BAS_BATTERY_LEVEL_READ_PERM
#define MYNEWT_VAL_BLE_SVC_BAS_BATTERY_LEVEL_READ_PERM (0)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_BAS_SYSINIT_STAGE
#define MYNEWT_VAL_BLE_SVC_BAS_SYSINIT_STAGE (303)
#endif
/*** @apache-mynewt-nimble/nimble/host/services/dis */
#ifndef MYNEWT_VAL_BLE_SVC_DIS_DEFAULT_READ_PERM
#define MYNEWT_VAL_BLE_SVC_DIS_DEFAULT_READ_PERM (-1)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_DIS_FIRMWARE_REVISION_DEFAULT
#define MYNEWT_VAL_BLE_SVC_DIS_FIRMWARE_REVISION_DEFAULT (NULL)
#endif
/* Value copied from BLE_SVC_DIS_DEFAULT_READ_PERM */
#ifndef MYNEWT_VAL_BLE_SVC_DIS_FIRMWARE_REVISION_READ_PERM
#define MYNEWT_VAL_BLE_SVC_DIS_FIRMWARE_REVISION_READ_PERM (-1)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_DIS_HARDWARE_REVISION_DEFAULT
#define MYNEWT_VAL_BLE_SVC_DIS_HARDWARE_REVISION_DEFAULT (NULL)
#endif
/* Value copied from BLE_SVC_DIS_DEFAULT_READ_PERM */
#ifndef MYNEWT_VAL_BLE_SVC_DIS_HARDWARE_REVISION_READ_PERM
#define MYNEWT_VAL_BLE_SVC_DIS_HARDWARE_REVISION_READ_PERM (-1)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_DIS_MANUFACTURER_NAME_DEFAULT
#define MYNEWT_VAL_BLE_SVC_DIS_MANUFACTURER_NAME_DEFAULT (NULL)
#endif
/* Value copied from BLE_SVC_DIS_DEFAULT_READ_PERM */
#ifndef MYNEWT_VAL_BLE_SVC_DIS_MANUFACTURER_NAME_READ_PERM
#define MYNEWT_VAL_BLE_SVC_DIS_MANUFACTURER_NAME_READ_PERM (-1)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_DIS_MODEL_NUMBER_DEFAULT
#define MYNEWT_VAL_BLE_SVC_DIS_MODEL_NUMBER_DEFAULT ("Apache Mynewt NimBLE")
#endif
#ifndef MYNEWT_VAL_BLE_SVC_DIS_MODEL_NUMBER_READ_PERM
#define MYNEWT_VAL_BLE_SVC_DIS_MODEL_NUMBER_READ_PERM (0)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_DIS_SERIAL_NUMBER_DEFAULT
#define MYNEWT_VAL_BLE_SVC_DIS_SERIAL_NUMBER_DEFAULT (NULL)
#endif
/* Value copied from BLE_SVC_DIS_DEFAULT_READ_PERM */
#ifndef MYNEWT_VAL_BLE_SVC_DIS_SERIAL_NUMBER_READ_PERM
#define MYNEWT_VAL_BLE_SVC_DIS_SERIAL_NUMBER_READ_PERM (-1)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_DIS_SOFTWARE_REVISION_DEFAULT
#define MYNEWT_VAL_BLE_SVC_DIS_SOFTWARE_REVISION_DEFAULT (NULL)
#endif
/* Value copied from BLE_SVC_DIS_DEFAULT_READ_PERM */
#ifndef MYNEWT_VAL_BLE_SVC_DIS_SOFTWARE_REVISION_READ_PERM
#define MYNEWT_VAL_BLE_SVC_DIS_SOFTWARE_REVISION_READ_PERM (-1)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_DIS_SYSINIT_STAGE
#define MYNEWT_VAL_BLE_SVC_DIS_SYSINIT_STAGE (303)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_DIS_SYSTEM_ID_DEFAULT
#define MYNEWT_VAL_BLE_SVC_DIS_SYSTEM_ID_DEFAULT (NULL)
#endif
/* Value copied from BLE_SVC_DIS_DEFAULT_READ_PERM */
#ifndef MYNEWT_VAL_BLE_SVC_DIS_SYSTEM_ID_READ_PERM
#define MYNEWT_VAL_BLE_SVC_DIS_SYSTEM_ID_READ_PERM (-1)
#endif
/*** @apache-mynewt-nimble/nimble/host/services/gap */
#ifndef MYNEWT_VAL_BLE_SVC_GAP_APPEARANCE
#define MYNEWT_VAL_BLE_SVC_GAP_APPEARANCE (0)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_GAP_APPEARANCE_WRITE_PERM
#define MYNEWT_VAL_BLE_SVC_GAP_APPEARANCE_WRITE_PERM (-1)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_GAP_CENTRAL_ADDRESS_RESOLUTION
#define MYNEWT_VAL_BLE_SVC_GAP_CENTRAL_ADDRESS_RESOLUTION (-1)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_GAP_DEVICE_NAME
#define MYNEWT_VAL_BLE_SVC_GAP_DEVICE_NAME ("nimble")
#endif
#ifndef MYNEWT_VAL_BLE_SVC_GAP_DEVICE_NAME_MAX_LENGTH
#define MYNEWT_VAL_BLE_SVC_GAP_DEVICE_NAME_MAX_LENGTH (31)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_GAP_DEVICE_NAME_WRITE_PERM
#define MYNEWT_VAL_BLE_SVC_GAP_DEVICE_NAME_WRITE_PERM (-1)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_GAP_PPCP_MAX_CONN_INTERVAL
#define MYNEWT_VAL_BLE_SVC_GAP_PPCP_MAX_CONN_INTERVAL (0)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_GAP_PPCP_MIN_CONN_INTERVAL
#define MYNEWT_VAL_BLE_SVC_GAP_PPCP_MIN_CONN_INTERVAL (0)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_GAP_PPCP_SLAVE_LATENCY
#define MYNEWT_VAL_BLE_SVC_GAP_PPCP_SLAVE_LATENCY (0)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_GAP_PPCP_SUPERVISION_TMO
#define MYNEWT_VAL_BLE_SVC_GAP_PPCP_SUPERVISION_TMO (0)
#endif
#ifndef MYNEWT_VAL_BLE_SVC_GAP_SYSINIT_STAGE
#define MYNEWT_VAL_BLE_SVC_GAP_SYSINIT_STAGE (301)
#endif
/*** @apache-mynewt-nimble/nimble/host/services/gatt */
#ifndef MYNEWT_VAL_BLE_SVC_GATT_SYSINIT_STAGE
#define MYNEWT_VAL_BLE_SVC_GATT_SYSINIT_STAGE (302)
#endif
/*** @apache-mynewt-nimble/nimble/host/services/ias */
#ifndef MYNEWT_VAL_BLE_SVC_IAS_SYSINIT_STAGE
#define MYNEWT_VAL_BLE_SVC_IAS_SYSINIT_STAGE (303)
#endif
/*** @apache-mynewt-nimble/nimble/host/services/ipss */
#ifndef MYNEWT_VAL_BLE_SVC_IPSS_SYSINIT_STAGE
#define MYNEWT_VAL_BLE_SVC_IPSS_SYSINIT_STAGE (303)
#endif
/*** @apache-mynewt-nimble/nimble/host/services/lls */
#ifndef MYNEWT_VAL_BLE_SVC_LLS_SYSINIT_STAGE
#define MYNEWT_VAL_BLE_SVC_LLS_SYSINIT_STAGE (303)
#endif
/*** @apache-mynewt-nimble/nimble/host/services/tps */
#ifndef MYNEWT_VAL_BLE_SVC_TPS_SYSINIT_STAGE
#define MYNEWT_VAL_BLE_SVC_TPS_SYSINIT_STAGE (303)
#endif
/*** @apache-mynewt-nimble/nimble/transport/socket */
#ifndef MYNEWT_VAL_BLE_ACL_BUF_COUNT
#define MYNEWT_VAL_BLE_ACL_BUF_COUNT (24)
#endif
#ifndef MYNEWT_VAL_BLE_ACL_BUF_SIZE
#define MYNEWT_VAL_BLE_ACL_BUF_SIZE (255)
#endif
#ifndef MYNEWT_VAL_BLE_HCI_ACL_OUT_COUNT
#define MYNEWT_VAL_BLE_HCI_ACL_OUT_COUNT (12)
#endif
#ifndef MYNEWT_VAL_BLE_HCI_EVT_BUF_SIZE
#define MYNEWT_VAL_BLE_HCI_EVT_BUF_SIZE (70)
#endif
#ifndef MYNEWT_VAL_BLE_HCI_EVT_HI_BUF_COUNT
#define MYNEWT_VAL_BLE_HCI_EVT_HI_BUF_COUNT (8)
#endif
#ifndef MYNEWT_VAL_BLE_HCI_EVT_LO_BUF_COUNT
#define MYNEWT_VAL_BLE_HCI_EVT_LO_BUF_COUNT (8)
#endif
#ifndef MYNEWT_VAL_BLE_SOCK_CLI_SYSINIT_STAGE
#define MYNEWT_VAL_BLE_SOCK_CLI_SYSINIT_STAGE (500)
#endif
#ifndef MYNEWT_VAL_BLE_SOCK_LINUX_DEV
#define MYNEWT_VAL_BLE_SOCK_LINUX_DEV (0)
#endif
/* Overridden by @apache-mynewt-nimble/targets/linux (defined by @apache-mynewt-nimble/nimble/transport/socket) */
#ifndef MYNEWT_VAL_BLE_SOCK_STACK_SIZE
#define MYNEWT_VAL_BLE_SOCK_STACK_SIZE (1028)
#endif
/* Overridden by @apache-mynewt-nimble/targets/linux (defined by @apache-mynewt-nimble/nimble/transport/socket) */
#ifndef MYNEWT_VAL_BLE_SOCK_TASK_PRIO
#define MYNEWT_VAL_BLE_SOCK_TASK_PRIO (3)
#endif
#ifndef MYNEWT_VAL_BLE_SOCK_TCP_PORT
#define MYNEWT_VAL_BLE_SOCK_TCP_PORT (14433)
#endif
/* Overridden by @apache-mynewt-nimble/targets/linux (defined by @apache-mynewt-nimble/nimble/transport/socket) */
#ifndef MYNEWT_VAL_BLE_SOCK_USE_LINUX_BLUE
#define MYNEWT_VAL_BLE_SOCK_USE_LINUX_BLUE (1)
#endif
/* Overridden by @apache-mynewt-nimble/targets/linux (defined by @apache-mynewt-nimble/nimble/transport/socket) */
#ifndef MYNEWT_VAL_BLE_SOCK_USE_TCP
#define MYNEWT_VAL_BLE_SOCK_USE_TCP (0)
#endif
/*** newt */
#ifndef MYNEWT_VAL_APP_NAME
#define MYNEWT_VAL_APP_NAME ("dummy_app")
#endif
#ifndef MYNEWT_VAL_APP_dummy_app
#define MYNEWT_VAL_APP_dummy_app (1)
#endif
#ifndef MYNEWT_VAL_ARCH_NAME
#define MYNEWT_VAL_ARCH_NAME ("dummy")
#endif
#ifndef MYNEWT_VAL_ARCH_dummy
#define MYNEWT_VAL_ARCH_dummy (1)
#endif
#ifndef MYNEWT_VAL_BSP_NAME
#define MYNEWT_VAL_BSP_NAME ("dummy_bsp")
#endif
#ifndef MYNEWT_VAL_BSP_dummy_bsp
#define MYNEWT_VAL_BSP_dummy_bsp (1)
#endif
#ifndef MYNEWT_VAL_NEWT_FEATURE_LOGCFG
#define MYNEWT_VAL_NEWT_FEATURE_LOGCFG (1)
#endif
#ifndef MYNEWT_VAL_NEWT_FEATURE_SYSDOWN
#define MYNEWT_VAL_NEWT_FEATURE_SYSDOWN (1)
#endif
#ifndef MYNEWT_VAL_TARGET_NAME
#define MYNEWT_VAL_TARGET_NAME ("linux")
#endif
#ifndef MYNEWT_VAL_TARGET_linux
#define MYNEWT_VAL_TARGET_linux (1)
#endif
#endif
| {
"pile_set_name": "Github"
} |
r"""
Manifolds
"""
#*****************************************************************************
# Copyright (C) 2015 Travis Scrimshaw <tscrim at ucdavis.edu>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#******************************************************************************
from sage.misc.abstract_method import abstract_method
from sage.misc.cachefunc import cached_method
from sage.categories.category_types import Category_over_base_ring
from sage.categories.category_with_axiom import CategoryWithAxiom_over_base_ring
from sage.categories.sets_cat import Sets
from sage.categories.fields import Fields
class Manifolds(Category_over_base_ring):
r"""
The category of manifolds over any topological field.
Let `k` be a topological field. A `d`-dimensional `k`-*manifold* `M`
is a second countable Hausdorff space such that the neighborhood of
any point `x \in M` is homeomorphic to `k^d`.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: C = Manifolds(RR); C
Category of manifolds over Real Field with 53 bits of precision
sage: C.super_categories()
[Category of topological spaces]
TESTS::
sage: TestSuite(C).run(skip="_test_category_over_bases")
"""
def __init__(self, base, name=None):
r"""
Initialize ``self``.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: C = Manifolds(RR)
sage: TestSuite(C).run(skip="_test_category_over_bases")
"""
if base not in Fields().Topological():
raise ValueError("base must be a topological field")
Category_over_base_ring.__init__(self, base, name)
@cached_method
def super_categories(self):
"""
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).super_categories()
[Category of topological spaces]
"""
return [Sets().Topological()]
def additional_structure(self):
r"""
Return ``None``.
Indeed, the category of manifolds defines no new
structure: a morphism of topological spaces between
manifolds is a manifold morphism.
.. SEEALSO:: :meth:`Category.additional_structure`
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).additional_structure()
"""
return None
class ParentMethods:
@abstract_method
def dimension(self):
"""
Return the dimension of ``self``.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: M = Manifolds(RR).example()
sage: M.dimension()
3
"""
class SubcategoryMethods:
@cached_method
def Connected(self):
"""
Return the full subcategory of the connected objects of ``self``.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).Connected()
Category of connected manifolds
over Real Field with 53 bits of precision
TESTS::
sage: Manifolds(RR).Connected.__module__
'sage.categories.manifolds'
"""
return self._with_axiom('Connected')
@cached_method
def FiniteDimensional(self):
"""
Return the full subcategory of the finite dimensional
objects of ``self``.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: C = Manifolds(RR).Connected().FiniteDimensional(); C
Category of finite dimensional connected manifolds
over Real Field with 53 bits of precision
TESTS::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).Connected().FiniteDimensional.__module__
'sage.categories.manifolds'
"""
return self._with_axiom('FiniteDimensional')
@cached_method
def Differentiable(self):
"""
Return the subcategory of the differentiable objects
of ``self``.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).Differentiable()
Category of differentiable manifolds
over Real Field with 53 bits of precision
TESTS::
sage: TestSuite(Manifolds(RR).Differentiable()).run()
sage: Manifolds(RR).Differentiable.__module__
'sage.categories.manifolds'
"""
return self._with_axiom('Differentiable')
@cached_method
def Smooth(self):
"""
Return the subcategory of the smooth objects of ``self``.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).Smooth()
Category of smooth manifolds
over Real Field with 53 bits of precision
TESTS::
sage: TestSuite(Manifolds(RR).Smooth()).run()
sage: Manifolds(RR).Smooth.__module__
'sage.categories.manifolds'
"""
return self._with_axiom('Smooth')
@cached_method
def Analytic(self):
"""
Return the subcategory of the analytic objects of ``self``.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).Analytic()
Category of analytic manifolds
over Real Field with 53 bits of precision
TESTS::
sage: TestSuite(Manifolds(RR).Analytic()).run()
sage: Manifolds(RR).Analytic.__module__
'sage.categories.manifolds'
"""
return self._with_axiom('Analytic')
@cached_method
def AlmostComplex(self):
"""
Return the subcategory of the almost complex objects
of ``self``.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).AlmostComplex()
Category of almost complex manifolds
over Real Field with 53 bits of precision
TESTS::
sage: TestSuite(Manifolds(RR).AlmostComplex()).run()
sage: Manifolds(RR).AlmostComplex.__module__
'sage.categories.manifolds'
"""
return self._with_axiom('AlmostComplex')
@cached_method
def Complex(self):
r"""
Return the subcategory of manifolds over `\CC` of ``self``.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(CC).Complex()
Category of complex manifolds over
Complex Field with 53 bits of precision
TESTS::
sage: TestSuite(Manifolds(CC).Complex()).run()
sage: Manifolds(CC).Complex.__module__
'sage.categories.manifolds'
"""
return ComplexManifolds(self.base())._with_axioms(self.axioms())
class Differentiable(CategoryWithAxiom_over_base_ring):
"""
The category of differentiable manifolds.
A differentiable manifold is a manifold with a differentiable atlas.
"""
class Smooth(CategoryWithAxiom_over_base_ring):
"""
The category of smooth manifolds.
A smooth manifold is a manifold with a smooth atlas.
"""
def extra_super_categories(self):
"""
Return the extra super categories of ``self``.
A smooth manifold is differentiable.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).Smooth().super_categories() # indirect doctest
[Category of differentiable manifolds
over Real Field with 53 bits of precision]
"""
return [Manifolds(self.base()).Differentiable()]
class Analytic(CategoryWithAxiom_over_base_ring):
r"""
The category of complex manifolds.
An analytic manifold is a manifold with an analytic atlas.
"""
def extra_super_categories(self):
"""
Return the extra super categories of ``self``.
An analytic manifold is smooth.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).Analytic().super_categories() # indirect doctest
[Category of smooth manifolds
over Real Field with 53 bits of precision]
"""
return [Manifolds(self.base()).Smooth()]
class AlmostComplex(CategoryWithAxiom_over_base_ring):
r"""
The category of almost complex manifolds.
An *almost complex manifold* `M` is a manifold with a smooth tensor
field `J` of rank `(1, 1)` such that `J^2 = -1` when regarded as a
vector bundle isomorphism `J : TM \to TM` on the tangent bundle.
The tensor field `J` is called the *almost complex structure* of `M`.
"""
def extra_super_categories(self):
"""
Return the extra super categories of ``self``.
An almost complex manifold is smooth.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).AlmostComplex().super_categories() # indirect doctest
[Category of smooth manifolds
over Real Field with 53 bits of precision]
"""
return [Manifolds(self.base()).Smooth()]
class FiniteDimensional(CategoryWithAxiom_over_base_ring):
"""
Category of finite dimensional manifolds.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: C = Manifolds(RR).FiniteDimensional()
sage: TestSuite(C).run(skip="_test_category_over_bases")
"""
class Connected(CategoryWithAxiom_over_base_ring):
"""
The category of connected manifolds.
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: C = Manifolds(RR).Connected()
sage: TestSuite(C).run(skip="_test_category_over_bases")
"""
class ComplexManifolds(Category_over_base_ring):
r"""
The category of complex manifolds.
A `d`-dimensional complex manifold is a manifold whose underlying
vector space is `\CC^d` and has a holomorphic atlas.
"""
@cached_method
def super_categories(self):
"""
EXAMPLES::
sage: from sage.categories.manifolds import Manifolds
sage: Manifolds(RR).super_categories()
[Category of topological spaces]
"""
return [Manifolds(self.base()).Analytic()]
| {
"pile_set_name": "Github"
} |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2017 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://oss.oracle.com/licenses/CDDL+GPL-1.1
* or LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.xml.ws.sdo.sample.service.types;
import commonj.sdo.Type;
import commonj.sdo.impl.HelperProvider;
import org.eclipse.persistence.sdo.SDODataObject;
public class ProcessEmpsElementImpl extends SDODataObject implements ProcessEmpsElement {
public static String SDO_URI = "http://sdo.sample.service/types/";
public ProcessEmpsElementImpl() {}
// public Type getType() {
// if(type == null){
// Type lookupType = HelperProvider.getTypeHelper().getType(SDO_URI, "ProcessEmpsElement");
// setType(lookupType);
// }
// return type;
// }
public java.lang.String getChangeOperation() {
return getString("changeOperation");
}
public void setChangeOperation(java.lang.String value) {
set("changeOperation" , value);
}
public java.util.List getEmp() {
return getList("emp");
}
public void setEmp(java.util.List value) {
set("emp" , value);
}
public com.sun.xml.ws.sdo.sample.service.types.ProcessControl getProcessControl() {
return (com.sun.xml.ws.sdo.sample.service.types.ProcessControl)get("processControl");
}
public void setProcessControl(com.sun.xml.ws.sdo.sample.service.types.ProcessControl value) {
set("processControl" , value);
}
}
| {
"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.
*/
#include "os/thread_local_storage.h"
#include <jni.h>
#include <malloc.h>
#include <stdio.h>
#include <windows.h>
#define UNKNOWN "UNKNOWN"
#define MAXTHRID 256
/** Key that allows us to retrieve thread-local storage */
static DWORD gTlsIndex = TLS_OUT_OF_INDEXES;
static void get_current_thread_id(JNIEnv* env, char* id, int max);
/**
* If the current thread has a JNIEnv in thread-local storage, then detaches the
* current thread from the JVM and also frees up the ThreadLocalState object.
*/
static void detachCurrentThreadFromJvm()
{
struct ThreadLocalState *state = NULL;
JNIEnv *env = NULL;
JavaVM *vm;
jint ret;
char thr_name[MAXTHRID];
if (threadLocalStorageGet(&state) || !state) {
return;
}
env = state->env;
if ((env == NULL) || (*env == NULL)) {
return;
}
ret = (*env)->GetJavaVM(env, &vm);
if (ret) {
fprintf(stderr,
"detachCurrentThreadFromJvm: GetJavaVM failed with error %d\n",
ret);
(*env)->ExceptionDescribe(env);
} else {
ret = (*vm)->DetachCurrentThread(vm);
if (ret != JNI_OK) {
(*env)->ExceptionDescribe(env);
get_current_thread_id(env, thr_name, MAXTHRID);
fprintf(stderr, "detachCurrentThreadFromJvm: Unable to detach thread %s "
"from the JVM. Error code: %d\n", thr_name, ret);
}
}
/* Free exception strings */
if (state->lastExceptionStackTrace) free(state->lastExceptionStackTrace);
if (state->lastExceptionRootCause) free(state->lastExceptionRootCause);
/* Free the state itself */
free(state);
}
static void get_current_thread_id(JNIEnv* env, char* id, int max) {
jclass cls;
jmethodID mth;
jobject thr;
jstring thr_name;
jlong thr_id = 0;
const char *thr_name_str;
cls = (*env)->FindClass(env, "java/lang/Thread");
mth = (*env)->GetStaticMethodID(env, cls, "currentThread",
"()Ljava/lang/Thread;");
thr = (*env)->CallStaticObjectMethod(env, cls, mth);
if (thr != NULL) {
mth = (*env)->GetMethodID(env, cls, "getId", "()J");
thr_id = (*env)->CallLongMethod(env, thr, mth);
(*env)->ExceptionDescribe(env);
mth = (*env)->GetMethodID(env, cls, "toString", "()Ljava/lang/String;");
thr_name = (jstring)(*env)->CallObjectMethod(env, thr, mth);
if (thr_name != NULL) {
thr_name_str = (*env)->GetStringUTFChars(env, thr_name, NULL);
// Treating the jlong as a long *should* be safe
snprintf(id, max, "%s:%ld", thr_name_str, thr_id);
// Release the char*
(*env)->ReleaseStringUTFChars(env, thr_name, thr_name_str);
} else {
(*env)->ExceptionDescribe(env);
// Treating the jlong as a long *should* be safe
snprintf(id, max, "%s:%ld", UNKNOWN, thr_id);
}
} else {
(*env)->ExceptionDescribe(env);
snprintf(id, max, "%s", UNKNOWN);
}
// Make sure the id is null terminated in case we overflow the max length
id[max - 1] = '\0';
}
void hdfsThreadDestructor(void *v)
{
// Ignore 'v' since it will contain the state and we will obtain it in the below
// call anyway.
detachCurrentThreadFromJvm();
}
/**
* Unlike pthreads, the Windows API does not seem to provide a convenient way to
* hook a callback onto thread shutdown. However, the Windows portable
* executable format does define a concept of thread-local storage callbacks.
* Here, we define a function and instruct the linker to set a pointer to that
* function in the segment for thread-local storage callbacks. See page 85 of
* Microsoft Portable Executable and Common Object File Format Specification:
* http://msdn.microsoft.com/en-us/gg463119.aspx
* This technique only works for implicit linking (OS loads DLL on demand), not
* for explicit linking (user code calls LoadLibrary directly). This effectively
* means that we have a known limitation: libhdfs may not work correctly if a
* Windows application attempts to use it via explicit linking.
*
* @param h module handle
* @param reason the reason for calling the callback
* @param pv reserved, unused
*/
static void NTAPI tlsCallback(PVOID h, DWORD reason, PVOID pv)
{
DWORD tlsIndex;
switch (reason) {
case DLL_THREAD_DETACH:
detachCurrentThreadFromJvm();
break;
case DLL_PROCESS_DETACH:
detachCurrentThreadFromJvm();
tlsIndex = gTlsIndex;
gTlsIndex = TLS_OUT_OF_INDEXES;
if (!TlsFree(tlsIndex)) {
fprintf(stderr, "tlsCallback: TlsFree failed with error %d\n",
GetLastError());
}
break;
default:
break;
}
}
/*
* A variable named _tls_used contains the TLS directory, which contains a list
* of pointers to callback functions. Normally, the linker won't retain this
* variable unless the executable has implicit thread-local variables, defined
* using the __declspec(thread) extended storage-class modifier. libhdfs
* doesn't use __declspec(thread), and we have no guarantee that the executable
* linked to libhdfs will use __declspec(thread). By forcing the linker to
* reference _tls_used, we guarantee that the binary retains the TLS directory.
* See Microsoft Visual Studio 10.0/VC/crt/src/tlssup.c .
*/
#ifdef _WIN64
#pragma comment(linker, "/INCLUDE:_tls_used")
#else
#pragma comment(linker, "/INCLUDE:__tls_used")
#endif
/*
* We must retain a pointer to the callback function. Force the linker to keep
* this symbol, even though it appears that nothing in our source code uses it.
*/
#ifdef _WIN64
#pragma comment(linker, "/INCLUDE:pTlsCallback")
#else
#pragma comment(linker, "/INCLUDE:_pTlsCallback")
#endif
/*
* Define constant pointer to our callback, and tell the linker to pin it into
* the TLS directory so that it receives thread callbacks. Use external linkage
* to protect against the linker discarding the seemingly unused symbol.
*/
#pragma const_seg(".CRT$XLB")
extern const PIMAGE_TLS_CALLBACK pTlsCallback;
const PIMAGE_TLS_CALLBACK pTlsCallback = tlsCallback;
#pragma const_seg()
struct ThreadLocalState* threadLocalStorageCreate()
{
struct ThreadLocalState *state;
state = (struct ThreadLocalState*)malloc(sizeof(struct ThreadLocalState));
if (state == NULL) {
fprintf(stderr,
"threadLocalStorageCreate: OOM - Unable to allocate thread local state\n");
return NULL;
}
state->lastExceptionStackTrace = NULL;
state->lastExceptionRootCause = NULL;
return state;
}
int threadLocalStorageGet(struct ThreadLocalState **state)
{
LPVOID tls;
DWORD ret;
if (TLS_OUT_OF_INDEXES == gTlsIndex) {
gTlsIndex = TlsAlloc();
if (TLS_OUT_OF_INDEXES == gTlsIndex) {
fprintf(stderr,
"threadLocalStorageGet: TlsAlloc failed with error %d\n",
TLS_OUT_OF_INDEXES);
return TLS_OUT_OF_INDEXES;
}
}
tls = TlsGetValue(gTlsIndex);
if (tls) {
*state = tls;
return 0;
} else {
ret = GetLastError();
if (ERROR_SUCCESS == ret) {
/* Thread-local storage contains NULL, because we haven't set it yet. */
*state = NULL;
return 0;
} else {
/*
* The API call failed. According to documentation, TlsGetValue cannot
* fail as long as the index is a valid index from a successful TlsAlloc
* call. This error handling is purely defensive.
*/
fprintf(stderr,
"threadLocalStorageGet: TlsGetValue failed with error %d\n", ret);
return ret;
}
}
}
int threadLocalStorageSet(struct ThreadLocalState *state)
{
DWORD ret = 0;
if (!TlsSetValue(gTlsIndex, (LPVOID)state)) {
ret = GetLastError();
fprintf(stderr,
"threadLocalStorageSet: TlsSetValue failed with error %d\n",
ret);
detachCurrentThreadFromJvm(state);
}
return ret;
}
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"filename" : "barbuttonicon_delete.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
/**
* Provides the Metadata Store support classes.
*/
package org.springframework.integration.hazelcast.metadata;
| {
"pile_set_name": "Github"
} |
// Copyright 2019 GM Cruise LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gke
import (
"context"
"errors"
"fmt"
"go.starlark.net/starlark"
"k8s.io/client-go/rest"
"github.com/cruise-automation/isopod/pkg/addon"
"github.com/cruise-automation/isopod/pkg/cloud"
)
const (
// ClusterKey is the name of the cluster field.
ClusterKey = "cluster"
// ProjectKey is the name of the project field.
ProjectKey = "project"
// LocationKey is the name of the location field.
LocationKey = "location"
// UseInternalIPKey indicates if connecting API server via private endpoint
UseInternalIPKey = "use_internal_ip"
)
var (
// asserts *GKE implements starlark.HasAttrs interface.
_ starlark.HasAttrs = (*GKE)(nil)
// asserts *GKE implements cloud.KubernetesVendor interface.
_ cloud.KubernetesVendor = (*GKE)(nil)
// RequiredFields is the list of required fields to initialize a GKE target.
RequiredFields = []string{ClusterKey, ProjectKey, LocationKey}
)
// GKE represents a GKE cluster. It includes critical information such as
// the cluster name, location, and project id, as well as other optional info.
type GKE struct {
*cloud.AbstractKubeVendor
svcAcctKeyFile, userAgent string
}
// NewGKEBuiltin creates a new GKE built-in.
func NewGKEBuiltin(svcAcctKeyFile, userAgent string) *starlark.Builtin {
return starlark.NewBuiltin(
"gke",
func(t *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
absKubeVendor, err := cloud.NewAbstractKubeVendor("gke", RequiredFields, kwargs)
if err != nil {
return nil, err
}
return &GKE{
AbstractKubeVendor: absKubeVendor,
svcAcctKeyFile: svcAcctKeyFile,
userAgent: userAgent,
}, nil
},
)
}
// KubeConfig is part of the cloud.KubernetesVendor interface.
func (g *GKE) KubeConfig(ctx context.Context) (*rest.Config, error) {
cluster, location, project, useInternalIP, err := clpFromClusterCtx(g.SkyCtx)
if err != nil {
return nil, fmt.Errorf("failed to extract cluster info from %v: %v", g, err)
}
return BuildKubeRestConfSACred(ctx, cluster, location, project, useInternalIP, g.svcAcctKeyFile, g.userAgent)
}
func stringFromValue(v starlark.Value) (string, error) {
if v == nil {
return "", errors.New("nil value")
}
s, ok := v.(starlark.String)
if !ok {
return "", fmt.Errorf("%v is not a starlark string (got a `%s')", v, v.Type())
}
return string(s), nil
}
func clpFromClusterCtx(c *addon.SkyCtx) (cluster, location, project, useInternalIP string, err error) {
if cluster, err = stringFromValue(c.Attrs[ClusterKey]); err != nil {
return
}
if location, err = stringFromValue(c.Attrs[LocationKey]); err != nil {
return
}
if project, err = stringFromValue(c.Attrs[ProjectKey]); err != nil {
return
}
if val := c.Attrs[UseInternalIPKey]; val != nil {
if v, ok := val.(starlark.String); ok {
useInternalIP = string(v)
}
}
return
}
| {
"pile_set_name": "Github"
} |
#ifndef PQCLEAN_SPHINCSHARAKA256FROBUST_AESNI_WOTS_H
#define PQCLEAN_SPHINCSHARAKA256FROBUST_AESNI_WOTS_H
#include "hash_state.h"
#include "params.h"
#include <stdint.h>
/**
* WOTS key generation. Takes a 32 byte seed for the private key, expands it to
* a full WOTS private key and computes the corresponding public key.
* It requires the seed pub_seed (used to generate bitmasks and hash keys)
* and the address of this WOTS key pair.
*
* Writes the computed public key to 'pk'.
*/
void PQCLEAN_SPHINCSHARAKA256FROBUST_AESNI_wots_gen_pk(
unsigned char *pk, const unsigned char *sk_seed,
const unsigned char *pub_seed, uint32_t addr[8],
const hash_state *hash_state_seeded);
/**
* Takes a n-byte message and the 32-byte seed for the private key to compute a
* signature that is placed at 'sig'.
*/
void PQCLEAN_SPHINCSHARAKA256FROBUST_AESNI_wots_sign(
unsigned char *sig, const unsigned char *msg,
const unsigned char *sk_seed, const unsigned char *pub_seed,
uint32_t addr[8], const hash_state *hash_state_seeded);
/**
* Takes a WOTS signature and an n-byte message, computes a WOTS public key.
*
* Writes the computed public key to 'pk'.
*/
void PQCLEAN_SPHINCSHARAKA256FROBUST_AESNI_wots_pk_from_sig(
unsigned char *pk,
const unsigned char *sig, const unsigned char *msg,
const unsigned char *pub_seed, uint32_t addr[8],
const hash_state *hash_state_seeded);
#endif
| {
"pile_set_name": "Github"
} |
<?if (Core::extra_features() == TRUE):?>
<?if (core::count($providers = Social::enabled_providers()) > 0 OR core::config('social.oauth2_enabled') == TRUE) :?>
<ul class="list-inline social-providers">
<?foreach ($providers as $key => $provider) :?>
<li>
<?if(strtolower($key) == 'live'):?>
<a class="zocial <?=strtolower($key) == 'live' ? 'windows' : ''?>" href="<?=Route::url('default',array('controller'=>'social','action'=>'login','id'=>strtolower($key)))?>">
<?=$key?>
</a>
<?elseif(strtolower($key) == 'facebook'):?>
<a href="<?=Route::url('default',array('controller'=>'social','action'=>'login','id'=>strtolower($key)))?>" style="display: block;">
<div class="_xvm _29o8">
<div class="_5h0c _5h0f" style="" role="button" tabindex="0">
<table class="uiGrid _51mz _5h0i _5f0n" cellspacing="0" cellpadding="0">
<tbody>
<tr class="_51mx">
<td class="_51m-">
<div class="_5h0j">
<span class="_5h0k">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 216 216" class="_5h0m" color="#FFFFFF"><path fill="#FFFFFF" d="
M204.1 0H11.9C5.3 0 0 5.3 0 11.9v192.2c0 6.6 5.3 11.9 11.9
11.9h103.5v-83.6H87.2V99.8h28.1v-24c0-27.9 17-43.1 41.9-43.1
11.9 0 22.2.9 25.2 1.3v29.2h-17.3c-13.5 0-16.2 6.4-16.2
15.9v20.8h32.3l-4.2 32.6h-28V216h55c6.6 0 11.9-5.3
11.9-11.9V11.9C216 5.3 210.7 0 204.1 0z"></path></svg>
</span>
</div>
</td>
<td class="_51m- _51mw">
<div class="_5h0s">
<div class="_5h0o"><?= _e('Continue with Facebook') ?></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</a>
<style>
._32qa button{
opacity:.4
}
._59ov{
height:100%;
height:910px;
position:relative;
top:-10px;
width:100%
}
._5ti_{
background-size:cover;
height:100%;
width:100%
}
._5tj2{
height:900px
}
._2mm3 ._5a8u .uiBoxGray{
background:#fff;
margin:0;
padding:12px
}
._2494{
height:100vh
}
._2495{
margin-top:-10px;
top:10px
}
._5h0c{
background-color:#e9ebee;
cursor:pointer;
display:inline-block;
vertical-align:top
}
._5h0c._5h0d{
border-radius:4px;
max-width:400px;
min-width:240px
}
._29o8{
display:inline-block
}
._xvm ._5h0c._5h0d{
min-width:initial
}
._5h0c._5h0f{
border-radius:3px;
max-width:320px;
min-width:200px
}
._xvm ._5h0c._5h0f{
min-width:initial
}
._5h0c._5h0g{
border-radius:3px;
max-width:200px
}
._5h0c._5h0h{
border-radius:2px;
margin:10px 0;
max-width:268px
}
._5h0i{
background-color:#4267b2;
border-radius:4px;
color:#fff
}
._5h0g ._5h0i{
border-radius:3px;
height:20px;
width:auto
}
._5h0g ._5h0i td:first-child,._5h0g ._xvp._5h0i td:last-child{
width:20px
}
._5h0f ._5h0i{
border-radius:3px;
height:28px
}
._xvm ._5h0c._5h0f ._5h0i{
max-width:240px;
min-width:initial;
width:auto;
margin-top: -6px
}
._5h0f ._5h0i td:first-child,._5h0f ._xvp._5h0i td:last-child{
width:28px
}
._xvm ._5h0c._5h0d ._5h0i{
max-width:272px;
min-width:initial;
width:auto
}
._5h0d ._5h0i{
height:40px
}
._5h0d ._5h0i td:first-child,._5h0d ._xvp._5h0i td:last-child,._41tb ._5h0d ._5h0i td:nth-child(3){
width:40px
}
._5h0h._5h0c ._5h0i{
height:40px;
table-layout:auto;
width:268px
}
._5h0c ._5h0j{
overflow:none;
white-space:nowrap
}
._5h0c ._5h0k{
float:left
}
._5h0h ._5h0k{
height:24px;
margin-left:8px
}
._5h0d td:last-child ._5h0k{
margin-left:0
}
._5h0d ._5h0k{
height:24px;
margin:8px
}
._5h0f ._5h0k{
height:16px;
margin:6px
}
._5h0g ._5h0k{
height:12px;
margin:4px
}
._5h0h ._5h0l,._5h0h ._5h0m,._5h0d ._5h0l,._5h0d ._5h0m{
height:24px;
width:24px
}
._5h0f ._5h0l,._5h0f ._5h0m{
height:16px;
width:16px
}
._5h0g ._5h0l,._5h0g ._5h0m{
height:12px;
width:12px
}
._5h0o{
border:none;
font-family:Helvetica, Arial, sans-serif;
letter-spacing:.25px;
overflow:hidden;
text-align:center;
text-overflow:clip;
white-space:nowrap
}
._5h0g ._5h0o{
font-size:11px;
max-width:150px;
padding:0 8px 0 2px
}
._5h0f ._5h0o{
font-size:13px;
margin-right:8px
}
._xvm ._5h0f ._5h0q ._5h0o{
margin:0 12px 0 6px;
max-width:166px
}
._5h0d ._5h0o{
font-size:16px;
margin-right:12px
}
._29o8._41tb ._5h0d td:only-child ._5h0o{
margin:auto 16px
}
._xvm ._5h0d ._5h0o{
margin:0 24px 0 12px
}
._xvm ._5h0d ._5h0q ._5h0o{
margin:0 12px 0 4px;
max-width:176px
}
._5h0h ._5h0o{
font-size:15px;
font-weight:bold;
letter-spacing:normal;
line-height:16px;
padding:0 22px;
white-space:normal
}
._5h0h ._5h0o._4lqf{
font-size:12px;
line-height:14px
}
._5h0h ._5h0s{
max-width:100%
}
.no_svg ._5h0m,.svg ._5h0l{
display:none
}
._5h0t{
float:right;
vertical-align:top
}
._5h0c._5h0g ._5h0t{
border-bottom-right-radius:3px;
border-top-right-radius:3px;
height:20px;
width:20px
}
._5h0c._5h0f ._5h0t{
border-bottom-right-radius:3px;
border-top-right-radius:3px;
height:28px;
width:28px
}
._xvm ._5h0c._5h0d td:first-child ._5h0t{
margin-right:8px
}
._5h0c._5h0d td:first-child ._5h0t{
border-bottom-left-radius:4px;
border-bottom-right-radius:0;
border-top-left-radius:4px;
border-top-right-radius:0
}
._5h0c._5h0d ._5h0t{
border-bottom-right-radius:4px;
border-top-right-radius:4px;
height:40px;
width:40px
}
._5h0c._5h0h ._5h0t{
border-bottom-right-radius:2px;
border-top-right-radius:2px;
height:40px;
width:40px
}
._29o8 ._2x7x{
background-color:#e9ebee;
border-bottom-left-radius:4px;
border-bottom-right-radius:4px;
text-align:center
}
._29o8 ._2x7y{
display:table;
margin:auto;
padding:5px 20px
}
._29o8 ._2x7x ._37q_{
display:table-cell;
vertical-align:middle
}
._29o8 ._2x7x ._37r0{
color:#444950;
display:table-cell;
font-size:10px;
padding-left:4px;
vertical-align:middle
}
._51mz{
border:0;
border-collapse:collapse;
border-spacing:0
}
._5f0n{
table-layout:fixed;
width:100%
}
.uiGrid .vTop{
vertical-align:top
}
.uiGrid .vMid{
vertical-align:middle
}
.uiGrid .vBot{
vertical-align:bottom
}
.uiGrid .hLeft{
text-align:left
}
.uiGrid .hCent{
text-align:center
}
.uiGrid .hRght{
text-align:right
}
._51mx:first-child>._51m-{
padding-top:0
}
._51mx:last-child>._51m-{
padding-bottom:0
}
._51mz ._51mw{
padding-right:0
}
._51mz ._51m-:first-child{
padding-left:0
}
._51mz._4r9u{
border-radius:50%;
overflow:hidden
}
._4mr9{
-webkit-touch-callout:none;
-webkit-user-select:none
}
._4mra{
-webkit-touch-callout:default;
-webkit-user-select:auto
}
._li._li._li{
overflow:initial
}
._72b0{
position:relative;
z-index:0
}
.uiLayer{
outline:none
}
._4qba{
font-style:normal
}
._4qbb,._4qbc,._4qbd{
background:none;
font-style:normal;
padding:0;
width:auto
}
._4qbd{
border-bottom:1px solid #f99
}
._4qbb,._4qbc{
border-bottom:1px solid #999
}
._4qbb:hover,._4qbc:hover,._4qbd:hover{
background-color:#fcc;
border-top:1px solid #ccc;
cursor:help
}
</style>
<?elseif(strtolower($key) == 'google'):?>
<a href="<?=Route::url('default',array('controller'=>'social','action'=>'login','id'=>strtolower($key)))?>" style="height:31px; width:180px; display: inline-block; margin-top: -5px;" class="abcRioButton abcRioButtonLightBlue">
<div class="abcRioButtonContentWrapper">
<div class="abcRioButtonIcon" style="padding:6px">
<div style="width:18px;height:18px;" class="abcRioButtonSvgImageWithFallback abcRioButtonIconImage abcRioButtonIconImage18">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="18px" height="18px" viewBox="0 0 48 48" class="abcRioButtonSvg">
<g>
<path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"></path>
<path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"></path>
<path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"></path>
<path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"></path>
<path fill="none" d="M0 0h48v48H0z"></path>
</g>
</svg>
</div>
</div>
<span style="font-size:12px;line-height:29px;" class="abcRioButtonContents">
<span id="not_signed_ineid4prr8k1y8"><?= _e('Sign in with Google') ?></span>
</span>
</div>
</a>
<style>
.abcRioButton {
-webkit-border-radius:1px;
border-radius:1px;
-webkit-box-shadow 0 2px 4px 0px rgba(0,0,0,.25);
box-shadow:0 2px 4px 0 rgba(0,0,0,.25);
-webkit-box-sizing:border-box;
box-sizing:border-box;
-webkit-transition:background-color .218s,border-color .218s,box-shadow .218s;
transition:background-color .218s,border-color .218s,box-shadow .218s;
-webkit-user-select:none;
-webkit-appearance:none;
background-color:#fff;
background-image:none;
color:#262626;
cursor:pointer;
outline:none;
overflow:hidden;
position:relative;
text-align:center;
vertical-align:middle;
white-space:nowrap;
width:auto
}
.abcRioButton:hover{
-webkit-box-shadow:0 0 3px 3px rgba(66,133,244,.3);
box-shadow:0 0 3px 3px rgba(66,133,244,.3)
}
.abcRioButtonLightBlue{
background-color:#fff;
color:#757575
}
.abcRioButtonLightBlue:hover{
background-color:#fff;
color:#757575;
text-decoration: none;
}
.abcRioButtonLightBlue:active{
background-color:#eee;
color:#6d6d6d
}
.abcRioButtonIcon{
float:left
}
.abcRioButtonBlue .abcRioButtonIcon{
background-color:#fff;
-webkit-border-radius:1px;
border-radius:1px
}
.abcRioButtonSvg{
display:block
}
.abcRioButtonContents{
font-family:Roboto,arial,sans-serif;
font-size:14px;
font-weight:500;
letter-spacing:.21px;
margin-left:6px;
margin-right:6px;
vertical-align:top
}
.abcRioButtonContentWrapper{
height:100%;
width:100%
}
.abcRioButtonBlue .abcRioButtonContentWrapper{
border:1px solid transparent
}
.abcRioButtonErrorState .abcRioButtonContentWrapper,.abcRioButtonWorkingState .abcRioButtonContentWrapper{
display:none
}
</style>
<?else:?>
<a class="zocial <?=strtolower($key)?>" href="<?=Route::url('default',array('controller'=>'social','action'=>'login','id'=>strtolower($key)))?>">
<?=$key?>
</a>
<?endif?>
</li>
<?endforeach?>
<?if (core::config('social.oauth2_enabled') == TRUE):?>
<li>
<a class="zocial secondary" href="<?=Route::url('default',array('controller'=>'social','action'=>'oauth','id'=>1))?>">
<?=__('OAuth')?>
</a>
</li>
<?endif?>
</ul>
<?endif?>
<?endif?>
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace WowPacketParser.Misc
{
// By Jon Skeet (Stack Overflow), modified
public class BiDictionary<TFirst, TSecond> : IDictionary<TFirst, TSecond>
{
readonly IDictionary<TFirst, TSecond> _firstToSecond = new Dictionary<TFirst, TSecond>();
readonly IDictionary<TSecond, TFirst> _secondToFirst = new Dictionary<TSecond, TFirst>();
public bool ContainsKey(TFirst key)
{
return _firstToSecond.ContainsKey(key);
}
public bool ContainsValue(TSecond value)
{
return _secondToFirst.ContainsKey(value);
}
public bool ContainsKey(TSecond key)
{
return _secondToFirst.ContainsKey(key);
}
public bool ContainsValue(TFirst value)
{
return _firstToSecond.ContainsKey(value);
}
public void Add(TFirst first, TSecond second)
{
TFirst frst;
TSecond snd;
if (_firstToSecond.TryGetValue(first, out snd))
{
Trace.WriteLine($"BiDictionary already contains <{second}, {first}>");
return;
}
if (_secondToFirst.TryGetValue(second, out frst))
{
Trace.WriteLine($"BiDictionary already contains <{first}, {second}>");
return;
}
_firstToSecond.Add(first, second);
_secondToFirst.Add(second, first);
}
public void Add(KeyValuePair<TFirst, TSecond> item)
{
Add(item.Key, item.Value);
}
public void Add(KeyValuePair<TSecond, TFirst> item)
{
Add(item.Value, item.Key);
}
public bool Remove(TFirst key)
{
if (_firstToSecond.Remove(key))
{
foreach (var pair in _secondToFirst.Where(pair => Equals(pair.Value, key)))
{
_secondToFirst.Remove(pair.Key);
return true;
}
}
return false;
}
public bool Remove(TSecond key)
{
if (_secondToFirst.Remove(key))
{
foreach (var pair in _firstToSecond.Where(pair => Equals(pair.Value, key)))
{
_firstToSecond.Remove(pair.Key);
return true;
}
}
return false;
}
public bool TryGetValue(TFirst key, out TSecond value)
{
return TryGetByFirst(key, out value);
}
public bool TryGetValue(TSecond key, out TFirst value)
{
return TryGetBySecond(key, out value);
}
TSecond IDictionary<TFirst, TSecond>.this[TFirst key]
{
get { return GetByFirst(key); }
set { _firstToSecond[key] = value; }
}
public ICollection<TFirst> Keys => _firstToSecond.Keys;
public ICollection<TSecond> Values => _firstToSecond.Values;
public bool Remove(KeyValuePair<TFirst, TSecond> item)
{
var invertedPair = new KeyValuePair<TSecond, TFirst>(item.Value, item.Key);
return _firstToSecond.Remove(item) && _secondToFirst.Remove(invertedPair);
}
public bool Remove(KeyValuePair<TSecond, TFirst> item)
{
var invertedPair = new KeyValuePair<TFirst, TSecond>(item.Value, item.Key);
return _secondToFirst.Remove(item) && _firstToSecond.Remove(invertedPair);
}
public int Count => _firstToSecond.Count;
public bool IsReadOnly => _firstToSecond.IsReadOnly;
public void Clear()
{
_firstToSecond.Clear();
_secondToFirst.Clear();
}
public bool Contains(KeyValuePair<TFirst, TSecond> item)
{
return _firstToSecond.Contains(item);
}
public bool Contains(KeyValuePair<TSecond, TFirst> item)
{
return _secondToFirst.Contains(item);
}
public void CopyTo(KeyValuePair<TFirst, TSecond>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public TSecond this[TFirst first]
{
get { return GetByFirst(first); }
set { SetByFirst(first, value); }
}
public TFirst this[TSecond second]
{
get { return GetBySecond(second); }
set { SetBySecond(second, value); }
}
public bool TryGetByFirst(TFirst first, out TSecond second)
{
return _firstToSecond.TryGetValue(first, out second);
}
public bool TryGetBySecond(TSecond second, out TFirst first)
{
return _secondToFirst.TryGetValue(second, out first);
}
public TSecond GetByFirst(TFirst first)
{
TSecond value;
if (_firstToSecond.TryGetValue(first, out value))
return value;
return default(TSecond);
}
public TFirst GetBySecond(TSecond second)
{
TFirst value;
if (_secondToFirst.TryGetValue(second, out value))
return value;
return default(TFirst);
}
public void SetByFirst(TFirst key, TSecond value)
{
TSecond oldVal = _firstToSecond[key];
if (!typeof(TSecond).IsValueType && oldVal == null)
return;
_firstToSecond[key] = value;
if (_secondToFirst.Remove(oldVal))
_secondToFirst.Add(value, key);
}
public void SetBySecond(TSecond key, TFirst value)
{
SetByFirst(value, key);
}
public IEnumerator<KeyValuePair<TFirst, TSecond>> GetEnumerator()
{
return _firstToSecond.GetEnumerator();
}
[ExcludeFromCodeCoverage]
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?><sld:StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:sld="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml" version="1.0.0">
<sld:NamedLayer>
<sld:Name/>
<sld:UserStyle>
<sld:Name>Default Styler</sld:Name>
<sld:FeatureTypeStyle>
<sld:Rule>
<sld:MinScaleDenominator>10000.0</sld:MinScaleDenominator>
<sld:LineSymbolizer>
<sld:Stroke>
<sld:CssParameter name="stroke">#ff0000</sld:CssParameter>
<sld:CssParameter name="stroke-width">2</sld:CssParameter>
</sld:Stroke>
</sld:LineSymbolizer>
</sld:Rule>
<sld:Rule>
<sld:MaxScaleDenominator>10000.0</sld:MaxScaleDenominator>
<sld:LineSymbolizer>
<sld:Stroke>
<sld:CssParameter name="stroke">#ff0000</sld:CssParameter>
<sld:CssParameter name="stroke-width">4</sld:CssParameter>
</sld:Stroke>
</sld:LineSymbolizer>
</sld:Rule>
<sld:Rule>
<sld:LineSymbolizer>
<sld:Stroke>
<sld:CssParameter name="stroke">#ff0000</sld:CssParameter>
</sld:Stroke>
</sld:LineSymbolizer>
</sld:Rule>
<sld:VendorOption name="ruleEvaluation">first</sld:VendorOption>
</sld:FeatureTypeStyle>
</sld:UserStyle>
</sld:NamedLayer>
</sld:StyledLayerDescriptor>
| {
"pile_set_name": "Github"
} |
//
// Utils.h
// FlexiSPY
//
// Created by Dominique Mayrand on 12/6/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
@class DbHealthInfo;
@class EventCount;
@interface Utils : NSObject {
}
+ (NSMutableArray*) getDiagnosticsWithDBHealthInfo: (DbHealthInfo *) aDBHealthInfo
withEventCount: (EventCount *) aEventCount
andLastConnectionTime: (NSString *) aLastConnectionTime;
+ (BOOL) isSupportSettingIDOfRemoteCmdCodeSettings: (NSInteger) aSettingID;
@end
@interface DiagnosticObject : NSObject{
NSString* mName;
NSString* mValue;
}
@property (nonatomic, retain) NSString* mName;
@property (nonatomic, retain) NSString* mValue;
-(id) initWithName:(NSString*) aName andValue: (NSString*) aValues;
-(void) dealloc;
@end
| {
"pile_set_name": "Github"
} |
/*ckwg +29
* Copyright 2018-2019 by Kitware, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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 name of Kitware, Inc. nor the names of any 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 AUTHORS 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.
*/
#ifndef VITAL_RANGE_INDIRECT_H
#define VITAL_RANGE_INDIRECT_H
#include <vital/range/defs.h>
namespace kwiver {
namespace vital {
namespace range {
//-----------------------------------------------------------------------------
/// Indirection range adapter.
/**
* This range adapter applies a level of indirection. This is typically used
* to suppress the dereferencing of a container iterator in a range-based
* \c for loop in order to allow iteration over the container's iterators,
* rather than the values.
*/
template < typename Range >
class indirect_view : public generic_view
{
protected:
using range_iterator_t = typename range_ref< Range >::iterator_t;
public:
using value_t = range_iterator_t;
indirect_view( indirect_view const& ) = default;
indirect_view( indirect_view&& ) = default;
class iterator
{
public:
iterator() = default;
iterator( iterator const& ) = default;
iterator& operator=( iterator const& ) = default;
bool operator!=( iterator const& other ) const
{ return m_iter != other.m_iter; }
value_t operator*() const { return m_iter; }
iterator& operator++() { ++m_iter; return *this; }
protected:
friend class indirect_view;
iterator( range_iterator_t const& iter ) : m_iter{ iter } {}
range_iterator_t m_iter;
};
indirect_view( Range&& range ) : m_range( std::forward< Range >( range ) ) {}
iterator begin() const { return { m_range.begin() }; }
iterator end() const { return { m_range.end() }; }
protected:
range_ref< Range const > m_range;
};
///////////////////////////////////////////////////////////////////////////////
KWIVER_MUTABLE_RANGE_ADAPTER( indirect )
} } } // end namespace
#endif
| {
"pile_set_name": "Github"
} |
# coding=utf-8
"""Tests for medusa/test_list_associated_files.py."""
from __future__ import unicode_literals
import os
from medusa import app
from medusa.post_processor import PostProcessor
import pytest
def _rar_basename(filepath, files):
for found_file in files:
if os.path.splitext(os.path.basename(found_file))[1] == '.rar':
return os.path.basename(os.path.splitext(os.path.basename(found_file))[0].lower())
@pytest.mark.parametrize('p', [
{ # p0: No associated files. Wrong basename
'path': 'media/postprocess/',
'structure': (
'bow.514.hdtv-lol[ettv].mkv',
'bow.514.hdtv-lol.srt',
{'samples': (
'sample.mkv', 'other.mkv',
{'inception': ()}
)}
),
'expected_associated_files': [],
'allowed_extensions': 'nfo,srt'
},
{ # p1: No associated files
'path': 'media/postprocess/',
'structure': (
'bow.514.hdtv-lol[ettv].mkv',
{'samples': (
'sample.mkv', 'other.mkv',
{'inception': (
'cool.txt', 'bla.nfo'
)}
)}
),
'expected_associated_files': [],
'allowed_extensions': 'nfo,srt'
},
{ # p2: No media file, so can't list associated files
'path': 'media/postprocess/',
'structure': (
'bow.514.hdtv-lol.srt',
),
'expected_associated_files': [],
'allowed_extensions': 'nfo,srt'
},
{ # p3: .srt and .nfo associated files. Check subfolders
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
'Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
'Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
'Show.S01E01.720p.HDTV.X264-DIMENSION.sfv',
{'samples': (
'sample.mkv', 'other.mkv',
{'inception': (
'cool.txt', 'bla.nfo'
)}
)}
),
'expected_associated_files': ['Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
'Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
],
'allowed_extensions': 'nfo,srt',
'subfolders': True,
'refine': True
},
{ # p4: Only .nfo associated file allowed
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
'Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
'Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
'Show.S01E01.720p.HDTV.X264-DIMENSION.sfv'
),
'expected_associated_files': ['Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
],
'allowed_extensions': 'nfo',
'refine': True
},
{ # p5: No allowed extensions
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
'Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
'Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
'Show.S01E01.720p.HDTV.X264-DIMENSION.sfv'
),
'expected_associated_files': [],
'allowed_extensions': '',
'refine': True
},
{ # p6: Associated file based on RARed file
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
'show.101.720p-dimension.rar',
'show.101.720p-dimension.nfo'
),
'expected_associated_files': ['show.101.720p-dimension.nfo'],
'allowed_extensions': 'nfo'
},
{ # p7: 'Subtitles only' param for associated files
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
'Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
'Show.S01E01.720p.HDTV.X264-DIMENSION.nfo',
'Show.S01E01.720p.HDTV.X264-DIMENSION.sfv'
),
'expected_associated_files': ['Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt'],
'allowed_extensions': 'nfo,srt',
'subtitles_only': True
},
{ # p8: Subtitle in subfolder. Check subfolders enabled
'path': 'media/postprocess/',
'structure': (
'Show.S01E01.720p.HDTV.X264-DIMENSION.mkv',
{'subs': (
'RARBG.txt', 'Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
)}
),
'expected_associated_files': ['Show.S01E01.720p.HDTV.X264-DIMENSION.pt-BR.srt',
],
'allowed_extensions': 'nfo,srt',
'subfolders': True
},
])
def test_list_associated_files(p, create_structure, monkeypatch):
"""Run the test."""
# Given
test_path = create_structure(p['path'], structure=p['structure'])
path = os.path.join(test_path, os.path.normcase(p['path']))
file_path = os.path.join(path, p['structure'][0])
expected_associated_files = p['expected_associated_files']
subtitles_only = p.get('subtitles_only', False)
subfolders = p.get('subfolders', False)
refine = p.get('refine', False)
monkeypatch.setattr(app, 'ALLOWED_EXTENSIONS', p['allowed_extensions'])
monkeypatch.setattr(app, 'MOVE_ASSOCIATED_FILES', 1)
processor = PostProcessor(file_path)
processor._rar_basename = _rar_basename
# When
found_associated_files = processor.list_associated_files(file_path, subfolders=subfolders,
subtitles_only=subtitles_only, refine=refine)
associated_files_basenames = [os.path.basename(i) for i in found_associated_files]
# Then
assert set(associated_files_basenames) == set(expected_associated_files)
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.