text
stringlengths 2
100k
| meta
dict |
---|---|
// Copyright (c) Vladimir Sadov. All rights reserved.
//
// This file is distributed under the MIT License. See LICENSE.md for details.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace NonBlocking
{
/// <summary>
/// Scalable 32bit counter that can be used from multiple threads.
/// </summary>
public sealed class Counter32: CounterBase
{
private class Cell
{
[StructLayout(LayoutKind.Explicit, Size = CACHE_LINE * 2 - OBJ_HEADER_SIZE)]
public struct SpacedCounter
{
[FieldOffset(CACHE_LINE - OBJ_HEADER_SIZE)]
public int cnt;
}
public SpacedCounter counter;
}
// spaced out counters
private Cell[] cells;
// default counter
private int cnt;
// delayed estimated count
private int lastCnt;
/// <summary>
/// Initializes a new instance of the <see
/// cref="Counter32"/>
/// </summary>
public Counter32()
{
}
/// <summary>
/// Returns the value of the counter at the time of the call.
/// </summary>
/// <remarks>
/// The value may miss in-progress updates if the counter is being concurrently modified.
/// </remarks>
public int Value
{
get
{
var count = this.cnt;
var cells = this.cells;
if (cells != null)
{
for (int i = 0; i < cells.Length; i++)
{
var cell = cells[i];
if (cell != null)
{
count += cell.counter.cnt;
}
else
{
break;
}
}
}
return count;
}
}
/// <summary>
/// Returns the approximate value of the counter at the time of the call.
/// </summary>
/// <remarks>
/// EstimatedValue could be significantly cheaper to obtain, but may be slightly delayed.
/// </remarks>
public int EstimatedValue
{
get
{
if (this.cells == null)
{
return this.cnt;
}
var curTicks = (uint)Environment.TickCount;
// more than a millisecond passed?
if (curTicks != lastCntTicks)
{
lastCntTicks = curTicks;
lastCnt = Value;
}
return lastCnt;
}
}
/// <summary>
/// Increments the counter by 1.
/// </summary>
public void Increment()
{
int curCellCount = this.cellCount;
var drift = increment(ref GetCntRef(curCellCount));
if (drift != 0)
{
TryAddCell(curCellCount);
}
}
/// <summary>
/// Decrements the counter by 1.
/// </summary>
public void Decrement()
{
int curCellCount = this.cellCount;
var drift = decrement(ref GetCntRef(curCellCount));
if (drift != 0)
{
TryAddCell(curCellCount);
}
}
/// <summary>
/// Increments the counter by 'value'.
/// </summary>
public void Add(int value)
{
int curCellCount = this.cellCount;
var drift = add(ref GetCntRef(curCellCount), value);
if (drift != 0)
{
TryAddCell(curCellCount);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ref int GetCntRef(int curCellCount)
{
ref var cntRef = ref cnt;
Cell[] cells;
if ((cells = this.cells) != null && curCellCount > 1)
{
var cell = cells[GetIndex((uint)curCellCount)];
if (cell != null)
{
cntRef = ref cell.counter.cnt;
}
}
return ref cntRef;
}
private static int increment(ref int val)
{
return -val - 1 + Interlocked.Increment(ref val);
}
private static int add(ref int val, int inc)
{
return -val - inc + Interlocked.Add(ref val, inc);
}
private static int decrement(ref int val)
{
return val - 1 - Interlocked.Decrement(ref val);
}
private void TryAddCell(int curCellCount)
{
if (curCellCount < s_MaxCellCount)
{
TryAddCellCore(curCellCount);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void TryAddCellCore(int curCellCount)
{
var cells = this.cells;
if (cells == null)
{
var newCells = new Cell[s_MaxCellCount];
cells = Interlocked.CompareExchange(ref this.cells, newCells, null) ?? newCells;
}
if (cells[curCellCount] == null)
{
Interlocked.CompareExchange(ref cells[curCellCount], new Cell(), null);
}
if (this.cellCount == curCellCount)
{
Interlocked.CompareExchange(ref this.cellCount, curCellCount + 1, curCellCount);
//if (Interlocked.CompareExchange(ref this.cellCount, curCellCount + 1, curCellCount) == curCellCount)
//{
// System.Console.WriteLine(curCellCount + 1);
//}
}
}
}
}
| {
"pile_set_name": "Github"
} |
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "runcmd", "runcmd\runcmd.vcproj", "{1C6185A9-871A-4F6E-9B2D-BE4399479784}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1C6185A9-871A-4F6E-9B2D-BE4399479784}.Debug|Win32.ActiveCfg = Debug|Win32
{1C6185A9-871A-4F6E-9B2D-BE4399479784}.Debug|Win32.Build.0 = Debug|Win32
{1C6185A9-871A-4F6E-9B2D-BE4399479784}.Release|Win32.ActiveCfg = Release|Win32
{1C6185A9-871A-4F6E-9B2D-BE4399479784}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
| {
"pile_set_name": "Github"
} |
var cdb = require('cartodb.js-v3');
var _ = require('underscore-cdb-v3');
/**
* Default model for a privacy option.
*/
module.exports = cdb.core.Model.extend({
defaults: {
privacy: 'PUBLIC',
disabled: false,
selected: false,
password: undefined
},
validate: function(attrs) {
if (attrs.disabled && attrs.selected) {
return 'Option can not be disabled and selected at the same time';
}
},
classNames: function() {
return _.chain(['disabled', 'selected'])
.map(function(attr) { return !!this.attributes[attr] ? 'is-'+attr : undefined; }, this)
.compact().value().join(' ');
},
canSave: function() {
return !this.get('disabled');
},
/**
* @param vis {Object} instance of cdb.admin.Visualization
* @param callbacks {Object}
*/
saveToVis: function(vis, callbacks) {
return vis.save(this._attrsToSave(), _.extend({ wait: true }, callbacks));
},
/**
* @returns {Object} attrs
* @protected
*/
_attrsToSave: function() {
return _.pick(this.attributes, 'privacy', 'password');
}
});
| {
"pile_set_name": "Github"
} |
{
"name": "MUSUBii",
"site": {
"title": "MUSUBii",
"description": "MUSUBiiは日本語サイトのインブラウザデザインを想定したシンプルで薄味のレスポンシブ対応CSSフレームワークです。",
"url": "https://musubii.qranoko.jp",
"twitter_id": "Qrac_JP",
"start_year": "2016"
},
"menus": [
{
"id": "getting-started",
"heading": "Getting Started",
"items": [
{
"id": "introduction",
"path": "/getting-started/introduction",
"title": "Introduction"
},
{
"id": "basic-structure",
"path": "/getting-started/basic-structure",
"title": "Basic Structure"
},
{
"id": "using-with-scss",
"path": "/getting-started/using-with-scss",
"title": "Using with SCSS"
},
{
"id": "using-with-postcss",
"path": "/getting-started/using-with-postcss",
"title": "Using with PostCSS"
},
{
"id": "css-variables",
"path": "/getting-started/css-variables",
"title": "CSS Variables"
},
{
"id": "dark-mode",
"path": "/getting-started/dark-mode",
"title": "Dark Mode"
},
{
"id": "support",
"path": "/getting-started/support",
"title": "Support"
},
{
"id": "license",
"path": "/getting-started/license",
"title": "License"
}
]
},
{
"id": "installation",
"heading": "Installation",
"items": [
{
"id": "npm",
"path": "/installation/npm",
"title": "npm"
},
{
"id": "next",
"path": "/installation/next",
"title": "Next"
},
{
"id": "gatsby",
"path": "/installation/gatsby",
"title": "Gatsby"
},
{
"id": "nuxt",
"path": "/installation/nuxt",
"title": "Nuxt"
},
{
"id": "gridsome",
"path": "/installation/gridsome",
"title": "Gridsome"
},
{
"id": "gulp",
"path": "/installation/gulp",
"title": "gulp"
},
{
"id": "cdn",
"path": "/installation/cdn",
"title": "CDN"
}
]
},
{
"id": "migration",
"heading": "Migration",
"items": [
{
"id": "v6-6-to-v7",
"path": "/migration/v6-6-to-v7",
"title": "v6.6.0 → v7.0.0"
},
{
"id": "v7-alpha-42-to-v7",
"path": "/migration/v7-alpha-42-to-v7",
"title": "v7.0.0-α → v7.0.0"
}
]
},
{
"id": "configs",
"heading": "Configs",
"items": [
{
"id": "variables",
"heading": "Variables",
"items": [
{
"id": "option",
"path": "/configs/variables/option",
"title": "Option"
},
{
"id": "breakpoint",
"path": "/configs/variables/breakpoint",
"title": "Break Point"
},
{
"id": "color",
"path": "/configs/variables/color",
"title": "Color"
},
{
"id": "font",
"path": "/configs/variables/font",
"title": "Font"
},
{
"id": "radius",
"path": "/configs/variables/radius",
"title": "Radius"
},
{
"id": "meter",
"path": "/configs/variables/meter",
"title": "Meter"
},
{
"id": "global",
"path": "/configs/variables/global",
"title": "Global"
}
]
},
{
"id": "mixins",
"heading": "Mixins",
"items": [
{
"id": "mediaquery",
"path": "/configs/mixins/mediaquery",
"title": "Media Query"
},
{
"id": "placeholder",
"path": "/configs/mixins/placeholder",
"title": "Placeholder"
},
{
"id": "safearea",
"path": "/configs/mixins/safearea",
"title": "Safe Area"
},
{
"id": "generate",
"path": "/configs/mixins/generate",
"title": "Generate"
}
]
},
{
"id": "themes",
"heading": "Themes",
"items": [
{
"id": "theme-common",
"path": "/configs/themes/theme-common",
"title": "Theme Common"
},
{
"id": "theme-light",
"path": "/configs/themes/theme-light",
"title": "Theme Light"
},
{
"id": "theme-dark",
"path": "/configs/themes/theme-dark",
"title": "Theme Dark"
},
{
"id": "convert",
"path": "/configs/themes/convert",
"title": "Convert"
}
]
}
]
},
{
"id": "styles",
"heading": "Styles",
"items": [
{
"id": "bases",
"heading": "Bases",
"items": [
{
"id": "root-light",
"path": "/styles/bases/root-light",
"title": "Root Light"
},
{
"id": "root-dark",
"path": "/styles/bases/root-dark",
"title": "Root Dark"
},
{
"id": "reset",
"path": "/styles/bases/reset",
"title": "Reset"
},
{
"id": "html",
"path": "/styles/bases/html",
"title": "HTML"
}
]
},
{
"id": "layouts",
"heading": "Layouts",
"items": [
{
"id": "section",
"path": "/styles/layouts/section",
"title": "Section"
},
{
"id": "grid",
"path": "/styles/layouts/grid",
"title": "Grid"
},
{
"id": "card",
"path": "/styles/layouts/card",
"title": "Card"
},
{
"id": "box",
"path": "/styles/layouts/box",
"title": "Box"
},
{
"id": "joint",
"path": "/styles/layouts/joint",
"title": "Joint"
}
]
},
{
"id": "elements",
"heading": "Elements",
"items": [
{
"id": "text",
"path": "/styles/elements/text",
"title": "Text"
},
{
"id": "button",
"path": "/styles/elements/button",
"title": "Button"
},
{
"id": "badge",
"path": "/styles/elements/badge",
"title": "Badge"
},
{
"id": "list",
"path": "/styles/elements/list",
"title": "List"
},
{
"id": "table",
"path": "/styles/elements/table",
"title": "Table"
},
{
"id": "form",
"path": "/styles/elements/form",
"title": "Form"
},
{
"id": "iframe",
"path": "/styles/elements/iframe",
"title": "iframe"
},
{
"id": "icon",
"path": "/styles/elements/icon",
"title": "Icon"
},
{
"id": "alert",
"path": "/styles/elements/alert",
"title": "Alert"
},
{
"id": "wysiwyg",
"path": "/styles/elements/wysiwyg",
"title": "WYSIWYG"
}
]
},
{
"id": "utilities",
"heading": "Utilities",
"items": [
{
"id": "display",
"path": "/styles/utilities/display",
"title": "Display"
},
{
"id": "size",
"path": "/styles/utilities/size",
"title": "Size"
},
{
"id": "flex",
"path": "/styles/utilities/flex",
"title": "Flex"
},
{
"id": "space",
"path": "/styles/utilities/space",
"title": "Space"
},
{
"id": "margin",
"path": "/styles/utilities/margin",
"title": "Margin"
},
{
"id": "padding",
"path": "/styles/utilities/padding",
"title": "Padding"
},
{
"id": "overflow",
"path": "/styles/utilities/overflow",
"title": "Overflow"
},
{
"id": "clearfix",
"path": "/styles/utilities/clearfix",
"title": "Clearfix"
}
]
}
]
}
]
}
| {
"pile_set_name": "Github"
} |
define("ace/snippets/fortran",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.snippetText =undefined;
exports.scope = "fortran";
}); (function() {
window.require(["ace/snippets/fortran"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<!--
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<html>
<head>
<meta charset="utf-8">
<title>CSS Test: various 'object-position' values on a fixed-size video element, with a PNG image and 'object-fit:contain'.</title>
<link rel="author" title="Daniel Holbert" href="mailto:[email protected]">
<link rel="help" href="http://www.w3.org/TR/css3-images/#sizing">
<link rel="help" href="http://www.w3.org/TR/css3-images/#the-object-fit">
<link rel="help" href="http://www.w3.org/TR/css3-images/#the-object-position">
<link rel="match" href="object-position-png-001-ref.html">
<style type="text/css">
video {
background: lightgray;
margin-right: 2px;
object-fit: contain;
float: left;
width: 20px;
height: 20px;
}
.op_y-7 { object-position: 50% -7% }
.op_y13 { object-position: 50% 13% }
.op_y23 { object-position: 50% 23% }
.op_y50 { object-position: 50% 50% }
.op_y75 { object-position: 50% 75% }
.op_y88 { object-position: 50% 88% }
.op_y111 { object-position: 50% 111% }
</style>
</head>
<body>
<video poster="support/colors-16x8.png" class="op_y-7"></video>
<video poster="support/colors-16x8.png" class="op_y13"></video>
<video poster="support/colors-16x8.png" class="op_y23"></video>
<video poster="support/colors-16x8.png" class="op_y50"></video>
<video poster="support/colors-16x8.png" class="op_y75"></video>
<video poster="support/colors-16x8.png" class="op_y88"></video>
<video poster="support/colors-16x8.png" class="op_y111"></video>
</body>
</html>
| {
"pile_set_name": "Github"
} |
Off-Topic • Re: Lustige Videos, Flashs, gifs, etc.
==================================================
Date: 2013-06-24 13:55:00

Statistik: Verfasst von
[Orbiter](http://forum.yacy-websuche.de/memberlist.php?mode=viewprofile&u=2)
--- Mo Jun 24, 2013 12:55 pm
------------------------------------------------------------------------
| {
"pile_set_name": "Github"
} |
.size 8000
.text@50
jp ltimaint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 30
ldff(00), a
xor a, a
ldff(ff), a
inc a
ldff(4d), a
stop, 00
ld a, fe
ldff(05), a
ldff(06), a
ld a, 04
ldff(07), a
ldff(ff), a
xor a, a
ldff(0f), a
ei
.text@1000
ltimaint:
nop
.text@11f4
ldff(0f), a
ldff a, (0f)
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
ld bc, 7a00
ld hl, 8000
ld d, 00
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
pop af
ld b, a
swap a
and a, 0f
ld(9800), a
ld a, b
and a, 0f
ld(9801), a
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
00 00 08 08 22 22 41 41
7f 7f 41 41 41 41 41 41
00 00 7e 7e 41 41 41 41
7e 7e 41 41 41 41 7e 7e
00 00 3e 3e 41 41 40 40
40 40 40 40 41 41 3e 3e
00 00 7e 7e 41 41 41 41
41 41 41 41 41 41 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 40 40
| {
"pile_set_name": "Github"
} |
<UserControl x:Class="Uno.UI.Samples.Content.UITests.ContentControlTestsControl.ContentControl_DefaultText"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Uno.UI.Samples.Content.UITests.ContentControlTests"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:Uno.UI.Samples.Controls"
xmlns:u="using:Uno.UI.Samples.Controls"
mc:Ignorable="d"
d:DesignHeight="1000"
d:DesignWidth="600">
<UserControl.Resources>
<Style x:Key="NextButtonStyle"
TargetType="Button">
<Setter Property="MinWidth"
Value="80" />
<Setter Property="MinHeight"
Value="66" />
<Setter Property="Background"
Value="Transparent" />
<Setter Property="BorderBrush"
Value="Blue" />
<Setter Property="BorderThickness"
Value="0" />
<Setter Property="Margin"
Value="0" />
<Setter Property="Padding"
Value="0" />
<Setter Property="HorizontalAlignment"
Value="Left" />
<Setter Property="HorizontalContentAlignment"
Value="Center" />
<Setter Property="VerticalContentAlignment"
Value="Center" />
<Setter Property="VerticalAlignment"
Value="Bottom" />
<Setter Property="FontWeight"
Value="Light" />
<Setter Property="FontSize"
Value="10" />
<Setter Property="Foreground"
Value="Blue" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="Pressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground"
Storyboard.TargetName="ContentPresenter">
<DiscreteObjectKeyFrame KeyTime="0"
Value="Yellow" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border x:Name="Border"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Margin="0">
<ContentPresenter x:Name="ContentPresenter"
AutomationProperties.AccessibilityView="Raw"
ContentTemplate="{TemplateBinding ContentTemplate}"
ContentTransitions="{TemplateBinding ContentTransitions}"
Content="{TemplateBinding Content}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
<!--Suppress: NVX004-->
<Border Background="Green"
Visibility="Collapsed" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<StackPanel Background="Gray">
<TextBlock Text="Should be black" />
<controls:SampleControl x:Name="sampleControl" SampleDescription="Demonstrates the behavior of the default textblock in a ContentControl." Foreground="Aqua">
<controls:SampleControl.SampleContent>
<DataTemplate>
<StackPanel Name="InnerStackPanel">
<TextBlock Text="test test test test" MaxLines="3" />
<Button Content="Should be centered horizontally"
Width="250"
BorderBrush="Red"
BorderThickness="1"
Style="{StaticResource NextButtonStyle}">
</Button>
</StackPanel>
</DataTemplate>
</controls:SampleControl.SampleContent>
</controls:SampleControl>
</StackPanel>
</UserControl>
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="refresh" content="0; url=https://docs.google.com/forms/d/e/1FAIpQLScVIOAllQg0Sc2djr81k_QGUUvLsfzGiUAgPdcTMJuqE7o6hg/viewform"/>
<title>FOSSASIA Volunteer Registration</title>
<meta name="description" content="FOSSASIA Volunteer Registration" />
<meta name="keywords" content="FOSSASIA Volunteer Registration" />
<meta name="generator" content="FOSSASIA Volunteer Registration" />
</head>
<body>
</body>
</html>
| {
"pile_set_name": "Github"
} |
Name: showPict
Type: property
Syntax: set the showPict of <card> to {true | false}
Summary:
This <property> is included in <LiveCode> for compatibility with
imported <HyperCard> stacks.
Associations: card
Introduced: 1.0
Platforms: desktop, server
Description:
In HyperCard, the <showPict> <property> determines whether the <card>
<image> is visible.
In LiveCode, setting this property does not cause a script error, but
doing so has no effect.
References: show (command), hide (command), property (glossary),
LiveCode (glossary), HyperCard (glossary), card (keyword),
image (keyword), visible (property)
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2019 Unbounded Systems, 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.
*/
import { PrimitiveComponent } from "@adpt/core";
import { ConnectToInstance } from "../ConnectTo";
import { NetworkScope } from "../NetworkService";
/**
* Abstract Redis component
*
* @remarks
* This component is used to denote a needed {@link https://redis.io | Redis} service.
* Users should use a style sheet to subsitute a concrete Redis instance that provides
* the service. {@link redis.TestRedis} is such a component, suitable for test
* environments.
*
* All implementations of this component should implmenent {@link ConnectToInstance}
* that provides a `REDIS_URI` variable of the form `redis://<hostname>:<port>`.
*
* @public
*/
export abstract class Redis extends PrimitiveComponent implements ConnectToInstance {
connectEnv(_scope?: NetworkScope) { return undefined; }
}
| {
"pile_set_name": "Github"
} |
<Canvas>
<Kind>42</Kind>
<Name>POINT LIGHT 1Settings</Name>
<IsMinified>0</IsMinified>
<XPosition>213.000045776</XPosition>
<YPosition>502.000000000</YPosition>
</Canvas>
<Widget>
<Kind>2</Kind>
<Name>ENABLE</Name>
<Value>1</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>X</Name>
<Value>0.000000000</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>Y</Name>
<Value>0.000000000</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>Z</Name>
<Value>0.000000000</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>AH</Name>
<Value>1.000000000</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>AS</Name>
<Value>0.000000000</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>AV</Name>
<Value>0.500000000</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>DH</Name>
<Value>1.000000000</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>DS</Name>
<Value>0.000000000</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>DV</Name>
<Value>0.500000000</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>SH</Name>
<Value>1.000000000</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>SS</Name>
<Value>0.000000000</Value>
</Widget>
<Widget>
<Kind>25</Kind>
<Name>SV</Name>
<Value>0.500000000</Value>
</Widget>
| {
"pile_set_name": "Github"
} |
var test = require("tap").test;
var nextTick = require('./');
test('should work', function (t) {
t.plan(5);
nextTick(function (a) {
t.ok(a);
nextTick(function (thing) {
t.equals(thing, 7);
}, 7);
}, true);
nextTick(function (a, b, c) {
t.equals(a, 'step');
t.equals(b, 3);
t.equals(c, 'profit');
}, 'step', 3, 'profit');
});
test('correct number of arguments', function (t) {
t.plan(1);
nextTick(function () {
t.equals(2, arguments.length, 'correct number');
}, 1, 2);
});
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env ruby
require_relative '../example'
example %q{
age = 19
if (age >= 18)
puts 'You can vote!'
else
puts 'You are too young to vote.'
end
}
example %q{
[0, 5, 57, 99, 101, 999].each do |weight|
puts weight
if (weight < 1)
puts 'very light'
elsif (weight < 10)
puts 'a bit of a load'
elsif (weight < 100)
puts 'heavy'
else
puts 'way too heavy'
end
end
}
example %q{
[0, 5, 57, 99, 101, 999].each do |weight|
puts weight
if weight < 1
puts 'very light'
elsif weight < 10
puts 'a bit of a load'
elsif weight < 100
puts 'heavy'
else
puts 'way too heavy'
end
end
}
example %q{
weight = 101
puts('way too heavy') if weight >= 100
}
example %q{
[99, 100, 101].each do |weight|
puts weight
puts('way too heavy') unless weight < 100
end
}
example %q{
[99, 100, 101].each do |weight|
puts weight
unless weight < 100
puts 'way too heavy'
end
end
}
| {
"pile_set_name": "Github"
} |
body = <<-EOF
<meta name="citation_title" content="Virtual Bumblebees Artificial Life Simulation">
<meta name="citation_author" content="P. Howard, II, James">
<meta name="citation_publication_date" content="2017/05/11">
<meta name="citation_journal_title" content="The Journal of Open Source Software">
<meta name="citation_pdf_url" content="http://www.theoj.org/joss-papers/joss.00256/10.21105.joss.00256.pdf">
<meta name="citation_doi" content="10.21105/joss.00256">
<meta name="citation_issn" content="2475-9066">
<div class="accepted-paper">
<h1>Virtual Bumblebees Artificial Life Simulation</h1>
<div class="columns links">
<div class="column four-fifths" style="padding-bottom: 10px;">
<strong>Authors</strong>
<ul class="author-list">
<li><a href="http://orcid.org/0000-0003-4530-1547" target="_blank">James P. Howard, II</a></li>
</ul>
</div>
<div class="one-third column">
<span class="repo">Repository:<br /><a href="https://github.com/howardjp/bumblebees">Repository link »</a></span>
</div>
<div class="one-third column">
<span class="paper">Paper:<br /><a href="http://www.theoj.org/joss-papers/joss.00256/10.21105.joss.00256.pdf">PDF link »</a></span>
</div>
<div class="one-third column">
<span class="paper">Review:<br /><a href="https://github.com/openjournals/joss-reviews/issues/256">View review issue »</a></span>
</div>
<div class="one-third column" style="padding-top: 20px;">
<span class="repo">DOI:<br /><a href="https://doi.org/10.21105/joss.00256">https://doi.org/10.21105/joss.00256</a></span>
</div>
<div class="one-third column" style="padding-top: 20px;">
<span class="paper">Status badge:<br /><img src="http://joss.theoj.org/papers/10.21105/joss.00256/status.svg"></span>
</div>
<div class="one-third column" style="padding-top: 20px;">
<span class="paper">Citation:<br />
<small>II, (2017). Virtual Bumblebees Artificial Life Simulation. <em>Journal of Open Source Software</em>, 2(13), 256, doi:10.21105/joss.00256</small>
</div>
</div>
<div class="paper-body">
<h1 id="summary">Summary</h1>
<p>In the 1980, Christopher Langton created the virtual ant or sometimes "vant" <span class="citation">(Langton 1986)</span>. The Langton ant is a cellular automaton such that a cell is occupied by the "ant." If the cell is black, the ant turns 90 degrees to the right and advances a single cell. If the cell is green, the ant turns 90 degrees to the left and advances a single cell. After exiting the cell, the ant flips the color of the cell. This leads to a variety of amazing interactions among multiple ants that effectively replicates eusocial behavior in a number of organisms.</p>
<p>In a popular book on artificial life, Levy describes the virtual ants slightly differently <span class="citation">(Levy 1992)</span>:</p>
<blockquote>
<p>The vant itself was a V-shaped construct that moved in the direction of its point. If the lead cell moved into a blank square on the imaginary grid, the vant continued moving in that direction. If the square was blue, the vant turned right and changed the color of that cell to yellow. If the square was yellow, the vant turned left and changed the color of the square to blue.</p>
</blockquote>
<p>Using Scrivner's implementation of the Langton Ant as a base <span class="citation">(Scrivener 2012)</span>, this software package implements the construction described by Levy in Javascript. This can be used to model eusocial behavior, network traffic, and other nonlinear problems.</p>
<h1 id="references" class="unnumbered">References</h1>
<div id="refs" class="references">
<div id="ref-langton:1986">
<p>Langton, Christopher G. 1986. “Studying Artificial Life with Cellular Automata.” <em>Physica D: Nonlinear Phenomena</em> 22 (1-3). Elsevier: 120–49.</p>
</div>
<div id="ref-levy:1992">
<p>Levy, Steven. 1992. <em>Artificial Life: The Quest for a New Creation</em>. New York: Pantheon.</p>
</div>
<div id="ref-scrivner:2012">
<p>Scrivener, Ross. 2012. “Langton’s Ants - in Javascript.” <a href="http://rossscrivener.co.uk/blog/langtons-ants-in-javascript" class="uri">http://rossscrivener.co.uk/blog/langtons-ants-in-javascript</a>.</p>
</div>
</div>
</div>
</div>
EOF
| {
"pile_set_name": "Github"
} |
//
// YPReplyTableFooterView.m
// Wuxianda
//
// Created by MichaelPPP on 16/7/8.
// Copyright © 2016年 michaelhuyp. All rights reserved.
//
#import "YPReplyTableFooterView.h"
@interface YPReplyTableFooterView ()
/** 更多评论按钮 */
@property (weak, nonatomic) IBOutlet UIButton *moreReplyBtn;
@end
@implementation YPReplyTableFooterView
#pragma mark - Override
- (void)awakeFromNib
{
[super awakeFromNib];
// self
self.autoresizingMask = UIViewAutoresizingNone;
}
@end
| {
"pile_set_name": "Github"
} |
<?php
/**
* Contains test class for /core/helpers/EEH_Parse_Shortcodes.helper.php
*
* @since 4.6
* @package Event Espresso
* @subpackage tests
*/
/**
* All tests for the EEH_Parse_Shortcodes class.
* The tests here are more integration type tests than pure unit tests due to the nature of the
* messages system.
*
* @since 4.6
* @package Event Espresso
* @subpackage tests
* @group messages
* @group agg
*/
class EEH_Parse_Shortcodes_Test extends EE_UnitTestCase
{
/**
* This will hold the created event object on setup, which can then be used to grab expected
* data from.
*
* @var EE_Event
*/
protected $_event;
/**
* This will hold the created datetime object on setup which can then be used to grab
* expected data from.
*
* @var EE_Datetime
*/
protected $_datetime;
/**
* This will hold the created ticket object on setup which can then be used to grab expected
* data from.
*
* @var null
*/
protected $_ticket;
/**
* Holds the mock class for EEH_Parse_Shortcodes
*
* @var EEH_Parse_Shortcodes_Mock
*/
protected $_parse_shortcodes_helper_mock;
public function setUp()
{
parent::setUp();
//all shortcode parse tests will require a full event to be setup with some datetimes and tickets.
$price = $this->factory->price_chained->create_object(array(
'PRC_name' => 'Not Free Price',
'PRC_amount' => '125.00',
));
$this->_ticket = $this->factory->ticket_chained->create_object(array('PRC_ID' => $price->ID()));
//update ticket price
$this->_ticket->set('TKT_price', '125.00');
$this->_ticket->set('TKT_name', 'Podracing Entry');
$this->_ticket->set('TKT_description', 'One entry in the event.');
$this->_datetime = $this->_ticket->first_datetime();
$this->_event = $this->_datetime->event();
//set the author of the event
$this->_event->set('EVT_wp_user', 1);
require_once EE_TESTS_DIR . 'mocks/core/helpers/EEH_Parse_Shortcodes_Mock.php';
$this->_parse_shortcodes_helper_mock = new EEH_Parse_Shortcodes_Mock;
}
/**
* This grabs an EE_Messages_Addressee object for the Preview data handler.
*
* @param string $context
* @return \EE_Messages_Addressee
*/
protected function _get_addressee($context = 'primary_attendee')
{
$aee = array();
$data = new EE_Messages_Preview_incoming_data(array('event_ids' => array($this->_event->ID())));
/**
* @see EE_message_type::_set_defautl_addressee_data()
*/
$addressee_data = array(
'billing' => $data->billing,
'taxes' => $data->taxes,
'tax_line_items' => $data->tax_line_items,
'additional_line_items' => $data->additional_line_items,
'grand_total_line_item' => $data->grand_total_line_item,
'txn' => $data->txn,
'payments' => $data->payments,
'payment' => isset($data->payment) ? $data->payment : null,
'reg_objs' => $data->reg_objs,
'registrations' => $data->registrations,
'datetimes' => $data->datetimes,
'tickets' => $data->tickets,
'line_items_with_children' => $data->line_items_with_children,
'questions' => $data->questions,
'answers' => $data->answers,
'txn_status' => $data->txn_status,
'total_ticket_count' => $data->total_ticket_count,
);
if (is_array($data->primary_attendee_data)) {
$addressee_data = array_merge($addressee_data, $data->primary_attendee_data);
$addressee_data['primary_att_obj'] = $data->primary_attendee_data['att_obj'];
$addressee_data['primary_reg_obj'] = $data->primary_attendee_data['reg_obj'];
}
/**
* @see EE_message_type::_process_data()
*/
switch ($context) {
case 'primary_attendee' :
case 'purchaser' :
$aee = $addressee_data;
$aee['events'] = $data->events;
$aee['attendees'] = $data->attendees;
break;
case 'attendee' :
//for the purpose of testing we're just going to do ONE attendee
$attendee = reset($data->attendees);
foreach ($attendee as $item => $value) {
$aee[$item] = $value;
if ($item == 'line_ref') {
foreach ($value as $event_id) {
$aee['events'][$event_id] = $data->events[$event_id];
}
}
}
$aee['reg_obj'] = array_shift($attendee['reg_objs']);
$aee['attendees'] = $data->attendees;
break;
case 'admin' :
//for the purpose of testing we're only setting up for the event we have active for testing.
$aee['user_id'] = $this->_event->get('EVT_wp_user');
$aee['events'] = $data->events;
$aee['attendees'] = $data->attendees;
}
return new EE_Messages_Addressee($aee);
}
/**
* This helper returns parsed content from the parser to be used for tests using the given params.
*
* @param string $messenger The slug for the messenger being tested.
* @param string $message_type The slug for the message type being tested.
* @param string $field The field being tested.
* @param string $context The context being tested.
* @param array|string $append Append content to a default template for testing with. If
* you want to append to multiple fields, then include an
* array indexed by field. Otherwise the string will be
* appended to the field sent in with the $field param.
* @param EE_Messages_Addressee $addressee Optionally include a
* messages addressee object if you do not wish
* to use the default one generated. This is
* useful for simulating exceptions and failures.
* @return string The parsed content.
*/
protected function _get_parsed_content($messenger, $message_type, $field, $context, $append = '', $addressee = null)
{
//grab the correct template @see EE_message_type::_get_templates()
/** @type EE_Message_Template_Group $mtpg */
$mtpg = EEM_Message_Template_Group::instance()->get_one(array(
array(
'MTP_messenger' => $messenger,
'MTP_message_type' => $message_type,
'MTP_is_global' => true,
),
));
$all_templates = $mtpg instanceof EE_Message_Template_Group ? $mtpg->context_templates() : array();
$templates = array();
foreach ($all_templates as $t_context => $template_fields) {
foreach ($template_fields as $template_field => $template_obj) {
$templates[$template_field][$t_context] = $template_obj->get('MTP_content');
}
}
//instantiate messenger and message type objects
$msg_class = 'EE_' . str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger))) . '_messenger';
$mt_class = 'EE_' . str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type))) . '_message_type';
/** @type EE_messenger $messenger */
$messenger = new $msg_class();
/** @type EE_message_type $message_type */
$message_type = new $mt_class();
//grab valid shortcodes and setup for parser.
$m_shortcodes = $messenger->get_valid_shortcodes();
$mt_shortcodes = $message_type->get_valid_shortcodes();
//just sending in the content field and primary_attendee context/data for testing.
$template = isset($templates[$field][$context]) ? $templates[$field][$context] : array();
/**
* if empty template then its possible that the requested field is inside the "content"
* field array.
*/
if (empty($template)) {
$template = isset($templates['content'][$context]) ? $templates['content'][$context] : array();
//verify the requested field is present
if (! empty($template) && is_array($template) && ! isset($template[$field])) {
return '';
}
}
//if $template is still empty then return an empty string
if (empty($template)) {
return '';
}
// any appends?
if (! empty($append)) {
if (is_array($template)) {
//we've already done a check for the presence of field above.
if (is_array($append)) {
foreach ($append as $a_field => $string) {
if (isset($template[$a_field])) {
$template[$a_field] = $template[$a_field] . $string;
}
}
} else {
$template[$field] = $template[$field] . $append;
}
} else {
//only append if $append is not an array because the $template is not an array.
if (! is_array($append)) {
$template .= $append;
}
}
}
$valid_shortcodes = isset($m_shortcodes[$field]) ? $m_shortcodes[$field] : $mt_shortcodes[$context];
$data = $addressee instanceof EE_Messages_Addressee ? $addressee : $this->_get_addressee();
//parser needs EE_Message object
$message = EE_Message_Factory::create(
array(
'MSG_messenger' => $messenger->name,
'MSG_message_type' => $message_type->name,
'MSG_context' => $context,
'GRP_ID' => $mtpg->ID(),
)
);
$parser = new EEH_Parse_Shortcodes();
return $parser->parse_message_template($template, $data, $valid_shortcodes, $message_type, $messenger,
$message);
}
/**
* Tests parsing the message template for email messenger, payment received message
* type.
*
* @group 7585
* @since 4.6
*/
public function test_parsing_email_payment_received()
{
$parsed = $this->_get_parsed_content('email', 'payment', 'content', 'primary_attendee');
//now that we have parsed let's test the results, note for the purpose of this test we are verifying transaction shortcodes and ticket shortcodes.
//testing [PRIMARY_REGISTRANT_FNAME], [PRIMARY_REGISTRANT_LNAME]
$this->assertContains('Luke Skywalker', $parsed);
//testing [PAYMENT_STATUS]
$this->assertContains('Incomplete', $parsed);
//testing [TXN_ID]
$this->assertContains('999999', $parsed);
//testing [TOTAL_COST] and [AMOUNT_DUE] (should be $125*3 + 20 shipping charge + taxes)
$total_cost = EEH_Template::format_currency('398.00');
$this->assertContains($total_cost, $parsed);
//but we should also have a count of TWO for this string
$this->assertEquals(2, substr_count($parsed, $total_cost));
//testing [AMOUNT_PAID]
$amount_paid = EEH_Template::format_currency('0');
$this->assertContains($amount_paid, $parsed);
//testing [TICKET_NAME]
$this->assertContains('Podracing Entry', $parsed);
//testing [TICKET_DESCRIPTION]
$this->assertContains('One entry in the event.', $parsed);
//testing [TICKET_PRICE]
$this->assertContains(EEH_Template::format_currency('125.00'), $parsed);
//testing [TKT_QTY_PURCHASED]
$expected = '<strong>Quantity Purchased:</strong> 3';
$this->assertContains($expected, $parsed,
'[TKT_QTY_PURCHASED] shortcode was not parsed correctly to the expected value which is 3');
}
/**
* Test parsing the html receipt message templates.
*
* @since 4.6
* @group 7623
*/
public function test_parsing_html_receipt()
{
//see https://events.codebasehq.com/projects/event-espresso/tickets/9337, I think when running all tests, html
//messenger is getting stuck deactivated and thus the generated message template for this test will be missing some
//info.
EE_Registry::instance()->load_lib('Message_Resource_Manager')->ensure_messenger_is_active('html');
//currently with @group 7623 just testing if there are any error notices.
$parsed = $this->_get_parsed_content('html', 'receipt', 'content', 'purchaser');
//testing [PAYMENT_GATEWAY]
$this->assertContains('Invoice', $parsed);
}
/**
* Test parsing the email registration message templates (registration approved).
*
* @since 4.6
* @group 7613
*/
public function test_parsing_email_registration()
{
//add in shortcodes for testing [ANSWER_*] as a part of the [ATTENDEE_LIST] parsing from the [EVENT_LIST] context.
$test_answer_attendee_list_event_list_append = array(
'event_list' => '[ATTENDEE_LIST]',
'attendee_list' => 'Custom Answer: [ANSWER_* What is your favorite planet?]',
'ticket_list' => '[ATTENDEE_LIST]',
'main' => '[ATTENDEE_LIST]',
);
$parsed = $this->_get_parsed_content('email', 'registration', 'attendee_list', 'attendee',
$test_answer_attendee_list_event_list_append);
//testing [ATTENDEE_LIST] and [ANSWER_*] which should appear three times (because [ATTENDEE_LIST] was added to three fields),
$this->assertEquals(3, substr_count($parsed, 'Custom Answer: Tattoine'));
}
/**
* This test is for testing an exception is thrown when invalid attendee
* object in the data sent to the parsers.
*
* @group 7659
* * @doesNotPerformAssertions
*/
public function test_invalid_attendee_obj_EE_Attendee_Shortcodes()
{
$addressee = $this->_get_addressee();
//manipulate to remove data
$addressee->registrations = array();
try {
$parsed_content = $this->_get_parsed_content('email', 'registration', 'content', 'admin', '', $addressee);
} catch (EE_Error $e) {
return;
}
$this->fail('Expected an exception for invalid EE_Attendee Object');
}
/**
* @group 10561
*/
public function test_is_conditional_shortcode()
{
//test is conditional shortcode
$this->assertTrue($this->_parse_shortcodes_helper_mock->is_conditional_shortcode('[IF_something_* id=10]'));
$non_conditional_expectations = array(
'[SOMETHING]',
'[WHEN_IF_NESTED]',
'[if_lowercase]',
'[/IF_CLOSING_TAG]'
);
foreach ($non_conditional_expectations as $non_conditional_expectation) {
//should not be conditional shortcode
$this->assertFalse(
$this->_parse_shortcodes_helper_mock->is_conditional_shortcode(
$non_conditional_expectation
),
sprintf(
'This shortcode pattern should not test as matching a conditional shortcode but it did: %s',
$non_conditional_expectation
)
);
}
}
} //end class EEH_Parse_Shortcodes_Test
| {
"pile_set_name": "Github"
} |
sap.ui.define([
'sap/ui/core/mvc/Controller',
'sap/ui/model/json/JSONModel'
],
function (Controller, JSONModel) {
"use strict";
return Controller.extend("sap.m.sample.PlanningCalendarAppointmentSizes.Page", {
onInit: function () {
// create model
var oModel = new JSONModel();
oModel.setData({
startDate: new Date("2017", "2", "08", "8", "0"),
people: [{
pic: "test-resources/sap/ui/documentation/sdk/images/John_Miller.png",
name: "John Miller",
role: "team member",
appointments: [
{
start: new Date("2017", "2", "7", "18", "00"),
end: new Date("2017", "2", "7", "19", "10"),
title: "Discussion of the plan",
info: "Online meeting",
type: "Type04",
tentative: false
},
{
start: new Date("2017", "2", "7", "14", "00"),
end: new Date("2017", "2", "7", "15", "15"),
title: "Department meeting",
type: "Type04",
tentative: false
},
{
start: new Date("2017", "2", "3", "10", "0"),
end: new Date("2017", "2", "7", "12", "0"),
title: "Workshop out of the country",
type: "Type07",
pic: "sap-icon://sap-ui5",
tentative: false
},
{
start: new Date("2017", "2", "8", "9", "0"),
end: new Date("2017", "2", "8", "11", "0"),
title: "Team meeting",
info: "room 105",
type: "Type01",
pic: "sap-icon://sap-ui5",
tentative: false
},
{
start: new Date("2017", "2", "8", "9", "30"),
end: new Date("2017", "2", "8", "11", "30"),
title: "Meeting with Max",
type: "Type02",
pic: "sap-icon://sap-ui5",
tentative: false
},
{
start: new Date("2017", "2", "8", "11", "0"),
end: new Date("2017", "2", "8", "13", "0"),
title: "Lunch",
info: "info",
description: "description",
type: "Type03",
pic: "",
tentative: true
},
{
start: new Date("2017", "2", "8", "11", "0"),
end: new Date("2017", "2", "8", "13", "0"),
title: "Meeting with the crew",
type: "Type04",
pic: "",
tentative: false
},
{
start: new Date("2017", "2", "9", "9", "0"),
end: new Date("2017", "2", "9", "16", "0"),
title: "Busy",
type: "Type08",
tentative: false
},
{
start: new Date("2017", "2", "10", "9", "0"),
end: new Date("2017", "2", "10", "11", "0"),
title: "Team meeting",
info: "room 105",
type: "Type01",
pic: "sap-icon://sap-ui5",
tentative: false
},
{
start: new Date("2017", "2", "10", "9", "30"),
end: new Date("2017", "2", "10", "16", "30"),
title: "Meeting with Max",
type: "Type02",
tentative: false
},
{
start: new Date("2017", "2", "11", "0", "0"),
end: new Date("2017", "2", "13", "23", "59"),
title: "Vacation",
info: "out of office",
type: "Type04",
tentative: false
},
{
start: new Date("2017", "2", "16", "00", "30"),
end: new Date("2017", "2", "16", "23", "30"),
title: "New Colleague",
info: "room 115",
type: "Type10",
tentative: true
},
{
start: new Date("2017", "9", "11", "0", "0"),
end: new Date("2017", "10", "13", "23", "59"),
title: "Vacation",
info: "out of office",
type: "Type04",
tentative: false
},
{
start: new Date("2017", "2", "8", "14", "0"),
end: new Date("2017", "2", "8", "15", "0"),
title: "Reminder",
type: "Type06"
}
]
},
{
pic: "sap-icon://employee",
name: "Max Mustermann",
role: "team member",
appointments: [{
start: new Date("2016", "11", "1", "00", "30"),
end: new Date("2017", "0", "31", "23", "30"),
title: "New product release",
info: "room 105",
type: "Type03",
tentative: true
},
{
start: new Date("2017", "2", "2", "08", "0"),
end: new Date("2017", "2", "2", "17", "0"),
title: "Education",
type: "Type05",
tentative: false
},
{
start: new Date("2017", "2", "3", "09", "00"),
end: new Date("2017", "2", "3", "10", "00"),
title: "New Product",
info: "room 105",
type: "Type03",
tentative: true
},
{
start: new Date("2017", "2", "8", "08", "0"),
end: new Date("2017", "2", "8", "13", "0"),
title: "Meet Donna",
type: "Type06",
tentative: false
},
{
start: new Date("2017", "2", "8", "13", "0"),
end: new Date("2017", "2", "9", "11", "0"),
title: "Team meeting",
info: "room 1",
type: "Type01",
pic: "sap-icon://sap-ui5",
tentative: false
},
{
start: new Date("2017", "2", "8", "13", "0"),
end: new Date("2017", "2", "8", "14", "59"),
title: "Team meeting2",
info: "room 2",
type: "Type01",
pic: "sap-icon://sap-ui5",
tentative: false
},
{
start: new Date("2017", "2", "9", "00", "00"),
end: new Date("2017", "2", "9", "23", "59"),
title: "Department meeting",
type: "Type04",
tentative: false
},
{
start: new Date("2017", "2", "12", "00", "00"),
end: new Date("2017", "2", "12", "12", "00"),
title: "Meeting with John",
type: "Type02",
tentative: false
},
{
start: new Date("2017", "2", "12", "12", "00"),
end: new Date("2017", "2", "12", "23", "59"),
title: "Team Building",
info: "out of office",
type: "Type10",
pic: "sap-icon://sap-ui5",
tentative: false
},
{
start: new Date("2017", "2", "13", "00", "00"),
end: new Date("2017", "2", "13", "12", "00"),
title: "New Product",
info: "room 325",
type: "Type07",
tentative: true
},
{
start: new Date("2017", "2", "13", "12", "00"),
end: new Date("2017", "2", "13", "23", "30"),
title: "New Product",
info: "room 105",
type: "Type03",
tentative: true
},
{
start: new Date("2017", "2", "14", "0", "0"),
end: new Date("2017", "2", "14", "12", "00"),
title: "Vacation",
info: "out of office",
type: "Type04",
tentative: false
},
{
start: new Date("2017", "2", "14", "12", "00"),
end: new Date("2017", "2", "14", "23", "30"),
title: "New product release",
info: "room 105",
type: "Type03",
tentative: true
}
],
headers: [{
start: new Date("2017", "2", "8", "8", "0"),
end: new Date("2017", "2", "8", "10", "0"),
title: "Development of UI5",
pic: "sap-icon://sap-ui5",
type: "Type07"
},
{
start: new Date("2017", "4", "1", "0", "0"),
end: new Date("2017", "7", "30", "23", "59"),
title: "New quarter",
type: "Type10",
tentative: false
}
]
}
]
});
this.getView().setModel(oModel);
},
handleAppointmentHeightChange: function (oEvent) {
var oPC = this.byId("PC1"),
sAppointmentHeight = oEvent.getParameter("selectedItem").getKey();
oPC.setAppointmentHeight(sAppointmentHeight);
},
handleSortChange: function (oEvent) {
//make a custom sort regarding alphabetical order
var oPC = this.byId("PC1"),
fnSelectedSort = oEvent.getParameter("selectedItem").getKey() === "custom" ? this.fnAlphabeticalOrder : null;
oPC.setCustomAppointmentsSorterCallback(fnSelectedSort);
},
handleAppointmentRoundingChange: function (oEvent){
var oPC = this.byId("PC1"),
sAppointmentRoundingWidth = oEvent.getParameter("selectedItem").getKey();
oPC.setAppointmentRoundWidth(sAppointmentRoundingWidth);
},
// custom function for appointments sort by alphabetical order
fnAlphabeticalOrder : function(oApp1, oApp2) {
if (oApp1.getTitle().toLowerCase() > oApp2.getTitle().toLowerCase()) {
return 1;
}
if (oApp1.getTitle().toLowerCase() < oApp2.getTitle().toLowerCase()) {
return -1;
}
return 0;
}
});
}); | {
"pile_set_name": "Github"
} |
function for$(makeNextFunc, $a$, compr) {
$i$for$();
if (compr===undefined) {compr = new for$.$$;}
Basic(compr);
Iterable($a$,compr);
compr.makeNextFunc = makeNextFunc;
return compr;
}
for$.$m$={nm:'Comprehension',pa:1,mod:$M$,d:['$','Iterable']};
function $i$for$() {
if (for$.$$===undefined) {
initTypeProto(for$, 'ceylon.language::Comprehension', $i$Basic(), $i$Iterable());
}
return for$;
}
$i$for$();
var for$$proto = for$.$$.prototype;
for$$proto.iterator = function() {
return for$iter(this.makeNextFunc(), this.$a$);
}
for$$proto.sequence = function() {
return Iterable.$$.prototype.sequence.call(this);
}
for$$proto.sequence.$m$={pa:3,mod:$M$,d:['$','Iterable','$m','sequence']}
x$.for$=for$;
function for$iter(nextFunc, $a$, it) {
$i$for$iter();
if (it===undefined) {it = new for$iter.$$;}
Basic(it);
Iterator($a$,it);
it.next = nextFunc;
return it;
}
for$iter.$m$={nm:'ComprehensionIterator',pa:1,mod:$M$,d:['$','Iterator']};
function $i$for$iter() {
if (for$iter.$$===undefined) {
initTypeProto(for$iter, 'ceylon.language::ComprehensionIterator',
$i$Basic(), $i$Iterator());
}
return for$iter;
}
$i$for$iter();
| {
"pile_set_name": "Github"
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Benoit Jacob <[email protected]>
// Copyright (C) 2015 Gael Guennebaud <[email protected]>
//
// 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/.
#if defined(EIGEN_TEST_PART_1)
// default
#elif defined(EIGEN_TEST_PART_2)
#define EIGEN_MAX_STATIC_ALIGN_BYTES 16
#define EIGEN_MAX_ALIGN_BYTES 16
#elif defined(EIGEN_TEST_PART_3)
#define EIGEN_MAX_STATIC_ALIGN_BYTES 32
#define EIGEN_MAX_ALIGN_BYTES 32
#elif defined(EIGEN_TEST_PART_4)
#define EIGEN_MAX_STATIC_ALIGN_BYTES 64
#define EIGEN_MAX_ALIGN_BYTES 64
#endif
#include "main.h"
typedef Matrix<float, 6,1> Vector6f;
typedef Matrix<float, 8,1> Vector8f;
typedef Matrix<float, 12,1> Vector12f;
typedef Matrix<double, 5,1> Vector5d;
typedef Matrix<double, 6,1> Vector6d;
typedef Matrix<double, 7,1> Vector7d;
typedef Matrix<double, 8,1> Vector8d;
typedef Matrix<double, 9,1> Vector9d;
typedef Matrix<double,10,1> Vector10d;
typedef Matrix<double,12,1> Vector12d;
struct TestNew1
{
MatrixXd m; // good: m will allocate its own array, taking care of alignment.
TestNew1() : m(20,20) {}
};
struct TestNew2
{
Matrix3d m; // good: m's size isn't a multiple of 16 bytes, so m doesn't have to be 16-byte aligned,
// 8-byte alignment is good enough here, which we'll get automatically
};
struct TestNew3
{
Vector2f m; // good: m's size isn't a multiple of 16 bytes, so m doesn't have to be 16-byte aligned
};
struct TestNew4
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Vector2d m;
float f; // make the struct have sizeof%16!=0 to make it a little more tricky when we allow an array of 2 such objects
};
struct TestNew5
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
float f; // try the f at first -- the EIGEN_ALIGN_MAX attribute of m should make that still work
Matrix4f m;
};
struct TestNew6
{
Matrix<float,2,2,DontAlign> m; // good: no alignment requested
float f;
};
template<bool Align> struct Depends
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(Align)
Vector2d m;
float f;
};
template<typename T>
void check_unalignedassert_good()
{
T *x, *y;
x = new T;
delete x;
y = new T[2];
delete[] y;
}
#if EIGEN_MAX_STATIC_ALIGN_BYTES>0
template<typename T>
void construct_at_boundary(int boundary)
{
char buf[sizeof(T)+256];
size_t _buf = reinterpret_cast<internal::UIntPtr>(buf);
_buf += (EIGEN_MAX_ALIGN_BYTES - (_buf % EIGEN_MAX_ALIGN_BYTES)); // make 16/32/...-byte aligned
_buf += boundary; // make exact boundary-aligned
T *x = ::new(reinterpret_cast<void*>(_buf)) T;
x[0].setZero(); // just in order to silence warnings
x->~T();
}
#endif
void unalignedassert()
{
#if EIGEN_MAX_STATIC_ALIGN_BYTES>0
construct_at_boundary<Vector2f>(4);
construct_at_boundary<Vector3f>(4);
construct_at_boundary<Vector4f>(16);
construct_at_boundary<Vector6f>(4);
construct_at_boundary<Vector8f>(EIGEN_MAX_ALIGN_BYTES);
construct_at_boundary<Vector12f>(16);
construct_at_boundary<Matrix2f>(16);
construct_at_boundary<Matrix3f>(4);
construct_at_boundary<Matrix4f>(EIGEN_MAX_ALIGN_BYTES);
construct_at_boundary<Vector2d>(16);
construct_at_boundary<Vector3d>(4);
construct_at_boundary<Vector4d>(EIGEN_MAX_ALIGN_BYTES);
construct_at_boundary<Vector5d>(4);
construct_at_boundary<Vector6d>(16);
construct_at_boundary<Vector7d>(4);
construct_at_boundary<Vector8d>(EIGEN_MAX_ALIGN_BYTES);
construct_at_boundary<Vector9d>(4);
construct_at_boundary<Vector10d>(16);
construct_at_boundary<Vector12d>(EIGEN_MAX_ALIGN_BYTES);
construct_at_boundary<Matrix2d>(EIGEN_MAX_ALIGN_BYTES);
construct_at_boundary<Matrix3d>(4);
construct_at_boundary<Matrix4d>(EIGEN_MAX_ALIGN_BYTES);
construct_at_boundary<Vector2cf>(16);
construct_at_boundary<Vector3cf>(4);
construct_at_boundary<Vector2cd>(EIGEN_MAX_ALIGN_BYTES);
construct_at_boundary<Vector3cd>(16);
#endif
check_unalignedassert_good<TestNew1>();
check_unalignedassert_good<TestNew2>();
check_unalignedassert_good<TestNew3>();
check_unalignedassert_good<TestNew4>();
check_unalignedassert_good<TestNew5>();
check_unalignedassert_good<TestNew6>();
check_unalignedassert_good<Depends<true> >();
#if EIGEN_MAX_STATIC_ALIGN_BYTES>0
if(EIGEN_MAX_ALIGN_BYTES>=16)
{
VERIFY_RAISES_ASSERT(construct_at_boundary<Vector4f>(8));
VERIFY_RAISES_ASSERT(construct_at_boundary<Vector8f>(8));
VERIFY_RAISES_ASSERT(construct_at_boundary<Vector12f>(8));
VERIFY_RAISES_ASSERT(construct_at_boundary<Vector2d>(8));
VERIFY_RAISES_ASSERT(construct_at_boundary<Vector4d>(8));
VERIFY_RAISES_ASSERT(construct_at_boundary<Vector6d>(8));
VERIFY_RAISES_ASSERT(construct_at_boundary<Vector8d>(8));
VERIFY_RAISES_ASSERT(construct_at_boundary<Vector10d>(8));
VERIFY_RAISES_ASSERT(construct_at_boundary<Vector12d>(8));
// Complexes are disabled because the compiler might aggressively vectorize
// the initialization of complex coeffs to 0 before we can check for alignedness
//VERIFY_RAISES_ASSERT(construct_at_boundary<Vector2cf>(8));
VERIFY_RAISES_ASSERT(construct_at_boundary<Vector4i>(8));
}
for(int b=8; b<EIGEN_MAX_ALIGN_BYTES; b+=8)
{
if(b<32) VERIFY_RAISES_ASSERT(construct_at_boundary<Vector8f>(b));
if(b<64) VERIFY_RAISES_ASSERT(construct_at_boundary<Matrix4f>(b));
if(b<32) VERIFY_RAISES_ASSERT(construct_at_boundary<Vector4d>(b));
if(b<32) VERIFY_RAISES_ASSERT(construct_at_boundary<Matrix2d>(b));
if(b<128) VERIFY_RAISES_ASSERT(construct_at_boundary<Matrix4d>(b));
//if(b<32) VERIFY_RAISES_ASSERT(construct_at_boundary<Vector2cd>(b));
}
#endif
}
void test_unalignedassert()
{
CALL_SUBTEST(unalignedassert());
}
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0 */
// Copyright (C) 2019 Hangzhou C-SKY Microsystems co.,ltd.
#ifndef _ASM_CSKY_PERF_REGS_H
#define _ASM_CSKY_PERF_REGS_H
/* Index of struct pt_regs */
enum perf_event_csky_regs {
PERF_REG_CSKY_TLS,
PERF_REG_CSKY_LR,
PERF_REG_CSKY_PC,
PERF_REG_CSKY_SR,
PERF_REG_CSKY_SP,
PERF_REG_CSKY_ORIG_A0,
PERF_REG_CSKY_A0,
PERF_REG_CSKY_A1,
PERF_REG_CSKY_A2,
PERF_REG_CSKY_A3,
PERF_REG_CSKY_REGS0,
PERF_REG_CSKY_REGS1,
PERF_REG_CSKY_REGS2,
PERF_REG_CSKY_REGS3,
PERF_REG_CSKY_REGS4,
PERF_REG_CSKY_REGS5,
PERF_REG_CSKY_REGS6,
PERF_REG_CSKY_REGS7,
PERF_REG_CSKY_REGS8,
PERF_REG_CSKY_REGS9,
#if defined(__CSKYABIV2__)
PERF_REG_CSKY_EXREGS0,
PERF_REG_CSKY_EXREGS1,
PERF_REG_CSKY_EXREGS2,
PERF_REG_CSKY_EXREGS3,
PERF_REG_CSKY_EXREGS4,
PERF_REG_CSKY_EXREGS5,
PERF_REG_CSKY_EXREGS6,
PERF_REG_CSKY_EXREGS7,
PERF_REG_CSKY_EXREGS8,
PERF_REG_CSKY_EXREGS9,
PERF_REG_CSKY_EXREGS10,
PERF_REG_CSKY_EXREGS11,
PERF_REG_CSKY_EXREGS12,
PERF_REG_CSKY_EXREGS13,
PERF_REG_CSKY_EXREGS14,
PERF_REG_CSKY_HI,
PERF_REG_CSKY_LO,
PERF_REG_CSKY_DCSR,
#endif
PERF_REG_CSKY_MAX,
};
#endif /* _ASM_CSKY_PERF_REGS_H */
| {
"pile_set_name": "Github"
} |
//
// Copyright (C) DataStax Inc.
//
// 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.
//
namespace Cassandra.Requests
{
internal class ValidHost
{
private ValidHost(Host host, HostDistance distance)
{
Host = host;
Distance = distance;
}
public Host Host { get; }
public HostDistance Distance { get; }
/// <summary>
/// Builds a <see cref="ValidHost"/> instance.
/// </summary>
/// <returns>Newly built instance if valid or <code>null</code> if not valid
/// (e.g. the host is ignored or the driver sees it as down)</returns>
public static ValidHost New(Host host, HostDistance distance)
{
if (distance == HostDistance.Ignored)
{
// We should not use an ignored host
return null;
}
if (!host.IsUp)
{
// The host is not considered UP by the driver.
// We could have filtered earlier by hosts that are considered UP, but we must
// check the host distance first.
return null;
}
return new ValidHost(host, distance);
}
}
} | {
"pile_set_name": "Github"
} |
name: Linter
on: [push, pull_request]
jobs:
linter:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Use Node.js 12.x
uses: actions/setup-node@v1
with:
node-version: '12.x'
- name: Cache NPM dependencies
uses: actions/cache@v1
with:
path: node_modules
key: ${{ runner.OS }}-npm-cache
restore-keys: |
${{ runner.OS }}-npm-cache
- name: Install Dependencies
run: yarn --frozen-lockfile --non-interactive
- name: Lint
run: |
yarn tslint
env:
CI: true
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.highlight.languages._all"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.highlight.languages._all"] = true;
dojo.provide("dojox.highlight.languages._all");
/* groups of similar languages */
dojo.require("dojox.highlight.languages._static");
dojo.require("dojox.highlight.languages._dynamic");
dojo.require("dojox.highlight.languages._www");
}
| {
"pile_set_name": "Github"
} |
import UIKit
public typealias Label = Text
public typealias UText = Text
/// aka `UILabel`
open class Text: UILabel, AnyDeclarativeProtocol, DeclarativeProtocolInternal {
public var declarativeView: Text { self }
public lazy var properties = Properties<Text>()
lazy var _properties = PropertiesInternal()
@State public var height: CGFloat = 0
@State public var width: CGFloat = 0
@State public var top: CGFloat = 0
@State public var leading: CGFloat = 0
@State public var left: CGFloat = 0
@State public var trailing: CGFloat = 0
@State public var right: CGFloat = 0
@State public var bottom: CGFloat = 0
@State public var centerX: CGFloat = 0
@State public var centerY: CGFloat = 0
var __height: State<CGFloat> { _height }
var __width: State<CGFloat> { _width }
var __top: State<CGFloat> { _top }
var __leading: State<CGFloat> { _leading }
var __left: State<CGFloat> { _left }
var __trailing: State<CGFloat> { _trailing }
var __right: State<CGFloat> { _right }
var __bottom: State<CGFloat> { _bottom }
var __centerX: State<CGFloat> { _centerX }
var __centerY: State<CGFloat> { _centerY }
public init (_ text: String) {
super.init(frame: .zero)
_setup()
self.text(text)
}
public init (_ localized: LocalizedString...) {
super.init(frame: .zero)
_setup()
self.text(String(localized))
}
public init (_ localized: [LocalizedString]) {
super.init(frame: .zero)
_setup()
self.text(String(localized))
}
public init (_ state: State<String>) {
super.init(frame: .zero)
_setup()
text(state)
}
public init (attributed state: State<[AttrStr]>) {
super.init(frame: .zero)
_setup()
attributedText(state)
}
public init (attributed attributedStrings: AttrStr...) {
super.init(frame: .zero)
_setup()
attributedText(attributedStrings)
}
public init (attributed attributedStrings: [AttrStr]) {
super.init(frame: .zero)
_setup()
attributedText(attributedStrings)
}
public init<V>(_ expressable: ExpressableState<V, String>) {
super.init(frame: .zero)
_setup()
text(expressable)
}
public init<V>(attributed expressable: ExpressableState<V, [AttrStr]>) {
super.init(frame: .zero)
_setup()
attributedText(expressable)
}
public init (@StateStringBuilder stateString: @escaping StateStringBuilder.Handler) {
super.init(frame: .zero)
_setup()
text(stateString())
}
public init (@StateStringBuilder stateString: @escaping StateAttrStringBuilder.Handler) {
super.init(frame: .zero)
_setup()
attributedText(stateString())
}
public override init(frame: CGRect) {
super.init(frame: frame)
_setup()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func _setup() {
translatesAutoresizingMaskIntoConstraints = false
clipsToBounds = true
}
open override func layoutSubviews() {
super.layoutSubviews()
onLayoutSubviews()
}
open override func didMoveToSuperview() {
super.didMoveToSuperview()
movedToSuperview()
}
}
extension Text: Refreshable {
/// Refreshes using `RefreshHandler`
public func refresh() {
if let stateString = _properties.stateString {
text(stateString())
} else if let stateAttrString = _properties.stateAttrString {
attributedText(stateAttrString())
}
}
}
extension Text: _Fontable {
func _setFont(_ v: UIFont?) {
font = v
}
}
extension Text: _Textable {
var _stateString: StateStringBuilder.Handler? {
get { _properties.stateString }
set { _properties.stateString = newValue }
}
var _stateAttrString: StateAttrStringBuilder.Handler? {
get { _properties.stateAttrString }
set { _properties.stateAttrString = newValue }
}
var _textChangeTransition: UIView.AnimationOptions? {
get { _properties.textChangeTransition }
set { _properties.textChangeTransition = newValue }
}
func _setText(_ v: String?) {
text = v
}
func _setText(_ v: NSMutableAttributedString?) {
attributedText = v
}
}
extension Text: _ViewTransitionable {
var _transitionableView: UIView { self }
}
extension Text: _Colorable {
var _colorState: State<UIColor> { properties.textColorState }
func _setColor(_ v: UIColor?) {
textColor = v
properties.textColor = v ?? .clear
}
}
extension Text: _TextAligmentable {
func _setTextAlignment(v: NSTextAlignment) {
textAlignment = v
}
}
extension Text: _TextLineable {
func _setNumbelOfLines(_ v: Int) {
numberOfLines = v
}
}
extension Text: _TextLineBreakModeable {
func _setLineBreakMode(_ v: NSLineBreakMode) {
lineBreakMode = v
}
}
extension Text: _TextAdjustsFontSizeable {
func _setAdjustsFontSizeToFitWidth(_ v: Bool) {
adjustsFontSizeToFitWidth = v
}
}
extension Text: _TextScaleable {
func _setMinimumScaleFactor(_ v: CGFloat) {
minimumScaleFactor = v
}
}
| {
"pile_set_name": "Github"
} |
// eslint-disable-next-line import/no-unresolved
import raxTestRenderer from 'rax-test-renderer';
function getRenderedTree(story: any, context: any, { renderer, ...rendererOptions }: any) {
const storyElement = story.render();
const currentRenderer = renderer || raxTestRenderer.create;
const tree = currentRenderer(storyElement, rendererOptions);
return tree;
}
export default getRenderedTree;
| {
"pile_set_name": "Github"
} |
**To list chat rooms**
The following ``list-rooms`` example displays a list of chat rooms in the specified account. The list is filtered to only those chat rooms that the specified member belongs to. ::
aws chime list-rooms \
--account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
--member-id 1ab2345c-67de-8901-f23g-45h678901j2k
Output::
{
"Room": {
"RoomId": "abcd1e2d-3e45-6789-01f2-3g45h67i890j",
"Name": "teamRoom",
"AccountId": "12a3456b-7c89-012d-3456-78901e23fg45",
"CreatedBy": "arn:aws:iam::111122223333:user/alejandro",
"CreatedTimestamp": "2019-12-02T22:29:31.549Z",
"UpdatedTimestamp": "2019-12-02T22:33:19.310Z"
}
}
For more information, see `Creating a Chat Room <https://docs.aws.amazon.com/chime/latest/ug/chime-chat-room.html>`__ in the *Amazon Chime User Guide*. | {
"pile_set_name": "Github"
} |
Manifest-Version: 1
Bundle-ManifestVersion: 2
Bundle-SymbolicName: c
Bundle-Version: 1.0.0
Provide-Capability: ns;ns=c
| {
"pile_set_name": "Github"
} |
// Copyright 2011 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package datastore
import (
"encoding/base64"
"errors"
"fmt"
"math"
"reflect"
"strings"
"github.com/golang/protobuf/proto"
"golang.org/x/net/context"
"google.golang.org/appengine/internal"
pb "google.golang.org/appengine/internal/datastore"
)
type operator int
const (
lessThan operator = iota
lessEq
equal
greaterEq
greaterThan
)
var operatorToProto = map[operator]*pb.Query_Filter_Operator{
lessThan: pb.Query_Filter_LESS_THAN.Enum(),
lessEq: pb.Query_Filter_LESS_THAN_OR_EQUAL.Enum(),
equal: pb.Query_Filter_EQUAL.Enum(),
greaterEq: pb.Query_Filter_GREATER_THAN_OR_EQUAL.Enum(),
greaterThan: pb.Query_Filter_GREATER_THAN.Enum(),
}
// filter is a conditional filter on query results.
type filter struct {
FieldName string
Op operator
Value interface{}
}
type sortDirection int
const (
ascending sortDirection = iota
descending
)
var sortDirectionToProto = map[sortDirection]*pb.Query_Order_Direction{
ascending: pb.Query_Order_ASCENDING.Enum(),
descending: pb.Query_Order_DESCENDING.Enum(),
}
// order is a sort order on query results.
type order struct {
FieldName string
Direction sortDirection
}
// NewQuery creates a new Query for a specific entity kind.
//
// An empty kind means to return all entities, including entities created and
// managed by other App Engine features, and is called a kindless query.
// Kindless queries cannot include filters or sort orders on property values.
func NewQuery(kind string) *Query {
return &Query{
kind: kind,
limit: -1,
}
}
// Query represents a datastore query.
type Query struct {
kind string
ancestor *Key
filter []filter
order []order
projection []string
distinct bool
keysOnly bool
eventual bool
limit int32
offset int32
start *pb.CompiledCursor
end *pb.CompiledCursor
err error
}
func (q *Query) clone() *Query {
x := *q
// Copy the contents of the slice-typed fields to a new backing store.
if len(q.filter) > 0 {
x.filter = make([]filter, len(q.filter))
copy(x.filter, q.filter)
}
if len(q.order) > 0 {
x.order = make([]order, len(q.order))
copy(x.order, q.order)
}
return &x
}
// Ancestor returns a derivative query with an ancestor filter.
// The ancestor should not be nil.
func (q *Query) Ancestor(ancestor *Key) *Query {
q = q.clone()
if ancestor == nil {
q.err = errors.New("datastore: nil query ancestor")
return q
}
q.ancestor = ancestor
return q
}
// EventualConsistency returns a derivative query that returns eventually
// consistent results.
// It only has an effect on ancestor queries.
func (q *Query) EventualConsistency() *Query {
q = q.clone()
q.eventual = true
return q
}
// Filter returns a derivative query with a field-based filter.
// The filterStr argument must be a field name followed by optional space,
// followed by an operator, one of ">", "<", ">=", "<=", or "=".
// Fields are compared against the provided value using the operator.
// Multiple filters are AND'ed together.
func (q *Query) Filter(filterStr string, value interface{}) *Query {
q = q.clone()
filterStr = strings.TrimSpace(filterStr)
if len(filterStr) < 1 {
q.err = errors.New("datastore: invalid filter: " + filterStr)
return q
}
f := filter{
FieldName: strings.TrimRight(filterStr, " ><=!"),
Value: value,
}
switch op := strings.TrimSpace(filterStr[len(f.FieldName):]); op {
case "<=":
f.Op = lessEq
case ">=":
f.Op = greaterEq
case "<":
f.Op = lessThan
case ">":
f.Op = greaterThan
case "=":
f.Op = equal
default:
q.err = fmt.Errorf("datastore: invalid operator %q in filter %q", op, filterStr)
return q
}
q.filter = append(q.filter, f)
return q
}
// Order returns a derivative query with a field-based sort order. Orders are
// applied in the order they are added. The default order is ascending; to sort
// in descending order prefix the fieldName with a minus sign (-).
func (q *Query) Order(fieldName string) *Query {
q = q.clone()
fieldName = strings.TrimSpace(fieldName)
o := order{
Direction: ascending,
FieldName: fieldName,
}
if strings.HasPrefix(fieldName, "-") {
o.Direction = descending
o.FieldName = strings.TrimSpace(fieldName[1:])
} else if strings.HasPrefix(fieldName, "+") {
q.err = fmt.Errorf("datastore: invalid order: %q", fieldName)
return q
}
if len(o.FieldName) == 0 {
q.err = errors.New("datastore: empty order")
return q
}
q.order = append(q.order, o)
return q
}
// Project returns a derivative query that yields only the given fields. It
// cannot be used with KeysOnly.
func (q *Query) Project(fieldNames ...string) *Query {
q = q.clone()
q.projection = append([]string(nil), fieldNames...)
return q
}
// Distinct returns a derivative query that yields de-duplicated entities with
// respect to the set of projected fields. It is only used for projection
// queries.
func (q *Query) Distinct() *Query {
q = q.clone()
q.distinct = true
return q
}
// KeysOnly returns a derivative query that yields only keys, not keys and
// entities. It cannot be used with projection queries.
func (q *Query) KeysOnly() *Query {
q = q.clone()
q.keysOnly = true
return q
}
// Limit returns a derivative query that has a limit on the number of results
// returned. A negative value means unlimited.
func (q *Query) Limit(limit int) *Query {
q = q.clone()
if limit < math.MinInt32 || limit > math.MaxInt32 {
q.err = errors.New("datastore: query limit overflow")
return q
}
q.limit = int32(limit)
return q
}
// Offset returns a derivative query that has an offset of how many keys to
// skip over before returning results. A negative value is invalid.
func (q *Query) Offset(offset int) *Query {
q = q.clone()
if offset < 0 {
q.err = errors.New("datastore: negative query offset")
return q
}
if offset > math.MaxInt32 {
q.err = errors.New("datastore: query offset overflow")
return q
}
q.offset = int32(offset)
return q
}
// Start returns a derivative query with the given start point.
func (q *Query) Start(c Cursor) *Query {
q = q.clone()
if c.cc == nil {
q.err = errors.New("datastore: invalid cursor")
return q
}
q.start = c.cc
return q
}
// End returns a derivative query with the given end point.
func (q *Query) End(c Cursor) *Query {
q = q.clone()
if c.cc == nil {
q.err = errors.New("datastore: invalid cursor")
return q
}
q.end = c.cc
return q
}
// toProto converts the query to a protocol buffer.
func (q *Query) toProto(dst *pb.Query, appID string) error {
if len(q.projection) != 0 && q.keysOnly {
return errors.New("datastore: query cannot both project and be keys-only")
}
dst.Reset()
dst.App = proto.String(appID)
if q.kind != "" {
dst.Kind = proto.String(q.kind)
}
if q.ancestor != nil {
dst.Ancestor = keyToProto(appID, q.ancestor)
if q.eventual {
dst.Strong = proto.Bool(false)
}
}
if q.projection != nil {
dst.PropertyName = q.projection
if q.distinct {
dst.GroupByPropertyName = q.projection
}
}
if q.keysOnly {
dst.KeysOnly = proto.Bool(true)
dst.RequirePerfectPlan = proto.Bool(true)
}
for _, qf := range q.filter {
if qf.FieldName == "" {
return errors.New("datastore: empty query filter field name")
}
p, errStr := valueToProto(appID, qf.FieldName, reflect.ValueOf(qf.Value), false)
if errStr != "" {
return errors.New("datastore: bad query filter value type: " + errStr)
}
xf := &pb.Query_Filter{
Op: operatorToProto[qf.Op],
Property: []*pb.Property{p},
}
if xf.Op == nil {
return errors.New("datastore: unknown query filter operator")
}
dst.Filter = append(dst.Filter, xf)
}
for _, qo := range q.order {
if qo.FieldName == "" {
return errors.New("datastore: empty query order field name")
}
xo := &pb.Query_Order{
Property: proto.String(qo.FieldName),
Direction: sortDirectionToProto[qo.Direction],
}
if xo.Direction == nil {
return errors.New("datastore: unknown query order direction")
}
dst.Order = append(dst.Order, xo)
}
if q.limit >= 0 {
dst.Limit = proto.Int32(q.limit)
}
if q.offset != 0 {
dst.Offset = proto.Int32(q.offset)
}
dst.CompiledCursor = q.start
dst.EndCompiledCursor = q.end
dst.Compile = proto.Bool(true)
return nil
}
// Count returns the number of results for the query.
//
// The running time and number of API calls made by Count scale linearly with
// the sum of the query's offset and limit. Unless the result count is
// expected to be small, it is best to specify a limit; otherwise Count will
// continue until it finishes counting or the provided context expires.
func (q *Query) Count(c context.Context) (int, error) {
// Check that the query is well-formed.
if q.err != nil {
return 0, q.err
}
// Run a copy of the query, with keysOnly true (if we're not a projection,
// since the two are incompatible), and an adjusted offset. We also set the
// limit to zero, as we don't want any actual entity data, just the number
// of skipped results.
newQ := q.clone()
newQ.keysOnly = len(newQ.projection) == 0
newQ.limit = 0
if q.limit < 0 {
// If the original query was unlimited, set the new query's offset to maximum.
newQ.offset = math.MaxInt32
} else {
newQ.offset = q.offset + q.limit
if newQ.offset < 0 {
// Do the best we can, in the presence of overflow.
newQ.offset = math.MaxInt32
}
}
req := &pb.Query{}
if err := newQ.toProto(req, internal.FullyQualifiedAppID(c)); err != nil {
return 0, err
}
res := &pb.QueryResult{}
if err := internal.Call(c, "datastore_v3", "RunQuery", req, res); err != nil {
return 0, err
}
// n is the count we will return. For example, suppose that our original
// query had an offset of 4 and a limit of 2008: the count will be 2008,
// provided that there are at least 2012 matching entities. However, the
// RPCs will only skip 1000 results at a time. The RPC sequence is:
// call RunQuery with (offset, limit) = (2012, 0) // 2012 == newQ.offset
// response has (skippedResults, moreResults) = (1000, true)
// n += 1000 // n == 1000
// call Next with (offset, limit) = (1012, 0) // 1012 == newQ.offset - n
// response has (skippedResults, moreResults) = (1000, true)
// n += 1000 // n == 2000
// call Next with (offset, limit) = (12, 0) // 12 == newQ.offset - n
// response has (skippedResults, moreResults) = (12, false)
// n += 12 // n == 2012
// // exit the loop
// n -= 4 // n == 2008
var n int32
for {
// The QueryResult should have no actual entity data, just skipped results.
if len(res.Result) != 0 {
return 0, errors.New("datastore: internal error: Count request returned too much data")
}
n += res.GetSkippedResults()
if !res.GetMoreResults() {
break
}
if err := callNext(c, res, newQ.offset-n, 0); err != nil {
return 0, err
}
}
n -= q.offset
if n < 0 {
// If the offset was greater than the number of matching entities,
// return 0 instead of negative.
n = 0
}
return int(n), nil
}
// callNext issues a datastore_v3/Next RPC to advance a cursor, such as that
// returned by a query with more results.
func callNext(c context.Context, res *pb.QueryResult, offset, limit int32) error {
if res.Cursor == nil {
return errors.New("datastore: internal error: server did not return a cursor")
}
req := &pb.NextRequest{
Cursor: res.Cursor,
}
if limit >= 0 {
req.Count = proto.Int32(limit)
}
if offset != 0 {
req.Offset = proto.Int32(offset)
}
if res.CompiledCursor != nil {
req.Compile = proto.Bool(true)
}
res.Reset()
return internal.Call(c, "datastore_v3", "Next", req, res)
}
// GetAll runs the query in the given context and returns all keys that match
// that query, as well as appending the values to dst.
//
// dst must have type *[]S or *[]*S or *[]P, for some struct type S or some non-
// interface, non-pointer type P such that P or *P implements PropertyLoadSaver.
//
// As a special case, *PropertyList is an invalid type for dst, even though a
// PropertyList is a slice of structs. It is treated as invalid to avoid being
// mistakenly passed when *[]PropertyList was intended.
//
// The keys returned by GetAll will be in a 1-1 correspondence with the entities
// added to dst.
//
// If q is a ``keys-only'' query, GetAll ignores dst and only returns the keys.
//
// The running time and number of API calls made by GetAll scale linearly with
// with the sum of the query's offset and limit. Unless the result count is
// expected to be small, it is best to specify a limit; otherwise GetAll will
// continue until it finishes collecting results or the provided context
// expires.
func (q *Query) GetAll(c context.Context, dst interface{}) ([]*Key, error) {
var (
dv reflect.Value
mat multiArgType
elemType reflect.Type
errFieldMismatch error
)
if !q.keysOnly {
dv = reflect.ValueOf(dst)
if dv.Kind() != reflect.Ptr || dv.IsNil() {
return nil, ErrInvalidEntityType
}
dv = dv.Elem()
mat, elemType = checkMultiArg(dv)
if mat == multiArgTypeInvalid || mat == multiArgTypeInterface {
return nil, ErrInvalidEntityType
}
}
var keys []*Key
for t := q.Run(c); ; {
k, e, err := t.next()
if err == Done {
break
}
if err != nil {
return keys, err
}
if !q.keysOnly {
ev := reflect.New(elemType)
if elemType.Kind() == reflect.Map {
// This is a special case. The zero values of a map type are
// not immediately useful; they have to be make'd.
//
// Funcs and channels are similar, in that a zero value is not useful,
// but even a freshly make'd channel isn't useful: there's no fixed
// channel buffer size that is always going to be large enough, and
// there's no goroutine to drain the other end. Theoretically, these
// types could be supported, for example by sniffing for a constructor
// method or requiring prior registration, but for now it's not a
// frequent enough concern to be worth it. Programmers can work around
// it by explicitly using Iterator.Next instead of the Query.GetAll
// convenience method.
x := reflect.MakeMap(elemType)
ev.Elem().Set(x)
}
if err = loadEntity(ev.Interface(), e); err != nil {
if _, ok := err.(*ErrFieldMismatch); ok {
// We continue loading entities even in the face of field mismatch errors.
// If we encounter any other error, that other error is returned. Otherwise,
// an ErrFieldMismatch is returned.
errFieldMismatch = err
} else {
return keys, err
}
}
if mat != multiArgTypeStructPtr {
ev = ev.Elem()
}
dv.Set(reflect.Append(dv, ev))
}
keys = append(keys, k)
}
return keys, errFieldMismatch
}
// Run runs the query in the given context.
func (q *Query) Run(c context.Context) *Iterator {
if q.err != nil {
return &Iterator{err: q.err}
}
t := &Iterator{
c: c,
limit: q.limit,
q: q,
prevCC: q.start,
}
var req pb.Query
if err := q.toProto(&req, internal.FullyQualifiedAppID(c)); err != nil {
t.err = err
return t
}
if err := internal.Call(c, "datastore_v3", "RunQuery", &req, &t.res); err != nil {
t.err = err
return t
}
offset := q.offset - t.res.GetSkippedResults()
for offset > 0 && t.res.GetMoreResults() {
t.prevCC = t.res.CompiledCursor
if err := callNext(t.c, &t.res, offset, t.limit); err != nil {
t.err = err
break
}
skip := t.res.GetSkippedResults()
if skip < 0 {
t.err = errors.New("datastore: internal error: negative number of skipped_results")
break
}
offset -= skip
}
if offset < 0 {
t.err = errors.New("datastore: internal error: query offset was overshot")
}
return t
}
// Iterator is the result of running a query.
type Iterator struct {
c context.Context
err error
// res is the result of the most recent RunQuery or Next API call.
res pb.QueryResult
// i is how many elements of res.Result we have iterated over.
i int
// limit is the limit on the number of results this iterator should return.
// A negative value means unlimited.
limit int32
// q is the original query which yielded this iterator.
q *Query
// prevCC is the compiled cursor that marks the end of the previous batch
// of results.
prevCC *pb.CompiledCursor
}
// Done is returned when a query iteration has completed.
var Done = errors.New("datastore: query has no more results")
// Next returns the key of the next result. When there are no more results,
// Done is returned as the error.
//
// If the query is not keys only and dst is non-nil, it also loads the entity
// stored for that key into the struct pointer or PropertyLoadSaver dst, with
// the same semantics and possible errors as for the Get function.
func (t *Iterator) Next(dst interface{}) (*Key, error) {
k, e, err := t.next()
if err != nil {
return nil, err
}
if dst != nil && !t.q.keysOnly {
err = loadEntity(dst, e)
}
return k, err
}
func (t *Iterator) next() (*Key, *pb.EntityProto, error) {
if t.err != nil {
return nil, nil, t.err
}
// Issue datastore_v3/Next RPCs as necessary.
for t.i == len(t.res.Result) {
if !t.res.GetMoreResults() {
t.err = Done
return nil, nil, t.err
}
t.prevCC = t.res.CompiledCursor
if err := callNext(t.c, &t.res, 0, t.limit); err != nil {
t.err = err
return nil, nil, t.err
}
if t.res.GetSkippedResults() != 0 {
t.err = errors.New("datastore: internal error: iterator has skipped results")
return nil, nil, t.err
}
t.i = 0
if t.limit >= 0 {
t.limit -= int32(len(t.res.Result))
if t.limit < 0 {
t.err = errors.New("datastore: internal error: query returned more results than the limit")
return nil, nil, t.err
}
}
}
// Extract the key from the t.i'th element of t.res.Result.
e := t.res.Result[t.i]
t.i++
if e.Key == nil {
return nil, nil, errors.New("datastore: internal error: server did not return a key")
}
k, err := protoToKey(e.Key)
if err != nil || k.Incomplete() {
return nil, nil, errors.New("datastore: internal error: server returned an invalid key")
}
return k, e, nil
}
// Cursor returns a cursor for the iterator's current location.
func (t *Iterator) Cursor() (Cursor, error) {
if t.err != nil && t.err != Done {
return Cursor{}, t.err
}
// If we are at either end of the current batch of results,
// return the compiled cursor at that end.
skipped := t.res.GetSkippedResults()
if t.i == 0 && skipped == 0 {
if t.prevCC == nil {
// A nil pointer (of type *pb.CompiledCursor) means no constraint:
// passing it as the end cursor of a new query means unlimited results
// (glossing over the integer limit parameter for now).
// A non-nil pointer to an empty pb.CompiledCursor means the start:
// passing it as the end cursor of a new query means 0 results.
// If prevCC was nil, then the original query had no start cursor, but
// Iterator.Cursor should return "the start" instead of unlimited.
return Cursor{&zeroCC}, nil
}
return Cursor{t.prevCC}, nil
}
if t.i == len(t.res.Result) {
return Cursor{t.res.CompiledCursor}, nil
}
// Otherwise, re-run the query offset to this iterator's position, starting from
// the most recent compiled cursor. This is done on a best-effort basis, as it
// is racy; if a concurrent process has added or removed entities, then the
// cursor returned may be inconsistent.
q := t.q.clone()
q.start = t.prevCC
q.offset = skipped + int32(t.i)
q.limit = 0
q.keysOnly = len(q.projection) == 0
t1 := q.Run(t.c)
_, _, err := t1.next()
if err != Done {
if err == nil {
err = fmt.Errorf("datastore: internal error: zero-limit query did not have zero results")
}
return Cursor{}, err
}
return Cursor{t1.res.CompiledCursor}, nil
}
var zeroCC pb.CompiledCursor
// Cursor is an iterator's position. It can be converted to and from an opaque
// string. A cursor can be used from different HTTP requests, but only with a
// query with the same kind, ancestor, filter and order constraints.
type Cursor struct {
cc *pb.CompiledCursor
}
// String returns a base-64 string representation of a cursor.
func (c Cursor) String() string {
if c.cc == nil {
return ""
}
b, err := proto.Marshal(c.cc)
if err != nil {
// The only way to construct a Cursor with a non-nil cc field is to
// unmarshal from the byte representation. We panic if the unmarshal
// succeeds but the marshaling of the unchanged protobuf value fails.
panic(fmt.Sprintf("datastore: internal error: malformed cursor: %v", err))
}
return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=")
}
// Decode decodes a cursor from its base-64 string representation.
func DecodeCursor(s string) (Cursor, error) {
if s == "" {
return Cursor{&zeroCC}, nil
}
if n := len(s) % 4; n != 0 {
s += strings.Repeat("=", 4-n)
}
b, err := base64.URLEncoding.DecodeString(s)
if err != nil {
return Cursor{}, err
}
cc := &pb.CompiledCursor{}
if err := proto.Unmarshal(b, cc); err != nil {
return Cursor{}, err
}
return Cursor{cc}, nil
}
| {
"pile_set_name": "Github"
} |
lf
lf
crlf
lf
lf
| {
"pile_set_name": "Github"
} |
from __future__ import print_function
import time
import base64
import random
import re
from streamlink.compat import urlparse
from streamlink.plugin import Plugin
from streamlink.plugin.api import useragents
from streamlink.stream import HLSStream
from streamlink.utils import parse_qsd
from streamlink.utils.crypto import decrypt_openssl
class Streann(Plugin):
url_re = re.compile(r"https?://ott\.streann.com/streaming/player\.html")
base_url = "https://ott.streann.com"
get_time_url = base_url + "/web/services/public/get-server-time"
token_url = base_url + "/loadbalancer/services/web-players/{playerId}/token/{type}/{dataId}/{deviceId}"
stream_url = base_url + "/loadbalancer/services/web-players/{type}s-reseller-secure/{dataId}/{playerId}" \
"/{token}/{resellerId}/playlist.m3u8?date={time}&device-type=web&device-name=web" \
"&device-os=web&device-id={deviceId}"
passphrase_re = re.compile(r'''CryptoJS\.AES\.decrypt\(.*?,\s*(['"])(?P<passphrase>(?:(?!\1).)*)\1\s*?\);''')
def __init__(self, url):
super(Streann, self).__init__(url)
self._device_id = None
self._headers = {"User-Agent": useragents.FIREFOX}
@classmethod
def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
@property
def device_id(self):
"""
Randomly generated deviceId.
:return:
"""
if self._device_id is None:
self._device_id = "".join(
random.choice("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") for _ in range(50))
return self._device_id
@property
def time(self):
res = self.session.http.get(self.get_time_url, headers=self._headers)
data = self.session.http.json(res)
return str(data.get("serverTime", int(time.time() * 1000)))
def passphrase(self):
self.logger.debug("passphrase ...")
res = self.session.http.get(self.url, headers=self._headers)
passphrase_m = self.passphrase_re.search(res.text)
return passphrase_m and passphrase_m.group("passphrase").encode("utf8")
def get_token(self, **config):
self.logger.debug("get_token ...")
pdata = dict(arg1=base64.b64encode("www.ellobo106.com".encode("utf8")),
arg2=base64.b64encode(self.time.encode("utf8")))
headers = {
"User-Agent": useragents.FIREFOX,
"Referer": self.url,
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded"
}
res = self.session.http.post(
self.token_url.format(deviceId=self.device_id, **config),
data=pdata,
headers=headers
)
data = self.session.http.json(res)
return data["token"]
def _get_streams(self):
# Get the query string
encrypted_data = urlparse(self.url).query
data = base64.b64decode(encrypted_data)
# and decrypt it
passphrase = self.passphrase()
if passphrase:
self.logger.debug("Found passphrase")
params = decrypt_openssl(data, passphrase)
config = parse_qsd(params.decode("utf8"))
hls_url = self.stream_url.format(time=self.time,
deviceId=self.device_id,
token=self.get_token(**config),
**config)
self.logger.debug("URL={0}".format(hls_url))
return HLSStream.parse_variant_playlist(self.session, hls_url, headers=self._headers)
__plugin__ = Streann
| {
"pile_set_name": "Github"
} |
/*
YUI 3.7.3 (build 5687)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("widget-base-ie",function(e,t){var n="boundingBox",r="contentBox",i="height",s="offsetHeight",o="",u=e.UA.ie,a=u<7,f=e.Widget.getClassName("tmp","forcesize"),l=e.Widget.getClassName("content","expanded");e.Widget.prototype._uiSizeCB=function(e){var t=this.get(n),c=this.get(r),h=this._bbs;h===undefined&&(this._bbs=h=!(u&&u<8&&t.get("ownerDocument").get("compatMode")!="BackCompat")),h?c.toggleClass(l,e):e?(a&&t.addClass(f),c.set(s,t.get(s)),a&&t.removeClass(f)):c.setStyle(i,o)}},"3.7.3",{requires:["widget-base"]});
| {
"pile_set_name": "Github"
} |
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: methodTemplate.tt
// Build date: 2017-10-08
// C# generater version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unoffical sample for the Dfareporting v2.8 API for C#.
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
//
// API Description: Manages your DoubleClick Campaign Manager ad campaigns and reports.
// API Documentation Link https://developers.google.com/doubleclick-advertisers/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Dfareporting/v2_8/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client)
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.Dfareporting.v2_8/
// Install Command: PM> Install-Package Google.Apis.Dfareporting.v2_8
//
//------------------------------------------------------------------------------
using Google.Apis.Dfareporting.v2_8;
using Google.Apis.Dfareporting.v2_8.Data;
using System;
namespace GoogleSamplecSharpSample.Dfareportingv2_8.Methods
{
public static class FloodlightActivityGroupsSample
{
/// <summary>
/// Gets one floodlight activity group by ID.
/// Documentation https://developers.google.com/dfareporting/v2.8/reference/floodlightActivityGroups/get
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="id">Floodlight activity Group ID.</param>
/// <returns>FloodlightActivityGroupResponse</returns>
public static FloodlightActivityGroup Get(DfareportingService service, string profileId, string id)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (profileId == null)
throw new ArgumentNullException(profileId);
if (id == null)
throw new ArgumentNullException(id);
// Make the request.
return service.FloodlightActivityGroups.Get(profileId, id).Execute();
}
catch (Exception ex)
{
throw new Exception("Request FloodlightActivityGroups.Get failed.", ex);
}
}
/// <summary>
/// Inserts a new floodlight activity group.
/// Documentation https://developers.google.com/dfareporting/v2.8/reference/floodlightActivityGroups/insert
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="body">A valid Dfareporting v2.8 body.</param>
/// <returns>FloodlightActivityGroupResponse</returns>
public static FloodlightActivityGroup Insert(DfareportingService service, string profileId, FloodlightActivityGroup body)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (profileId == null)
throw new ArgumentNullException(profileId);
// Make the request.
return service.FloodlightActivityGroups.Insert(body, profileId).Execute();
}
catch (Exception ex)
{
throw new Exception("Request FloodlightActivityGroups.Insert failed.", ex);
}
}
public class FloodlightActivityGroupsListOptionalParms
{
/// Select only floodlight activity groups with the specified advertiser ID. Must specify either advertiserId or floodlightConfigurationId for a non-empty result.
public string AdvertiserId { get; set; }
/// Select only floodlight activity groups with the specified floodlight configuration ID. Must specify either advertiserId, or floodlightConfigurationId for a non-empty result.
public string FloodlightConfigurationId { get; set; }
/// Select only floodlight activity groups with the specified IDs. Must specify either advertiserId or floodlightConfigurationId for a non-empty result.
public string Ids { get; set; }
/// Maximum number of results to return.
public int? MaxResults { get; set; }
/// Value of the nextPageToken from the previous result page.
public string PageToken { get; set; }
/// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "floodlightactivitygroup*2015" will return objects with names like "floodlightactivitygroup June 2015", "floodlightactivitygroup April 2015", or simply "floodlightactivitygroup 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "floodlightactivitygroup" will match objects with name "my floodlightactivitygroup activity", "floodlightactivitygroup 2015", or simply "floodlightactivitygroup".
public string SearchString { get; set; }
/// Field by which to sort the list.
public string SortField { get; set; }
/// Order of sorted results.
public string SortOrder { get; set; }
/// Select only floodlight activity groups with the specified floodlight activity group type.
public string Type { get; set; }
}
/// <summary>
/// Retrieves a list of floodlight activity groups, possibly filtered. This method supports paging.
/// Documentation https://developers.google.com/dfareporting/v2.8/reference/floodlightActivityGroups/list
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="optional">Optional paramaters.</param>
/// <returns>FloodlightActivityGroupsListResponseResponse</returns>
public static FloodlightActivityGroupsListResponse List(DfareportingService service, string profileId, FloodlightActivityGroupsListOptionalParms optional = null)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (profileId == null)
throw new ArgumentNullException(profileId);
// Building the initial request.
var request = service.FloodlightActivityGroups.List(profileId);
// Applying optional parameters to the request.
request = (FloodlightActivityGroupsResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);
// Requesting data.
return request.Execute();
}
catch (Exception ex)
{
throw new Exception("Request FloodlightActivityGroups.List failed.", ex);
}
}
/// <summary>
/// Updates an existing floodlight activity group. This method supports patch semantics.
/// Documentation https://developers.google.com/dfareporting/v2.8/reference/floodlightActivityGroups/patch
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="id">Floodlight activity Group ID.</param>
/// <param name="body">A valid Dfareporting v2.8 body.</param>
/// <returns>FloodlightActivityGroupResponse</returns>
public static FloodlightActivityGroup Patch(DfareportingService service, string profileId, string id, FloodlightActivityGroup body)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (profileId == null)
throw new ArgumentNullException(profileId);
if (id == null)
throw new ArgumentNullException(id);
// Make the request.
return service.FloodlightActivityGroups.Patch(body, profileId, id).Execute();
}
catch (Exception ex)
{
throw new Exception("Request FloodlightActivityGroups.Patch failed.", ex);
}
}
/// <summary>
/// Updates an existing floodlight activity group.
/// Documentation https://developers.google.com/dfareporting/v2.8/reference/floodlightActivityGroups/update
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="body">A valid Dfareporting v2.8 body.</param>
/// <returns>FloodlightActivityGroupResponse</returns>
public static FloodlightActivityGroup Update(DfareportingService service, string profileId, FloodlightActivityGroup body)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (profileId == null)
throw new ArgumentNullException(profileId);
// Make the request.
return service.FloodlightActivityGroups.Update(body, profileId).Execute();
}
catch (Exception ex)
{
throw new Exception("Request FloodlightActivityGroups.Update failed.", ex);
}
}
}
public static class SampleHelpers
{
/// <summary>
/// Using reflection to apply optional parameters to the request.
///
/// If the optonal parameters are null then we will just return the request as is.
/// </summary>
/// <param name="request">The request. </param>
/// <param name="optional">The optional parameters. </param>
/// <returns></returns>
public static object ApplyOptionalParms(object request, object optional)
{
if (optional == null)
return request;
System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties();
foreach (System.Reflection.PropertyInfo property in optionalProperties)
{
// Copy value from optional parms to the request. They should have the same names and datatypes.
System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name);
if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null
piShared.SetValue(request, property.GetValue(optional, null), null);
}
return request;
}
}
} | {
"pile_set_name": "Github"
} |
<?
$item = $this->item;
$title = $item ? 'Edit User Role' : 'Create User Role';
$title = $this->_($title);
$method = $item ? 'put' : 'post';
$this->headTitle($title, 'SET');
$this->textDelay('breadcrumbText', $title);
if($this->form){
$form = $this->form;
} else {
if($item) {
$form = new User\Form\RoleEditForm();
$form->setMethod('put');
} else {
$form = new User\Form\RoleForm();
$form->setMethod('post');
}
}
$form->setView($this)
->setAction($this->uri('/admin/user/role/'))
->bind($item)
->prepare();
?>
<input id="flash-messenger" type="hidden" value="<?=is_array($this->flashMessenger) ? implode(',', $this->flashMessenger) : ''?>" />
<div id="user-create-succeed" class="alert alert-success hide">
<a href="#" data-dismiss="alert" class="close">x</a>
<h4 class="alert-heading"><?=$this->_('New Role Created')?></h4>
</div>
<div id="user-edit-succeed" class="alert alert-success hide">
<a href="#" data-dismiss="alert" class="close">x</a>
<h4 class="alert-heading"><?=$this->_('Role Edit Succeed')?></h4>
</div>
<div id="user-edit-failed" class="alert alert-error hide">
<a href="#" data-dismiss="alert" class="close">x</a>
<h4 class="alert-heading"><?=$this->_('Role Edit Failed')?></h4>
</div>
<div class="row">
<form <?=$this->formAttr($form)?>>
<?=$form->restful();?>
<?=$form->helper('id');?>
<div class="span10">
<div class="slate">
<div class="page-header">
<?if($item):?>
<div class="btn-group pull-right">
<a href="<?=$this->uri('/admin/user/role/create')?>" class="btn"><?=$this->_('Clear Cache')?></a>
<a href="<?=$this->uri('/admin/user/role/remove/' . $item['id'], 'c', array('c' => $this->uri('/admin/user/role/' . $item['id']))); ?>" class="btn"><?=$this->_('Delete')?></a>
</div>
<?endif?>
<h2><?=$title?></h2>
</div>
<fieldset class="">
</fieldset>
</div>
</div><!--span10 end-->
<div class="span10">
<div class="slate">
<div class="page-header">
<h3><?=$this->_('Role Basic Info')?></h3>
</div>
<fieldset class="form-horizontal">
<?=$form->helper('id', array('class' => ''))?>
<div class="control-group <?=$form->isError('roleName') ? 'error' : '';?>">
<?=$form->helper('roleName', 'label', array('class' => 'control-label'))?>
<div class="controls">
<?=$form->helper('roleName', array('class' => 'required'))?>
<div class="help-block"><?=$form->helper('roleName', 'formElementErrors')?></div>
</div>
</div>
<div class="control-group <?=$form->isError('roleKey') ? 'error' : '';?>">
<?=$form->helper('roleKey', 'label', array('class' => 'control-label'))?>
<div class="controls">
<?=$form->helper('roleKey', array('class' => 'disabled', 'disabled' => 'disabled'))?>
<div class="help-block">
<p><?=$this->_('Will display on urls and templates, uppercase letters and underline only.')?></p>
<?=$form->helper('roleKey', 'formElementErrors')?>
</div>
</div>
</div>
<div class="control-group <?=$form->isError('description') ? 'error' : '';?>">
<?=$form->helper('description', 'label', array('class' => 'control-label'))?>
<div class="controls">
<?=$form->helper('description', array('class' => ''))?>
<div class="help-block"><?=$form->helper('description', 'formElementErrors')?></div>
</div>
</div>
</fieldset>
</div>
</div><!--span5 end-->
<div class="span10">
<div class="slate">
<div class="page-header">
<h2><?=$this->_('Permissions')?></h2>
</div>
</div>
</div><!--span10 end-->
<div class="span10 listing-buttons">
<button id="save-publish" class="btn btn-success btn-large"><?=$this->_('Save')?></button>
</div>
</form>
</div> | {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `MIN` constant in crate `std`.">
<meta name="keywords" content="rust, rustlang, rust-lang, MIN">
<title>std::i32::MIN - Rust</title>
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
<link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<a href='../../std/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a>
<p class='location'><a href='../index.html'>std</a>::<wbr><a href='index.html'>i32</a></p><script>window.sidebarCurrent = {name: 'MIN', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>std</a>::<wbr><a href='index.html'>i32</a>::<wbr><a class='constant' href=''>MIN</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-24' class='srclink' href='../../core/i32/constant.MIN.html?gotosrc=24' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const MIN: <a class='primitive' href='../primitive.i32.html'>i32</a><code> = </code><code>-1 as i32 << BITS - 1</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "std";
window.playgroundUrl = "https://play.rust-lang.org/";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script src="../../playpen.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html> | {
"pile_set_name": "Github"
} |
import Application from '../../app';
import config from '../../config/environment';
import { merge } from '@ember/polyfills';
import { run } from '@ember/runloop';
export default function startApp(attrs) {
let attributes = merge({}, config.APP);
attributes = merge(attributes, attrs); // use defaults, but you can override;
return run(() => {
let application = Application.create(attributes);
application.setupForTesting();
application.injectTestHelpers();
return application;
});
}
| {
"pile_set_name": "Github"
} |
.login-openid-or {
display: block;
position: relative;
height: 50px;
color: #bbbbbb;
font-size: 12px;
> span {
position: absolute;
z-index: 2;
top: 50%;
left: 50%;
padding: 0 10px;
transform: translate(-50%, -50%);
background: #ffffff;
white-space: nowrap;
}
&::before {
content: '';
position: absolute;
z-index: 1;
top: 50%;
left: 0;
width: 100%;
height: 1px;
border-top: 1px solid #f1f1f1;
}
}
#login-openid-providers-list > a {
width: 100%;
height: 58px;
margin: 0 auto 10px;
line-height: 58px;
}
| {
"pile_set_name": "Github"
} |
'''The systemBase provides the base class implementation for standard
system Base implementations. This systemBase itself is not intended
to be instantiated as the regular Thespian System Base, but instead it
provides a base class that should be subclassed by the various System
Base implementations.
'''
import logging
from thespian.actors import *
from thespian.system import *
from thespian.system.utilis import thesplog
from thespian.system.timing import toTimeDeltaOrNone, ExpirationTimer, unexpired
from thespian.system.messages.admin import *
from thespian.system.messages.status import *
from thespian.system.transport import *
import threading
from contextlib import closing
from datetime import timedelta
import os
MAX_SYSTEM_SHUTDOWN_DELAY = timedelta(seconds=10)
MAX_CHILD_ACTOR_CREATE_DELAY = timedelta(seconds=50)
MAX_CAPABILITY_UPDATE_DELAY = timedelta(seconds=5)
MAX_LOAD_SOURCE_DELAY = timedelta(seconds=61)
MAX_ADMIN_STATUS_REQ_DELAY = timedelta(seconds=2)
MAX_TELL_PERIOD = timedelta(seconds=60)
def ensure_TZ_set():
# Actor engines handle timeouts and tend to sample system time
# frequently. Under Linux, if TZ is not set to a value,
# /etc/localtime or similar is consulted on each call to obtain
# system time which can negatively affect performance. This
# function attempts to set TZ if possible/reasonable.
if 'TZ' in os.environ:
return
for fname in ('/etc/localtime',
'/usr/local/etc/localtime'):
if os.path.exists(fname):
os.environ['TZ'] = ':' + fname
return
# OK if it's not set, just may be slower
class TransmitTrack(object):
def __init__(self, transport, adminAddr):
self._newActorAddress = None
self._pcrFAILED = None
self._transport = transport
self._adminAddr = adminAddr
@property
def failed(self):
return self._pcrFAILED is not None
@property
def failure(self):
return self._pcrFAILED
@property
def failure_message(self):
return getattr(self, '_pcrMessage', None)
def transmit_failed(self, result, intent):
if result == SendStatus.DeadTarget and \
intent.targetAddr != self._adminAddr:
# Forward message to the dead letter handler; if the
# forwarding fails, just discard the message.
self._transport.scheduleTransmit(
None,
TransmitIntent(self._adminAddr,
DeadEnvelope(intent.targetAddr, intent.message)))
self._pcrFAILED = result
self._transport.abort_run()
class NewActorResponse(TransmitTrack):
def __init__(self, transport, adminAddr, *args, **kw):
super(NewActorResponse, self).__init__(transport, adminAddr, *args, **kw)
self._newActorAddress = None
@property
def pending(self):
return self._newActorAddress is None and not self.failed
@property
def actor_address(self):
return self._newActorAddress
def __call__(self, envelope):
if isinstance(envelope.message, PendingActorResponse):
self._newActorAddress = False if envelope.message.errorCode else \
envelope.message.actualAddress
self._pcrFAILED = envelope.message.errorCode
self._pcrMessage = getattr(envelope.message, 'errorStr', None)
# Stop running transport; got new actor address (or failure)
return False
# Discard everything else. Previous requests and operations
# may have caused there to be messages sent back to this
# endpoint that are queued ahead of the PendingActorResponse.
return True # Keep waiting for the PendingActorResponse
class ExternalOpsToActors(object):
def __init__(self, adminAddr, transport=None):
self._numPrimaries = 0
self._cv = threading.Condition()
self._transport_runner = False
# Expects self.transport has already been set by subclass __init__
self.adminAddr = adminAddr
if transport:
self.transport = transport
def _run_transport(self, maximumDuration=None, txonly=False,
incomingHandler=None):
# This is where multiple external threads are synchronized for
# receives. Transmits will flow down into the transmit layer
# where they are queued with thread safety, but threads
# blocking on a receive will all be lined up through this point.
max_runtime = ExpirationTimer(maximumDuration)
with self._cv:
while self._transport_runner:
self._cv.wait(max_runtime.view().remainingSeconds())
if max_runtime.view().expired():
return None
self._transport_runner = True
try:
r = Thespian__UpdateWork()
while isinstance(r, Thespian__UpdateWork):
r = self.transport.run(TransmitOnly if txonly else incomingHandler,
max_runtime.view().remaining())
return r
# incomingHandler callback could deadlock on this same thread; is it ever not None?
finally:
with self._cv:
self._transport_runner = False
self._cv.notify()
def _tx_to_actor(self, actorAddress, message):
# Send a message from this external process to an actor.
# Returns a TransmitTrack object that can be used to check for
# transmit errors.
txwatch = TransmitTrack(self.transport, self.adminAddr)
self.transport.scheduleTransmit(
None,
TransmitIntent(actorAddress, message,
onError=txwatch.transmit_failed))
return txwatch
def _tx_to_admin(self, message):
return self._tx_to_actor(self.adminAddr, message)
def newPrimaryActor(self, actorClass, targetActorRequirements, globalName,
sourceHash=None):
self._numPrimaries = self._numPrimaries + 1
actorClassName = '%s.%s'%(actorClass.__module__, actorClass.__name__) \
if hasattr(actorClass, '__name__') else actorClass
with closing(self.transport.external_transport_clone()) as tx_external:
response = NewActorResponse(tx_external, self.adminAddr)
tx_external.scheduleTransmit(
None,
TransmitIntent(self.adminAddr,
PendingActor(actorClassName,
None, self._numPrimaries,
targetActorRequirements,
globalName=globalName,
sourceHash=sourceHash),
onError=response.transmit_failed))
endwait = ExpirationTimer(MAX_CHILD_ACTOR_CREATE_DELAY)
# Do not use _run_transport: the tx_external transport
# context acquired above is unique to this thread and
# should not be synchronized/restricted by other threads.
tx_external.run(response, MAX_CHILD_ACTOR_CREATE_DELAY)
# Other items might abort the transport run... like transmit
# failures on a previous ask() that itself already timed out.
while response.pending and not endwait.view().expired():
tx_external.run(response, MAX_CHILD_ACTOR_CREATE_DELAY)
if response.failed:
if response.failure == PendingActorResponse.ERROR_Invalid_SourceHash:
raise InvalidActorSourceHash(sourceHash)
if response.failure == PendingActorResponse.ERROR_Invalid_ActorClass:
raise InvalidActorSpecification(actorClass,
response.failure_message)
if response.failure == PendingActorResponse.ERROR_Import:
info = response.failure_message
if info:
thesplog('Actor Create Failure, Import Error: %s', info)
raise ImportError(str(actorClass) + ': ' + info)
thesplog('Actor Create Failure, Import Error')
raise ImportError(actorClass)
if response.failure == PendingActorResponse.ERROR_No_Compatible_ActorSystem:
raise NoCompatibleSystemForActor(
actorClass, 'No compatible ActorSystem could be found')
raise ActorSystemFailure("Could not request new Actor from Admin (%s)"
% (response.failure))
if response.actor_address:
return response.actor_address
if response.actor_address is False:
raise NoCompatibleSystemForActor(
actorClass, 'No compatible ActorSystem could be found')
raise ActorSystemRequestTimeout(
'No response received to PendingActor request to Admin'
' at %s from %s'%(str(self.adminAddr),
str(self.transport.myAddress)))
def tell(self, anActor, msg):
attemptLimit = ExpirationTimer(MAX_TELL_PERIOD)
# transport may not use sockets, but this helps error handling
# in case it does.
import socket
for attempt in range(5000):
try:
txwatch = self._tx_to_actor(anActor, msg)
for attemptTime in unexpired(attemptLimit):
if not self._run_transport(attemptTime.remaining(),
txonly=True):
# all transmits completed
return
if txwatch.failed:
raise ActorSystemFailure(
'Error sending to %s: %s' % (str(anActor),
str(txwatch.failure)))
raise ActorSystemRequestTimeout(
'Unable to send to %s within %s' %
(str(anActor), str(MAX_TELL_PERIOD)))
except socket.error as ex:
import errno
if errno.EMFILE == ex.errno:
import time
time.sleep(0.1)
else:
raise
def listen(self, timeout):
while True:
response = self._run_transport(toTimeDeltaOrNone(timeout))
if not isinstance(response, ReceiveEnvelope):
break
# Do not send miscellaneous ActorSystemMessages to the caller
# that it might not recognize.
if not isInternalActorSystemMessage(response.message):
return response.message
return None
def ask(self, anActor, msg, timeout):
txwatch = self._tx_to_actor(anActor, msg) # KWQ: pass timeout on tx??
askLimit = ExpirationTimer(toTimeDeltaOrNone(timeout))
for remTime in unexpired(askLimit):
response = self._run_transport(remTime.remaining())
if txwatch.failed:
if txwatch.failure in [SendStatus.DeadTarget,
SendStatus.Failed,
SendStatus.NotSent]:
# Silent failure; not all transports can indicate
# this, so for conformity the Dead Letter handler is
# the intended method of handling this issue.
return None
raise ActorSystemFailure('Transmit of ask message to %s failed (%s)'%(
str(anActor),
str(txwatch.failure)))
if not isinstance(response, ReceiveEnvelope):
# Timed out or other failure, give up.
break
# Do not send miscellaneous ActorSystemMessages to the
# caller that it might not recognize. If one of those was
# recieved, loop to get another response.
if not isInternalActorSystemMessage(response.message):
return response.message
return None
class systemBase(ExternalOpsToActors):
"""This is the systemBase base class that various Thespian System Base
implementations should subclass. The System Base is
instantiated by each process that wishes to utilize an Actor
System and runs in the context of that process (as opposed to
the System Admin that may run in its own process).
This base is not present in the Actors themselves, only in the
external application that wish to talk to Actors.
Depending on the System Base implementation chosen by that
process, the instantiation may be private to that process or
shared by other processes; in the former case, there will be an
instance of this class in each process accessing the shared
Actor System, representing the Portal between the "external"
environment of that process and the shared Actor System
Implementation.
All ActorAddresses generated via newActor and newPrimaryActor
are local to this ActorSystemBase instance. Any and *all*
messages sent to other Actors must be able to be appropriately
serialized; this allows the pickling/unpickling process to
translate an ActorAddress from a local representation to a
global or remote representation.
"""
def __init__(self, system, logDefs = None):
ensure_TZ_set()
# Expects self.transport has already been set by subclass __init__
super(systemBase, self).__init__(
self.transport.getAdminAddr(system.capabilities))
tryingTime = ExpirationTimer(MAX_SYSTEM_SHUTDOWN_DELAY + timedelta(seconds=1))
while not tryingTime.view().expired():
if not self.transport.probeAdmin(self.adminAddr):
self._startAdmin(self.adminAddr,
self.transport.myAddress,
system.capabilities,
logDefs)
if self._verifyAdminRunning(): return
import time
time.sleep(0.5) # Previous version may have been exiting
if not self._verifyAdminRunning():
raise InvalidActorAddress(self.adminAddr,
'not a valid or useable ActorSystem Admin')
# KWQ: more details? couldn't start @ addr? response was ? instead of expected Thespian_SystemStatus?
def _verifyAdminRunning(self):
"""Returns boolean verification that the Admin is running and
available. Will query the admin for a positive response,
blocking until one is received.
"""
txwatch = self._tx_to_admin(QueryExists())
response = self._run_transport(MAX_ADMIN_STATUS_REQ_DELAY)
return not txwatch.failed and \
isinstance(response, ReceiveEnvelope) and \
isinstance(response.message, QueryAck) \
and not response.message.inShutdown
def __getstate__(self):
raise CannotPickle('ActorSystem cannot be Pickled.')
def shutdown(self):
thesplog('ActorSystem shutdown requested.', level=logging.INFO)
time_to_quit = ExpirationTimer(MAX_SYSTEM_SHUTDOWN_DELAY)
txwatch = self._tx_to_admin(SystemShutdown())
for remaining_time in unexpired(time_to_quit):
response = self._run_transport(remaining_time.remaining())
if txwatch.failed:
thesplog('Could not send shutdown request to Admin'
'; aborting but not necessarily stopped',
level=logging.WARNING)
return
if isinstance(response, ReceiveEnvelope):
if isinstance(response.message, SystemShutdownCompleted):
break
else:
thesplog('Expected shutdown completed message, got: %s', response.message,
level=logging.WARNING)
elif isinstance(response, (Thespian__Run_Expired,
Thespian__Run_Terminated,
Thespian__Run_Expired)):
break
else:
thesplog('No response to Admin shutdown request; Actor system not completely shutdown',
level=logging.ERROR)
self.transport.close()
thesplog('ActorSystem shutdown complete.')
def updateCapability(self, capabilityName, capabilityValue=None):
attemptLimit = ExpirationTimer(MAX_CAPABILITY_UPDATE_DELAY)
txwatch = self._tx_to_admin(CapabilityUpdate(capabilityName,
capabilityValue))
for remaining_time in unexpired(attemptLimit):
if not self._run_transport(remaining_time.remaining(), txonly=True):
return # all transmits completed
if txwatch.failed:
raise ActorSystemFailure(
'Error sending capability updates to Admin: %s' %
str(txwatch.failure))
raise ActorSystemRequestTimeout(
'Unable to confirm capability update in %s' %
str(MAX_CAPABILITY_UPDATE_DELAY))
def loadActorSource(self, fname):
loadLimit = ExpirationTimer(MAX_LOAD_SOURCE_DELAY)
f = fname if hasattr(fname, 'read') else open(fname, 'rb')
try:
d = f.read()
import hashlib
hval = hashlib.md5(d).hexdigest()
txwatch = self._tx_to_admin(
ValidateSource(hval, d, getattr(f, 'name',
str(fname)
if hasattr(fname, 'read')
else fname)))
for load_time in unexpired(loadLimit):
if not self._run_transport(load_time.remaining(), txonly=True):
# All transmits completed
return hval
if txwatch.failed:
raise ActorSystemFailure(
'Error sending source load to Admin: %s' %
str(txwatch.failure))
raise ActorSystemRequestTimeout('Load source timeout: ' +
str(loadLimit))
finally:
f.close()
def unloadActorSource(self, sourceHash):
loadLimit = ExpirationTimer(MAX_LOAD_SOURCE_DELAY)
txwatch = self._tx_to_admin(ValidateSource(sourceHash, None))
for load_time in unexpired(loadLimit):
if not self._run_transport(load_time.remaining(), txonly=True):
return # all transmits completed
if txwatch.failed:
raise ActorSystemFailure(
'Error sending source unload to Admin: %s' %
str(txwatch.failure))
raise ActorSystemRequestTimeout('Unload source timeout: ' +
str(loadLimit))
def external_clone(self):
"""Get a separate local endpoint that does not commingle traffic with
the the main ActorSystem or other contexts. Makes internal
blocking calls, so primarily appropriate for a
multi-threaded client environment.
"""
return BaseContext(self.adminAddr, self.transport)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Actors that involve themselves in topology
def preRegisterRemoteSystem(self, remoteAddress, remoteCapabilities):
self.send(self.adminAddr,
ConventionRegister(
self.transport.getAddressFromString(remoteAddress),
remoteCapabilities,
preRegister=True))
def deRegisterRemoteSystem(self, remoteAddress):
self.send(
self.adminAddr,
ConventionDeRegister(
remoteAddress
if isinstance(remoteAddress, ActorAddress) else
self.transport.getAddressFromString(remoteAddress)))
class BaseContext(ExternalOpsToActors):
def __init__(self, adminAddr, transport):
super(BaseContext, self).__init__(adminAddr,
transport.external_transport_clone())
def exit_context(self):
self.transport.close()
| {
"pile_set_name": "Github"
} |
/*
* This file is part of LaTeXDraw.
* Copyright (c) 2005-2020 Arnaud BLOUIN
* LaTeXDraw 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.
* LaTeXDraw is distributed 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.
*/
package net.sf.latexdraw.model.impl;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import net.sf.latexdraw.model.api.shape.Group;
import net.sf.latexdraw.model.api.shape.Text;
import net.sf.latexdraw.model.api.shape.TextPosition;
import org.jetbrains.annotations.NotNull;
/**
* This trait encapsulates the code of the group related to the support of texts.
* @author Arnaud Blouin
*/
interface GroupTextBase extends Group {
/** May return the first free hand shape of the group. */
default @NotNull Optional<Text> firstIText() {
return txtShapes().stream().filter(sh -> sh.isTypeOf(Text.class)).findFirst();
}
default @NotNull List<Text> txtShapes() {
return getShapes().stream().filter(sh -> sh instanceof Text).map(sh -> (Text) sh).collect(Collectors.toList());
}
@Override
default @NotNull TextPosition getTextPosition() {
return firstIText().map(sh -> sh.getTextPosition()).orElse(TextPosition.BOT_LEFT);
}
@Override
default void setTextPosition(final @NotNull TextPosition textPosition) {
txtShapes().forEach(sh -> sh.setTextPosition(textPosition));
}
@Override
default @NotNull String getText() {
return firstIText().map(sh -> sh.getText()).orElse("");
}
@Override
default void setText(final @NotNull String text) {
txtShapes().forEach(sh -> sh.setText(text));
}
}
| {
"pile_set_name": "Github"
} |
/*
* $Id$
*
* SARL is an general-purpose agent programming language.
* More details on http://www.sarl.io
*
* Copyright (C) 2014-2020 the original authors or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sarl.lang.scoping.extensions.numbers.arithmetic;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.xtext.xbase.lib.Inline;
import org.eclipse.xtext.xbase.lib.Pure;
/** Provide static operators for numbers of type {@code Float}.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @since 0.7
* @see "https://github.com/eclipse/xtext-extras/issues/186"
*/
@SuppressWarnings("checkstyle:methodcount")
public final class FloatArithmeticExtensions {
private FloatArithmeticExtensions() {
//
}
/** The unary {@code minus} operator. This is the equivalent to
* the Java's {@code -} function. This function is not null-safe.
*
* @param number a number.
* @return {@code -number}
*/
@Pure
@Inline(value = "(-($1.floatValue()))", constantExpression = true)
public static float operator_minus(Float number) {
return -number.floatValue();
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2)", constantExpression = true)
public static float operator_minus(Float left, long right) {
return left.floatValue() - right;
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2)", constantExpression = true)
public static float operator_minus(Float left, byte right) {
return left.floatValue() - right;
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2)", constantExpression = true)
public static float operator_minus(Float left, int right) {
return left.floatValue() - right;
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2)", constantExpression = true)
public static float operator_minus(Float left, short right) {
return left.floatValue() - right;
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2)", constantExpression = true)
public static double operator_minus(Float left, double right) {
return left.floatValue() - right;
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2)", constantExpression = true)
public static float operator_minus(Float left, float right) {
return left.floatValue() - right;
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2.doubleValue())", constantExpression = true)
public static double operator_minus(Float left, Number right) {
return left.floatValue() - right.doubleValue();
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2.longValue())", constantExpression = true)
public static float operator_minus(Float left, Long right) {
return left.floatValue() - right.longValue();
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2.byteValue())", constantExpression = true)
public static float operator_minus(Float left, Byte right) {
return left.floatValue() - right.byteValue();
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2.floatValue())", constantExpression = true)
public static float operator_minus(Float left, Float right) {
return left.floatValue() - right.floatValue();
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2.intValue())", constantExpression = true)
public static float operator_minus(Float left, Integer right) {
return left.floatValue() - right.intValue();
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2.shortValue())", constantExpression = true)
public static float operator_minus(Float left, Short right) {
return left.floatValue() - right.shortValue();
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2.intValue())", constantExpression = true)
public static float operator_minus(Float left, AtomicInteger right) {
return left.floatValue() - right.intValue();
}
/** The binary {@code minus} operator. This is the equivalent to
* the Java {@code -} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left-right}
*/
@Pure
@Inline(value = "($1.floatValue() - $2.longValue())", constantExpression = true)
public static float operator_minus(Float left, AtomicLong right) {
return left.floatValue() - right.longValue();
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2)", constantExpression = true)
public static float operator_plus(Float left, long right) {
return left.floatValue() + right;
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2)", constantExpression = true)
public static float operator_plus(Float left, byte right) {
return left.floatValue() + right;
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2)", constantExpression = true)
public static float operator_plus(Float left, int right) {
return left.floatValue() + right;
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2)", constantExpression = true)
public static float operator_plus(Float left, short right) {
return left.floatValue() + right;
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2)", constantExpression = true)
public static double operator_plus(Float left, double right) {
return left.floatValue() + right;
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2)", constantExpression = true)
public static float operator_plus(Float left, float right) {
return left.floatValue() + right;
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2.longValue())", constantExpression = true)
public static float operator_plus(Float left, Long right) {
return left.floatValue() + right.longValue();
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2.byteValue())", constantExpression = true)
public static float operator_plus(Float left, Byte right) {
return left.floatValue() + right.byteValue();
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2.floatValue())", constantExpression = true)
public static float operator_plus(Float left, Float right) {
return left.floatValue() + right.floatValue();
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2.intValue())", constantExpression = true)
public static float operator_plus(Float left, Integer right) {
return left.floatValue() + right.intValue();
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2.shortValue())", constantExpression = true)
public static float operator_plus(Float left, Short right) {
return left.floatValue() + right.shortValue();
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2.intValue())", constantExpression = true)
public static float operator_plus(Float left, AtomicInteger right) {
return left.floatValue() + right.intValue();
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2.longValue())", constantExpression = true)
public static float operator_plus(Float left, AtomicLong right) {
return left.floatValue() + right.longValue();
}
/** The binary {@code plus} operator. This is the equivalent to
* the Java {@code +} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left+right}
*/
@Pure
@Inline(value = "($1.floatValue() + $2.doubleValue())", constantExpression = true)
public static double operator_plus(Float left, Number right) {
return left.floatValue() + right.doubleValue();
}
/** The binary {@code power} operator. This is the equivalent to
* the Java's {@code Math.pow()} function. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code Math::pow(left, right)}
*/
@Pure
@Inline(value = "$3.pow($1.floatValue(), $2)", imported = Math.class)
public static double operator_power(Float left, long right) {
return Math.pow(left.floatValue(), right);
}
/** The binary {@code power} operator. This is the equivalent to
* the Java's {@code Math.pow()} function. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code Math::pow(left, right)}
*/
@Pure
@Inline(value = "$3.pow($1.floatValue(), $2)", imported = Math.class)
public static double operator_power(Float left, byte right) {
return Math.pow(left.floatValue(), right);
}
/** The binary {@code power} operator. This is the equivalent to
* the Java's {@code Math.pow()} function. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code Math::pow(left, right)}
*/
@Pure
@Inline(value = "$3.pow($1.floatValue(), $2)", imported = Math.class)
public static double operator_power(Float left, int right) {
return Math.pow(left.floatValue(), right);
}
/** The binary {@code power} operator. This is the equivalent to
* the Java's {@code Math.pow()} function.
*
* @param left a number.
* @param right a number.
* @return {@code Math::pow(left, right)}
*/
@Pure
@Inline(value = "$3.pow($1.floatValue(), $2)", imported = Math.class)
public static double operator_power(Float left, short right) {
return Math.pow(left.floatValue(), right);
}
/** The binary {@code power} operator. This is the equivalent to
* the Java's {@code Math.pow()} function. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code Math::pow(left, right)}
*/
@Pure
@Inline(value = "$3.pow($1.floatValue(), $2)", imported = Math.class)
public static double operator_power(Float left, double right) {
return Math.pow(left.floatValue(), right);
}
/** The binary {@code power} operator. This is the equivalent to
* the Java's {@code Math.pow()} function. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code Math::pow(left, right)}
*/
@Pure
@Inline(value = "$3.pow($1.floatValue(), $2)", imported = Math.class)
public static double operator_power(Float left, float right) {
return Math.pow(left.floatValue(), right);
}
/** The binary {@code power} operator. This is the equivalent to
* the Java's {@code Math.pow()} function. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code Math::pow(left, right)}
*/
@Pure
@Inline(value = "$3.pow($1.floatValue(), $2.doubleValue())", imported = Math.class)
public static double operator_power(Float left, Number right) {
return Math.pow(left.floatValue(), right.doubleValue());
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2)", constantExpression = true)
public static float operator_divide(Float left, long right) {
return left.floatValue() / right;
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2)", constantExpression = true)
public static float operator_divide(Float left, byte right) {
return left.floatValue() / right;
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2)", constantExpression = true)
public static float operator_divide(Float left, int right) {
return left.floatValue() / right;
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2)", constantExpression = true)
public static float operator_divide(Float left, short right) {
return left.floatValue() / right;
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2)", constantExpression = true)
public static double operator_divide(Float left, double right) {
return left.floatValue() / right;
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2)", constantExpression = true)
public static float operator_divide(Float left, float right) {
return left.floatValue() / right;
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2.longValue())", constantExpression = true)
public static float operator_divide(Float left, Long right) {
return left.floatValue() / right.longValue();
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2.byteValue())", constantExpression = true)
public static float operator_divide(Float left, Byte right) {
return left.floatValue() / right.byteValue();
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2.floatValue())", constantExpression = true)
public static float operator_divide(Float left, Float right) {
return left.floatValue() / right.floatValue();
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2.intValue())", constantExpression = true)
public static float operator_divide(Float left, Integer right) {
return left.floatValue() / right.intValue();
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2.doubleValue())", constantExpression = true)
public static double operator_divide(Float left, Number right) {
return left.floatValue() / right.doubleValue();
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2.shortValue())", constantExpression = true)
public static float operator_divide(Float left, Short right) {
return left.floatValue() / right.shortValue();
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2.intValue())", constantExpression = true)
public static float operator_divide(Float left, AtomicInteger right) {
return left.floatValue() / right.intValue();
}
/** The binary {@code divide} operator. This is the equivalent to
* the Java {@code /} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left/right}
*/
@Pure
@Inline(value = "($1.floatValue() / $2.longValue())", constantExpression = true)
public static float operator_divide(Float left, AtomicLong right) {
return left.floatValue() / right.longValue();
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2)", constantExpression = true)
public static float operator_multiply(Float left, long right) {
return left.floatValue() * right;
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2)", constantExpression = true)
public static float operator_multiply(Float left, byte right) {
return left.floatValue() * right;
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2)", constantExpression = true)
public static float operator_multiply(Float left, int right) {
return left.floatValue() * right;
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2)", constantExpression = true)
public static float operator_multiply(Float left, short right) {
return left.floatValue() * right;
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2)", constantExpression = true)
public static double operator_multiply(Float left, double right) {
return left.floatValue() * right;
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2)", constantExpression = true)
public static float operator_multiply(Float left, float right) {
return left.floatValue() * right;
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2.longValue())", constantExpression = true)
public static float operator_multiply(Float left, Long right) {
return left.floatValue() * right.longValue();
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2.byteValue())", constantExpression = true)
public static float operator_multiply(Float left, Byte right) {
return left.floatValue() * right.byteValue();
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2.floatValue())", constantExpression = true)
public static float operator_multiply(Float left, Float right) {
return left.floatValue() * right.floatValue();
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2.intValue())", constantExpression = true)
public static float operator_multiply(Float left, Integer right) {
return left.floatValue() * right.intValue();
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2.doubleValue())", constantExpression = true)
public static double operator_multiply(Float left, Number right) {
return left.floatValue() * right.doubleValue();
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2.shortValue())", constantExpression = true)
public static float operator_multiply(Float left, Short right) {
return left.floatValue() * right.shortValue();
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2.intValue())", constantExpression = true)
public static float operator_multiply(Float left, AtomicInteger right) {
return left.floatValue() * right.intValue();
}
/** The binary {@code multiply} operator. This is the equivalent to
* the Java {@code *} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left*right}
*/
@Pure
@Inline(value = "($1.floatValue() * $2.longValue())", constantExpression = true)
public static float operator_multiply(Float left, AtomicLong right) {
return left.floatValue() * right.longValue();
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2)", constantExpression = true)
public static float operator_modulo(Float left, long right) {
return left.floatValue() % right;
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2)", constantExpression = true)
public static float operator_modulo(Float left, byte right) {
return left.floatValue() % right;
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2)", constantExpression = true)
public static float operator_modulo(Float left, int right) {
return left.floatValue() % right;
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2)", constantExpression = true)
public static float operator_modulo(Float left, short right) {
return left.floatValue() % right;
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2)", constantExpression = true)
public static double operator_modulo(Float left, double right) {
return left.floatValue() % right;
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2)", constantExpression = true)
public static float operator_modulo(Float left, float right) {
return left.floatValue() % right;
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2.longValue())", constantExpression = true)
public static float operator_modulo(Float left, Long right) {
return left.floatValue() % right.longValue();
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2.byteValue())", constantExpression = true)
public static float operator_modulo(Float left, Byte right) {
return left.floatValue() % right.byteValue();
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2.floatValue())", constantExpression = true)
public static float operator_modulo(Float left, Float right) {
return left.floatValue() % right.floatValue();
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2.intValue())", constantExpression = true)
public static float operator_modulo(Float left, Integer right) {
return left.floatValue() % right.intValue();
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2.doubleValue())", constantExpression = true)
public static double operator_modulo(Float left, Number right) {
return left.floatValue() % right.doubleValue();
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2.shortValue())", constantExpression = true)
public static float operator_modulo(Float left, Short right) {
return left.floatValue() % right.shortValue();
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2.intValue())", constantExpression = true)
public static float operator_modulo(Float left, AtomicInteger right) {
return left.floatValue() % right.intValue();
}
/** The binary {@code modulo} operator. This is the equivalent to
* the Java {@code %} operator. This function is not null-safe.
*
* @param left a number.
* @param right a number.
* @return {@code left%right}
*/
@Pure
@Inline(value = "($1.floatValue() % $2.longValue())", constantExpression = true)
public static float operator_modulo(Float left, AtomicLong right) {
return left.floatValue() % right.longValue();
}
}
| {
"pile_set_name": "Github"
} |
from django.apps import AppConfig
class ProfilesConfig(AppConfig):
name = 'profiles'
| {
"pile_set_name": "Github"
} |
// Copyright Jetstack Ltd. See LICENSE for details.
//
// 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 v1alpha1
// Taint structure for instancepool node taints
type Taint struct {
Key string `json:"key,omitempty"`
Value string `json:"value,omitempty"`
Effect string `json:"effect,omitempty"`
}
| {
"pile_set_name": "Github"
} |
/*
* IMG I2S output controller driver
*
* Copyright (C) 2015 Imagination Technologies Ltd.
*
* Author: Damien Horsley <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*/
#include <linux/clk.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/reset.h>
#include <sound/core.h>
#include <sound/dmaengine_pcm.h>
#include <sound/initval.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#define IMG_I2S_OUT_TX_FIFO 0x0
#define IMG_I2S_OUT_CTL 0x4
#define IMG_I2S_OUT_CTL_DATA_EN_MASK BIT(24)
#define IMG_I2S_OUT_CTL_ACTIVE_CHAN_MASK 0xffe000
#define IMG_I2S_OUT_CTL_ACTIVE_CHAN_SHIFT 13
#define IMG_I2S_OUT_CTL_FRM_SIZE_MASK BIT(8)
#define IMG_I2S_OUT_CTL_MASTER_MASK BIT(6)
#define IMG_I2S_OUT_CTL_CLK_MASK BIT(5)
#define IMG_I2S_OUT_CTL_CLK_EN_MASK BIT(4)
#define IMG_I2S_OUT_CTL_FRM_CLK_POL_MASK BIT(3)
#define IMG_I2S_OUT_CTL_BCLK_POL_MASK BIT(2)
#define IMG_I2S_OUT_CTL_ME_MASK BIT(0)
#define IMG_I2S_OUT_CH_CTL 0x4
#define IMG_I2S_OUT_CHAN_CTL_CH_MASK BIT(11)
#define IMG_I2S_OUT_CHAN_CTL_LT_MASK BIT(10)
#define IMG_I2S_OUT_CHAN_CTL_FMT_MASK 0xf0
#define IMG_I2S_OUT_CHAN_CTL_FMT_SHIFT 4
#define IMG_I2S_OUT_CHAN_CTL_JUST_MASK BIT(3)
#define IMG_I2S_OUT_CHAN_CTL_CLKT_MASK BIT(1)
#define IMG_I2S_OUT_CHAN_CTL_ME_MASK BIT(0)
#define IMG_I2S_OUT_CH_STRIDE 0x20
struct img_i2s_out {
void __iomem *base;
struct clk *clk_sys;
struct clk *clk_ref;
struct snd_dmaengine_dai_dma_data dma_data;
struct device *dev;
unsigned int max_i2s_chan;
void __iomem *channel_base;
bool force_clk_active;
unsigned int active_channels;
struct reset_control *rst;
struct snd_soc_dai_driver dai_driver;
u32 suspend_ctl;
u32 *suspend_ch_ctl;
};
static int img_i2s_out_runtime_suspend(struct device *dev)
{
struct img_i2s_out *i2s = dev_get_drvdata(dev);
clk_disable_unprepare(i2s->clk_ref);
clk_disable_unprepare(i2s->clk_sys);
return 0;
}
static int img_i2s_out_runtime_resume(struct device *dev)
{
struct img_i2s_out *i2s = dev_get_drvdata(dev);
int ret;
ret = clk_prepare_enable(i2s->clk_sys);
if (ret) {
dev_err(dev, "clk_enable failed: %d\n", ret);
return ret;
}
ret = clk_prepare_enable(i2s->clk_ref);
if (ret) {
dev_err(dev, "clk_enable failed: %d\n", ret);
clk_disable_unprepare(i2s->clk_sys);
return ret;
}
return 0;
}
static inline void img_i2s_out_writel(struct img_i2s_out *i2s, u32 val,
u32 reg)
{
writel(val, i2s->base + reg);
}
static inline u32 img_i2s_out_readl(struct img_i2s_out *i2s, u32 reg)
{
return readl(i2s->base + reg);
}
static inline void img_i2s_out_ch_writel(struct img_i2s_out *i2s,
u32 chan, u32 val, u32 reg)
{
writel(val, i2s->channel_base + (chan * IMG_I2S_OUT_CH_STRIDE) + reg);
}
static inline u32 img_i2s_out_ch_readl(struct img_i2s_out *i2s, u32 chan,
u32 reg)
{
return readl(i2s->channel_base + (chan * IMG_I2S_OUT_CH_STRIDE) + reg);
}
static inline void img_i2s_out_ch_disable(struct img_i2s_out *i2s, u32 chan)
{
u32 reg;
reg = img_i2s_out_ch_readl(i2s, chan, IMG_I2S_OUT_CH_CTL);
reg &= ~IMG_I2S_OUT_CHAN_CTL_ME_MASK;
img_i2s_out_ch_writel(i2s, chan, reg, IMG_I2S_OUT_CH_CTL);
}
static inline void img_i2s_out_ch_enable(struct img_i2s_out *i2s, u32 chan)
{
u32 reg;
reg = img_i2s_out_ch_readl(i2s, chan, IMG_I2S_OUT_CH_CTL);
reg |= IMG_I2S_OUT_CHAN_CTL_ME_MASK;
img_i2s_out_ch_writel(i2s, chan, reg, IMG_I2S_OUT_CH_CTL);
}
static inline void img_i2s_out_disable(struct img_i2s_out *i2s)
{
u32 reg;
reg = img_i2s_out_readl(i2s, IMG_I2S_OUT_CTL);
reg &= ~IMG_I2S_OUT_CTL_ME_MASK;
img_i2s_out_writel(i2s, reg, IMG_I2S_OUT_CTL);
}
static inline void img_i2s_out_enable(struct img_i2s_out *i2s)
{
u32 reg;
reg = img_i2s_out_readl(i2s, IMG_I2S_OUT_CTL);
reg |= IMG_I2S_OUT_CTL_ME_MASK;
img_i2s_out_writel(i2s, reg, IMG_I2S_OUT_CTL);
}
static void img_i2s_out_reset(struct img_i2s_out *i2s)
{
int i;
u32 core_ctl, chan_ctl;
core_ctl = img_i2s_out_readl(i2s, IMG_I2S_OUT_CTL) &
~IMG_I2S_OUT_CTL_ME_MASK &
~IMG_I2S_OUT_CTL_DATA_EN_MASK;
if (!i2s->force_clk_active)
core_ctl &= ~IMG_I2S_OUT_CTL_CLK_EN_MASK;
chan_ctl = img_i2s_out_ch_readl(i2s, 0, IMG_I2S_OUT_CH_CTL) &
~IMG_I2S_OUT_CHAN_CTL_ME_MASK;
reset_control_assert(i2s->rst);
reset_control_deassert(i2s->rst);
for (i = 0; i < i2s->max_i2s_chan; i++)
img_i2s_out_ch_writel(i2s, i, chan_ctl, IMG_I2S_OUT_CH_CTL);
for (i = 0; i < i2s->active_channels; i++)
img_i2s_out_ch_enable(i2s, i);
img_i2s_out_writel(i2s, core_ctl, IMG_I2S_OUT_CTL);
img_i2s_out_enable(i2s);
}
static int img_i2s_out_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
struct img_i2s_out *i2s = snd_soc_dai_get_drvdata(dai);
u32 reg;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
reg = img_i2s_out_readl(i2s, IMG_I2S_OUT_CTL);
if (!i2s->force_clk_active)
reg |= IMG_I2S_OUT_CTL_CLK_EN_MASK;
reg |= IMG_I2S_OUT_CTL_DATA_EN_MASK;
img_i2s_out_writel(i2s, reg, IMG_I2S_OUT_CTL);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
img_i2s_out_reset(i2s);
break;
default:
return -EINVAL;
}
return 0;
}
static int img_i2s_out_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params, struct snd_soc_dai *dai)
{
struct img_i2s_out *i2s = snd_soc_dai_get_drvdata(dai);
unsigned int channels, i2s_channels;
long pre_div_a, pre_div_b, diff_a, diff_b, rate, clk_rate;
int i;
u32 reg, control_mask, control_set = 0;
snd_pcm_format_t format;
rate = params_rate(params);
format = params_format(params);
channels = params_channels(params);
i2s_channels = channels / 2;
if (format != SNDRV_PCM_FORMAT_S32_LE)
return -EINVAL;
if ((channels < 2) ||
(channels > (i2s->max_i2s_chan * 2)) ||
(channels % 2))
return -EINVAL;
pre_div_a = clk_round_rate(i2s->clk_ref, rate * 256);
if (pre_div_a < 0)
return pre_div_a;
pre_div_b = clk_round_rate(i2s->clk_ref, rate * 384);
if (pre_div_b < 0)
return pre_div_b;
diff_a = abs((pre_div_a / 256) - rate);
diff_b = abs((pre_div_b / 384) - rate);
/* If diffs are equal, use lower clock rate */
if (diff_a > diff_b)
clk_set_rate(i2s->clk_ref, pre_div_b);
else
clk_set_rate(i2s->clk_ref, pre_div_a);
/*
* Another driver (eg alsa machine driver) may have rejected the above
* change. Get the current rate and set the register bit according to
* the new minimum diff
*/
clk_rate = clk_get_rate(i2s->clk_ref);
diff_a = abs((clk_rate / 256) - rate);
diff_b = abs((clk_rate / 384) - rate);
if (diff_a > diff_b)
control_set |= IMG_I2S_OUT_CTL_CLK_MASK;
control_set |= ((i2s_channels - 1) <<
IMG_I2S_OUT_CTL_ACTIVE_CHAN_SHIFT) &
IMG_I2S_OUT_CTL_ACTIVE_CHAN_MASK;
control_mask = IMG_I2S_OUT_CTL_CLK_MASK |
IMG_I2S_OUT_CTL_ACTIVE_CHAN_MASK;
img_i2s_out_disable(i2s);
reg = img_i2s_out_readl(i2s, IMG_I2S_OUT_CTL);
reg = (reg & ~control_mask) | control_set;
img_i2s_out_writel(i2s, reg, IMG_I2S_OUT_CTL);
for (i = 0; i < i2s_channels; i++)
img_i2s_out_ch_enable(i2s, i);
for (; i < i2s->max_i2s_chan; i++)
img_i2s_out_ch_disable(i2s, i);
img_i2s_out_enable(i2s);
i2s->active_channels = i2s_channels;
return 0;
}
static int img_i2s_out_set_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct img_i2s_out *i2s = snd_soc_dai_get_drvdata(dai);
int i, ret;
bool force_clk_active;
u32 chan_control_mask, control_mask, chan_control_set = 0;
u32 reg, control_set = 0;
force_clk_active = ((fmt & SND_SOC_DAIFMT_CLOCK_MASK) ==
SND_SOC_DAIFMT_CONT);
if (force_clk_active)
control_set |= IMG_I2S_OUT_CTL_CLK_EN_MASK;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
break;
case SND_SOC_DAIFMT_CBS_CFS:
control_set |= IMG_I2S_OUT_CTL_MASTER_MASK;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
control_set |= IMG_I2S_OUT_CTL_BCLK_POL_MASK;
break;
case SND_SOC_DAIFMT_NB_IF:
control_set |= IMG_I2S_OUT_CTL_BCLK_POL_MASK;
control_set |= IMG_I2S_OUT_CTL_FRM_CLK_POL_MASK;
break;
case SND_SOC_DAIFMT_IB_NF:
break;
case SND_SOC_DAIFMT_IB_IF:
control_set |= IMG_I2S_OUT_CTL_FRM_CLK_POL_MASK;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
chan_control_set |= IMG_I2S_OUT_CHAN_CTL_CLKT_MASK;
break;
case SND_SOC_DAIFMT_LEFT_J:
break;
default:
return -EINVAL;
}
control_mask = IMG_I2S_OUT_CTL_CLK_EN_MASK |
IMG_I2S_OUT_CTL_MASTER_MASK |
IMG_I2S_OUT_CTL_BCLK_POL_MASK |
IMG_I2S_OUT_CTL_FRM_CLK_POL_MASK;
chan_control_mask = IMG_I2S_OUT_CHAN_CTL_CLKT_MASK;
ret = pm_runtime_get_sync(i2s->dev);
if (ret < 0)
return ret;
img_i2s_out_disable(i2s);
reg = img_i2s_out_readl(i2s, IMG_I2S_OUT_CTL);
reg = (reg & ~control_mask) | control_set;
img_i2s_out_writel(i2s, reg, IMG_I2S_OUT_CTL);
for (i = 0; i < i2s->active_channels; i++)
img_i2s_out_ch_disable(i2s, i);
for (i = 0; i < i2s->max_i2s_chan; i++) {
reg = img_i2s_out_ch_readl(i2s, i, IMG_I2S_OUT_CH_CTL);
reg = (reg & ~chan_control_mask) | chan_control_set;
img_i2s_out_ch_writel(i2s, i, reg, IMG_I2S_OUT_CH_CTL);
}
for (i = 0; i < i2s->active_channels; i++)
img_i2s_out_ch_enable(i2s, i);
img_i2s_out_enable(i2s);
pm_runtime_put(i2s->dev);
i2s->force_clk_active = force_clk_active;
return 0;
}
static const struct snd_soc_dai_ops img_i2s_out_dai_ops = {
.trigger = img_i2s_out_trigger,
.hw_params = img_i2s_out_hw_params,
.set_fmt = img_i2s_out_set_fmt
};
static int img_i2s_out_dai_probe(struct snd_soc_dai *dai)
{
struct img_i2s_out *i2s = snd_soc_dai_get_drvdata(dai);
snd_soc_dai_init_dma_data(dai, &i2s->dma_data, NULL);
return 0;
}
static const struct snd_soc_component_driver img_i2s_out_component = {
.name = "img-i2s-out"
};
static int img_i2s_out_dma_prepare_slave_config(struct snd_pcm_substream *st,
struct snd_pcm_hw_params *params, struct dma_slave_config *sc)
{
unsigned int i2s_channels = params_channels(params) / 2;
struct snd_soc_pcm_runtime *rtd = st->private_data;
struct snd_dmaengine_dai_dma_data *dma_data;
int ret;
dma_data = snd_soc_dai_get_dma_data(rtd->cpu_dai, st);
ret = snd_hwparams_to_dma_slave_config(st, params, sc);
if (ret)
return ret;
sc->dst_addr = dma_data->addr;
sc->dst_addr_width = dma_data->addr_width;
sc->dst_maxburst = 4 * i2s_channels;
return 0;
}
static const struct snd_dmaengine_pcm_config img_i2s_out_dma_config = {
.prepare_slave_config = img_i2s_out_dma_prepare_slave_config
};
static int img_i2s_out_probe(struct platform_device *pdev)
{
struct img_i2s_out *i2s;
struct resource *res;
void __iomem *base;
int i, ret;
unsigned int max_i2s_chan_pow_2;
u32 reg;
struct device *dev = &pdev->dev;
i2s = devm_kzalloc(&pdev->dev, sizeof(*i2s), GFP_KERNEL);
if (!i2s)
return -ENOMEM;
platform_set_drvdata(pdev, i2s);
i2s->dev = &pdev->dev;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(base))
return PTR_ERR(base);
i2s->base = base;
if (of_property_read_u32(pdev->dev.of_node, "img,i2s-channels",
&i2s->max_i2s_chan)) {
dev_err(&pdev->dev, "No img,i2s-channels property\n");
return -EINVAL;
}
max_i2s_chan_pow_2 = 1 << get_count_order(i2s->max_i2s_chan);
i2s->channel_base = base + (max_i2s_chan_pow_2 * 0x20);
i2s->rst = devm_reset_control_get_exclusive(&pdev->dev, "rst");
if (IS_ERR(i2s->rst)) {
if (PTR_ERR(i2s->rst) != -EPROBE_DEFER)
dev_err(&pdev->dev, "No top level reset found\n");
return PTR_ERR(i2s->rst);
}
i2s->clk_sys = devm_clk_get(&pdev->dev, "sys");
if (IS_ERR(i2s->clk_sys)) {
if (PTR_ERR(i2s->clk_sys) != -EPROBE_DEFER)
dev_err(dev, "Failed to acquire clock 'sys'\n");
return PTR_ERR(i2s->clk_sys);
}
i2s->clk_ref = devm_clk_get(&pdev->dev, "ref");
if (IS_ERR(i2s->clk_ref)) {
if (PTR_ERR(i2s->clk_ref) != -EPROBE_DEFER)
dev_err(dev, "Failed to acquire clock 'ref'\n");
return PTR_ERR(i2s->clk_ref);
}
i2s->suspend_ch_ctl = devm_kcalloc(dev,
i2s->max_i2s_chan, sizeof(*i2s->suspend_ch_ctl), GFP_KERNEL);
if (!i2s->suspend_ch_ctl)
return -ENOMEM;
pm_runtime_enable(&pdev->dev);
if (!pm_runtime_enabled(&pdev->dev)) {
ret = img_i2s_out_runtime_resume(&pdev->dev);
if (ret)
goto err_pm_disable;
}
ret = pm_runtime_get_sync(&pdev->dev);
if (ret < 0)
goto err_suspend;
reg = IMG_I2S_OUT_CTL_FRM_SIZE_MASK;
img_i2s_out_writel(i2s, reg, IMG_I2S_OUT_CTL);
reg = IMG_I2S_OUT_CHAN_CTL_JUST_MASK |
IMG_I2S_OUT_CHAN_CTL_LT_MASK |
IMG_I2S_OUT_CHAN_CTL_CH_MASK |
(8 << IMG_I2S_OUT_CHAN_CTL_FMT_SHIFT);
for (i = 0; i < i2s->max_i2s_chan; i++)
img_i2s_out_ch_writel(i2s, i, reg, IMG_I2S_OUT_CH_CTL);
img_i2s_out_reset(i2s);
pm_runtime_put(&pdev->dev);
i2s->active_channels = 1;
i2s->dma_data.addr = res->start + IMG_I2S_OUT_TX_FIFO;
i2s->dma_data.addr_width = 4;
i2s->dma_data.maxburst = 4;
i2s->dai_driver.probe = img_i2s_out_dai_probe;
i2s->dai_driver.playback.channels_min = 2;
i2s->dai_driver.playback.channels_max = i2s->max_i2s_chan * 2;
i2s->dai_driver.playback.rates = SNDRV_PCM_RATE_8000_192000;
i2s->dai_driver.playback.formats = SNDRV_PCM_FMTBIT_S32_LE;
i2s->dai_driver.ops = &img_i2s_out_dai_ops;
ret = devm_snd_soc_register_component(&pdev->dev,
&img_i2s_out_component, &i2s->dai_driver, 1);
if (ret)
goto err_suspend;
ret = devm_snd_dmaengine_pcm_register(&pdev->dev,
&img_i2s_out_dma_config, 0);
if (ret)
goto err_suspend;
return 0;
err_suspend:
if (!pm_runtime_status_suspended(&pdev->dev))
img_i2s_out_runtime_suspend(&pdev->dev);
err_pm_disable:
pm_runtime_disable(&pdev->dev);
return ret;
}
static int img_i2s_out_dev_remove(struct platform_device *pdev)
{
pm_runtime_disable(&pdev->dev);
if (!pm_runtime_status_suspended(&pdev->dev))
img_i2s_out_runtime_suspend(&pdev->dev);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int img_i2s_out_suspend(struct device *dev)
{
struct img_i2s_out *i2s = dev_get_drvdata(dev);
int i, ret;
u32 reg;
if (pm_runtime_status_suspended(dev)) {
ret = img_i2s_out_runtime_resume(dev);
if (ret)
return ret;
}
for (i = 0; i < i2s->max_i2s_chan; i++) {
reg = img_i2s_out_ch_readl(i2s, i, IMG_I2S_OUT_CH_CTL);
i2s->suspend_ch_ctl[i] = reg;
}
i2s->suspend_ctl = img_i2s_out_readl(i2s, IMG_I2S_OUT_CTL);
img_i2s_out_runtime_suspend(dev);
return 0;
}
static int img_i2s_out_resume(struct device *dev)
{
struct img_i2s_out *i2s = dev_get_drvdata(dev);
int i, ret;
u32 reg;
ret = img_i2s_out_runtime_resume(dev);
if (ret)
return ret;
for (i = 0; i < i2s->max_i2s_chan; i++) {
reg = i2s->suspend_ch_ctl[i];
img_i2s_out_ch_writel(i2s, i, reg, IMG_I2S_OUT_CH_CTL);
}
img_i2s_out_writel(i2s, i2s->suspend_ctl, IMG_I2S_OUT_CTL);
if (pm_runtime_status_suspended(dev))
img_i2s_out_runtime_suspend(dev);
return 0;
}
#endif
static const struct of_device_id img_i2s_out_of_match[] = {
{ .compatible = "img,i2s-out" },
{}
};
MODULE_DEVICE_TABLE(of, img_i2s_out_of_match);
static const struct dev_pm_ops img_i2s_out_pm_ops = {
SET_RUNTIME_PM_OPS(img_i2s_out_runtime_suspend,
img_i2s_out_runtime_resume, NULL)
SET_SYSTEM_SLEEP_PM_OPS(img_i2s_out_suspend, img_i2s_out_resume)
};
static struct platform_driver img_i2s_out_driver = {
.driver = {
.name = "img-i2s-out",
.of_match_table = img_i2s_out_of_match,
.pm = &img_i2s_out_pm_ops
},
.probe = img_i2s_out_probe,
.remove = img_i2s_out_dev_remove
};
module_platform_driver(img_i2s_out_driver);
MODULE_AUTHOR("Damien Horsley <[email protected]>");
MODULE_DESCRIPTION("IMG I2S Output Driver");
MODULE_LICENSE("GPL v2");
| {
"pile_set_name": "Github"
} |
**Xamarin is not responsible for, nor does it grant any licenses to, third-party packages. Some packages may require or install dependencies which are governed by additional licenses.**
Note: This component is a derived work of [StikkyHeader](https://github.com/carlonzo/StikkyHeader), which is subject to the [Apache License, Version 2.0](https://github.com/carlonzo/StikkyHeader/blob/develop/LICENSE)
### Xamarin Component for Sticky Header
**The MIT License (MIT)**
Copyright (c) .NET Foundation Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20160601
| {
"pile_set_name": "Github"
} |
# recycler-view-swipe-to-delete
Sample project showing "swipe to delete" on a recycler view with no 3rd parties involved. It also include drawing on empty space while items are animating and an "undo" option
Blog post with gif animations of the sample app:
http://nemanjakovacevic.net/blog/english/2016/01/12/recyclerview-swipe-to-delete-no-3rd-party-lib-necessary/
| {
"pile_set_name": "Github"
} |
DEFINED_PHASES=compile install preinst prepare setup unpack
DEPEND=virtual/libusb:1 virtual/libudev virtual/jpeg:0 opengl? ( media-libs/freeglut ) java? ( >=virtual/jre-1.5:* ) doc? ( app-doc/doxygen ) java? ( >=virtual/jdk-1.5:* ) >=dev-vcs/git-1.8.2.1[curl] java? ( >=dev-java/java-config-2.2.0-r3 )
DESCRIPTION=OpenNI2 SDK
EAPI=5
HOMEPAGE=https://structure.io/openni
IUSE=doc java neon opengl static-libs elibc_FreeBSD java
LICENSE=Apache-2.0
PROPERTIES=live
RDEPEND=virtual/libusb:1 virtual/libudev virtual/jpeg:0 opengl? ( media-libs/freeglut ) java? ( >=virtual/jre-1.5:* ) java? ( >=dev-java/java-config-2.2.0-r3 )
SLOT=0
_eclasses_=desktop 7fd20552ce4cc97e8acb132a499a7dd8 eapi7-ver f9ec87e93172b25ce65a85303dc06964 edos2unix 33e347e171066657f91f8b0c72ec8773 epatch ed88001f77c6dd0d5f09e45c1a5b480e estack 686eaab303305a908fd57b2fd7617800 eutils 2d5b3f4b315094768576b6799e4f926e flag-o-matic 09a8beb8e6a8e02dc1e1bd83ac353741 git-r3 3e7ec3d6619213460c85e2aa48398441 java-pkg-opt-2 77d2e22d0de7640f817d20e861c0ff3f java-utils-2 ec7a89849c84f93e9c6db27812923888 l10n 8cdd85e169b835d518bc2fd59f780d8e ltprune db8b7ce9d0e663594bcb4a4e72131a79 multilib 98584e405e2b0264d37e8f728327fed1 preserve-libs ef207dc62baddfddfd39a164d9797648 toolchain-funcs 605c126bed8d87e4378d5ff1645330cb vcs-clean 2a0f74a496fa2b1552c4f3398258b7bf versionator 2352c3fc97241f6a02042773c8287748 wrapper 4251d4c84c25f59094fd557e0063a974
_md5_=a3bb921af0b1cd48215784be809d7c3a
| {
"pile_set_name": "Github"
} |
[99999999 GP]
04100000 98fd2514 05F5E0FF
[9999999 EXP]
04100000 98fd2554 0098967F | {
"pile_set_name": "Github"
} |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Gapps
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Gdata_Feed
*/
//$1 'Zend/Gdata/Feed.php';
/**
* @see Zend_Gdata_Gapps_UserEntry
*/
//$1 'Zend/Gdata/Gapps/UserEntry.php';
/**
* Data model for a collection of Google Apps user entries, usually
* provided by the Google Apps servers.
*
* For information on requesting this feed from a server, see the Google
* Apps service class, Zend_Gdata_Gapps.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Gapps
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_Gapps_UserFeed extends Zend_Gdata_Feed
{
protected $_entryClassName = 'Zend_Gdata_Gapps_UserEntry';
protected $_feedClassName = 'Zend_Gdata_Gapps_UserFeed';
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* @author Björn Schießle <[email protected]>
* @author Georg Ehrke <[email protected]>
* @author Joas Schilling <[email protected]>
* @author Lukas Reschke <[email protected]>
* @author Morris Jobke <[email protected]>
* @author Robin Appelman <[email protected]>
* @author Roeland Jago Douma <[email protected]>
* @author Thomas Müller <[email protected]>
* @author Vincent Cloutier <[email protected]>
*
* @copyright Copyright (c) 2018, ownCloud GmbH
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Sharing\Tests\Controllers;
use OC\Files\Filesystem;
use OCA\FederatedFileSharing\FederatedShareProvider;
use OCA\Files_Sharing\Controllers\ShareController;
use OCP\AppFramework\Http\NotFoundResponse;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\ISession;
use OCP\IURLGenerator;
use OCP\IUserManager;
use OCP\Security\ISecureRandom;
use OCP\Share\Exceptions\ShareNotFound;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\GenericEvent;
/**
* @group DB
*
* @package OCA\Files_Sharing\Controllers
*/
class ShareControllerTest extends \Test\TestCase {
/** @var string */
private $user;
/** @var string */
private $oldUser;
/** @var string */
private $appName = 'files_sharing';
/** @var ShareController */
private $shareController;
/** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */
private $urlGenerator;
/** @var ISession | \PHPUnit\Framework\MockObject\MockObject */
private $session;
/** @var \OCP\IPreview | \PHPUnit\Framework\MockObject\MockObject */
private $previewManager;
/** @var \OCP\IConfig | \PHPUnit\Framework\MockObject\MockObject */
private $config;
/** @var \OC\Share20\Manager | \PHPUnit\Framework\MockObject\MockObject */
private $shareManager;
/** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */
private $userManager;
/** @var EventDispatcher | \PHPUnit\Framework\MockObject\MockObject */
private $eventDispatcher;
protected function setUp(): void {
parent::setUp();
$this->appName = 'files_sharing';
$this->shareManager = $this->getMockBuilder('\OC\Share20\Manager')->disableOriginalConstructor()->getMock();
$this->urlGenerator = $this->createMock('\OCP\IURLGenerator');
$this->session = $this->createMock('\OCP\ISession');
$this->previewManager = $this->createMock('\OCP\IPreview');
$this->config = $this->createMock('\OCP\IConfig');
$this->userManager = $this->createMock('\OCP\IUserManager');
$this->eventDispatcher = new EventDispatcher();
$this->shareController = new \OCA\Files_Sharing\Controllers\ShareController(
$this->appName,
$this->createMock('\OCP\IRequest'),
$this->config,
$this->urlGenerator,
$this->userManager,
$this->createMock('\OCP\ILogger'),
$this->createMock('\OCP\Activity\IManager'),
$this->shareManager,
$this->session,
$this->previewManager,
$this->createMock('\OCP\Files\IRootFolder'),
$this->eventDispatcher
);
// Store current user
$this->oldUser = \OC_User::getUser();
// Create a dummy user
$this->user = \OC::$server->getSecureRandom()->generate(12, ISecureRandom::CHAR_LOWER);
\OC::$server->getUserManager()->createUser($this->user, $this->user);
\OC_Util::tearDownFS();
$this->loginAsUser($this->user);
}
protected function tearDown(): void {
\OC_Util::tearDownFS();
\OC_User::setUserId('');
Filesystem::tearDown();
$user = \OC::$server->getUserManager()->get($this->user);
if ($user !== null) {
$user->delete();
}
\OC_User::setIncognitoMode(false);
\OC::$server->getSession()->set('public_link_authenticated', '');
// Set old user
\OC_User::setUserId($this->oldUser);
\OC_Util::setupFS($this->oldUser);
parent::tearDown();
}
public function testShowAuthenticateNotAuthenticated() {
$share = \OC::$server->getShareManager()->newShare();
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$response = $this->shareController->showAuthenticate('token');
$expectedResponse = new TemplateResponse($this->appName, 'authenticate', [], 'guest');
$this->assertEquals($expectedResponse, $response);
}
public function testShowAuthenticateAuthenticatedForDifferentShare() {
$share = \OC::$server->getShareManager()->newShare();
$share->setId(1);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
$this->session->method('get')->with('public_link_authenticated')->willReturn('2');
$response = $this->shareController->showAuthenticate('token');
$expectedResponse = new TemplateResponse($this->appName, 'authenticate', [], 'guest');
$this->assertEquals($expectedResponse, $response);
}
public function testShowAuthenticateCorrectShare() {
$share = \OC::$server->getShareManager()->newShare();
$share->setId(1);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
$this->session->method('get')->with('public_link_authenticated')->willReturn('1');
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with('files_sharing.sharecontroller.showShare', ['token' => 'token'])
->willReturn('redirect');
$response = $this->shareController->showAuthenticate('token');
$expectedResponse = new RedirectResponse('redirect');
$this->assertEquals($expectedResponse, $response);
}
public function testAuthenticateInvalidToken() {
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->will($this->throwException(new \OCP\Share\Exceptions\ShareNotFound()));
$response = $this->shareController->authenticate('token');
$expectedResponse = new NotFoundResponse();
$this->assertEquals($expectedResponse, $response);
}
public function testAuthenticateValidPassword() {
$share = \OC::$server->getShareManager()->newShare();
$share->setId(42);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$this->shareManager
->expects($this->once())
->method('checkPassword')
->with($share, 'validpassword')
->willReturn(true);
$this->session
->expects($this->once())
->method('set')
->with('public_link_authenticated', '42');
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with('files_sharing.sharecontroller.showShare', ['token'=>'token'])
->willReturn('redirect');
$beforeLinkAuthCalled = false;
$this->eventDispatcher->addListener(
'share.beforelinkauth', function () use (&$beforeLinkAuthCalled) {
$beforeLinkAuthCalled = true;
}
);
$afterLinkAuthCalled = false;
$this->eventDispatcher->addListener(
'share.afterlinkauth', function () use (&$afterLinkAuthCalled) {
$afterLinkAuthCalled = true;
}
);
$response = $this->shareController->authenticate('token', 'validpassword');
$expectedResponse = new RedirectResponse('redirect');
$this->assertEquals($expectedResponse, $response);
$this->assertEquals(true, $beforeLinkAuthCalled);
$this->assertEquals(true, $afterLinkAuthCalled);
}
public function testAuthenticateInvalidPassword() {
$share = \OC::$server->getShareManager()->newShare();
$share->setNodeId(100)
->setNodeType('file')
->setToken('token')
->setSharedBy('initiator')
->setId(42);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$this->shareManager
->expects($this->once())
->method('checkPassword')
->with($share, 'invalidpassword')
->willReturn(false);
$this->session
->expects($this->never())
->method('set');
$hookListner = $this->getMockBuilder('Dummy')->setMethods(['access'])->getMock();
\OCP\Util::connectHook('OCP\Share', 'share_link_access', $hookListner, 'access');
$calledShareLinkAccess = [];
$this->eventDispatcher->addListener('share.linkaccess',
function (GenericEvent $event) use (&$calledShareLinkAccess) {
$calledShareLinkAccess[] = 'share.linkaccess';
$calledShareLinkAccess[] = $event;
});
$beforeLinkAuthCalled = false;
$this->eventDispatcher->addListener(
'share.beforelinkauth', function () use (&$beforeLinkAuthCalled) {
$beforeLinkAuthCalled = true;
}
);
$afterLinkAuthCalled = false;
$this->eventDispatcher->addListener(
'share.afterlinkauth', function () use (&$afterLinkAuthCalled) {
$afterLinkAuthCalled = true;
}
);
$hookListner->expects($this->once())
->method('access')
->with($this->callback(function (array $data) {
return $data['itemType'] === 'file' &&
$data['itemSource'] === 100 &&
$data['uidOwner'] === 'initiator' &&
$data['token'] === 'token' &&
$data['errorCode'] === 403 &&
$data['errorMessage'] === 'Wrong password';
}));
$response = $this->shareController->authenticate('token', 'invalidpassword');
$expectedResponse = new TemplateResponse($this->appName, 'authenticate', ['wrongpw' => true], 'guest');
$this->assertEquals($expectedResponse, $response);
$this->assertEquals('share.linkaccess', $calledShareLinkAccess[0]);
$this->assertInstanceOf(GenericEvent::class, $calledShareLinkAccess[1]);
$this->assertArrayHasKey('shareObject', $calledShareLinkAccess[1]);
$this->assertEquals('42', $calledShareLinkAccess[1]->getArgument('shareObject')->getId());
$this->assertEquals('file', $calledShareLinkAccess[1]->getArgument('shareObject')->getNodeType());
$this->assertEquals('initiator', $calledShareLinkAccess[1]->getArgument('shareObject')->getSharedBy());
$this->assertEquals('token', $calledShareLinkAccess[1]->getArgument('shareObject')->getToken());
$this->assertEquals(403, $calledShareLinkAccess[1]->getArgument('errorCode'));
$this->assertEquals('Wrong password', $calledShareLinkAccess[1]->getArgument('errorMessage'));
$this->assertEquals(true, $beforeLinkAuthCalled);
$this->assertEquals(false, $afterLinkAuthCalled);
}
public function testShowShareInvalidToken() {
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('invalidtoken')
->will($this->throwException(new ShareNotFound()));
// Test without a not existing token
$response = $this->shareController->showShare('invalidtoken');
$expectedResponse = new NotFoundResponse();
$this->assertEquals($expectedResponse, $response);
}
public function testShowShareNotAuthenticated() {
$share = \OC::$server->getShareManager()->newShare();
$share->setPassword('password');
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('validtoken')
->willReturn($share);
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with('files_sharing.sharecontroller.authenticate', ['token' => 'validtoken'])
->willReturn('redirect');
// Test without a not existing token
$response = $this->shareController->showShare('validtoken');
$expectedResponse = new RedirectResponse('redirect');
$this->assertEquals($expectedResponse, $response);
}
public function testShowShare() {
$owner = $this->createMock('OCP\IUser');
$owner->method('getDisplayName')->willReturn('ownerDisplay');
$owner->method('getUID')->willReturn('ownerUID');
$file = $this->createMock('OCP\Files\File');
$file->method('getName')->willReturn('file1.txt');
$file->method('getMimetype')->willReturn('text/plain');
$file->method('getSize')->willReturn(33);
$file->method('isReadable')->willReturn(true);
$file->method('isShareable')->willReturn(true);
$share = \OC::$server->getShareManager()->newShare();
$share->setId(42);
$share->setPassword('password')
->setShareOwner('ownerUID')
->setNode($file)
->setPermissions(\OCP\Constants::PERMISSION_READ)
->setTarget('/file1.txt');
$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
$this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
$this->config->method('getSystemValue')
->willReturnMap(
[
['max_filesize_animated_gifs_public_sharing', 10, 10],
['enable_previews', true, true],
['preview_max_x', 1024, 1024],
['preview_max_y', 1024, 1024],
]
);
$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$this->userManager->method('get')->with('ownerUID')->willReturn($owner);
$loadAdditionalScriptsCalled = false;
$this->eventDispatcher->addListener('OCA\Files_Sharing::loadAdditionalScripts', function () use (&$loadAdditionalScriptsCalled) {
$loadAdditionalScriptsCalled = true;
});
$response = $this->shareController->showShare('token');
$sharedTmplParams = [
'displayName' => 'ownerDisplay',
'owner' => 'ownerUID',
'filename' => 'file1.txt',
'directory_path' => '/file1.txt',
'mimetype' => 'text/plain',
'dirToken' => 'token',
'sharingToken' => 'token',
'protected' => 'true',
'dir' => '',
'downloadURL' => null,
'fileSize' => '33 B',
'nonHumanFileSize' => 33,
'maxSizeAnimateGif' => 10,
'previewSupported' => true,
'previewEnabled' => true,
'previewMaxX' => 1024,
'previewMaxY' => 1024,
'shareUrl' => null,
'previewImage' => null,
'canDownload' => true,
'sharePermission' => true
];
$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
$csp->addAllowedFrameDomain('\'self\'');
$expectedResponse = new TemplateResponse($this->appName, 'public', $sharedTmplParams, 'base');
$expectedResponse->setContentSecurityPolicy($csp);
$this->assertEquals($expectedResponse, $response);
$this->assertTrue($loadAdditionalScriptsCalled, 'Hook for loading additional scripts was called');
}
/**
*/
public function testShowShareInvalid() {
$this->expectException(\OCP\Files\NotFoundException::class);
$owner = $this->createMock('OCP\IUser');
$owner->method('getDisplayName')->willReturn('ownerDisplay');
$owner->method('getUID')->willReturn('ownerUID');
$file = $this->createMock('OCP\Files\File');
$file->method('getName')->willReturn('file1.txt');
$file->method('getMimetype')->willReturn('text/plain');
$file->method('getSize')->willReturn(33);
$file->method('isShareable')->willReturn(false);
$file->method('isReadable')->willReturn(true);
$share = \OC::$server->getShareManager()->newShare();
$share->setId(42);
$share->setPassword('password')
->setShareOwner('ownerUID')
->setNode($file)
->setTarget('/file1.txt');
$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
$this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
$this->config->method('getSystemValue')
->willReturnMap(
[
['max_filesize_animated_gifs_public_sharing', 10, 10],
['enable_previews', true, true],
]
);
$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$this->userManager->method('get')->with('ownerUID')->willReturn($owner);
$this->shareController->showShare('token');
}
public function testDownloadShare() {
$share = $this->createMock('\OCP\Share\IShare');
$share->method('getPassword')->willReturn('password');
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('validtoken')
->willReturn($share);
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with('files_sharing.sharecontroller.authenticate', ['token' => 'validtoken'])
->willReturn('redirect');
// Test with a password protected share and no authentication
$response = $this->shareController->downloadShare('validtoken');
$expectedResponse = new RedirectResponse('redirect');
$this->assertEquals($expectedResponse, $response);
}
/**
*/
public function testDownloadShareNoReadPermission() {
$this->expectException(\OCP\Files\NotFoundException::class);
$share = $this->createMock('\OCP\Share\IShare');
$share->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_CREATE);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('validtoken')
->willReturn($share);
$this->shareController->downloadShare('validtoken');
}
}
| {
"pile_set_name": "Github"
} |
// license:GPL-2.0+
// copyright-holders:Jarek Burczynski
/***************************************************************************
Functions to emulate video hardware on these Taito games:
- rastan
***************************************************************************/
#include "emu.h"
#include "includes/rastan.h"
#include "screen.h"
/***************************************************************************/
void rastan_state::rastan_colpri_cb(u32 &sprite_colbank, u32 &pri_mask, u16 sprite_ctrl)
{
/* bits 5-7 are the sprite palette bank */
sprite_colbank = (sprite_ctrl & 0xe0) >> 1;
pri_mask = 0; /* sprites over everything */
}
void rastan_state::spritectrl_w(u16 data)
{
m_pc090oj->sprite_ctrl_w(data);
/* bit 4 unused */
/* bits 0 and 1 are coin lockout */
machine().bookkeeping().coin_lockout_w(1, ~data & 0x01);
machine().bookkeeping().coin_lockout_w(0, ~data & 0x02);
/* bits 2 and 3 are the coin counters */
machine().bookkeeping().coin_counter_w(1, data & 0x04);
machine().bookkeeping().coin_counter_w(0, data & 0x08);
}
/***************************************************************************/
u32 rastan_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
int layer[2];
m_pc080sn->tilemap_update();
layer[0] = 0;
layer[1] = 1;
screen.priority().fill(0, cliprect);
m_pc080sn->tilemap_draw(screen, bitmap, cliprect, layer[0], TILEMAP_DRAW_OPAQUE, 1);
m_pc080sn->tilemap_draw(screen, bitmap, cliprect, layer[1], 0, 2);
m_pc090oj->draw_sprites(screen, bitmap, cliprect);
return 0;
}
| {
"pile_set_name": "Github"
} |
/* OR1K ELF support for BFD. Derived from ppc.h.
Copyright (C) 2002, 2010 Free Software Foundation, Inc.
Contributed by Ivan Guzvinec <[email protected]>
This file is part of BFD, the Binary File Descriptor library.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
#ifndef _ELF_OR1K_H
#define _ELF_OR1K_H
#include "elf/reloc-macros.h"
/* Relocations. */
START_RELOC_NUMBERS (elf_or32_reloc_type)
RELOC_NUMBER (R_OR32_NONE, 0)
RELOC_NUMBER (R_OR32_32, 1)
RELOC_NUMBER (R_OR32_16, 2)
RELOC_NUMBER (R_OR32_8, 3)
RELOC_NUMBER (R_OR32_CONST, 4)
RELOC_NUMBER (R_OR32_CONSTH, 5)
RELOC_NUMBER (R_OR32_JUMPTARG, 6)
RELOC_NUMBER (R_OR32_GNU_VTENTRY, 7)
RELOC_NUMBER (R_OR32_GNU_VTINHERIT, 8)
END_RELOC_NUMBERS (R_OR32_max)
/* Four bit OR32 machine type field. */
#define EF_OR32_MACH 0x0000000f
/* Various CPU types. */
#define E_OR32_MACH_BASE 0x00000000
#define E_OR32_MACH_UNUSED1 0x00000001
#define E_OR32_MACH_UNUSED2 0x00000002
#define E_OR32_MACH_UNUSED4 0x00000003
/* Processor specific section headers, sh_type field */
#define SHT_ORDERED SHT_HIPROC /* Link editor is to sort the \
entries in this section \
based on the address \
specified in the associated \
symbol table entry. */
#endif /* _ELF_OR1K_H */
| {
"pile_set_name": "Github"
} |
<ul class="thumbnail-group">
{% for image in images %}
<li>
{{ entity.name }}
<a href="{{ image|resize({'width': 1024,'height': 1024,'type': 4}) }}" data-fc-modules="modal" class="thumbnail">
<img src="{{ image|resize({'width': 150,'height': 150,'type': 5}) }}" width="150" height="150"/>
</a>
<ul class="thumbnail-actions">
<li>
<a href="{{ url('admin_image_delete', { id: image.id }) }}"
data-fc-modules="confirm" data-fc-name="{{ image.name }}"
data-fc-text="{{ 'ui.confirm.delete'|trans }}">
<i class="icon-trash-o"></i>
</a>
</li>
</ul>
</li>
{% endfor %}
</ul>
| {
"pile_set_name": "Github"
} |
////
/// Menu toggle component.
///
/// @group Components
/// @author Lee Anthony <[email protected]>
/// @link https://github.com/seothemes/genesis-starter-theme
////
.menu-toggle {
display: flex;
align-items: center;
justify-content: center;
margin: 0;
padding: 0;
background-color: transparent;
order: 1;
@include size($spacing--m * $perfect-fifth);
@include mq(m) {
display: none;
}
@include hover-focus {
background-color: transparent;
}
&:focus {
outline: $base--border;
}
.hamburger,
.hamburger:before,
.hamburger:after {
display: block;
position: absolute;
width: $spacing--m * $perfect-fifth;
height: 3px;
background-color: $color--text;
content: "";
}
.hamburger {
top: auto;
right: auto;
bottom: auto;
margin: auto;
&:before {
top: -$spacing--s;
}
&:after {
bottom: -$spacing--s;
}
}
&.activated {
.hamburger {
background-color: transparent;
&:before {
top: 0;
transform: rotate(45deg);
}
&:after {
bottom: 0;
transform: rotate(-45deg);
}
}
}
}
| {
"pile_set_name": "Github"
} |
#
# Copyright (c) 2011-2014 Todd C. Miller <[email protected]>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# @configure_input@
#
#### Start of system configuration section. ####
srcdir = @srcdir@
top_builddir = @top_builddir@
top_srcdir = @top_srcdir@
includedir = @includedir@
cross_compiling = @CROSS_COMPILING@
# Our install program supports extra flags...
INSTALL = $(SHELL) $(top_srcdir)/install-sh -c
INSTALL_OWNER = -o $(install_uid) -g $(install_gid)
# Where to install things...
prefix = @prefix@
exec_prefix = @exec_prefix@
bindir = @bindir@
sbindir = @sbindir@
sysconfdir = @sysconfdir@
libexecdir = @libexecdir@
datarootdir = @datarootdir@
localstatedir = @localstatedir@
# User and group ids the installed files should be "owned" by
install_uid = 0
install_gid = 0
#### End of system configuration section. ####
SHELL = @SHELL@
all:
Makefile: $(srcdir)/Makefile.in
(cd $(top_builddir) && ./config.status --file include/Makefile)
.SUFFIXES: .h
pre-install:
install: install-includes
install-dirs:
$(SHELL) $(top_srcdir)/mkinstalldirs $(DESTDIR)$(includedir)
install-binaries:
install-doc:
install-includes: install-dirs
$(INSTALL) $(INSTALL_OWNER) -m 0644 $(srcdir)/sudo_plugin.h $(DESTDIR)$(includedir)
install-plugin:
uninstall:
-rm -f $(DESTDIR)$(includedir)/sudo_plugin.h
splint:
cppcheck:
check:
clean:
mostlyclean: clean
distclean: clean
-rm -rf Makefile
clobber: distclean
realclean: distclean
cleandir: distclean
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<product version="3" modelHash="-25c2198bd19btbqij35ohtazvhn4l58">
<files names="EditorAspectDescriptorImpl.java:ErrorReportingRoot_Editor.java:ErrorReportingRoot_EditorBuilder_a.java" />
</product>
| {
"pile_set_name": "Github"
} |
// Copyright 2017 The Lynx Authors. All rights reserved.
#ifndef LYNX_RENDER_VIEW_H_
#define LYNX_RENDER_VIEW_H_
#include "render/impl/render_object_impl.h"
#include "render/render_object.h"
namespace lynx {
class View : public RenderObject {
public:
View(const char* tag_name,
uint64_t id,
RenderObjectImpl* proxy,
RenderTreeHost* host);
View(const char* tag_name,
RenderObjectType type,
uint64_t id,
RenderObjectImpl* proxy,
RenderTreeHost* host);
virtual ~View() {}
virtual base::Size OnMeasure(int width_descriptor,
int height_descriptor) override;
protected:
virtual void OnLayout(int left, int top, int right, int bottom) override;
};
} // namespace lynx
#endif // LYNX_RENDER_VIEW_H_
| {
"pile_set_name": "Github"
} |
import Ad from './ad.vue';
export default Ad;
| {
"pile_set_name": "Github"
} |
# Description:
# S3 support for TensorFlow.
package(default_visibility = ["//visibility:public"])
licenses(["notice"]) # Apache 2.0
exports_files(["LICENSE"])
load(
"//tensorflow:tensorflow.bzl",
"tf_cc_binary",
"tf_cc_test",
)
tf_cc_binary(
name = "libs3_file_system_shared.so",
srcs = [
"aws_crypto.cc",
"aws_crypto.h",
"aws_logging.cc",
"aws_logging.h",
"s3_file_system.cc",
"s3_file_system.h",
],
copts = ["-Wno-sign-compare"],
defines = select({
"//conditions:default": [
"ENABLE_CURL_CLIENT",
"ENABLE_NO_ENCRYPTION",
],
}),
linkshared = 1,
deps = [
"//tensorflow/core:framework_headers_lib",
"//tensorflow/core/platform:retrying_file_system",
"//tensorflow/core/platform:retrying_utils",
"@aws",
"@com_google_protobuf//:protobuf_headers",
"@curl",
],
)
cc_library(
name = "aws_crypto",
srcs = [
"aws_crypto.cc",
],
hdrs = [
"aws_crypto.h",
],
deps = [
"@aws",
"@boringssl//:crypto",
],
alwayslink = 1,
)
cc_library(
name = "aws_logging",
srcs = [
"aws_logging.cc",
],
hdrs = [
"aws_logging.h",
],
deps = [
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
"//tensorflow/core/platform:stringprintf",
"@aws",
],
alwayslink = 1,
)
cc_library(
name = "s3_file_system",
srcs = [
"s3_file_system.cc",
],
hdrs = [
"s3_file_system.h",
],
deps = select({
"@org_tensorflow//tensorflow:windows": [
"//tensorflow/core/platform:retrying_file_system",
],
"//conditions:default": [],
}) + [
":aws_crypto",
":aws_logging",
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
"//tensorflow/core/platform:path",
"//tensorflow/core/platform:str_util",
"@aws",
],
alwayslink = 1,
)
tf_cc_test(
name = "s3_file_system_test",
size = "small",
srcs = [
"s3_file_system_test.cc",
],
tags = [
"manual",
],
deps = [
":s3_file_system",
"//tensorflow/core:lib",
"//tensorflow/core:lib_internal",
"//tensorflow/core:test",
"//tensorflow/core:test_main",
"//tensorflow/core/platform:path",
"@aws",
],
)
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2018 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.grpc;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import java.net.SocketAddress;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
/**
* This is an internal API. Do NOT use.
*/
@Internal
public final class InternalChannelz {
private static final Logger log = Logger.getLogger(InternalChannelz.class.getName());
private static final InternalChannelz INSTANCE = new InternalChannelz();
private final ConcurrentNavigableMap<Long, InternalInstrumented<ServerStats>> servers
= new ConcurrentSkipListMap<>();
private final ConcurrentNavigableMap<Long, InternalInstrumented<ChannelStats>> rootChannels
= new ConcurrentSkipListMap<>();
private final ConcurrentMap<Long, InternalInstrumented<ChannelStats>> subchannels
= new ConcurrentHashMap<>();
// An InProcessTransport can appear in both otherSockets and perServerSockets simultaneously
private final ConcurrentMap<Long, InternalInstrumented<SocketStats>> otherSockets
= new ConcurrentHashMap<>();
private final ConcurrentMap<Long, ServerSocketMap> perServerSockets
= new ConcurrentHashMap<>();
// A convenience class to avoid deeply nested types.
private static final class ServerSocketMap
extends ConcurrentSkipListMap<Long, InternalInstrumented<SocketStats>> {
private static final long serialVersionUID = -7883772124944661414L;
}
@VisibleForTesting
public InternalChannelz() {
}
public static InternalChannelz instance() {
return INSTANCE;
}
/** Adds a server. */
public void addServer(InternalInstrumented<ServerStats> server) {
ServerSocketMap prev = perServerSockets.put(id(server), new ServerSocketMap());
assert prev == null;
add(servers, server);
}
/** Adds a subchannel. */
public void addSubchannel(InternalInstrumented<ChannelStats> subchannel) {
add(subchannels, subchannel);
}
/** Adds a root channel. */
public void addRootChannel(InternalInstrumented<ChannelStats> rootChannel) {
add(rootChannels, rootChannel);
}
/** Adds a socket. */
public void addClientSocket(InternalInstrumented<SocketStats> socket) {
add(otherSockets, socket);
}
public void addListenSocket(InternalInstrumented<SocketStats> socket) {
add(otherSockets, socket);
}
/** Adds a server socket. */
public void addServerSocket(
InternalInstrumented<ServerStats> server, InternalInstrumented<SocketStats> socket) {
ServerSocketMap serverSockets = perServerSockets.get(id(server));
assert serverSockets != null;
add(serverSockets, socket);
}
/** Removes a server. */
public void removeServer(InternalInstrumented<ServerStats> server) {
remove(servers, server);
ServerSocketMap prev = perServerSockets.remove(id(server));
assert prev != null;
assert prev.isEmpty();
}
public void removeSubchannel(InternalInstrumented<ChannelStats> subchannel) {
remove(subchannels, subchannel);
}
public void removeRootChannel(InternalInstrumented<ChannelStats> channel) {
remove(rootChannels, channel);
}
public void removeClientSocket(InternalInstrumented<SocketStats> socket) {
remove(otherSockets, socket);
}
public void removeListenSocket(InternalInstrumented<SocketStats> socket) {
remove(otherSockets, socket);
}
/** Removes a server socket. */
public void removeServerSocket(
InternalInstrumented<ServerStats> server, InternalInstrumented<SocketStats> socket) {
ServerSocketMap socketsOfServer = perServerSockets.get(id(server));
assert socketsOfServer != null;
remove(socketsOfServer, socket);
}
/** Returns a {@link RootChannelList}. */
public RootChannelList getRootChannels(long fromId, int maxPageSize) {
List<InternalInstrumented<ChannelStats>> channelList
= new ArrayList<>();
Iterator<InternalInstrumented<ChannelStats>> iterator
= rootChannels.tailMap(fromId).values().iterator();
while (iterator.hasNext() && channelList.size() < maxPageSize) {
channelList.add(iterator.next());
}
return new RootChannelList(channelList, !iterator.hasNext());
}
/** Returns a channel. */
@Nullable
public InternalInstrumented<ChannelStats> getChannel(long id) {
return rootChannels.get(id);
}
/** Returns a subchannel. */
@Nullable
public InternalInstrumented<ChannelStats> getSubchannel(long id) {
return subchannels.get(id);
}
/** Returns a server list. */
public ServerList getServers(long fromId, int maxPageSize) {
List<InternalInstrumented<ServerStats>> serverList
= new ArrayList<>(maxPageSize);
Iterator<InternalInstrumented<ServerStats>> iterator
= servers.tailMap(fromId).values().iterator();
while (iterator.hasNext() && serverList.size() < maxPageSize) {
serverList.add(iterator.next());
}
return new ServerList(serverList, !iterator.hasNext());
}
/** Returns socket refs for a server. */
@Nullable
public ServerSocketsList getServerSockets(long serverId, long fromId, int maxPageSize) {
ServerSocketMap serverSockets = perServerSockets.get(serverId);
if (serverSockets == null) {
return null;
}
List<InternalWithLogId> socketList = new ArrayList<>(maxPageSize);
Iterator<InternalInstrumented<SocketStats>> iterator
= serverSockets.tailMap(fromId).values().iterator();
while (socketList.size() < maxPageSize && iterator.hasNext()) {
socketList.add(iterator.next());
}
return new ServerSocketsList(socketList, !iterator.hasNext());
}
/** Returns a socket. */
@Nullable
public InternalInstrumented<SocketStats> getSocket(long id) {
InternalInstrumented<SocketStats> clientSocket = otherSockets.get(id);
if (clientSocket != null) {
return clientSocket;
}
return getServerSocket(id);
}
private InternalInstrumented<SocketStats> getServerSocket(long id) {
for (ServerSocketMap perServerSockets : perServerSockets.values()) {
InternalInstrumented<SocketStats> serverSocket = perServerSockets.get(id);
if (serverSocket != null) {
return serverSocket;
}
}
return null;
}
@VisibleForTesting
public boolean containsServer(InternalLogId serverRef) {
return contains(servers, serverRef);
}
@VisibleForTesting
public boolean containsSubchannel(InternalLogId subchannelRef) {
return contains(subchannels, subchannelRef);
}
public InternalInstrumented<ChannelStats> getRootChannel(long id) {
return rootChannels.get(id);
}
@VisibleForTesting
public boolean containsClientSocket(InternalLogId transportRef) {
return contains(otherSockets, transportRef);
}
private static <T extends InternalInstrumented<?>> void add(Map<Long, T> map, T object) {
T prev = map.put(object.getLogId().getId(), object);
assert prev == null;
}
private static <T extends InternalInstrumented<?>> void remove(Map<Long, T> map, T object) {
T prev = map.remove(id(object));
assert prev != null;
}
private static <T extends InternalInstrumented<?>> boolean contains(
Map<Long, T> map, InternalLogId id) {
return map.containsKey(id.getId());
}
public static final class RootChannelList {
public final List<InternalInstrumented<ChannelStats>> channels;
public final boolean end;
/** Creates an instance. */
public RootChannelList(List<InternalInstrumented<ChannelStats>> channels, boolean end) {
this.channels = checkNotNull(channels);
this.end = end;
}
}
public static final class ServerList {
public final List<InternalInstrumented<ServerStats>> servers;
public final boolean end;
/** Creates an instance. */
public ServerList(List<InternalInstrumented<ServerStats>> servers, boolean end) {
this.servers = checkNotNull(servers);
this.end = end;
}
}
public static final class ServerSocketsList {
public final List<InternalWithLogId> sockets;
public final boolean end;
/** Creates an instance. */
public ServerSocketsList(List<InternalWithLogId> sockets, boolean end) {
this.sockets = sockets;
this.end = end;
}
}
@Immutable
public static final class ServerStats {
public final long callsStarted;
public final long callsSucceeded;
public final long callsFailed;
public final long lastCallStartedNanos;
public final List<InternalInstrumented<SocketStats>> listenSockets;
/**
* Creates an instance.
*/
public ServerStats(
long callsStarted,
long callsSucceeded,
long callsFailed,
long lastCallStartedNanos,
List<InternalInstrumented<SocketStats>> listenSockets) {
this.callsStarted = callsStarted;
this.callsSucceeded = callsSucceeded;
this.callsFailed = callsFailed;
this.lastCallStartedNanos = lastCallStartedNanos;
this.listenSockets = checkNotNull(listenSockets);
}
public static final class Builder {
private long callsStarted;
private long callsSucceeded;
private long callsFailed;
private long lastCallStartedNanos;
public List<InternalInstrumented<SocketStats>> listenSockets = new ArrayList<>();
public Builder setCallsStarted(long callsStarted) {
this.callsStarted = callsStarted;
return this;
}
public Builder setCallsSucceeded(long callsSucceeded) {
this.callsSucceeded = callsSucceeded;
return this;
}
public Builder setCallsFailed(long callsFailed) {
this.callsFailed = callsFailed;
return this;
}
public Builder setLastCallStartedNanos(long lastCallStartedNanos) {
this.lastCallStartedNanos = lastCallStartedNanos;
return this;
}
/** Sets the listen sockets. */
public Builder addListenSockets(List<InternalInstrumented<SocketStats>> listenSockets) {
checkNotNull(listenSockets, "listenSockets");
for (InternalInstrumented<SocketStats> ss : listenSockets) {
this.listenSockets.add(checkNotNull(ss, "null listen socket"));
}
return this;
}
/**
* Builds an instance.
*/
public ServerStats build() {
return new ServerStats(
callsStarted,
callsSucceeded,
callsFailed,
lastCallStartedNanos,
listenSockets);
}
}
}
/**
* A data class to represent a channel's stats.
*/
@Immutable
public static final class ChannelStats {
public final String target;
public final ConnectivityState state;
@Nullable public final ChannelTrace channelTrace;
public final long callsStarted;
public final long callsSucceeded;
public final long callsFailed;
public final long lastCallStartedNanos;
public final List<InternalWithLogId> subchannels;
public final List<InternalWithLogId> sockets;
/**
* Creates an instance.
*/
private ChannelStats(
String target,
ConnectivityState state,
@Nullable ChannelTrace channelTrace,
long callsStarted,
long callsSucceeded,
long callsFailed,
long lastCallStartedNanos,
List<InternalWithLogId> subchannels,
List<InternalWithLogId> sockets) {
checkState(
subchannels.isEmpty() || sockets.isEmpty(),
"channels can have subchannels only, subchannels can have either sockets OR subchannels, "
+ "neither can have both");
this.target = target;
this.state = state;
this.channelTrace = channelTrace;
this.callsStarted = callsStarted;
this.callsSucceeded = callsSucceeded;
this.callsFailed = callsFailed;
this.lastCallStartedNanos = lastCallStartedNanos;
this.subchannels = checkNotNull(subchannels);
this.sockets = checkNotNull(sockets);
}
public static final class Builder {
private String target;
private ConnectivityState state;
private ChannelTrace channelTrace;
private long callsStarted;
private long callsSucceeded;
private long callsFailed;
private long lastCallStartedNanos;
private List<InternalWithLogId> subchannels = Collections.emptyList();
private List<InternalWithLogId> sockets = Collections.emptyList();
public Builder setTarget(String target) {
this.target = target;
return this;
}
public Builder setState(ConnectivityState state) {
this.state = state;
return this;
}
public Builder setChannelTrace(ChannelTrace channelTrace) {
this.channelTrace = channelTrace;
return this;
}
public Builder setCallsStarted(long callsStarted) {
this.callsStarted = callsStarted;
return this;
}
public Builder setCallsSucceeded(long callsSucceeded) {
this.callsSucceeded = callsSucceeded;
return this;
}
public Builder setCallsFailed(long callsFailed) {
this.callsFailed = callsFailed;
return this;
}
public Builder setLastCallStartedNanos(long lastCallStartedNanos) {
this.lastCallStartedNanos = lastCallStartedNanos;
return this;
}
/** Sets the subchannels. */
public Builder setSubchannels(List<InternalWithLogId> subchannels) {
checkState(sockets.isEmpty());
this.subchannels = Collections.unmodifiableList(checkNotNull(subchannels));
return this;
}
/** Sets the sockets. */
public Builder setSockets(List<InternalWithLogId> sockets) {
checkState(subchannels.isEmpty());
this.sockets = Collections.unmodifiableList(checkNotNull(sockets));
return this;
}
/**
* Builds an instance.
*/
public ChannelStats build() {
return new ChannelStats(
target,
state,
channelTrace,
callsStarted,
callsSucceeded,
callsFailed,
lastCallStartedNanos,
subchannels,
sockets);
}
}
}
@Immutable
public static final class ChannelTrace {
public final long numEventsLogged;
public final long creationTimeNanos;
public final List<Event> events;
private ChannelTrace(long numEventsLogged, long creationTimeNanos, List<Event> events) {
this.numEventsLogged = numEventsLogged;
this.creationTimeNanos = creationTimeNanos;
this.events = events;
}
public static final class Builder {
private Long numEventsLogged;
private Long creationTimeNanos;
private List<Event> events = Collections.emptyList();
public Builder setNumEventsLogged(long numEventsLogged) {
this.numEventsLogged = numEventsLogged;
return this;
}
public Builder setCreationTimeNanos(long creationTimeNanos) {
this.creationTimeNanos = creationTimeNanos;
return this;
}
public Builder setEvents(List<Event> events) {
this.events = Collections.unmodifiableList(new ArrayList<>(events));
return this;
}
/** Builds a new ChannelTrace instance. */
public ChannelTrace build() {
checkNotNull(numEventsLogged, "numEventsLogged");
checkNotNull(creationTimeNanos, "creationTimeNanos");
return new ChannelTrace(numEventsLogged, creationTimeNanos, events);
}
}
@Immutable
public static final class Event {
public final String description;
public final Severity severity;
public final long timestampNanos;
// the oneof child_ref field in proto: one of channelRef and channelRef
@Nullable public final InternalWithLogId channelRef;
@Nullable public final InternalWithLogId subchannelRef;
public enum Severity {
CT_UNKNOWN, CT_INFO, CT_WARNING, CT_ERROR
}
private Event(
String description, Severity severity, long timestampNanos,
@Nullable InternalWithLogId channelRef, @Nullable InternalWithLogId subchannelRef) {
this.description = description;
this.severity = checkNotNull(severity, "severity");
this.timestampNanos = timestampNanos;
this.channelRef = channelRef;
this.subchannelRef = subchannelRef;
}
@Override
public int hashCode() {
return Objects.hashCode(description, severity, timestampNanos, channelRef, subchannelRef);
}
@Override
public boolean equals(Object o) {
if (o instanceof Event) {
Event that = (Event) o;
return Objects.equal(description, that.description)
&& Objects.equal(severity, that.severity)
&& timestampNanos == that.timestampNanos
&& Objects.equal(channelRef, that.channelRef)
&& Objects.equal(subchannelRef, that.subchannelRef);
}
return false;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("description", description)
.add("severity", severity)
.add("timestampNanos", timestampNanos)
.add("channelRef", channelRef)
.add("subchannelRef", subchannelRef)
.toString();
}
public static final class Builder {
private String description;
private Severity severity;
private Long timestampNanos;
private InternalWithLogId channelRef;
private InternalWithLogId subchannelRef;
public Builder setDescription(String description) {
this.description = description;
return this;
}
public Builder setTimestampNanos(long timestampNanos) {
this.timestampNanos = timestampNanos;
return this;
}
public Builder setSeverity(Severity severity) {
this.severity = severity;
return this;
}
public Builder setChannelRef(InternalWithLogId channelRef) {
this.channelRef = channelRef;
return this;
}
public Builder setSubchannelRef(InternalWithLogId subchannelRef) {
this.subchannelRef = subchannelRef;
return this;
}
/** Builds a new Event instance. */
public Event build() {
checkNotNull(description, "description");
checkNotNull(severity, "severity");
checkNotNull(timestampNanos, "timestampNanos");
checkState(
channelRef == null || subchannelRef == null,
"at least one of channelRef and subchannelRef must be null");
return new Event(description, severity, timestampNanos, channelRef, subchannelRef);
}
}
}
}
public static final class Security {
@Nullable
public final Tls tls;
@Nullable
public final OtherSecurity other;
public Security(Tls tls) {
this.tls = checkNotNull(tls);
this.other = null;
}
public Security(OtherSecurity other) {
this.tls = null;
this.other = checkNotNull(other);
}
}
public static final class OtherSecurity {
public final String name;
@Nullable
public final Object any;
/**
* Creates an instance.
* @param name the name.
* @param any a com.google.protobuf.Any object
*/
public OtherSecurity(String name, @Nullable Object any) {
this.name = checkNotNull(name);
checkState(
any == null || any.getClass().getName().endsWith("com.google.protobuf.Any"),
"the 'any' object must be of type com.google.protobuf.Any");
this.any = any;
}
}
@Immutable
public static final class Tls {
public final String cipherSuiteStandardName;
@Nullable public final Certificate localCert;
@Nullable public final Certificate remoteCert;
/**
* A constructor only for testing.
*/
public Tls(String cipherSuiteName, Certificate localCert, Certificate remoteCert) {
this.cipherSuiteStandardName = cipherSuiteName;
this.localCert = localCert;
this.remoteCert = remoteCert;
}
/**
* Creates an instance.
*/
public Tls(SSLSession session) {
String cipherSuiteStandardName = session.getCipherSuite();
Certificate localCert = null;
Certificate remoteCert = null;
Certificate[] localCerts = session.getLocalCertificates();
if (localCerts != null) {
localCert = localCerts[0];
}
try {
Certificate[] peerCerts = session.getPeerCertificates();
if (peerCerts != null) {
// The javadoc of getPeerCertificate states that the peer's own certificate is the first
// element of the list.
remoteCert = peerCerts[0];
}
} catch (SSLPeerUnverifiedException e) {
// peer cert is not available
log.log(
Level.FINE,
String.format("Peer cert not available for peerHost=%s", session.getPeerHost()),
e);
}
this.cipherSuiteStandardName = cipherSuiteStandardName;
this.localCert = localCert;
this.remoteCert = remoteCert;
}
}
public static final class SocketStats {
@Nullable public final TransportStats data;
@Nullable public final SocketAddress local;
@Nullable public final SocketAddress remote;
public final SocketOptions socketOptions;
// Can be null if plaintext
@Nullable public final Security security;
/** Creates an instance. */
public SocketStats(
TransportStats data,
@Nullable SocketAddress local,
@Nullable SocketAddress remote,
SocketOptions socketOptions,
Security security) {
this.data = data;
this.local = checkNotNull(local, "local socket");
this.remote = remote;
this.socketOptions = checkNotNull(socketOptions);
this.security = security;
}
}
public static final class TcpInfo {
public final int state;
public final int caState;
public final int retransmits;
public final int probes;
public final int backoff;
public final int options;
public final int sndWscale;
public final int rcvWscale;
public final int rto;
public final int ato;
public final int sndMss;
public final int rcvMss;
public final int unacked;
public final int sacked;
public final int lost;
public final int retrans;
public final int fackets;
public final int lastDataSent;
public final int lastAckSent;
public final int lastDataRecv;
public final int lastAckRecv;
public final int pmtu;
public final int rcvSsthresh;
public final int rtt;
public final int rttvar;
public final int sndSsthresh;
public final int sndCwnd;
public final int advmss;
public final int reordering;
TcpInfo(int state, int caState, int retransmits, int probes, int backoff, int options,
int sndWscale, int rcvWscale, int rto, int ato, int sndMss, int rcvMss, int unacked,
int sacked, int lost, int retrans, int fackets, int lastDataSent, int lastAckSent,
int lastDataRecv, int lastAckRecv, int pmtu, int rcvSsthresh, int rtt, int rttvar,
int sndSsthresh, int sndCwnd, int advmss, int reordering) {
this.state = state;
this.caState = caState;
this.retransmits = retransmits;
this.probes = probes;
this.backoff = backoff;
this.options = options;
this.sndWscale = sndWscale;
this.rcvWscale = rcvWscale;
this.rto = rto;
this.ato = ato;
this.sndMss = sndMss;
this.rcvMss = rcvMss;
this.unacked = unacked;
this.sacked = sacked;
this.lost = lost;
this.retrans = retrans;
this.fackets = fackets;
this.lastDataSent = lastDataSent;
this.lastAckSent = lastAckSent;
this.lastDataRecv = lastDataRecv;
this.lastAckRecv = lastAckRecv;
this.pmtu = pmtu;
this.rcvSsthresh = rcvSsthresh;
this.rtt = rtt;
this.rttvar = rttvar;
this.sndSsthresh = sndSsthresh;
this.sndCwnd = sndCwnd;
this.advmss = advmss;
this.reordering = reordering;
}
public static final class Builder {
private int state;
private int caState;
private int retransmits;
private int probes;
private int backoff;
private int options;
private int sndWscale;
private int rcvWscale;
private int rto;
private int ato;
private int sndMss;
private int rcvMss;
private int unacked;
private int sacked;
private int lost;
private int retrans;
private int fackets;
private int lastDataSent;
private int lastAckSent;
private int lastDataRecv;
private int lastAckRecv;
private int pmtu;
private int rcvSsthresh;
private int rtt;
private int rttvar;
private int sndSsthresh;
private int sndCwnd;
private int advmss;
private int reordering;
public Builder setState(int state) {
this.state = state;
return this;
}
public Builder setCaState(int caState) {
this.caState = caState;
return this;
}
public Builder setRetransmits(int retransmits) {
this.retransmits = retransmits;
return this;
}
public Builder setProbes(int probes) {
this.probes = probes;
return this;
}
public Builder setBackoff(int backoff) {
this.backoff = backoff;
return this;
}
public Builder setOptions(int options) {
this.options = options;
return this;
}
public Builder setSndWscale(int sndWscale) {
this.sndWscale = sndWscale;
return this;
}
public Builder setRcvWscale(int rcvWscale) {
this.rcvWscale = rcvWscale;
return this;
}
public Builder setRto(int rto) {
this.rto = rto;
return this;
}
public Builder setAto(int ato) {
this.ato = ato;
return this;
}
public Builder setSndMss(int sndMss) {
this.sndMss = sndMss;
return this;
}
public Builder setRcvMss(int rcvMss) {
this.rcvMss = rcvMss;
return this;
}
public Builder setUnacked(int unacked) {
this.unacked = unacked;
return this;
}
public Builder setSacked(int sacked) {
this.sacked = sacked;
return this;
}
public Builder setLost(int lost) {
this.lost = lost;
return this;
}
public Builder setRetrans(int retrans) {
this.retrans = retrans;
return this;
}
public Builder setFackets(int fackets) {
this.fackets = fackets;
return this;
}
public Builder setLastDataSent(int lastDataSent) {
this.lastDataSent = lastDataSent;
return this;
}
public Builder setLastAckSent(int lastAckSent) {
this.lastAckSent = lastAckSent;
return this;
}
public Builder setLastDataRecv(int lastDataRecv) {
this.lastDataRecv = lastDataRecv;
return this;
}
public Builder setLastAckRecv(int lastAckRecv) {
this.lastAckRecv = lastAckRecv;
return this;
}
public Builder setPmtu(int pmtu) {
this.pmtu = pmtu;
return this;
}
public Builder setRcvSsthresh(int rcvSsthresh) {
this.rcvSsthresh = rcvSsthresh;
return this;
}
public Builder setRtt(int rtt) {
this.rtt = rtt;
return this;
}
public Builder setRttvar(int rttvar) {
this.rttvar = rttvar;
return this;
}
public Builder setSndSsthresh(int sndSsthresh) {
this.sndSsthresh = sndSsthresh;
return this;
}
public Builder setSndCwnd(int sndCwnd) {
this.sndCwnd = sndCwnd;
return this;
}
public Builder setAdvmss(int advmss) {
this.advmss = advmss;
return this;
}
public Builder setReordering(int reordering) {
this.reordering = reordering;
return this;
}
/** Builds an instance. */
public TcpInfo build() {
return new TcpInfo(
state, caState, retransmits, probes, backoff, options, sndWscale, rcvWscale,
rto, ato, sndMss, rcvMss, unacked, sacked, lost, retrans, fackets, lastDataSent,
lastAckSent, lastDataRecv, lastAckRecv, pmtu, rcvSsthresh, rtt, rttvar, sndSsthresh,
sndCwnd, advmss, reordering);
}
}
}
public static final class SocketOptions {
public final Map<String, String> others;
// In netty, the value of a channel option may be null.
@Nullable public final Integer soTimeoutMillis;
@Nullable public final Integer lingerSeconds;
@Nullable public final TcpInfo tcpInfo;
/** Creates an instance. */
public SocketOptions(
@Nullable Integer timeoutMillis,
@Nullable Integer lingerSeconds,
@Nullable TcpInfo tcpInfo,
Map<String, String> others) {
checkNotNull(others);
this.soTimeoutMillis = timeoutMillis;
this.lingerSeconds = lingerSeconds;
this.tcpInfo = tcpInfo;
this.others = Collections.unmodifiableMap(new HashMap<>(others));
}
public static final class Builder {
private final Map<String, String> others = new HashMap<>();
private TcpInfo tcpInfo;
private Integer timeoutMillis;
private Integer lingerSeconds;
/** The value of {@link java.net.Socket#getSoTimeout()}. */
public Builder setSocketOptionTimeoutMillis(Integer timeoutMillis) {
this.timeoutMillis = timeoutMillis;
return this;
}
/** The value of {@link java.net.Socket#getSoLinger()}.
* Note: SO_LINGER is typically expressed in seconds.
*/
public Builder setSocketOptionLingerSeconds(Integer lingerSeconds) {
this.lingerSeconds = lingerSeconds;
return this;
}
public Builder setTcpInfo(TcpInfo tcpInfo) {
this.tcpInfo = tcpInfo;
return this;
}
public Builder addOption(String name, String value) {
others.put(name, checkNotNull(value));
return this;
}
public Builder addOption(String name, int value) {
others.put(name, Integer.toString(value));
return this;
}
public Builder addOption(String name, boolean value) {
others.put(name, Boolean.toString(value));
return this;
}
public SocketOptions build() {
return new SocketOptions(timeoutMillis, lingerSeconds, tcpInfo, others);
}
}
}
/**
* A data class to represent transport stats.
*/
@Immutable
public static final class TransportStats {
public final long streamsStarted;
public final long lastLocalStreamCreatedTimeNanos;
public final long lastRemoteStreamCreatedTimeNanos;
public final long streamsSucceeded;
public final long streamsFailed;
public final long messagesSent;
public final long messagesReceived;
public final long keepAlivesSent;
public final long lastMessageSentTimeNanos;
public final long lastMessageReceivedTimeNanos;
public final long localFlowControlWindow;
public final long remoteFlowControlWindow;
// TODO(zpencer): report socket flags and other info
/**
* Creates an instance.
*/
public TransportStats(
long streamsStarted,
long lastLocalStreamCreatedTimeNanos,
long lastRemoteStreamCreatedTimeNanos,
long streamsSucceeded,
long streamsFailed,
long messagesSent,
long messagesReceived,
long keepAlivesSent,
long lastMessageSentTimeNanos,
long lastMessageReceivedTimeNanos,
long localFlowControlWindow,
long remoteFlowControlWindow) {
this.streamsStarted = streamsStarted;
this.lastLocalStreamCreatedTimeNanos = lastLocalStreamCreatedTimeNanos;
this.lastRemoteStreamCreatedTimeNanos = lastRemoteStreamCreatedTimeNanos;
this.streamsSucceeded = streamsSucceeded;
this.streamsFailed = streamsFailed;
this.messagesSent = messagesSent;
this.messagesReceived = messagesReceived;
this.keepAlivesSent = keepAlivesSent;
this.lastMessageSentTimeNanos = lastMessageSentTimeNanos;
this.lastMessageReceivedTimeNanos = lastMessageReceivedTimeNanos;
this.localFlowControlWindow = localFlowControlWindow;
this.remoteFlowControlWindow = remoteFlowControlWindow;
}
}
/** Unwraps a {@link InternalLogId} to return a {@code long}. */
public static long id(InternalWithLogId withLogId) {
return withLogId.getLogId().getId();
}
}
| {
"pile_set_name": "Github"
} |
//
//=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// 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 BOOST_GRAPH_BREADTH_FIRST_SEARCH_HPP
#define BOOST_GRAPH_BREADTH_FIRST_SEARCH_HPP
/*
Breadth First Search Algorithm (Cormen, Leiserson, and Rivest p. 470)
*/
#include <boost/config.hpp>
#include <vector>
#include <boost/pending/queue.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/graph_concepts.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/named_function_params.hpp>
#include <boost/graph/overloading.hpp>
#include <boost/graph/graph_concepts.hpp>
#include <boost/graph/two_bit_color_map.hpp>
#include <boost/concept/assert.hpp>
#ifdef BOOST_GRAPH_USE_MPI
#include <boost/graph/distributed/concepts.hpp>
#endif // BOOST_GRAPH_USE_MPI
namespace boost {
template <class Visitor, class Graph>
struct BFSVisitorConcept {
void constraints() {
BOOST_CONCEPT_ASSERT(( CopyConstructibleConcept<Visitor> ));
vis.initialize_vertex(u, g);
vis.discover_vertex(u, g);
vis.examine_vertex(u, g);
vis.examine_edge(e, g);
vis.tree_edge(e, g);
vis.non_tree_edge(e, g);
vis.gray_target(e, g);
vis.black_target(e, g);
vis.finish_vertex(u, g);
}
Visitor vis;
Graph g;
typename graph_traits<Graph>::vertex_descriptor u;
typename graph_traits<Graph>::edge_descriptor e;
};
// Multiple-source version
template <class IncidenceGraph, class Buffer, class BFSVisitor,
class ColorMap, class SourceIterator>
void breadth_first_visit
(const IncidenceGraph& g,
SourceIterator sources_begin, SourceIterator sources_end,
Buffer& Q, BFSVisitor vis, ColorMap color)
{
BOOST_CONCEPT_ASSERT(( IncidenceGraphConcept<IncidenceGraph> ));
typedef graph_traits<IncidenceGraph> GTraits;
typedef typename GTraits::vertex_descriptor Vertex;
BOOST_CONCEPT_ASSERT(( BFSVisitorConcept<BFSVisitor, IncidenceGraph> ));
BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<ColorMap, Vertex> ));
typedef typename property_traits<ColorMap>::value_type ColorValue;
typedef color_traits<ColorValue> Color;
typename GTraits::out_edge_iterator ei, ei_end;
for (; sources_begin != sources_end; ++sources_begin) {
Vertex s = *sources_begin;
put(color, s, Color::gray()); vis.discover_vertex(s, g);
Q.push(s);
}
while (! Q.empty()) {
Vertex u = Q.top(); Q.pop(); vis.examine_vertex(u, g);
for (boost::tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) {
Vertex v = target(*ei, g); vis.examine_edge(*ei, g);
ColorValue v_color = get(color, v);
if (v_color == Color::white()) { vis.tree_edge(*ei, g);
put(color, v, Color::gray()); vis.discover_vertex(v, g);
Q.push(v);
} else { vis.non_tree_edge(*ei, g);
if (v_color == Color::gray()) vis.gray_target(*ei, g);
else vis.black_target(*ei, g);
}
} // end for
put(color, u, Color::black()); vis.finish_vertex(u, g);
} // end while
} // breadth_first_visit
// Single-source version
template <class IncidenceGraph, class Buffer, class BFSVisitor,
class ColorMap>
void breadth_first_visit
(const IncidenceGraph& g,
typename graph_traits<IncidenceGraph>::vertex_descriptor s,
Buffer& Q, BFSVisitor vis, ColorMap color)
{
typename graph_traits<IncidenceGraph>::vertex_descriptor sources[1] = {s};
breadth_first_visit(g, sources, sources + 1, Q, vis, color);
}
template <class VertexListGraph, class SourceIterator,
class Buffer, class BFSVisitor,
class ColorMap>
void breadth_first_search
(const VertexListGraph& g,
SourceIterator sources_begin, SourceIterator sources_end,
Buffer& Q, BFSVisitor vis, ColorMap color)
{
// Initialization
typedef typename property_traits<ColorMap>::value_type ColorValue;
typedef color_traits<ColorValue> Color;
typename boost::graph_traits<VertexListGraph>::vertex_iterator i, i_end;
for (boost::tie(i, i_end) = vertices(g); i != i_end; ++i) {
vis.initialize_vertex(*i, g);
put(color, *i, Color::white());
}
breadth_first_visit(g, sources_begin, sources_end, Q, vis, color);
}
template <class VertexListGraph, class Buffer, class BFSVisitor,
class ColorMap>
void breadth_first_search
(const VertexListGraph& g,
typename graph_traits<VertexListGraph>::vertex_descriptor s,
Buffer& Q, BFSVisitor vis, ColorMap color)
{
typename graph_traits<VertexListGraph>::vertex_descriptor sources[1] = {s};
breadth_first_search(g, sources, sources + 1, Q, vis, color);
}
namespace graph { struct bfs_visitor_event_not_overridden {}; }
template <class Visitors = null_visitor>
class bfs_visitor {
public:
bfs_visitor() { }
bfs_visitor(Visitors vis) : m_vis(vis) { }
template <class Vertex, class Graph>
graph::bfs_visitor_event_not_overridden
initialize_vertex(Vertex u, Graph& g)
{
invoke_visitors(m_vis, u, g, ::boost::on_initialize_vertex());
return graph::bfs_visitor_event_not_overridden();
}
template <class Vertex, class Graph>
graph::bfs_visitor_event_not_overridden
discover_vertex(Vertex u, Graph& g)
{
invoke_visitors(m_vis, u, g, ::boost::on_discover_vertex());
return graph::bfs_visitor_event_not_overridden();
}
template <class Vertex, class Graph>
graph::bfs_visitor_event_not_overridden
examine_vertex(Vertex u, Graph& g)
{
invoke_visitors(m_vis, u, g, ::boost::on_examine_vertex());
return graph::bfs_visitor_event_not_overridden();
}
template <class Edge, class Graph>
graph::bfs_visitor_event_not_overridden
examine_edge(Edge e, Graph& g)
{
invoke_visitors(m_vis, e, g, ::boost::on_examine_edge());
return graph::bfs_visitor_event_not_overridden();
}
template <class Edge, class Graph>
graph::bfs_visitor_event_not_overridden
tree_edge(Edge e, Graph& g)
{
invoke_visitors(m_vis, e, g, ::boost::on_tree_edge());
return graph::bfs_visitor_event_not_overridden();
}
template <class Edge, class Graph>
graph::bfs_visitor_event_not_overridden
non_tree_edge(Edge e, Graph& g)
{
invoke_visitors(m_vis, e, g, ::boost::on_non_tree_edge());
return graph::bfs_visitor_event_not_overridden();
}
template <class Edge, class Graph>
graph::bfs_visitor_event_not_overridden
gray_target(Edge e, Graph& g)
{
invoke_visitors(m_vis, e, g, ::boost::on_gray_target());
return graph::bfs_visitor_event_not_overridden();
}
template <class Edge, class Graph>
graph::bfs_visitor_event_not_overridden
black_target(Edge e, Graph& g)
{
invoke_visitors(m_vis, e, g, ::boost::on_black_target());
return graph::bfs_visitor_event_not_overridden();
}
template <class Vertex, class Graph>
graph::bfs_visitor_event_not_overridden
finish_vertex(Vertex u, Graph& g)
{
invoke_visitors(m_vis, u, g, ::boost::on_finish_vertex());
return graph::bfs_visitor_event_not_overridden();
}
BOOST_GRAPH_EVENT_STUB(on_initialize_vertex,bfs)
BOOST_GRAPH_EVENT_STUB(on_discover_vertex,bfs)
BOOST_GRAPH_EVENT_STUB(on_examine_vertex,bfs)
BOOST_GRAPH_EVENT_STUB(on_examine_edge,bfs)
BOOST_GRAPH_EVENT_STUB(on_tree_edge,bfs)
BOOST_GRAPH_EVENT_STUB(on_non_tree_edge,bfs)
BOOST_GRAPH_EVENT_STUB(on_gray_target,bfs)
BOOST_GRAPH_EVENT_STUB(on_black_target,bfs)
BOOST_GRAPH_EVENT_STUB(on_finish_vertex,bfs)
protected:
Visitors m_vis;
};
template <class Visitors>
bfs_visitor<Visitors>
make_bfs_visitor(Visitors vis) {
return bfs_visitor<Visitors>(vis);
}
typedef bfs_visitor<> default_bfs_visitor;
namespace detail {
template <class VertexListGraph, class ColorMap, class BFSVisitor,
class P, class T, class R>
void bfs_helper
(VertexListGraph& g,
typename graph_traits<VertexListGraph>::vertex_descriptor s,
ColorMap color,
BFSVisitor vis,
const bgl_named_params<P, T, R>& params,
boost::mpl::false_)
{
typedef graph_traits<VertexListGraph> Traits;
// Buffer default
typedef typename Traits::vertex_descriptor Vertex;
typedef boost::queue<Vertex> queue_t;
queue_t Q;
breadth_first_search
(g, s,
choose_param(get_param(params, buffer_param_t()), boost::ref(Q)).get(),
vis, color);
}
#ifdef BOOST_GRAPH_USE_MPI
template <class DistributedGraph, class ColorMap, class BFSVisitor,
class P, class T, class R>
void bfs_helper
(DistributedGraph& g,
typename graph_traits<DistributedGraph>::vertex_descriptor s,
ColorMap color,
BFSVisitor vis,
const bgl_named_params<P, T, R>& params,
boost::mpl::true_);
#endif // BOOST_GRAPH_USE_MPI
//-------------------------------------------------------------------------
// Choose between default color and color parameters. Using
// function dispatching so that we don't require vertex index if
// the color default is not being used.
template <class ColorMap>
struct bfs_dispatch {
template <class VertexListGraph, class P, class T, class R>
static void apply
(VertexListGraph& g,
typename graph_traits<VertexListGraph>::vertex_descriptor s,
const bgl_named_params<P, T, R>& params,
ColorMap color)
{
bfs_helper
(g, s, color,
choose_param(get_param(params, graph_visitor),
make_bfs_visitor(null_visitor())),
params,
boost::mpl::bool_<
boost::is_base_and_derived<
distributed_graph_tag,
typename graph_traits<VertexListGraph>::traversal_category>::value>());
}
};
template <>
struct bfs_dispatch<param_not_found> {
template <class VertexListGraph, class P, class T, class R>
static void apply
(VertexListGraph& g,
typename graph_traits<VertexListGraph>::vertex_descriptor s,
const bgl_named_params<P, T, R>& params,
param_not_found)
{
null_visitor null_vis;
bfs_helper
(g, s,
make_two_bit_color_map
(num_vertices(g),
choose_const_pmap(get_param(params, vertex_index),
g, vertex_index)),
choose_param(get_param(params, graph_visitor),
make_bfs_visitor(null_vis)),
params,
boost::mpl::bool_<
boost::is_base_and_derived<
distributed_graph_tag,
typename graph_traits<VertexListGraph>::traversal_category>::value>());
}
};
} // namespace detail
#if 1
// Named Parameter Variant
template <class VertexListGraph, class P, class T, class R>
void breadth_first_search
(const VertexListGraph& g,
typename graph_traits<VertexListGraph>::vertex_descriptor s,
const bgl_named_params<P, T, R>& params)
{
// The graph is passed by *const* reference so that graph adaptors
// (temporaries) can be passed into this function. However, the
// graph is not really const since we may write to property maps
// of the graph.
VertexListGraph& ng = const_cast<VertexListGraph&>(g);
typedef typename get_param_type< vertex_color_t, bgl_named_params<P,T,R> >::type C;
detail::bfs_dispatch<C>::apply(ng, s, params,
get_param(params, vertex_color));
}
#endif
// This version does not initialize colors, user has to.
template <class IncidenceGraph, class P, class T, class R>
void breadth_first_visit
(const IncidenceGraph& g,
typename graph_traits<IncidenceGraph>::vertex_descriptor s,
const bgl_named_params<P, T, R>& params)
{
// The graph is passed by *const* reference so that graph adaptors
// (temporaries) can be passed into this function. However, the
// graph is not really const since we may write to property maps
// of the graph.
IncidenceGraph& ng = const_cast<IncidenceGraph&>(g);
typedef graph_traits<IncidenceGraph> Traits;
// Buffer default
typedef typename Traits::vertex_descriptor vertex_descriptor;
typedef boost::queue<vertex_descriptor> queue_t;
queue_t Q;
breadth_first_visit
(ng, s,
choose_param(get_param(params, buffer_param_t()), boost::ref(Q)).get(),
choose_param(get_param(params, graph_visitor),
make_bfs_visitor(null_visitor())),
choose_pmap(get_param(params, vertex_color), ng, vertex_color)
);
}
namespace graph {
namespace detail {
template <typename Graph, typename Source>
struct breadth_first_search_impl {
typedef void result_type;
template <typename ArgPack>
void operator()(const Graph& g, const Source& source, const ArgPack& arg_pack) {
using namespace boost::graph::keywords;
typename boost::graph_traits<Graph>::vertex_descriptor sources[1] = {source};
boost::queue<typename boost::graph_traits<Graph>::vertex_descriptor> Q;
boost::breadth_first_search(g,
&sources[0],
&sources[1],
boost::unwrap_ref(arg_pack[_buffer | boost::ref(Q)]),
arg_pack[_visitor | make_bfs_visitor(null_visitor())],
boost::detail::make_color_map_from_arg_pack(g, arg_pack));
}
};
}
BOOST_GRAPH_MAKE_FORWARDING_FUNCTION(breadth_first_search, 2, 4)
}
#if 0
// Named Parameter Variant
BOOST_GRAPH_MAKE_OLD_STYLE_PARAMETER_FUNCTION(breadth_first_search, 2)
#endif
} // namespace boost
#ifdef BOOST_GRAPH_USE_MPI
# include <boost/graph/distributed/breadth_first_search.hpp>
#endif
#endif // BOOST_GRAPH_BREADTH_FIRST_SEARCH_HPP
| {
"pile_set_name": "Github"
} |
# --
# Copyright (C) 2001-2020 OTRS AG, https://otrs.com/
# --
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (GPL). If you
# did not receive this file, see https://www.gnu.org/licenses/gpl-3.0.txt.
# --
use strict;
use warnings;
use utf8;
use vars (qw($Self));
# get helper object
$Kernel::OM->ObjectParamAdd(
'Kernel::System::UnitTest::Helper' => {
RestoreDatabase => 1,
},
);
my $Helper = $Kernel::OM->Get('Kernel::System::UnitTest::Helper');
# get config object
my $ConfigObject = $Kernel::OM->Get('Kernel::Config');
# configure auth backend to db
$ConfigObject->Set(
Key => 'AuthBackend',
Value => 'DB',
);
# no additional auth backends
for my $Count ( 1 .. 10 ) {
$ConfigObject->Set(
Key => "AuthBackend$Count",
Value => '',
);
}
# disable email checks to create new user
$ConfigObject->Set(
Key => 'CheckEmailAddresses',
Value => 0,
);
my $TestUserID;
my $UserRand = 'example-user' . $Helper->GetRandomID();
# get user object
my $UserObject = $Kernel::OM->Get('Kernel::System::User');
# add test user
$TestUserID = $UserObject->UserAdd(
UserFirstname => 'Firstname Test1',
UserLastname => 'Lastname Test1',
UserLogin => $UserRand,
UserEmail => $UserRand . '@example.com',
ValidID => 1,
ChangeUserID => 1,
) || die "Could not create test user";
my @Tests = (
{
Password => 'simple',
AuthResult => $UserRand,
},
{
Password => 'very long password line which is unusual',
AuthResult => $UserRand,
},
{
Password => 'Переводчик',
AuthResult => $UserRand,
},
{
Password => 'كل ما تحب معرفته عن',
AuthResult => $UserRand,
},
{
Password => ' ',
AuthResult => $UserRand,
},
{
Password => "\n",
AuthResult => $UserRand,
},
{
Password => "\t",
AuthResult => $UserRand,
},
{
Password => "a" x 64, # max length for plain
AuthResult => $UserRand,
},
# SQL security tests
{
Password => "'UNION'",
AuthResult => $UserRand,
},
{
Password => "';",
AuthResult => $UserRand,
},
);
for my $CryptType (qw(plain crypt apr1 md5 sha1 sha2 sha512 bcrypt)) {
# make sure that the customer user objects gets recreated for each loop.
$Kernel::OM->ObjectsDiscard(
Objects => [
'Kernel::System::User',
'Kernel::System::Auth',
],
);
$ConfigObject->Set(
Key => "AuthModule::DB::CryptType",
Value => $CryptType
);
# get needed objects
my $UserObject = $Kernel::OM->Get('Kernel::System::User');
my $AuthObject = $Kernel::OM->Get('Kernel::System::Auth');
TEST:
for my $Test (@Tests) {
my $PasswordSet = $UserObject->SetPassword(
UserLogin => $UserRand,
PW => $Test->{Password},
);
if ( $CryptType eq 'plain' && $Test->{PlainFail} ) {
$Self->False(
$PasswordSet,
"Password set"
);
next TEST;
}
$Self->True(
$PasswordSet,
"Password set"
);
my $AuthResult = $AuthObject->Auth(
User => $UserRand,
Pw => $Test->{Password},
);
$Self->Is(
$AuthResult,
$Test->{AuthResult},
"CryptType $CryptType Password '$Test->{Password}'",
);
if ( $CryptType eq 'bcrypt' ) {
my $OldCost = $ConfigObject->Get('AuthModule::DB::bcryptCost') // 12;
my $NewCost = $OldCost + 2;
# Increase cost and check if old passwords can still be used.
$ConfigObject->Set(
Key => 'AuthModule::DB::bcryptCost',
Value => $NewCost,
);
$AuthResult = $AuthObject->Auth(
User => $UserRand,
Pw => $Test->{Password},
);
$Self->Is(
$AuthResult,
$Test->{AuthResult},
"CryptType $CryptType old Password '$Test->{Password}' with changed default cost ($NewCost)",
);
$PasswordSet = $UserObject->SetPassword(
UserLogin => $UserRand,
PW => $Test->{Password},
);
$Self->True(
$PasswordSet,
"Password set - with new cost $NewCost"
);
$AuthResult = $AuthObject->Auth(
User => $UserRand,
Pw => $Test->{Password},
);
$Self->Is(
$AuthResult,
$Test->{AuthResult},
"CryptType $CryptType new Password '$Test->{Password}' with changed default cost ($NewCost)",
);
# Restore old cost value
$ConfigObject->Set(
Key => 'AuthModule::DB::bcryptCost',
Value => $OldCost,
);
}
$AuthResult = $AuthObject->Auth(
User => $UserRand,
Pw => $Test->{Password},
);
$Self->Is(
$AuthResult,
$Test->{AuthResult},
"CryptType $CryptType Password '$Test->{Password}' (cached)",
);
$AuthResult = $AuthObject->Auth(
User => $UserRand,
Pw => 'wrong_pw',
);
$Self->False(
$AuthResult,
"CryptType $CryptType Password '$Test->{Password}' (wrong password)",
);
$AuthResult = $AuthObject->Auth(
User => 'non_existing_user_id',
Pw => $Test->{Password},
);
$Self->False(
$AuthResult,
"CryptType $CryptType Password '$Test->{Password}' (wrong user)",
);
}
}
# Check auth for user which password is encrypted by crypt algorithm different than system one.
@Tests = (
{
Password => 'test111test111test111',
UserLogin => 'example-user' . $Helper->GetRandomID(),
CryptType => 'crypt',
},
{
Password => 'test222test222test222',
UserLogin => 'example-user' . $Helper->GetRandomID(),
CryptType => 'sha1',
}
);
my $AuthObject = $Kernel::OM->Get('Kernel::System::Auth');
# Create users.
for my $Test (@Tests) {
my $UserID = $UserObject->UserAdd(
UserFirstname => $Test->{CryptType} . '-Firstname',
UserLastname => $Test->{CryptType} . '-Lastname',
UserLogin => $Test->{UserLogin},
UserEmail => $Test->{UserLogin} . '@example.com',
ValidID => 1,
ChangeUserID => 1,
);
$Self->True(
$UserID,
"UserID $UserID is created",
);
$Kernel::OM->ObjectsDiscard(
Objects => [
'Kernel::System::User',
'Kernel::System::Auth',
],
);
$ConfigObject->Set(
Key => "AuthModule::DB::CryptType",
Value => $Test->{CryptType},
);
$UserObject = $Kernel::OM->Get('Kernel::System::User');
$AuthObject = $Kernel::OM->Get('Kernel::System::Auth');
my $PasswordSet = $UserObject->SetPassword(
UserLogin => $Test->{UserLogin},
PW => $Test->{Password},
);
$Self->True(
$PasswordSet,
"Password '$Test->{Password}' is set"
);
}
# System is set to sha1 crypt type at this moment and
# we try to authenticate first created user (password is encrypted by different crypt type).
my $Result = $AuthObject->Auth(
User => $Tests[0]->{UserLogin},
Pw => $Tests[0]->{Password},
);
$Self->True(
$Result,
"System crypt type - $Tests[1]->{CryptType}, crypt type for user password - $Tests[0]->{CryptType}, user password '$Tests[0]->{Password}'",
);
# cleanup is done by RestoreDatabase
1;
| {
"pile_set_name": "Github"
} |
// test process:
// $ node eeprom.js
// $ node eeprom.js -w test-eeproms.json
// $ echo "a18bf9b65d676cd0a6e07b13fa06a362 test-cape.eeprom" | md5sum -c
// $ node eeprom.js -rmy-eeproms.json cape:test-cape.eeprom
// $ node eeprom.js -r cape:test-cape.eeprom verify-eeproms.json
// $ diff my-eeproms.json verify-eeproms.json
// $ node eeprom.js -wmy-eeproms.json test-cape.eeprom verify-cape.eeprom
// $ echo "a18bf9b65d676cd0a6e07b13fa06a362 verify-cape.eeprom" | md5sum -c
var printUsage = function() {
var usageString =
'Print usage:\n' +
'\n' +
' node bonescript/eeprom.js -h\n' +
'\n' +
'\n' +
'Read eeproms and write the output to a JSON-compatible file:\n' +
'\n' +
' node bonescript/eeprom.js [-r [type:source.eeprom ...] destination.json] \n' +
'\n' +
' type : the word "bone" or "cape"\n' +
' source.eeprom : source eeprom file\n' +
'\n' +
'\n' +
'Read JSON eeproms file and write the output to eeprom(s):\n' +
'\n' +
' node bonescript/eeprom.js -w source.json [[source-eeprom] destination.eeprom]\n' +
'\n' +
' source.json : source JSON file containing one or more eeprom structures\n' +
' destination.eeprom : where to write the output,\n' +
' must either match eeprom structure name or\n' +
' provide a source-eeprom parameter\n' +
' source-eeprom : which eeprom structure to use as source\n';
winston.error(usageString);
};
// Only run this section when run as a stand-alone application
if(!module.parent) {
var eeproms = {};
var destinationJSON = '';
process.argv.shift();
process.argv.shift();
if((process.argv.length > 0) && (process.argv[0].match(/^-w/i))) {
// Write EEPROMs
var sourceJSON = process.argv.shift().substr(2);
var sourceEeprom = '';
var destinationEeprom = '';
if(sourceJSON === '') {
sourceJSON = process.argv.shift();
}
if(process.argv.length > 2) {
printUsage();
throw('Too many arguments');
} else if(process.argv.length > 0) {
sourceEeprom = destinationEeprom = process.argv.pop();
if(process.argv.length > 0) {
sourceEeprom = process.argv.pop();
}
}
try {
winston.info('Reading '+sourceJSON);
var jsonFile = fs.readFileSync(sourceJSON, 'ascii');
winston.info('Parsing '+sourceJSON);
if(debug) winston.info(jsonFile);
eeproms = JSON.parse(jsonFile);
} catch(ex) {
throw('Unable to parse '+sourceJSON+': '+ex);
}
// If source file isn't nested, make it
if(eeproms.type) {
if(destinationEeprom === '') {
printUsage();
throw('Destination must be specified if not part of the JSON file');
}
eeproms[destinationEeprom] = eeproms;
}
for(var x in eeproms) {
if((sourceEeprom === '') || (x == sourceEeprom)) {
winston.info('Writing eeprom '+x);
if(eeproms[x].type != 'cape') {
throw('Only type "cape" is currently handled');
}
fillCapeEepromData(eeproms[x]);
if(debug) winston.debug(util.inspect(eepromData, true, null));
if(destinationEeprom === '') {
fs.writeFileSync(x, eepromData);
} else {
winston.info('Writing to file '+destinationEeprom);
fs.writeFileSync(destinationEeprom, eepromData);
}
} else {
winston.info('Skipping eeprom '+x);
}
}
} else if(process.argv.length === 0 ||
((process.argv.length > 0) && (process.argv[0].match(/^-r/i)))) {
// Read EEPROMs
var eepromsToRead = defaultEepromFiles;
if(process.argv.length > 0) {
destinationJSON = process.argv.shift().substr(2);
if(destinationJSON === '') {
destinationJSON = process.argv.pop();
}
}
if(process.argv.length > 0) {
eepromsToRead = {};
while(process.argv.length > 0) {
var eepromFile = process.argv.shift().split(':');
if(eepromFile.length != 2) {
printUsage();
throw('Source eeproms must be of the format <type>:<file>');
}
eepromsToRead[eepromFile[1]] = { type: eepromFile[2] };
}
}
eeproms = readEeproms(eepromsToRead);
if(eeproms == {}) {
winston.info('No valid EEPROM contents found');
} else {
var eepromsString = JSON.stringify(eeproms, null, 2);
if(destinationJSON === '') {
console.log(eepromsString);
} else {
winston.info('Writing JSON file to '+destinationJSON);
fs.writeFileSync(destinationJSON, eepromsString);
}
}
} else {
printUsage();
return(0);
}
}
| {
"pile_set_name": "Github"
} |
source "https://rubygems.org"
gemspec
| {
"pile_set_name": "Github"
} |
#ifndef __UIEDIT_H__
#define __UIEDIT_H__
#pragma once
namespace DuiLib
{
class CEditWnd;
class UILIB_API CEditUI : public CLabelUI
{
friend class CEditWnd;
public:
CEditUI();
~CEditUI(){};
LPCTSTR GetClass() const;
LPVOID GetInterface(LPCTSTR pstrName);
UINT GetControlFlags() const;
void SetEnabled(bool bEnable = true);
void SetText(LPCTSTR pstrText);
void SetMaxChar(UINT uMax);
UINT GetMaxChar();
void SetReadOnly(bool bReadOnly);
bool IsReadOnly() const;
void SetPasswordMode(bool bPasswordMode);
bool IsPasswordMode() const;
void SetPasswordChar(TCHAR cPasswordChar);
TCHAR GetPasswordChar() const;
void SetNumberOnly(bool bNumberOnly);
bool IsNumberOnly() const;
int GetWindowStyls() const;
LPCTSTR GetNormalImage();
void SetNormalImage(LPCTSTR pStrImage);
LPCTSTR GetHotImage();
void SetHotImage(LPCTSTR pStrImage);
LPCTSTR GetFocusedImage();
void SetFocusedImage(LPCTSTR pStrImage);
LPCTSTR GetDisabledImage();
void SetDisabledImage(LPCTSTR pStrImage);
void SetNativeEditBkColor(DWORD dwBkColor);
DWORD GetNativeEditBkColor() const;
void SetSel(long nStartChar, long nEndChar);
void SetSelAll();
void SetReplaceSel(LPCTSTR lpszReplace);
void SetPos(RECT rc);
void SetVisible(bool bVisible = true);
void SetInternVisible(bool bVisible = true);
SIZE EstimateSize(SIZE szAvailable);
void DoEvent(TEventUI& event);
void SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue);
void PaintStatusImage(HDC hDC);
void PaintText(HDC hDC);
protected:
CEditWnd* m_pWindow;
UINT m_uMaxChar;
bool m_bReadOnly;
bool m_bPasswordMode;
TCHAR m_cPasswordChar;
UINT m_uButtonState;
CDuiString m_sNormalImage;
CDuiString m_sHotImage;
CDuiString m_sFocusedImage;
CDuiString m_sDisabledImage;
DWORD m_dwEditbkColor;
int m_iWindowStyls;
};
}
#endif // __UIEDIT_H__ | {
"pile_set_name": "Github"
} |
StartChar: Amacron
Encoding: 256 256 204
GlifName: A_macron
Width: 1190
VWidth: 0
Flags: W
HStem: 0 21G<40 209.491 980.509 1150> 342 140<360 830> 1396 20G<513.22 676.78> 1586 134<310 880>
LayerCount: 3
Back
Fore
SplineSet
310 1720 m 1
880 1720 l 1
880 1586 l 1
310 1586 l 1
310 1720 l 1
EndSplineSet
Refer: 13 65 N 1 0 0 1 0 0 3
Validated: 1
Layer: 2
EndChar
| {
"pile_set_name": "Github"
} |
.clipboardy-iframe-container {
width: 100%;
height: 0;
position: relative;
transition: visibility 0.4s, opacity 0.4s ease-in;
visibility: visible;
opacity: 1;
z-index: 10;
&.clipboardy-hidden {
opacity: 0;
visibility: hidden;
-webkit-transition-delay: 1.2s;
}
.clipboardy-iframe {
position: absolute;
width: 200px;
height: 28px;
top: -18px;
right: 0;
-webkit-user-select: none;
z-index: 2;
}
&.clipboardy-buttons-layout-right {
.clipboardy-iframe {
width: 50px;
height: 100px;
top: 0;
right: -35px;
}
}
}
*[data-source-id] {
transition: opacity 0.2s ease-out;
&.clipboardy-collapsed {
opacity: 0.6;
overflow: hidden !important;
height: 60px !important;
}
} | {
"pile_set_name": "Github"
} |
//
// SentryNSURLRequest.h
// Sentry
//
// Created by Daniel Griesser on 05/05/2017.
// Copyright © 2017 Sentry. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class SentryDsn, SentryEvent;
@interface SentryNSURLRequest : NSMutableURLRequest
- (_Nullable instancetype)initStoreRequestWithDsn:(SentryDsn *)dsn
andEvent:(SentryEvent *)event
didFailWithError:(NSError *_Nullable *_Nullable)error;
- (_Nullable instancetype)initStoreRequestWithDsn:(SentryDsn *)dsn
andData:(NSData *)data
didFailWithError:(NSError *_Nullable *_Nullable)error;
@end
NS_ASSUME_NONNULL_END
| {
"pile_set_name": "Github"
} |
#' @param file Something that identifies the file of interest on your Google
#' Drive. Can be a name or path, a file id or URL marked with [as_id()], or a
#' [`dribble`].
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.actuate.autoconfigure.mail;
import java.util.Map;
import org.springframework.boot.actuate.autoconfigure.health.CompositeHealthContributorConfiguration;
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
import org.springframework.boot.actuate.health.HealthContributor;
import org.springframework.boot.actuate.mail.MailHealthIndicator;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;
/**
* {@link EnableAutoConfiguration Auto-configuration} for {@link MailHealthIndicator}.
*
* @author Johannes Edmeier
* @since 2.0.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JavaMailSenderImpl.class)
@ConditionalOnBean(JavaMailSenderImpl.class)
@ConditionalOnEnabledHealthIndicator("mail")
@AutoConfigureAfter(MailSenderAutoConfiguration.class)
public class MailHealthContributorAutoConfiguration
extends CompositeHealthContributorConfiguration<MailHealthIndicator, JavaMailSenderImpl> {
@Bean
@ConditionalOnMissingBean(name = { "mailHealthIndicator", "mailHealthContributor" })
public HealthContributor mailHealthContributor(Map<String, JavaMailSenderImpl> mailSenders) {
return createContributor(mailSenders);
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Requests for PHP
*
* Inspired by Requests for Python.
*
* Based on concepts from SimplePie_File, RequestCore and WP_Http.
*
* @package Requests
*/
/**
* Requests for PHP
*
* Inspired by Requests for Python.
*
* Based on concepts from SimplePie_File, RequestCore and WP_Http.
*
* @package Requests
*/
class Requests {
/**
* POST method
*
* @var string
*/
const POST = 'POST';
/**
* PUT method
*
* @var string
*/
const PUT = 'PUT';
/**
* GET method
*
* @var string
*/
const GET = 'GET';
/**
* HEAD method
*
* @var string
*/
const HEAD = 'HEAD';
/**
* DELETE method
*
* @var string
*/
const DELETE = 'DELETE';
/**
* OPTIONS method
*
* @var string
*/
const OPTIONS = 'OPTIONS';
/**
* TRACE method
*
* @var string
*/
const TRACE = 'TRACE';
/**
* PATCH method
*
* @link https://tools.ietf.org/html/rfc5789
* @var string
*/
const PATCH = 'PATCH';
/**
* Default size of buffer size to read streams
*
* @var integer
*/
const BUFFER_SIZE = 1160;
/**
* Current version of Requests
*
* @var string
*/
const VERSION = '1.7-3470169';
/**
* Registered transport classes
*
* @var array
*/
protected static $transports = array();
/**
* Selected transport name
*
* Use {@see get_transport()} instead
*
* @var array
*/
public static $transport = array();
/**
* Default certificate path.
*
* @see Requests::get_certificate_path()
* @see Requests::set_certificate_path()
*
* @var string
*/
protected static $certificate_path;
/**
* This is a static class, do not instantiate it
*
* @codeCoverageIgnore
*/
private function __construct() {}
/**
* Autoloader for Requests
*
* Register this with {@see register_autoloader()} if you'd like to avoid
* having to create your own.
*
* (You can also use `spl_autoload_register` directly if you'd prefer.)
*
* @codeCoverageIgnore
*
* @param string $class Class name to load
*/
public static function autoloader($class) {
// Check that the class starts with "Requests"
if (strpos($class, 'Requests') !== 0) {
return;
}
$file = str_replace('_', '/', $class);
if (file_exists(dirname(__FILE__) . '/' . $file . '.php')) {
require_once(dirname(__FILE__) . '/' . $file . '.php');
}
}
/**
* Register the built-in autoloader
*
* @codeCoverageIgnore
*/
public static function register_autoloader() {
spl_autoload_register(array('Requests', 'autoloader'));
}
/**
* Register a transport
*
* @param string $transport Transport class to add, must support the Requests_Transport interface
*/
public static function add_transport($transport) {
if (empty(self::$transports)) {
self::$transports = array(
'Requests_Transport_cURL',
'Requests_Transport_fsockopen',
);
}
self::$transports = array_merge(self::$transports, array($transport));
}
/**
* Get a working transport
*
* @throws Requests_Exception If no valid transport is found (`notransport`)
* @return Requests_Transport
*/
protected static function get_transport($capabilities = array()) {
// Caching code, don't bother testing coverage
// @codeCoverageIgnoreStart
// array of capabilities as a string to be used as an array key
ksort($capabilities);
$cap_string = serialize($capabilities);
// Don't search for a transport if it's already been done for these $capabilities
if (isset(self::$transport[$cap_string]) && self::$transport[$cap_string] !== null) {
$class = self::$transport[$cap_string];
return new $class();
}
// @codeCoverageIgnoreEnd
if (empty(self::$transports)) {
self::$transports = array(
'Requests_Transport_cURL',
'Requests_Transport_fsockopen',
);
}
// Find us a working transport
foreach (self::$transports as $class) {
if (!class_exists($class)) {
continue;
}
$result = call_user_func(array($class, 'test'), $capabilities);
if ($result) {
self::$transport[$cap_string] = $class;
break;
}
}
if (self::$transport[$cap_string] === null) {
throw new Requests_Exception('No working transports found', 'notransport', self::$transports);
}
$class = self::$transport[$cap_string];
return new $class();
}
/**#@+
* @see request()
* @param string $url
* @param array $headers
* @param array $options
* @return Requests_Response
*/
/**
* Send a GET request
*/
public static function get($url, $headers = array(), $options = array()) {
return self::request($url, $headers, null, self::GET, $options);
}
/**
* Send a HEAD request
*/
public static function head($url, $headers = array(), $options = array()) {
return self::request($url, $headers, null, self::HEAD, $options);
}
/**
* Send a DELETE request
*/
public static function delete($url, $headers = array(), $options = array()) {
return self::request($url, $headers, null, self::DELETE, $options);
}
/**
* Send a TRACE request
*/
public static function trace($url, $headers = array(), $options = array()) {
return self::request($url, $headers, null, self::TRACE, $options);
}
/**#@-*/
/**#@+
* @see request()
* @param string $url
* @param array $headers
* @param array $data
* @param array $options
* @return Requests_Response
*/
/**
* Send a POST request
*/
public static function post($url, $headers = array(), $data = array(), $options = array()) {
return self::request($url, $headers, $data, self::POST, $options);
}
/**
* Send a PUT request
*/
public static function put($url, $headers = array(), $data = array(), $options = array()) {
return self::request($url, $headers, $data, self::PUT, $options);
}
/**
* Send an OPTIONS request
*/
public static function options($url, $headers = array(), $data = array(), $options = array()) {
return self::request($url, $headers, $data, self::OPTIONS, $options);
}
/**
* Send a PATCH request
*
* Note: Unlike {@see post} and {@see put}, `$headers` is required, as the
* specification recommends that should send an ETag
*
* @link https://tools.ietf.org/html/rfc5789
*/
public static function patch($url, $headers, $data = array(), $options = array()) {
return self::request($url, $headers, $data, self::PATCH, $options);
}
/**#@-*/
/**
* Main interface for HTTP requests
*
* This method initiates a request and sends it via a transport before
* parsing.
*
* The `$options` parameter takes an associative array with the following
* options:
*
* - `timeout`: How long should we wait for a response?
* Note: for cURL, a minimum of 1 second applies, as DNS resolution
* operates at second-resolution only.
* (float, seconds with a millisecond precision, default: 10, example: 0.01)
* - `connect_timeout`: How long should we wait while trying to connect?
* (float, seconds with a millisecond precision, default: 10, example: 0.01)
* - `useragent`: Useragent to send to the server
* (string, default: php-requests/$version)
* - `follow_redirects`: Should we follow 3xx redirects?
* (boolean, default: true)
* - `redirects`: How many times should we redirect before erroring?
* (integer, default: 10)
* - `blocking`: Should we block processing on this request?
* (boolean, default: true)
* - `filename`: File to stream the body to instead.
* (string|boolean, default: false)
* - `auth`: Authentication handler or array of user/password details to use
* for Basic authentication
* (Requests_Auth|array|boolean, default: false)
* - `proxy`: Proxy details to use for proxy by-passing and authentication
* (Requests_Proxy|array|string|boolean, default: false)
* - `max_bytes`: Limit for the response body size.
* (integer|boolean, default: false)
* - `idn`: Enable IDN parsing
* (boolean, default: true)
* - `transport`: Custom transport. Either a class name, or a
* transport object. Defaults to the first working transport from
* {@see getTransport()}
* (string|Requests_Transport, default: {@see getTransport()})
* - `hooks`: Hooks handler.
* (Requests_Hooker, default: new Requests_Hooks())
* - `verify`: Should we verify SSL certificates? Allows passing in a custom
* certificate file as a string. (Using true uses the system-wide root
* certificate store instead, but this may have different behaviour
* across transports.)
* (string|boolean, default: library/Requests/Transport/cacert.pem)
* - `verifyname`: Should we verify the common name in the SSL certificate?
* (boolean: default, true)
* - `data_format`: How should we send the `$data` parameter?
* (string, one of 'query' or 'body', default: 'query' for
* HEAD/GET/DELETE, 'body' for POST/PUT/OPTIONS/PATCH)
*
* @throws Requests_Exception On invalid URLs (`nonhttp`)
*
* @param string $url URL to request
* @param array $headers Extra headers to send with the request
* @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
* @param string $type HTTP request type (use Requests constants)
* @param array $options Options for the request (see description for more information)
* @return Requests_Response
*/
public static function request($url, $headers = array(), $data = array(), $type = self::GET, $options = array()) {
if (empty($options['type'])) {
$options['type'] = $type;
}
$options = array_merge(self::get_default_options(), $options);
self::set_defaults($url, $headers, $data, $type, $options);
$options['hooks']->dispatch('requests.before_request', array(&$url, &$headers, &$data, &$type, &$options));
if (!empty($options['transport'])) {
$transport = $options['transport'];
if (is_string($options['transport'])) {
$transport = new $transport();
}
}
else {
$need_ssl = (0 === stripos($url, 'https://'));
$capabilities = array('ssl' => $need_ssl);
$transport = self::get_transport($capabilities);
}
$response = $transport->request($url, $headers, $data, $options);
$options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options));
return self::parse_response($response, $url, $headers, $data, $options);
}
/**
* Send multiple HTTP requests simultaneously
*
* The `$requests` parameter takes an associative or indexed array of
* request fields. The key of each request can be used to match up the
* request with the returned data, or with the request passed into your
* `multiple.request.complete` callback.
*
* The request fields value is an associative array with the following keys:
*
* - `url`: Request URL Same as the `$url` parameter to
* {@see Requests::request}
* (string, required)
* - `headers`: Associative array of header fields. Same as the `$headers`
* parameter to {@see Requests::request}
* (array, default: `array()`)
* - `data`: Associative array of data fields or a string. Same as the
* `$data` parameter to {@see Requests::request}
* (array|string, default: `array()`)
* - `type`: HTTP request type (use Requests constants). Same as the `$type`
* parameter to {@see Requests::request}
* (string, default: `Requests::GET`)
* - `cookies`: Associative array of cookie name to value, or cookie jar.
* (array|Requests_Cookie_Jar)
*
* If the `$options` parameter is specified, individual requests will
* inherit options from it. This can be used to use a single hooking system,
* or set all the types to `Requests::POST`, for example.
*
* In addition, the `$options` parameter takes the following global options:
*
* - `complete`: A callback for when a request is complete. Takes two
* parameters, a Requests_Response/Requests_Exception reference, and the
* ID from the request array (Note: this can also be overridden on a
* per-request basis, although that's a little silly)
* (callback)
*
* @param array $requests Requests data (see description for more information)
* @param array $options Global and default options (see {@see Requests::request})
* @return array Responses (either Requests_Response or a Requests_Exception object)
*/
public static function request_multiple($requests, $options = array()) {
$options = array_merge(self::get_default_options(true), $options);
if (!empty($options['hooks'])) {
$options['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
if (!empty($options['complete'])) {
$options['hooks']->register('multiple.request.complete', $options['complete']);
}
}
foreach ($requests as $id => &$request) {
if (!isset($request['headers'])) {
$request['headers'] = array();
}
if (!isset($request['data'])) {
$request['data'] = array();
}
if (!isset($request['type'])) {
$request['type'] = self::GET;
}
if (!isset($request['options'])) {
$request['options'] = $options;
$request['options']['type'] = $request['type'];
}
else {
if (empty($request['options']['type'])) {
$request['options']['type'] = $request['type'];
}
$request['options'] = array_merge($options, $request['options']);
}
self::set_defaults($request['url'], $request['headers'], $request['data'], $request['type'], $request['options']);
// Ensure we only hook in once
if ($request['options']['hooks'] !== $options['hooks']) {
$request['options']['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
if (!empty($request['options']['complete'])) {
$request['options']['hooks']->register('multiple.request.complete', $request['options']['complete']);
}
}
}
unset($request);
if (!empty($options['transport'])) {
$transport = $options['transport'];
if (is_string($options['transport'])) {
$transport = new $transport();
}
}
else {
$transport = self::get_transport();
}
$responses = $transport->request_multiple($requests, $options);
foreach ($responses as $id => &$response) {
// If our hook got messed with somehow, ensure we end up with the
// correct response
if (is_string($response)) {
$request = $requests[$id];
self::parse_multiple($response, $request);
$request['options']['hooks']->dispatch('multiple.request.complete', array(&$response, $id));
}
}
return $responses;
}
/**
* Get the default options
*
* @see Requests::request() for values returned by this method
* @param boolean $multirequest Is this a multirequest?
* @return array Default option values
*/
protected static function get_default_options($multirequest = false) {
$defaults = array(
'timeout' => 10,
'connect_timeout' => 10,
'useragent' => 'php-requests/' . self::VERSION,
'protocol_version' => 1.1,
'redirected' => 0,
'redirects' => 10,
'follow_redirects' => true,
'blocking' => true,
'type' => self::GET,
'filename' => false,
'auth' => false,
'proxy' => false,
'cookies' => false,
'max_bytes' => false,
'idn' => true,
'hooks' => null,
'transport' => null,
'verify' => Requests::get_certificate_path(),
'verifyname' => true,
);
if ($multirequest !== false) {
$defaults['complete'] = null;
}
return $defaults;
}
/**
* Get default certificate path.
*
* @return string Default certificate path.
*/
public static function get_certificate_path() {
if ( ! empty( Requests::$certificate_path ) ) {
return Requests::$certificate_path;
}
return dirname(__FILE__) . '/Requests/Transport/cacert.pem';
}
/**
* Set default certificate path.
*
* @param string $path Certificate path, pointing to a PEM file.
*/
public static function set_certificate_path( $path ) {
Requests::$certificate_path = $path;
}
/**
* Set the default values
*
* @param string $url URL to request
* @param array $headers Extra headers to send with the request
* @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
* @param string $type HTTP request type
* @param array $options Options for the request
* @return array $options
*/
protected static function set_defaults(&$url, &$headers, &$data, &$type, &$options) {
if (!preg_match('/^http(s)?:\/\//i', $url, $matches)) {
throw new Requests_Exception('Only HTTP(S) requests are handled.', 'nonhttp', $url);
}
if (empty($options['hooks'])) {
$options['hooks'] = new Requests_Hooks();
}
if (is_array($options['auth'])) {
$options['auth'] = new Requests_Auth_Basic($options['auth']);
}
if ($options['auth'] !== false) {
$options['auth']->register($options['hooks']);
}
if (is_string($options['proxy']) || is_array($options['proxy'])) {
$options['proxy'] = new Requests_Proxy_HTTP($options['proxy']);
}
if ($options['proxy'] !== false) {
$options['proxy']->register($options['hooks']);
}
if (is_array($options['cookies'])) {
$options['cookies'] = new Requests_Cookie_Jar($options['cookies']);
}
elseif (empty($options['cookies'])) {
$options['cookies'] = new Requests_Cookie_Jar();
}
if ($options['cookies'] !== false) {
$options['cookies']->register($options['hooks']);
}
if ($options['idn'] !== false) {
$iri = new Requests_IRI($url);
$iri->host = Requests_IDNAEncoder::encode($iri->ihost);
$url = $iri->uri;
}
// Massage the type to ensure we support it.
$type = strtoupper($type);
if (!isset($options['data_format'])) {
if (in_array($type, array(self::HEAD, self::GET, self::DELETE))) {
$options['data_format'] = 'query';
}
else {
$options['data_format'] = 'body';
}
}
}
/**
* HTTP response parser
*
* @throws Requests_Exception On missing head/body separator (`requests.no_crlf_separator`)
* @throws Requests_Exception On missing head/body separator (`noversion`)
* @throws Requests_Exception On missing head/body separator (`toomanyredirects`)
*
* @param string $headers Full response text including headers and body
* @param string $url Original request URL
* @param array $req_headers Original $headers array passed to {@link request()}, in case we need to follow redirects
* @param array $req_data Original $data array passed to {@link request()}, in case we need to follow redirects
* @param array $options Original $options array passed to {@link request()}, in case we need to follow redirects
* @return Requests_Response
*/
protected static function parse_response($headers, $url, $req_headers, $req_data, $options) {
$return = new Requests_Response();
if (!$options['blocking']) {
return $return;
}
$return->raw = $headers;
$return->url = $url;
if (!$options['filename']) {
if (($pos = strpos($headers, "\r\n\r\n")) === false) {
// Crap!
throw new Requests_Exception('Missing header/body separator', 'requests.no_crlf_separator');
}
$headers = substr($return->raw, 0, $pos);
$return->body = substr($return->raw, $pos + strlen("\n\r\n\r"));
}
else {
$return->body = '';
}
// Pretend CRLF = LF for compatibility (RFC 2616, section 19.3)
$headers = str_replace("\r\n", "\n", $headers);
// Unfold headers (replace [CRLF] 1*( SP | HT ) with SP) as per RFC 2616 (section 2.2)
$headers = preg_replace('/\n[ \t]/', ' ', $headers);
$headers = explode("\n", $headers);
preg_match('#^HTTP/(1\.\d)[ \t]+(\d+)#i', array_shift($headers), $matches);
if (empty($matches)) {
throw new Requests_Exception('Response could not be parsed', 'noversion', $headers);
}
$return->protocol_version = (float) $matches[1];
$return->status_code = (int) $matches[2];
if ($return->status_code >= 200 && $return->status_code < 300) {
$return->success = true;
}
foreach ($headers as $header) {
list($key, $value) = explode(':', $header, 2);
$value = trim($value);
preg_replace('#(\s+)#i', ' ', $value);
$return->headers[$key] = $value;
}
if (isset($return->headers['transfer-encoding'])) {
$return->body = self::decode_chunked($return->body);
unset($return->headers['transfer-encoding']);
}
if (isset($return->headers['content-encoding'])) {
$return->body = self::decompress($return->body);
}
//fsockopen and cURL compatibility
if (isset($return->headers['connection'])) {
unset($return->headers['connection']);
}
$options['hooks']->dispatch('requests.before_redirect_check', array(&$return, $req_headers, $req_data, $options));
if ($return->is_redirect() && $options['follow_redirects'] === true) {
if (isset($return->headers['location']) && $options['redirected'] < $options['redirects']) {
if ($return->status_code === 303) {
$options['type'] = self::GET;
}
$options['redirected']++;
$location = $return->headers['location'];
if (strpos($location, 'http://') !== 0 && strpos($location, 'https://') !== 0) {
// relative redirect, for compatibility make it absolute
$location = Requests_IRI::absolutize($url, $location);
$location = $location->uri;
}
$hook_args = array(
&$location,
&$req_headers,
&$req_data,
&$options,
$return
);
$options['hooks']->dispatch('requests.before_redirect', $hook_args);
$redirected = self::request($location, $req_headers, $req_data, $options['type'], $options);
$redirected->history[] = $return;
return $redirected;
}
elseif ($options['redirected'] >= $options['redirects']) {
throw new Requests_Exception('Too many redirects', 'toomanyredirects', $return);
}
}
$return->redirects = $options['redirected'];
$options['hooks']->dispatch('requests.after_request', array(&$return, $req_headers, $req_data, $options));
return $return;
}
/**
* Callback for `transport.internal.parse_response`
*
* Internal use only. Converts a raw HTTP response to a Requests_Response
* while still executing a multiple request.
*
* @param string $response Full response text including headers and body (will be overwritten with Response instance)
* @param array $request Request data as passed into {@see Requests::request_multiple()}
* @return null `$response` is either set to a Requests_Response instance, or a Requests_Exception object
*/
public static function parse_multiple(&$response, $request) {
try {
$url = $request['url'];
$headers = $request['headers'];
$data = $request['data'];
$options = $request['options'];
$response = self::parse_response($response, $url, $headers, $data, $options);
}
catch (Requests_Exception $e) {
$response = $e;
}
}
/**
* Decoded a chunked body as per RFC 2616
*
* @see https://tools.ietf.org/html/rfc2616#section-3.6.1
* @param string $data Chunked body
* @return string Decoded body
*/
protected static function decode_chunked($data) {
if (!preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', trim($data))) {
return $data;
}
$decoded = '';
$encoded = $data;
while (true) {
$is_chunked = (bool) preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', $encoded, $matches);
if (!$is_chunked) {
// Looks like it's not chunked after all
return $data;
}
$length = hexdec(trim($matches[1]));
if ($length === 0) {
// Ignore trailer headers
return $decoded;
}
$chunk_length = strlen($matches[0]);
$decoded .= substr($encoded, $chunk_length, $length);
$encoded = substr($encoded, $chunk_length + $length + 2);
if (trim($encoded) === '0' || empty($encoded)) {
return $decoded;
}
}
// We'll never actually get down here
// @codeCoverageIgnoreStart
}
// @codeCoverageIgnoreEnd
/**
* Convert a key => value array to a 'key: value' array for headers
*
* @param array $array Dictionary of header values
* @return string[] List of headers
*/
public static function flatten($array) {
$return = array();
foreach ($array as $key => $value) {
$return[] = sprintf('%s: %s', $key, $value);
}
return $return;
}
/**
* Convert a key => value array to a 'key: value' array for headers
*
* @codeCoverageIgnore
* @deprecated Misspelling of {@see Requests::flatten}
* @param array $array Dictionary of header values
* @return string[] List of headers
*/
public static function flattern($array) {
return self::flatten($array);
}
/**
* Decompress an encoded body
*
* Implements gzip, compress and deflate. Guesses which it is by attempting
* to decode.
*
* @param string $data Compressed data in one of the above formats
* @return string Decompressed string
*/
public static function decompress($data) {
if (substr($data, 0, 2) !== "\x1f\x8b" && substr($data, 0, 2) !== "\x78\x9c") {
// Not actually compressed. Probably cURL ruining this for us.
return $data;
}
if (function_exists('gzdecode') && ($decoded = @gzdecode($data)) !== false) {
return $decoded;
}
elseif (function_exists('gzinflate') && ($decoded = @gzinflate($data)) !== false) {
return $decoded;
}
elseif (($decoded = self::compatible_gzinflate($data)) !== false) {
return $decoded;
}
elseif (function_exists('gzuncompress') && ($decoded = @gzuncompress($data)) !== false) {
return $decoded;
}
return $data;
}
/**
* Decompression of deflated string while staying compatible with the majority of servers.
*
* Certain Servers will return deflated data with headers which PHP's gzinflate()
* function cannot handle out of the box. The following function has been created from
* various snippets on the gzinflate() PHP documentation.
*
* Warning: Magic numbers within. Due to the potential different formats that the compressed
* data may be returned in, some "magic offsets" are needed to ensure proper decompression
* takes place. For a simple progmatic way to determine the magic offset in use, see:
* https://core.trac.wordpress.org/ticket/18273
*
* @since 2.8.1
* @link https://core.trac.wordpress.org/ticket/18273
* @link https://secure.php.net/manual/en/function.gzinflate.php#70875
* @link https://secure.php.net/manual/en/function.gzinflate.php#77336
*
* @param string $gzData String to decompress.
* @return string|bool False on failure.
*/
public static function compatible_gzinflate($gzData) {
// Compressed data might contain a full zlib header, if so strip it for
// gzinflate()
if (substr($gzData, 0, 3) == "\x1f\x8b\x08") {
$i = 10;
$flg = ord(substr($gzData, 3, 1));
if ($flg > 0) {
if ($flg & 4) {
list($xlen) = unpack('v', substr($gzData, $i, 2));
$i = $i + 2 + $xlen;
}
if ($flg & 8) {
$i = strpos($gzData, "\0", $i) + 1;
}
if ($flg & 16) {
$i = strpos($gzData, "\0", $i) + 1;
}
if ($flg & 2) {
$i = $i + 2;
}
}
$decompressed = self::compatible_gzinflate(substr($gzData, $i));
if (false !== $decompressed) {
return $decompressed;
}
}
// If the data is Huffman Encoded, we must first strip the leading 2
// byte Huffman marker for gzinflate()
// The response is Huffman coded by many compressors such as
// java.util.zip.Deflater, Ruby’s Zlib::Deflate, and .NET's
// System.IO.Compression.DeflateStream.
//
// See https://decompres.blogspot.com/ for a quick explanation of this
// data type
$huffman_encoded = false;
// low nibble of first byte should be 0x08
list(, $first_nibble) = unpack('h', $gzData);
// First 2 bytes should be divisible by 0x1F
list(, $first_two_bytes) = unpack('n', $gzData);
if (0x08 == $first_nibble && 0 == ($first_two_bytes % 0x1F)) {
$huffman_encoded = true;
}
if ($huffman_encoded) {
if (false !== ($decompressed = @gzinflate(substr($gzData, 2)))) {
return $decompressed;
}
}
if ("\x50\x4b\x03\x04" == substr($gzData, 0, 4)) {
// ZIP file format header
// Offset 6: 2 bytes, General-purpose field
// Offset 26: 2 bytes, filename length
// Offset 28: 2 bytes, optional field length
// Offset 30: Filename field, followed by optional field, followed
// immediately by data
list(, $general_purpose_flag) = unpack('v', substr($gzData, 6, 2));
// If the file has been compressed on the fly, 0x08 bit is set of
// the general purpose field. We can use this to differentiate
// between a compressed document, and a ZIP file
$zip_compressed_on_the_fly = (0x08 == (0x08 & $general_purpose_flag));
if (!$zip_compressed_on_the_fly) {
// Don't attempt to decode a compressed zip file
return $gzData;
}
// Determine the first byte of data, based on the above ZIP header
// offsets:
$first_file_start = array_sum(unpack('v2', substr($gzData, 26, 4)));
if (false !== ($decompressed = @gzinflate(substr($gzData, 30 + $first_file_start)))) {
return $decompressed;
}
return false;
}
// Finally fall back to straight gzinflate
if (false !== ($decompressed = @gzinflate($gzData))) {
return $decompressed;
}
// Fallback for all above failing, not expected, but included for
// debugging and preventing regressions and to track stats
if (false !== ($decompressed = @gzinflate(substr($gzData, 2)))) {
return $decompressed;
}
return false;
}
public static function match_domain($host, $reference) {
// Check for a direct match
if ($host === $reference) {
return true;
}
// Calculate the valid wildcard match if the host is not an IP address
// Also validates that the host has 3 parts or more, as per Firefox's
// ruleset.
$parts = explode('.', $host);
if (ip2long($host) === false && count($parts) >= 3) {
$parts[0] = '*';
$wildcard = implode('.', $parts);
if ($wildcard === $reference) {
return true;
}
}
return false;
}
}
| {
"pile_set_name": "Github"
} |
/*
* FreeRTOS Kernel V10.4.1
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
#ifndef TCP_H
#define TCP_H
#define htonl(A) ((((A) & 0xff000000) >> 24) | (((A) & 0x00ff0000) >> 8) | (((A) & 0x0000ff00) << 8) | (((A) & 0x000000ff) << 24))
void vTCPHardReset( void );
long lTCPSoftReset( void );
long lTCPCreateSocket( void );
long lTCPListen( void );
long lProcessConnection( void );
void vTCPListen( void );
#endif
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0940"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1967AF8A20D96F480043C0E7"
BuildableName = "Bartinter.app"
BlueprintName = "Bartinter"
ReferencedContainer = "container:Bartinter.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "195444A820E14E66004B03C5"
BuildableName = "BartinterTests.xctest"
BlueprintName = "BartinterTests"
ReferencedContainer = "container:Bartinter.xcodeproj">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "19F320E420E16392008D1587"
BuildableName = "BartinterUITests.xctest"
BlueprintName = "BartinterUITests"
ReferencedContainer = "container:Bartinter.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1967AF8A20D96F480043C0E7"
BuildableName = "Bartinter.app"
BlueprintName = "Bartinter"
ReferencedContainer = "container:Bartinter.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1967AF8A20D96F480043C0E7"
BuildableName = "Bartinter.app"
BlueprintName = "Bartinter"
ReferencedContainer = "container:Bartinter.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1967AF8A20D96F480043C0E7"
BuildableName = "Bartinter.app"
BlueprintName = "Bartinter"
ReferencedContainer = "container:Bartinter.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
| {
"pile_set_name": "Github"
} |
# Copyright 2016 Jared Boone <[email protected]>
#
# This file is part of PortaPack.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
cmake_minimum_required(VERSION 2.8.9)
cmake_policy(SET CMP0005 NEW)
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_LIST_DIR}/firmware/toolchain-arm-cortex-m.cmake)
project(portapack-h1)
#set(VERSION "")
if (NOT DEFINED VERSION)
execute_process(
COMMAND git log -n 1 --format=%h
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
RESULT_VARIABLE GIT_VERSION_FOUND
ERROR_QUIET
OUTPUT_VARIABLE GIT_VERSION
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if (GIT_VERSION_FOUND)
set(VERSION "unknown")
else (GIT_VERSION_FOUND)
set(VERSION "local-${GIT_VERSION}")
endif (GIT_VERSION_FOUND)
endif()
set(LICENSE_PATH ${CMAKE_CURRENT_LIST_DIR}/LICENSE)
set(HARDWARE_PATH ${CMAKE_CURRENT_LIST_DIR}/hardware)
add_subdirectory(hackrf/firmware/hackrf_usb)
set(HACKRF_FIRMWARE_DFU_FILENAME hackrf_usb.dfu)
set(HACKRF_FIRMWARE_BIN_FILENAME hackrf_usb_ram.bin)
set(HACKRF_CPLD_XSVF_FILENAME default.xsvf)
set(HACKRF_PATH ${CMAKE_CURRENT_LIST_DIR}/hackrf)
set(HACKRF_CPLD_TOOL ${HACKRF_PATH}/firmware/tools/cpld_bitstream.py)
set(HACKRF_CPLD_XSVF_PATH ${HACKRF_PATH}/firmware/cpld/sgpio_if/${HACKRF_CPLD_XSVF_FILENAME})
set(HACKRF_FIRMWARE_DFU_IMAGE ${hackrf_usb_BINARY_DIR}/${HACKRF_FIRMWARE_DFU_FILENAME})
set(HACKRF_FIRMWARE_BIN_IMAGE ${hackrf_usb_BINARY_DIR}/${HACKRF_FIRMWARE_BIN_FILENAME})
add_subdirectory(firmware)
| {
"pile_set_name": "Github"
} |
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
/**
* @file
* API for event export in iCalendar format
* as outlined in Internet Calendaring and
* Scheduling Core Object Specification
*/
class CRM_Utils_ICalendar {
/**
* Escape text elements for safe ICalendar use.
*
* @param string $text
* Text to escape.
*
* @return string
*/
public static function formatText($text) {
$text = strip_tags($text);
$text = str_replace("\\", "\\\\", $text);
$text = str_replace(',', '\,', $text);
$text = str_replace(';', '\;', $text);
$text = str_replace(["\r\n", "\n", "\r"], "\\n ", $text);
$text = implode("\n ", str_split($text, 50));
return $text;
}
/**
* Restore iCal formatted text to normal.
*
* @param string $text
* Text to unescape.
*
* @return string
*/
public static function unformatText($text) {
$text = str_replace('\n ', "\n", $text);
$text = str_replace('\;', ';', $text);
$text = str_replace('\,', ',', $text);
$text = str_replace("\\\\", "\\", $text);
$text = str_replace("DQUOTE", "\"", $text);
return $text;
}
/**
* Escape date elements for safe ICalendar use.
*
* @param $date
* Date to escape.
*
* @param bool $gdata
*
* @return string
* Escaped date
*/
public static function formatDate($date, $gdata = FALSE) {
if ($gdata) {
return date("Y-m-d\TH:i:s.000",
strtotime($date)
);
}
else {
return date("Ymd\THis",
strtotime($date)
);
}
}
/**
* Send the ICalendar to the browser with the specified content type
* - 'text/calendar' : used for downloaded ics file
* - 'text/plain' : used for iCal formatted feed
* - 'text/xml' : used for gData or rss formatted feeds
*
*
* @param string $calendar
* The calendar data to be published.
* @param string $content_type
* @param string $charset
* The character set to use, defaults to 'us-ascii'.
* @param string $fileName
* The file name (for downloads).
* @param string $disposition
* How the file should be sent ('attachment' for downloads).
*/
public static function send($calendar, $content_type = 'text/calendar', $charset = 'us-ascii', $fileName = NULL, $disposition = NULL) {
$config = CRM_Core_Config::singleton();
$lang = $config->lcMessages;
CRM_Utils_System::setHttpHeader("Content-Language", $lang);
CRM_Utils_System::setHttpHeader("Content-Type", "$content_type; charset=$charset");
if ($content_type == 'text/calendar') {
CRM_Utils_System::setHttpHeader('Content-Length', strlen($calendar));
CRM_Utils_System::setHttpHeader("Content-Disposition", "$disposition; filename=\"$fileName\"");
CRM_Utils_System::setHttpHeader("Pragma", "no-cache");
CRM_Utils_System::setHttpHeader("Expires", "0");
CRM_Utils_System::setHttpHeader("Cache-Control", "no-cache, must-revalidate");
}
echo $calendar;
}
}
| {
"pile_set_name": "Github"
} |
from base import *
DIR = "QA262"
CONF = """
vserver!1!rule!2620!match = directory
vserver!1!rule!2620!match!directory = /%(DIR)s
vserver!1!rule!2620!handler = redir
vserver!1!rule!2620!handler!rewrite!1!show = 1
vserver!1!rule!2620!handler!rewrite!1!regex = ^/(.*)$
vserver!1!rule!2620!handler!rewrite!1!substring = /First_Rule/$1
vserver!1!rule!2620!handler!rewrite!2!show = 1
vserver!1!rule!2620!handler!rewrite!2!regex = ^/(.*)$
vserver!1!rule!2620!handler!rewrite!2!substring = /Second_Rule/$1
vserver!1!rule!2620!handler!rewrite!3!show = 1
vserver!1!rule!2620!handler!rewrite!3!regex = ^/(.*)$
vserver!1!rule!2620!handler!rewrite!3!substring = /Third_Rule/$1
"""
class Test (TestBase):
def __init__ (self):
TestBase.__init__ (self, __file__)
self.name = "Request Redir evaluation order"
self.request = "GET /%(DIR)s/whatever HTTP/1.0\r\n" % (globals())
self.conf = CONF %(globals())
self.expected_error = 301
self.expected_content = "First_Rule"
self.forbidden_content = ['Second_Rule', 'Third_Rule']
| {
"pile_set_name": "Github"
} |
// (C) Copyright John Maddock 2007.
// Use, modification and distribution are 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)
//
// This file is machine generated, do not edit by hand
// Polynomial evaluation using second order Horners rule
#ifndef BOOST_MATH_TOOLS_RAT_EVAL_10_HPP
#define BOOST_MATH_TOOLS_RAT_EVAL_10_HPP
namespace boost{ namespace math{ namespace tools{ namespace detail{
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T*, const U*, const V&, const boost::integral_constant<int, 0>*) BOOST_MATH_NOEXCEPT(V)
{
return static_cast<V>(0);
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V&, const boost::integral_constant<int, 1>*) BOOST_MATH_NOEXCEPT(V)
{
return static_cast<V>(a[0]) / static_cast<V>(b[0]);
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const boost::integral_constant<int, 2>*) BOOST_MATH_NOEXCEPT(V)
{
return static_cast<V>((a[1] * x + a[0]) / (b[1] * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const boost::integral_constant<int, 3>*) BOOST_MATH_NOEXCEPT(V)
{
return static_cast<V>(((a[2] * x + a[1]) * x + a[0]) / ((b[2] * x + b[1]) * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const boost::integral_constant<int, 4>*) BOOST_MATH_NOEXCEPT(V)
{
return static_cast<V>((((a[3] * x + a[2]) * x + a[1]) * x + a[0]) / (((b[3] * x + b[2]) * x + b[1]) * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const boost::integral_constant<int, 5>*) BOOST_MATH_NOEXCEPT(V)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[4] * x2 + a[2];
t[1] = a[3] * x2 + a[1];
t[2] = b[4] * x2 + b[2];
t[3] = b[3] * x2 + b[1];
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[4]);
t[2] += static_cast<V>(b[4]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const boost::integral_constant<int, 6>*) BOOST_MATH_NOEXCEPT(V)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[5] * x2 + a[3];
t[1] = a[4] * x2 + a[2];
t[2] = b[5] * x2 + b[3];
t[3] = b[4] * x2 + b[2];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[1]);
t[1] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[1]);
t[3] += static_cast<V>(b[0]);
t[0] *= x;
t[2] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z;
t[2] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const boost::integral_constant<int, 7>*) BOOST_MATH_NOEXCEPT(V)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[6] * x2 + a[4];
t[1] = a[5] * x2 + a[3];
t[2] = b[6] * x2 + b[4];
t[3] = b[5] * x2 + b[3];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[2]);
t[1] += static_cast<V>(a[1]);
t[2] += static_cast<V>(b[2]);
t[3] += static_cast<V>(b[1]);
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[6]);
t[2] += static_cast<V>(b[6]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const boost::integral_constant<int, 8>*) BOOST_MATH_NOEXCEPT(V)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[7] * x2 + a[5];
t[1] = a[6] * x2 + a[4];
t[2] = b[7] * x2 + b[5];
t[3] = b[6] * x2 + b[4];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[3]);
t[1] += static_cast<V>(a[2]);
t[2] += static_cast<V>(b[3]);
t[3] += static_cast<V>(b[2]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[1]);
t[1] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[1]);
t[3] += static_cast<V>(b[0]);
t[0] *= x;
t[2] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z;
t[2] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const boost::integral_constant<int, 9>*) BOOST_MATH_NOEXCEPT(V)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[8] * x2 + a[6];
t[1] = a[7] * x2 + a[5];
t[2] = b[8] * x2 + b[6];
t[3] = b[7] * x2 + b[5];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[3]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[3]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[2]);
t[1] += static_cast<V>(a[1]);
t[2] += static_cast<V>(b[2]);
t[3] += static_cast<V>(b[1]);
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[8]);
t[2] += static_cast<V>(b[8]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const boost::integral_constant<int, 10>*) BOOST_MATH_NOEXCEPT(V)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[9] * x2 + a[7];
t[1] = a[8] * x2 + a[6];
t[2] = b[9] * x2 + b[7];
t[3] = b[8] * x2 + b[6];
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[5]);
t[1] += static_cast<V>(a[4]);
t[2] += static_cast<V>(b[5]);
t[3] += static_cast<V>(b[4]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[3]);
t[1] += static_cast<V>(a[2]);
t[2] += static_cast<V>(b[3]);
t[3] += static_cast<V>(b[2]);
t[0] *= x2;
t[1] *= x2;
t[2] *= x2;
t[3] *= x2;
t[0] += static_cast<V>(a[1]);
t[1] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[1]);
t[3] += static_cast<V>(b[0]);
t[0] *= x;
t[2] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[4]);
t[1] += static_cast<V>(a[5]);
t[2] += static_cast<V>(b[4]);
t[3] += static_cast<V>(b[5]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[6]);
t[1] += static_cast<V>(a[7]);
t[2] += static_cast<V>(b[6]);
t[3] += static_cast<V>(b[7]);
t[0] *= z2;
t[1] *= z2;
t[2] *= z2;
t[3] *= z2;
t[0] += static_cast<V>(a[8]);
t[1] += static_cast<V>(a[9]);
t[2] += static_cast<V>(b[8]);
t[3] += static_cast<V>(b[9]);
t[0] *= z;
t[2] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
}}}} // namespaces
#endif // include guard
| {
"pile_set_name": "Github"
} |
// @target: es2015
class Test {
#y = 123;
static something(obj: { [key: string]: Test }) {
obj[(new class { #x = 1; readonly s = "prop"; }).s].#y = 1;
obj[(new class { #x = 1; readonly s = "prop"; }).s].#y += 1;
}
}
| {
"pile_set_name": "Github"
} |
import QtQuick 2.0
BorderImage {
id : borderImage
readonly property real dp : 3
readonly property bool ninePatch : true
property alias fillArea : fillAreaItem
source : Qt.resolvedUrl("../drawable-xxhdpi/art_shadow_depth_4.png")
border.left : 108
border.right : 108
border.top : 108
border.bottom : 108
Item {
id : fillAreaItem
anchors.fill: parent
anchors.leftMargin: 108
anchors.rightMargin: 108
anchors.topMargin: 108
anchors.bottomMargin: 108
readonly property int rightMargin: 108
readonly property int bottomMargin: 108
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016-2019 David Karnok
*
* 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 hu.akarnokd.rxjava3.string;
import java.util.concurrent.atomic.AtomicBoolean;
import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.disposables.Disposable;
final class ObservableCharSequence extends Observable<Integer> {
final CharSequence string;
ObservableCharSequence(CharSequence string) {
this.string = string;
}
@Override
protected void subscribeActual(Observer<? super Integer> observer) {
Disposable d = new BooleanDisposable();
observer.onSubscribe(d);
CharSequence s = string;
int len = s.length();
for (int i = 0; i < len; i++) {
if (d.isDisposed()) {
return;
}
observer.onNext((int)s.charAt(i));
}
if (d.isDisposed()) {
return;
}
observer.onComplete();
}
static final class BooleanDisposable extends AtomicBoolean implements Disposable {
private static final long serialVersionUID = -4762798297183704664L;
@Override
public void dispose() {
lazySet(true);
}
@Override
public boolean isDisposed() {
return get();
}
}
}
| {
"pile_set_name": "Github"
} |
//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#pragma once
#include "Prerequisites/BsPrerequisitesUtil.h"
#include "Reflection/BsRTTIType.h"
#include "Reflection/BsRTTIPlain.h"
#include "Serialization/BsSerializedObject.h"
#include "FileSystem/BsDataStream.h"
namespace bs
{
/** @cond RTTI */
/** @addtogroup RTTI-Impl-Utility
* @{
*/
class BS_UTILITY_EXPORT SerializedInstanceRTTI : public RTTIType <SerializedInstance, IReflectable, SerializedInstanceRTTI>
{
public:
const String& getRTTIName() override
{
static String name = "SerializedInstance";
return name;
}
UINT32 getRTTIId() override
{
return TID_SerializedInstance;
}
SPtr<IReflectable> newRTTIObject() override
{
return nullptr;
}
};
class BS_UTILITY_EXPORT SerializedFieldRTTI : public RTTIType <SerializedField, SerializedInstance, SerializedFieldRTTI>
{
private:
SPtr<DataStream> getData(SerializedField* obj, UINT32& size)
{
size = obj->size;
return bs_shared_ptr_new<MemoryDataStream>(obj->value, obj->size);
}
void setData(SerializedField* obj, const SPtr<DataStream>& value, UINT32 size)
{
obj->value = (UINT8*)bs_alloc(size);
obj->size = size;
obj->ownsMemory = true;
value->read(obj->value, size);
}
public:
SerializedFieldRTTI()
{
addDataBlockField("data", 0, &SerializedFieldRTTI::getData, &SerializedFieldRTTI::setData);
}
const String& getRTTIName() override
{
static String name = "SerializedField";
return name;
}
UINT32 getRTTIId() override
{
return TID_SerializedField;
}
SPtr<IReflectable> newRTTIObject() override
{
return bs_shared_ptr_new<SerializedField>();
}
};
class BS_UTILITY_EXPORT SerializedDataBlockRTTI : public RTTIType <SerializedDataBlock, SerializedInstance, SerializedDataBlockRTTI>
{
private:
SPtr<DataStream> getData(SerializedDataBlock* obj, UINT32& size)
{
size = obj->size;
obj->stream->seek(obj->offset);
return obj->stream;
}
void setData(SerializedDataBlock* obj, const SPtr<DataStream>& value, UINT32 size)
{
SPtr<MemoryDataStream> memStream = bs_shared_ptr_new<MemoryDataStream>(size);
value->read(memStream->data(), size);
obj->stream = memStream;
obj->size = size;
obj->offset = 0;
}
public:
SerializedDataBlockRTTI()
{
addDataBlockField("data", 0, &SerializedDataBlockRTTI::getData, &SerializedDataBlockRTTI::setData);
}
const String& getRTTIName() override
{
static String name = "SerializedDataBlock";
return name;
}
UINT32 getRTTIId() override
{
return TID_SerializedDataBlock;
}
SPtr<IReflectable> newRTTIObject() override
{
return bs_shared_ptr_new<SerializedDataBlock>();
}
};
class BS_UTILITY_EXPORT SerializedObjectRTTI : public RTTIType <SerializedObject, SerializedInstance, SerializedObjectRTTI>
{
private:
SerializedSubObject& getEntry(SerializedObject* obj, UINT32 arrayIdx)
{
return obj->subObjects[arrayIdx];
}
void setEntry(SerializedObject* obj, UINT32 arrayIdx, SerializedSubObject& val)
{
obj->subObjects[arrayIdx] = val;
}
UINT32 getNumEntries(SerializedObject* obj)
{
return (UINT32)obj->subObjects.size();
}
void setNumEntries(SerializedObject* obj, UINT32 numEntries)
{
obj->subObjects = Vector<SerializedSubObject>(numEntries);
}
public:
SerializedObjectRTTI()
{
addReflectableArrayField("entries", 1, &SerializedObjectRTTI::getEntry, &SerializedObjectRTTI::getNumEntries,
&SerializedObjectRTTI::setEntry, &SerializedObjectRTTI::setNumEntries);
}
const String& getRTTIName() override
{
static String name = "SerializedObject";
return name;
}
UINT32 getRTTIId() override
{
return TID_SerializedObject;
}
SPtr<IReflectable> newRTTIObject() override
{
return bs_shared_ptr_new<SerializedObject>();
}
};
class BS_UTILITY_EXPORT SerializedArrayRTTI : public RTTIType <SerializedArray, SerializedInstance, SerializedArrayRTTI>
{
private:
UINT32& getNumElements(SerializedArray* obj)
{
return obj->numElements;
}
void setNumElements(SerializedArray* obj, UINT32& val)
{
obj->numElements = val;
}
SerializedArrayEntry& getEntry(SerializedArray* obj, UINT32 arrayIdx)
{
return mSequentialEntries[arrayIdx];
}
void setEntry(SerializedArray* obj, UINT32 arrayIdx, SerializedArrayEntry& val)
{
obj->entries[val.index] = val;
}
UINT32 getNumEntries(SerializedArray* obj)
{
return (UINT32)mSequentialEntries.size();
}
void setNumEntries(SerializedArray* obj, UINT32 numEntries)
{
obj->entries = UnorderedMap<UINT32, SerializedArrayEntry>();
}
public:
SerializedArrayRTTI()
{
addPlainField("numElements", 0, &SerializedArrayRTTI::getNumElements, &SerializedArrayRTTI::setNumElements);
addReflectableArrayField("entries", 1, &SerializedArrayRTTI::getEntry, &SerializedArrayRTTI::getNumEntries,
&SerializedArrayRTTI::setEntry, &SerializedArrayRTTI::setNumEntries);
}
void onSerializationStarted(IReflectable* obj, SerializationContext* context) override
{
SerializedArray* serializedArray = static_cast<SerializedArray*>(obj);
for (auto& entry : serializedArray->entries)
mSequentialEntries.push_back(entry.second);
}
const String& getRTTIName() override
{
static String name = "SerializedArray";
return name;
}
UINT32 getRTTIId() override
{
return TID_SerializedArray;
}
SPtr<IReflectable> newRTTIObject() override
{
return bs_shared_ptr_new<SerializedArray>();
}
private:
Vector<SerializedArrayEntry> mSequentialEntries;
};
class BS_UTILITY_EXPORT SerializedSubObjectRTTI : public RTTIType <SerializedSubObject, IReflectable, SerializedSubObjectRTTI>
{
private:
UINT32& getTypeId(SerializedSubObject* obj)
{
return obj->typeId;
}
void setTypeId(SerializedSubObject* obj, UINT32& val)
{
obj->typeId = val;
}
SerializedEntry& getEntry(SerializedSubObject* obj, UINT32 arrayIdx)
{
return mSequentialEntries[arrayIdx];
}
void setEntry(SerializedSubObject* obj, UINT32 arrayIdx, SerializedEntry& val)
{
obj->entries[val.fieldId] = val;
}
UINT32 getNumEntries(SerializedSubObject* obj)
{
return (UINT32)mSequentialEntries.size();
}
void setNumEntries(SerializedSubObject* obj, UINT32 numEntries)
{
obj->entries = UnorderedMap<UINT32, SerializedEntry>();
}
public:
SerializedSubObjectRTTI()
{
addPlainField("typeId", 0, &SerializedSubObjectRTTI::getTypeId, &SerializedSubObjectRTTI::setTypeId);
addReflectableArrayField("entries", 1, &SerializedSubObjectRTTI::getEntry, &SerializedSubObjectRTTI::getNumEntries,
&SerializedSubObjectRTTI::setEntry, &SerializedSubObjectRTTI::setNumEntries);
}
void onSerializationStarted(IReflectable* obj, SerializationContext* context) override
{
SerializedSubObject* serializableObject = static_cast<SerializedSubObject*>(obj);
for (auto& entry : serializableObject->entries)
mSequentialEntries.push_back(entry.second);
}
const String& getRTTIName() override
{
static String name = "SerializedSubObject";
return name;
}
UINT32 getRTTIId() override
{
return TID_SerializedSubObject;
}
SPtr<IReflectable> newRTTIObject() override
{
return bs_shared_ptr_new<SerializedSubObject>();
}
private:
Vector<SerializedEntry> mSequentialEntries;
};
class BS_UTILITY_EXPORT SerializedEntryRTTI : public RTTIType <SerializedEntry, IReflectable, SerializedEntryRTTI>
{
private:
UINT32& getFieldId(SerializedEntry* obj)
{
return obj->fieldId;
}
void setFieldId(SerializedEntry* obj, UINT32& val)
{
obj->fieldId = val;
}
SPtr<SerializedInstance> getSerialized(SerializedEntry* obj)
{
return obj->serialized;
}
void setSerialized(SerializedEntry* obj, SPtr<SerializedInstance> val)
{
obj->serialized = val;
}
public:
SerializedEntryRTTI()
{
addPlainField("fieldId", 0, &SerializedEntryRTTI::getFieldId, &SerializedEntryRTTI::setFieldId);
addReflectablePtrField("serialized", 1, &SerializedEntryRTTI::getSerialized, &SerializedEntryRTTI::setSerialized);
}
const String& getRTTIName() override
{
static String name = "SerializedEntry";
return name;
}
UINT32 getRTTIId() override
{
return TID_SerializedEntry;
}
SPtr<IReflectable> newRTTIObject() override
{
return bs_shared_ptr_new<SerializedEntry>();
}
};
class BS_UTILITY_EXPORT SerializedArrayEntryRTTI : public RTTIType <SerializedArrayEntry, IReflectable, SerializedArrayEntryRTTI>
{
private:
UINT32& getArrayIdx(SerializedArrayEntry* obj)
{
return obj->index;
}
void setArrayIdx(SerializedArrayEntry* obj, UINT32& val)
{
obj->index = val;
}
SPtr<SerializedInstance> getSerialized(SerializedArrayEntry* obj)
{
return obj->serialized;
}
void setSerialized(SerializedArrayEntry* obj, SPtr<SerializedInstance> val)
{
obj->serialized = val;
}
public:
SerializedArrayEntryRTTI()
{
addPlainField("index", 0, &SerializedArrayEntryRTTI::getArrayIdx, &SerializedArrayEntryRTTI::setArrayIdx);
addReflectablePtrField("serialized", 1, &SerializedArrayEntryRTTI::getSerialized, &SerializedArrayEntryRTTI::setSerialized);
}
const String& getRTTIName() override
{
static String name = "SerializedArrayEntry";
return name;
}
UINT32 getRTTIId() override
{
return TID_SerializedArrayEntry;
}
SPtr<IReflectable> newRTTIObject() override
{
return bs_shared_ptr_new<SerializedArrayEntry>();
}
};
/** @} */
/** @endcond */
}
| {
"pile_set_name": "Github"
} |
define("ace/snippets/ftl",["require","exports","module"],function(e,t,n){"use strict";t.snippetText="",t.scope="ftl"});
(function() {
window.require(["ace/snippets/ftl"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!--
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.
--><taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>Tags20</short-name>
<uri>http://tomcat.apache.org/tags20</uri>
<tag>
<name>Echo</name>
<tag-class>org.apache.jasper.compiler.TestValidator$Echo</tag-class>
<body-content>empty</body-content>
<attribute>
<name>echo</name>
<required>yes</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib> | {
"pile_set_name": "Github"
} |
<?php
namespace Doctrine\Tests\Common\Cache;
use Doctrine\Common\Cache\ApcCache;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\Common\Cache\ChainCache;
class ChainCacheTest extends CacheTest
{
protected function _getCacheDriver()
{
return new ChainCache(array(new ArrayCache()));
}
public function testGetStats()
{
$cache = $this->_getCacheDriver();
$stats = $cache->getStats();
$this->assertInternalType('array', $stats);
}
public function testOnlyFetchFirstOne()
{
$cache1 = new ArrayCache();
$cache2 = $this->getMockForAbstractClass('Doctrine\Common\Cache\CacheProvider');
$cache2->expects($this->never())->method('doFetch');
$chainCache = new ChainCache(array($cache1, $cache2));
$chainCache->save('id', 'bar');
$this->assertEquals('bar', $chainCache->fetch('id'));
}
public function testFetchPropagateToFastestCache()
{
$cache1 = new ArrayCache();
$cache2 = new ArrayCache();
$cache2->save('bar', 'value');
$chainCache = new ChainCache(array($cache1, $cache2));
$this->assertFalse($cache1->contains('bar'));
$result = $chainCache->fetch('bar');
$this->assertEquals('value', $result);
$this->assertTrue($cache2->contains('bar'));
}
public function testNamespaceIsPropagatedToAllProviders()
{
$cache1 = new ArrayCache();
$cache2 = new ArrayCache();
$chainCache = new ChainCache(array($cache1, $cache2));
$chainCache->setNamespace('bar');
$this->assertEquals('bar', $cache1->getNamespace());
$this->assertEquals('bar', $cache2->getNamespace());
}
public function testDeleteToAllProviders()
{
$cache1 = $this->getMockForAbstractClass('Doctrine\Common\Cache\CacheProvider');
$cache2 = $this->getMockForAbstractClass('Doctrine\Common\Cache\CacheProvider');
$cache1->expects($this->once())->method('doDelete');
$cache2->expects($this->once())->method('doDelete');
$chainCache = new ChainCache(array($cache1, $cache2));
$chainCache->delete('bar');
}
public function testFlushToAllProviders()
{
$cache1 = $this->getMockForAbstractClass('Doctrine\Common\Cache\CacheProvider');
$cache2 = $this->getMockForAbstractClass('Doctrine\Common\Cache\CacheProvider');
$cache1->expects($this->once())->method('doFlush');
$cache2->expects($this->once())->method('doFlush');
$chainCache = new ChainCache(array($cache1, $cache2));
$chainCache->flushAll();
}
protected function isSharedStorage()
{
return false;
}
} | {
"pile_set_name": "Github"
} |
// Copyright 2020 The go-hep 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 rdict
import (
"reflect"
"go-hep.org/x/hep/groot/rbytes"
"go-hep.org/x/hep/groot/rmeta"
)
// type arrayMode int32
type elemDescr struct {
otype rmeta.Enum
ntype rmeta.Enum
offset int // actually an index to the struct's field or to array's element
length int
elem rbytes.StreamerElement
method []int
oclass string
nclass string
mbr interface{} // member streamer
}
type streamerConfig struct {
si *StreamerInfo
eid int // element ID
descr *elemDescr
offset int // offset/index within object. negative if no offset to be applied.
length int // number of elements for fixed-length arrays
count func() int // optional func to give the length of ROOT's C var-len arrays.
}
func (cfg *streamerConfig) counter(recv interface{}) int {
if cfg.count != nil {
return cfg.count()
}
return int(reflect.ValueOf(recv).Elem().FieldByIndex(cfg.descr.method).Int())
}
func (cfg *streamerConfig) adjust(recv interface{}) interface{} {
if cfg == nil || cfg.offset < 0 {
return recv
}
rv := reflect.ValueOf(recv).Elem()
switch rv.Kind() {
case reflect.Struct:
return rv.Field(cfg.offset).Addr().Interface()
case reflect.Array, reflect.Slice:
return rv.Index(cfg.offset).Addr().Interface()
default:
return recv
}
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the 2amigos/yii2-usuario project.
*
* (c) 2amigOS! <http://2amigos.us/>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Da\User\Model;
use Da\User\Traits\AuthManagerAwareTrait;
use Da\User\Validator\RbacItemsValidator;
use Yii;
use yii\base\InvalidConfigException;
use yii\base\Model;
class Assignment extends Model
{
use AuthManagerAwareTrait;
public $items = [];
public $user_id;
public $updated = false;
/**
* {@inheritdoc}
*
* @throws InvalidConfigException
*/
public function init()
{
parent::init();
if ($this->user_id === null) {
throw new InvalidConfigException('"user_id" must be set.');
}
$this->items = array_keys($this->getAuthManager()->getItemsByUser($this->user_id));
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'items' => Yii::t('usuario', 'Items'),
];
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
['user_id', 'required'],
['items', RbacItemsValidator::class],
['user_id', 'integer'],
];
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<title>Async-graphql Book</title>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<style>
div {
margin: 18pt;
font-size: 24pt;
}
</style>
</head>
<body>
<h1>Async-graphql Book</h1>
<p>This book is available in multiple languages:</p>
<ul>
<li><a href="en/index.html">English</a></li>
<li><a href="zh-CN/index.html">简体中文</a></li>
</ul>
</body>
</html>
| {
"pile_set_name": "Github"
} |
Description:
Return the canonical absolute name of a given file.
Files:
lib/canonicalize.h
lib/canonicalize.c
m4/canonicalize.m4
Depends-on:
areadlink-with-size
double-slash-root
errno
extensions
file-set
filename
hash-triple-simple
lstat
memmove
nocrash
pathmax
stat
sys_stat
xalloc
xgetcwd
configure.ac:
gl_FUNC_CANONICALIZE_FILENAME_MODE
gl_MODULE_INDICATOR([canonicalize])
gl_MODULE_INDICATOR_FOR_TESTS([canonicalize])
gl_STDLIB_MODULE_INDICATOR([canonicalize_file_name])
Makefile.am:
lib_SOURCES += canonicalize.c
Include:
"canonicalize.h"
License:
GPL
Maintainer:
Jim Meyering
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<thing:thing-descriptions bindingId="knx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:thing="https://openhab.org/schemas/thing-description/v1.0.0"
xsi:schemaLocation="https://openhab.org/schemas/thing-description/v1.0.0 https://openhab.org/schemas/thing-description-1.0.0.xsd">
<!-- Bridge Thing Type -->
<bridge-type id="ip">
<label>KNX/IP Gateway</label>
<description>This is a KNX IP interface or router</description>
<config-description>
<parameter name="type" type="text">
<label>IP Connection Type</label>
<description>The ip connection type for connecting to the KNX bus. Could be either TUNNEL or ROUTER</description>
<required>true</required>
<options>
<option value="TUNNEL">Tunnel</option>
<option value="ROUTER">Router</option>
</options>
</parameter>
<parameter name="ipAddress" type="text">
<label>Network Address</label>
<description>Network address of the KNX/IP gateway</description>
<context>network-address</context>
</parameter>
<parameter name="portNumber" type="integer">
<description>Port number of the KNX/IP gateway</description>
<required>false</required> <!-- Only required in TUNNEL mode -->
<label>Port</label>
<default>3671</default>
</parameter>
<parameter name="localIp" type="text">
<label>Local Network Address</label>
<description>Network address of the local host to be used to set up the connection to the KNX/IP gateway</description>
<context>network-address</context>
</parameter>
<parameter name="localSourceAddr" type="text">
<label>Local Device Address</label>
<description>The Physical Address (Individual Address) in x.y.z notation for identification of this KNX/IP gateway
within the KNX bus</description>
<default>0.0.0</default>
</parameter>
<parameter name="useNAT" type="boolean">
<label>Use NAT</label>
<description>Set to "true" when having network address translation between this server and the gateway</description>
<default>false</default>
</parameter>
<parameter name="readingPause" type="integer">
<label>Reading Pause</label>
<description>Time in milliseconds of how long should be paused between two read requests to the bus during
initialization</description>
<default>50</default>
</parameter>
<parameter name="responseTimeout" type="integer">
<label>Response Timeout</label>
<description>Seconds to wait for a response from the KNX bus</description>
<default>10</default>
</parameter>
<parameter name="readRetriesLimit" type="integer">
<label>Read Retries Limit</label>
<description>Limits the read retries while initialization from the KNX bus</description>
<default>3</default>
</parameter>
<parameter name="autoReconnectPeriod" type="integer">
<label>Auto Reconnect Period</label>
<description>Seconds between connection retries when KNX link has been lost, 0 means never retry, minimum 30s</description>
<default>60</default>
</parameter>
</config-description>
</bridge-type>
</thing:thing-descriptions>
| {
"pile_set_name": "Github"
} |
import datetime
from pytds import tz
def test_tz():
assert tz.FixedOffsetTimezone(0, 'UTC').tzname(None) == 'UTC'
lz = tz.LocalTimezone()
jan_1 = datetime.datetime(2010, 1, 1, 0, 0)
july_1 = datetime.datetime(2010, 7, 1, 0, 0)
assert isinstance(lz.tzname(jan_1), str)
lz.dst(jan_1)
lz.dst(july_1)
lz.utcoffset(jan_1)
lz.utcoffset(july_1)
| {
"pile_set_name": "Github"
} |
#include "stdafx.h"
#include "PModuleFunc.h"
#include "Common.h"
#include <Psapi.h>
#include "resource.h"
#pragma comment(lib,"psapi.lib")
extern WIN_VERSION GetWindowsVersion();
extern WIN_VERSION WinVersion;
extern ULONG_PTR g_ulProcessId;
COLUMNSTRUCT g_Column_ProcessModule[] =
{
{ L"地址", 125 },
{ L"大小", 70 },
{ L"入口地址", 125 },
{ L"模块名称", 270 }
};
UINT g_Column_ProcessModule_Count = 4; //进程列表列数
extern int dpix;
extern int dpiy;
VOID HsInitPModuleDetailList(CListCtrl *m_ListCtrl)
{
while(m_ListCtrl->DeleteColumn(0));
m_ListCtrl->DeleteAllItems();
m_ListCtrl->SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES|LVS_EX_HEADERDRAGDROP);
UINT i;
for (i = 0;i<g_Column_ProcessModule_Count;i++)
{
if (i==1)
{
m_ListCtrl->InsertColumn(i, g_Column_ProcessModule[i].szTitle,LVCFMT_RIGHT,(int)(g_Column_ProcessModule[i].nWidth*(dpix/96.0)));
}
else
{
m_ListCtrl->InsertColumn(i, g_Column_ProcessModule[i].szTitle,LVCFMT_LEFT,(int)(g_Column_ProcessModule[i].nWidth*(dpix/96.0)));
}
}
if (HsIs64BitWindows())
{
EnableDebugPri64();
}
else
{
EnableDebugPri32();
}
}
VOID HsLoadPModuleDetailList(CListCtrl *m_ListCtrl)
{
PROCESSMODULE_INFO mi[1024] = {0};
m_ListCtrl->DeleteAllItems();
ULONG_PTR ulCount = EnumProcessModule(mi);
CString strBase;
CString strSize;
CString strEntryPoint;
if (ulCount>0)
{
UINT i = 0;
for (i=0;i<ulCount;i++)
{
strBase.Format(L"0x%p",mi[i].ulBase);
strSize.Format(L"0x%X",mi[i].ulSize);
strEntryPoint.Format(L"0x%p",mi[i].ulEntryPoint);
CString strPathName(mi[i].szPath);
int n = m_ListCtrl->InsertItem(m_ListCtrl->GetItemCount(),strBase);
m_ListCtrl->SetItemText(n,1,strSize);
m_ListCtrl->SetItemText(n,2,strEntryPoint);
m_ListCtrl->SetItemText(n,3,strPathName);
}
}
}
BOOL EnableDebugPri64()
{
typedef long (__fastcall *pfnRtlAdjustPrivilege64)(ULONG,ULONG,ULONG,PVOID);
pfnRtlAdjustPrivilege64 RtlAdjustPrivilege;
DWORD dwRetVal = 0;
LPTHREAD_START_ROUTINE FuncAddress = NULL;
#ifdef _UNICODE
FuncAddress = (PTHREAD_START_ROUTINE)::GetProcAddress(::GetModuleHandle(_T("Kernel32")), "LoadLibraryW");
#else
FuncAddress = (PTHREAD_START_ROUTINE)::GetProcAddress(::GetModuleHandle(_T("Kernel32")), "LoadLibraryA");
#endif
if (FuncAddress==NULL)
{
return FALSE;
}
RtlAdjustPrivilege=(pfnRtlAdjustPrivilege64)GetProcAddress((HMODULE)(FuncAddress(L"ntdll.dll")),"RtlAdjustPrivilege");
if (RtlAdjustPrivilege==NULL)
{
return FALSE;
}
RtlAdjustPrivilege(20,1,0,&dwRetVal);
return TRUE;
}
BOOL EnableDebugPri32()
{
HANDLE hToken;
TOKEN_PRIVILEGES pTP;
LUID uID;
if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken))
{
printf("OpenProcessToken is Error\n");
return FALSE;
}
if (!LookupPrivilegeValue(NULL,SE_DEBUG_NAME,&uID))
{
printf("LookupPrivilegeValue is Error\n");
return FALSE;
}
pTP.PrivilegeCount = 1;
pTP.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
pTP.Privileges[0].Luid = uID;
//在这里我们进行调整权限
if (!AdjustTokenPrivileges(hToken,false,&pTP,sizeof(TOKEN_PRIVILEGES),NULL,NULL))
{
printf("AdjuestTokenPrivileges is Error\n");
return FALSE;
}
return TRUE;
}
ULONG_PTR EnumProcessModule(_PROCESSMODULE_INFO* mi)
{
MODULEINFO ModInfor;
char szModName[MAX_PATH];
HMODULE hMods[1024];
DWORD cbNeeded,i;
HANDLE hProcess;
hProcess = OpenProcess(PROCESS_ALL_ACCESS,0,(DWORD)g_ulProcessId);
if (hProcess==0)
{
return 0;
}
if(EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
{
for (i=0; i<=cbNeeded/sizeof(HMODULE); i++ )
{
GetModuleInformation(hProcess, hMods[i], &ModInfor, sizeof(MODULEINFO));
GetModuleFileNameExA(hProcess, hMods[i], szModName, 260);
mi[i].ulBase=(ULONG_PTR)(ModInfor.lpBaseOfDll);
mi[i].ulSize=(ULONG_PTR)(ModInfor.SizeOfImage);
mi[i].ulEntryPoint=(ULONG_PTR)(ModInfor.EntryPoint);
strcpy_s(mi[i].szPath,szModName);
}
CloseHandle(hProcess);
return cbNeeded/sizeof(HMODULE);
}
else
{
CloseHandle(hProcess);
return 0;
}
}
| {
"pile_set_name": "Github"
} |
package google
import (
"testing"
"github.com/docker/machine/libmachine/drivers"
"github.com/stretchr/testify/assert"
)
func TestSetConfigFromFlags(t *testing.T) {
driver := NewDriver("", "")
checkFlags := &drivers.CheckDriverOptions{
FlagsValues: map[string]interface{}{
"google-project": "PROJECT",
},
CreateFlags: driver.GetCreateFlags(),
}
err := driver.SetConfigFromFlags(checkFlags)
assert.NoError(t, err)
assert.Empty(t, checkFlags.InvalidFlags)
}
| {
"pile_set_name": "Github"
} |
GLOBAL_SIM_BASE_CLK clk reset a
0 0 1 0X0
0 1 1 0X0
0 0 0 0X0
0 1 0 0X0
0 0 0 0X1
0 1 0 0X1
0 0 0 0X2
0 1 0 0X2
0 0 0 0X3
0 1 0 0X3 | {
"pile_set_name": "Github"
} |
{
"title": "Receiving a Notification in Android",
"type": "mobile"
} | {
"pile_set_name": "Github"
} |
/**
* Solarized Light theme for reveal.js.
* Author: Achim Staebler
*/
// Default mixins and settings -----------------
@import "../template/mixins";
@import "../template/settings";
// ---------------------------------------------
// Include theme-specific fonts
@font-face {
font-family: 'League Gothic';
src: url('../../lib/font/league_gothic-webfont.eot');
src: url('../../lib/font/league_gothic-webfont.eot?#iefix') format('embedded-opentype'),
url('../../lib/font/league_gothic-webfont.woff') format('woff'),
url('../../lib/font/league_gothic-webfont.ttf') format('truetype'),
url('../../lib/font/league_gothic-webfont.svg#LeagueGothicRegular') format('svg');
font-weight: normal;
font-style: normal;
}
@import url(https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic);
/**
* Solarized colors by Ethan Schoonover
*/
html * {
color-profile: sRGB;
rendering-intent: auto;
}
// Solarized colors
$base03: #002b36;
$base02: #073642;
$base01: #586e75;
$base00: #657b83;
$base0: #839496;
$base1: #93a1a1;
$base2: #eee8d5;
$base3: #fdf6e3;
$yellow: #b58900;
$orange: #cb4b16;
$red: #dc322f;
$magenta: #d33682;
$violet: #6c71c4;
$blue: #268bd2;
$cyan: #2aa198;
$green: #859900;
// Override theme settings (see ../template/settings.scss)
$mainColor: $base00;
$headingColor: $base01;
$headingTextShadow: none;
$backgroundColor: $base3;
$linkColor: $blue;
$linkColorHover: lighten( $linkColor, 20% );
$selectionBackgroundColor: $magenta;
// Background generator
// @mixin bodyBackground() {
// @include radial-gradient( rgba($base3,1), rgba(lighten($base3, 20%),1) );
// }
// Theme template ------------------------------
@import "../template/theme";
// ---------------------------------------------
| {
"pile_set_name": "Github"
} |
"STORE_DESCRIPTION" = "VLC برای سیستم عامل iOS یک پورت از پخش کننده رایگان VLC برای iPhone , iPad و iPod touch می باشد.\nاین برنامه میتواند تمام فیلمها، نمایشها و موسیقی های شما را در اکثر فرمت ها به صورت مستقیم و بدون نیاز به تبدیل پخش نماید.\nاین برنامه اجازه همگام سازی با Dropbox, GDrive, OneDrive, Box, iCloud Drive, iTunes, دانلود مستقیم و اشتراک گذار و پخش جاری بر بستر wifi از SMB, FTP, UPnP/DLNA media servers و وب می باشد.\nVLC قادر به پشتیبانی از زیرنویسهای پیشرفته شامل تطابق کامل با SSA ، چندین صدا و کنترل بر سرعت پخش می باشد.\nVLC برای iOS کاملا رایگان و متن باز است.";
"STORE_DESCRIPTION_TV" = "پخش کننده رسانه VLC یک پخش کننده چند رسانه ای با قابلیت استفاده بر سیستم های مختلف , رایگان و باز است. تمام ویدیو ها و موسیقی های شما در اکثر فرمت ها مستقیما و بدون تبدیل پخش می شوند. این پخش کننده اجازه جریان و همگام سازی از خدمات cloud مثل (Dropbox, Onedrive, Box) , بازپخش از مک یا کامپیوتر شخصی تان از طریق یک Web UI و نیز جریان از سرور های SMB, FTP, UPnP/DLNA و Web را هم میدهد. VLC قادر به پشتیبانی از زیرنویس های پیشرفته شامل تطبیق کامل با SSA , چندین صدا و کنترل بر سرعت پخش میباشد. VLC برای ios کاملا رایگان و متن باز است. فراداده ها و کارهای هنری توسط TMDb و Hatchet ارائه می شود که پایگاه های اطلاعاتی فیلم و موسیقی هستند.\n";
"CHOOSE_AUDIO_TRACK" = "انتخاب قطعه صوتی";
"CHOOSE_SUBTITLE_TRACK" = "انتخاب قطعه زیرنویس";
"OPEN_TRACK_PANEL" = "گشودن قطعه انتخابی";
"CHOOSE_TITLE" = "انتخاب عنوان";
"CHOOSE_CHAPTER" = "انتخاب فصل";
"CHAPTER_SELECTION_TITLE" = "فصل ها";
"TITLE" = "عنوان";
"CHAPTER" = "فصل";
"MINIMIZE_PLAYBACK_VIEW" = "پخش حداقل";
"TRACK_SELECTION" = "قطعه انتخابی";
"AUDIO" = "صدا";
"SUBTITLES" = "زیرنویسها";
"LANGUAGE" = "زبان";
"MEDIA_INFO" = "اطلاعات رسانه";
"VIDEO_DIMENSIONS" = "ابعاد کلیپ";
"FORMAT_VIDEO_DIMENSIONS" = "%ix%i پیکسل";
"FORMAT_AUDIO_TRACKS" = "%i قطعه صوتی";
"ONE_AUDIO_TRACK" = "یک قطعه صوتی";
"FORMAT_SPU_TRACKS" = "%i قطعه زیرنویس";
"ONE_SPU_TRACK" = "یک قطعه زیرنویس";
"TRACKS" = "%i قطعه";
"TRACK" = "%i قطعه";
"PLAYING_EXTERNALLY_TITLE" = "تلویزیون متصل شد";
"PLAYING_EXTERNALLY_DESC" = "این ویدیو در تلویزیون در حال پخش است";
"PLAYING_EXTERNALLY_ADDITION" = "\n هم اکنون در حال پخش در:"; /* \n should stay in every translation */
"VFILTER_HUE" = "فام";
"VFILTER_CONTRAST" = "کنتراست";
"VFILTER_BRIGHTNESS" = "روشنی";
"VFILTER_SATURATION" = "غلظت";
"VFILTER_GAMMA" = "گاما";
"PREAMP" = "Preamp";
"DB_FORMAT" = "%i dB";
"CHOOSE_EQUALIZER_PROFILES" = "انتخاب پروفایل اکولایزر";
"PLAYBACK_FAILED" = "پخش ناموفق بود";
"PLEASE_WAIT" = "لطفا صبرکنید";
"AR_CHANGED" = "نسبت تصویر: %@";
"DEFAULT" = "پیشفرض";
"FILL_TO_SCREEN" = "برش برای پر کردن صفحه";
"PLAYBACK_SPEED" = "سرعت پخش";
"SPU_DELAY" = "تاخیر زمانی زیرنویس";
"AUDIO_DELAY" = "تاخیر زمانی صدا";
"BUTTON_SLEEP_TIMER" = "زمان خواب";
"SLEEP_TIMER_UPDATED" = "زمان خواب به روز شد";
"CONTINUE_PLAYBACK" = "ادامه پخش؟";
"CONTINUE_PLAYBACK_LONG" = "آیا دوست دارید پخش \"%@\" را از جایی که خارج شدید ادامه دهید؟";
"BUTTON_ABOUT" = "درباره";
"BUTTON_BACK" = "عقب";
"BUTTON_DONE" = "تمام";
"BUTTON_CANCEL" = "انصراف";
"BUTTON_SAVE" = "ذخیره";
"BUTTON_DOWNLOAD" = "دانلود";
"BUTTON_DELETE" = "حذف";
"BUTTON_OK" = "تایید";
"BUTTON_CONTRIBUTE" = "مشارکت";
"BUTTON_CONNECT" = "اتصال";
"BUTTON_RENAME" = "تغییر نام";
"BUTTON_LEARN_MORE" = "بیشتر بدانید";
"BUTTON_LOGOUT" = "خارج شدن";
"BUTTON_CONTINUE" = "ادامه";
"BUTTON_SET" = "Set";
"BUTTON_RESET" = "Reset";
"BUTTON_RESCAN" = "Rescan";
"PRIVATE_PLAYBACK_TOGGLE" = "پخش خصوصی";
"SCAN_SUBTITLE_TOGGLE" = "بررسی سریع زیرنویس ها";
"BUTTON_RENDERER" = "Casting devices";
"BUTTON_RENDERER_HINT" = "Show a menu of available casting devices";
"UPGRADING_LIBRARY" = "ارتقای کتابخانه رسانه ای";
"OPEN_NETWORK" = "بازکردن استریم شبکه";
"NETWORK_TITLE" = "جریان شبکه";
"OPEN_NETWORK_HELP" = "برای باز کردن مستقیم استریم، یکی از آدرس های FTP, MMS, RTMP, RTSP, HTTP را وارد کنید.";
"HTTP_UPLOAD_SERVER_OFF" = "سرور غیرفعال";
"HTTP_UPLOAD_NO_CONNECTIVITY" = "نبود اتصال WiFi فعال";
"OPEN_STREAM_OR_DOWNLOAD" = "آیا مایل به دانلودید یا می خواهید URLپخش شود؟";
"SHARED_VLC_IOS_LIBRARY" = "VLC را برای کتابخانه iOS اشتراک بگذارید";
"SMB_CIFS_FILE_SERVERS" = "فایل سرور ها (SMB)";
"SMB_CIFS_FILE_SERVERS_SHORT" = "SMB";
"HTTP_DOWNLOAD_CANCELLED" = "دانلود از سوی کاربر لغو شد";
"DOWNLOAD_FROM_HTTP_HELP" = "برای دانلود فایل روی %@ خود، یک آدرس وارد کنید. ";
"DOWNLOAD_FROM_HTTP" = "دانلودها";
"ERROR_NUMBER" = "خطای %i رخ داد";
"DOWNLOAD_FAILED" = "دانلود ناموفق بود";
"FILE_NOT_SUPPORTED" = "فرمت فایل پشتیبانی نشده";
"FILE_NOT_SUPPORTED_LONG" = "The file format used by %@ is not supported by this version of VLC for iOS.";
"SCHEME_NOT_SUPPORTED" = "رویه نشانی پشتیبانی نمی شود";
"SCHEME_NOT_SUPPORTED_LONG" = "طرح آدرس (%@) پشتیبانی نمیشود. لطفا از آدرس هایی که با HTTP, HTTPS or FTP شروع میشود، استفاده کنید. ";
"RENAME_MEDIA_TO" = "نام جدید وارد کنید برای %@";
"FOLDER_EMPTY" = "Empty folder";
"SHARING_ACTION_SHEET_TITLE_CHOOSE_FILE" = "انتخاب فایل برای گشودن:";
"SHARING_ACTIVITY_OPEN_IN_TITLE" = "باز کن در...";
"SHARING_ERROR_NO_FILES" = "نمی توان فایلی برای اشتراک پیدا کرد";
"SHARING_ERROR_NO_APPLICATIONS" = "نمی توان اپایکیشنی برای باز کردن این گونه فایل ها یافت";
"SHARING_SUCCESS_CAMERA_ROLL" = "فایل با موفقیت در عکس های دوربین ذخیره شد";
"STREAMVC_DETAILTEXT" = "Play streams directly without downloading";
"DOWNLOADVC_DETAILTEXT" = "Download files directly to your device";
"HEADER_TITLE_RENDERER" = "Select a casting device";
"NETWORK" = "Network";
"LOCAL_NETWORK" = "شبکهی محلی";
"CONNECT_TO_SERVER" = "اتصال به سرور";
"FILE_SERVER" = "File Servers";
"USER_LABEL" = "کاربر";
"PASSWORD_LABEL" = "گذرواژه";
"DISABLE_LABEL" = "غیرفعال";
"BUTTON_ANONYMOUS_LOGIN" = "ورود ناشناس";
"LOCAL_SERVER_REFRESH" = "دوباره";
"LOCAL_SERVER_LAST_UPDATE" = "آخرین تاریخ آپدیت شده در %@";
"LOCAL_SERVER_CONNECTION_FAILED_TITLE" = "اتصال به سرور ناموفق";
"LOCAL_SERVER_CONNECTION_FAILED_MESSAGE" = "لطفا آدرس سرور و مشخصات کاربری خود را چک کنید.";
"CLOUD_SERVICES" = "سرویس های ابری";
"LOGIN" = "ورود";
"LOGGED_IN" = "وارد شده";
"LOGGED_IN_SERVICES" = "%d logged in services";
"LOGGED_IN_SERVICE" = "1 logged in service";
"DROPBOX_DOWNLOAD" = "دانلود فایل؟";
"DROPBOX_DL_LONG" = "آیا مایلید \"%@\" را در %@ خود دانلود کنید؟";
"DROPBOX_LOGIN" = "ورود";
"GDRIVE_ERROR_FETCHING_FILES" = "خطا هنگام بازگرداندن فایل ها";
"GDRIVE_DOWNLOAD_SUCCESSFUL" = "فایل با موفقیت دانلود شد";
"GDRIVE_DOWNLOAD_SUCCESSFUL_TITLE" = "موفق";
"GDRIVE_ERROR_DOWNLOADING_FILE" = "هنگام دانلود کردن با خطایی رخ داد";
"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE" = "خطا";
"ONEDRIVE_MEDIA_WITHOUT_URL" = "The selected Media doesn't have a playable url";
"DISK_FULL" = "به حد ذخیره سازی رسیده است";
"DISK_FULL_FORMAT" = "%@ نمیتواند درون %@ ذخیره سازی کند، زیرا شما فضای آزاد کافی در اختیار ندارید.";
"NUM_OF_FILES" = "%i فایل";
"ONE_FILE" = "۱ پرونده";
"NO_FILES" = "نبود فایل قابل پشتیبانی";
"DOWNLOADING" = "در حال دانلود...";
"REMAINING_TIME" = "زمان باقی مانده: %@";
"BIOMETRIC_UNLOCK" = "Unlock Media Library\nCancel to enter Passcode";
//PAPasscode Strings that we need to localize for them
"%d Failed Passcode Attempts" = "%d Failed Passcode Attempts";
"1 Failed Passcode Attempt" = "1 Failed Passcode Attempt";
"Change Passcode" = "Change Passcode";
"Enter Passcode" = "Enter Passcode";
"Enter a passcode" = "Enter a passcode";
"Enter your new passcode" = "Enter your new passcode";
"Enter your old passcode" = "Enter your old passcode";
"Enter your passcode" = "Enter your passcode";
"Next" = "Next";
"Passcodes did not match. Try again." = "Passcodes did not match. Try again.";
"Re-enter your new passcode" = "Re-enter your new passcode";
"Re-enter your passcode" = "Re-enter your passcode";
"Set Passcode" = "Set Passcode";
"Settings" = "تنظیمات"; // plain text key to keep compatibility with InAppSettingsKit's upstream
"ON" = "روشن";
"OFF" = "خاموش";
"EMPTY_LIBRARY" = "خالی کردن کتابخانه رسانه ای";
"EMPTY_LIBRARY_LONG" = "For playback, you can stream media from a server on your local network, from the cloud or synchronize media to your device using iTunes, WiFi Upload or Cloud services.";
"EMPTY_PLAYLIST" = "Empty playlist";
"EMPTY_PLAYLIST_DESCRIPTION" = "Add media while editing in the respective categories.";
"PLAYBACK_SCRUB_HELP" = "برای تنظیم میزان تغییر کشش، انگشت خود را به پایین بکشید.";
"PLAYBACK_SCRUB_HIGH" = "سایش سرعت بالا";
"PLAYBACK_SCRUB_HALF" = "سایش نصف سرعت";
"PLAYBACK_SCRUB_QUARTER" = "سایش ربع سرعت";
"PLAYBACK_SCRUB_FINE" = "سایش دقیق";
"PLAYBACK_POSITION" = "موقعیت پخش";
"VIDEO_FILTER" = "صافیهای ویدئو";
"VIDEO_FILTER_RESET_BUTTON" = "تنظیم مجدد فیلترهای ویدیو";
"VIDEO_ASPECT_RATIO_BUTTON" = "تغییر نسبت تصویر ویدیو";
"PLAY_PAUSE_BUTTON" = "اجرا یا توقف پخش ";
"BWD_BUTTON" = "پرش به عقب";
"FWD_BUTTON" = "پرش به جلو";
"PLAY_BUTTON" = "پخش";
"NEXT_BUTTON" = "Next";
"PREV_BUTTON" = "Previous";
"PLAY_ALL_BUTTON" = "پخش همه";
"VERSION_FORMAT" = "نسخه: %@";
"BASED_ON_FORMAT" = "بر پایه:</br>%@";
"NEW" = "تازه";
"BUG_REPORT_TITLE" = "گزارش اشکال";
"BUG_REPORT_MESSAGE" = "آیا مایل هستید تا یک گزارش اشکال بنویسید؟";
"BUG_REPORT_BUTTON" = "بازکردن Safari";
"VO_VIDEOPLAYER_TITLE" = "ویدیو پلیر";
"VO_VIDEOPLAYER_DOUBLETAP" = "دوبار ضربه برای آشکار یا پنهان کردن کنترل های پخش";
"FIRST_STEPS_ITUNES" = "همگام سازی فایل iTunes";
"FIRST_STEPS_ITUNES_TITLE" = "Sync With Your Computer";
"FIRST_STEPS_ITUNES_DETAILS" = "Connect your device to iTunes and select your device. Select \"File Sharing\" on the left side menu of iTunes and look for VLC to transfer files";
"FIRST_STEPS_WIFI_TITLE" = "Share via Wifi";
"FIRST_STEPS_WIFI_DETAILS" = "Enter the generated URL in your favorite web browser while connected to the same network as your phone";
"FIRST_STEPS_CLOUDS" = "ابرها";
"FIRST_STEPS_CLOUD_TITLE" = "Cloud";
"FIRST_STEPS_CLOUD_DETAILS" = "Upload your media to a cloud service like Google Drive or Dropbox to remotely download or stream them.";
"PLEX_CHECK_ACCOUNT" = "حساب Plex خود را در تنظیمات چک کنید";
"PLEX_ERROR_ACCOUNT" = "خطا در ورود Plex";
"UNAUTHORIZED" = "غیر مجاز";
"SERVER" = "سرور";
"SERVER_PORT" = "پورت";
"NO_SERVER_FOUND" = "سروری یافت نشد";
"NO_RECENT_STREAMS" = "هیچ جریانی به تازگی پخش نشده است";
"WEBINTF_TITLE" = "انتشار از طریق WiFi";
"WEBINTF_DROPFILES" = "رها کردن فایل ها";
"WEBINTF_DROPFILES_LONG" = "فایل ها را در پنجره رها کنید تا در %@ اضافه شود.<br> یا با کلیک روی دکمه \"+\" از دایالوگ جمع کننده فایل استفاده کنید.";
"WEBINTF_DOWNLOADFILES" = "دانلود فایل ها";
"WEBINTF_DOWNLOADFILES_LONG" = "کافیست برای دانلود، بر روی فایلی که می خواهید کلیک کنید در %@";
"WEBINTF_TITLE_ATV" = "پخش از راه دور";
"WEBINTF_DROPFILES_LONG_ATV" = "فایل ها را در پنجره رها کنید تا در %@ اضافه شود.<br> یا با کلیک روی دکمه \"+\" از دایالوگ جمع کننده فایل استفاده کنید.";
"WEBINTF_URL_SENT" = "ارسال آدرس موفقیت آمیز بود.";
"WEBINTF_URL_EMPTY" = "آدرس اینترنتی نمیتواند خالی باشد";
"WEBINTF_URL_INVALID" = "آدرس نامعتبر میباشد.";
"WEBINTF_AUTH_REQUIRED" = "Please enter the passcode you set in VLC iOS:";
"WEBINTF_AUTH_WRONG_PASSCODE" = "Wrong passcode.<br>Remaining attempts: ";
"WEBINTF_AUTH_BANNED" = "You entered too many wrong passcodes.<br>Please restart VLC iOS and try again.";
"DURATION" = "مدت پخش";
"TITLE" = "عنوان";
// strings from VLCKit
// accessibility labels for the playlist
"LONGPRESS_TO_STOP" = "برای توقف پخش فشار طولانی دهید";
// ATV specific
"AUDIO_INFO_VC_TITLE" = "Audio Info";
"CLOUD_LOGIN_LONG" = "To access Cloud Services, sign-in to iCloud on both this Apple TV and an iOS device with the same Apple ID and enable Keychain Sharing in System Settings.\nAfterwards, login to the cloud provider of your choice using the VLC app on your iOS device. Finally, select it on this screen.";
"ENTER_URL" = "برای پخش آدرس را وارد کنید";
"HTTP_SERVER_ON" = "غیرفعال سازی پخش از راه دور";
"HTTP_SERVER_OFF" = "فعال سازی پخش از راه دور";
"CACHED_MEDIA" = "رسانه های ذخیره سازی";
"CACHED_MEDIA_LONG" = "Media shown here is stored locally on your Apple TV. Note that contents can be removed by the operating system without prior notice anytime when VLC is not running in case your device runs out of storage.";
"DOWNLOAD_SUBS_FROM_OSO" = "دانلود زیرنویس ها از OpenSubtitles.org...";
"FOUND_SUBS" = "زیرنویس های یافت شده";
"USE_SPDIF" = "استفاده از عبور - از طریق (S/PDIF)";
"PLAYBACK" = "بازپخش";
"REPEAT_MODE" = "تکرار";
"REPEAT_DISABLED" = "غیرفعال";
"REPEAT_SINGLE" = "تکی";
"REPEAT_FOLDER" = "پوشه";
// Local Network Service Names
"UPNP_LONG" = "پلاگین پخش جهانی (UPnP)";
"UPNP_SHORT" = "UPnP";
"PLEX_LONG" = "سرور رسانه Plex (از طریق Bonjour)";
"PLEX_SHORT" = "Plex";
"FTP_SHORT" = "FTP";
"SFTP_SHORT" = "SFTP";
"NFS_LONG" = "Network File System (NFS)";
"NFS_SHORT" = "NFS";
"BONJOUR_FILE_SERVERS" = "BONJOUR File Server";
"DSM_WORKGROUP" = "Workgroup";
"URL_NOT_SUPPORTED" = "The URL can't be opened";
// Insert %@ where play-pause-glyph should be placed
"DELETE_ITEM_HINT" = "برای حذف %@ را فشار دهید"; /* Insert %@ where play-pause-glyph should be placed */
"DELETE_MESSAGE" = "Confirm the deletion of the selection";
"DELETE_MESSAGE_PLAYLIST" = "Are you sure to delete the selected playlist?\nAssociated media files won't be deleted.";
"DELETE_MESSAGE_PLAYLIST_CONTENT" = "Are you sure to remove the selected media from the playlist?\nThey won't be deleted from the disk.";
"DELETE_TITLE" = "Delete Selection";
//Drag and Drop
"THIS_FILE" = "این فایل";
"NOT_SUPPORTED_FILETYPE" = "%@ is not a supported filetype by VLC";
"FILE_EXISTS" = "%@ درحال حاضر وجود دارد";
"PROTOCOL_NOT_SELECTED" = "پروتکل انتخاب نشده است";
"Settings" = "تنظیمات";
"ERROR" = "خطا";
"OK" = "Ok";
"SORT" = "Sort";
"SORT_BY" = "مرتب سازی بر اساس";
"SEARCH" = "جستجو";
"VIDEO" = "ویدیو";
// MediaViewController Swipable Header
"ALBUMS" = "آلبومها";
"ARTISTS" = "هنرمندان";
"EPISODES" = "قسمتها";
"GENRES" = "ژانرها";
"ALL_VIDEOS" = "All videos";
"SONGS" = "موسیقیها";
"PLAYLISTS" = "Playlists";
"VIDEO_GROUPS" = "Video groups";
"MODIFIED_DATE" = "Modified date";
"NAME" = "Name";
//EDIT
"BUTTON_EDIT" = "Edit";
"BUTTON_EDIT_HINT" = "Edit mode";
"ADD_TO_PLAYLIST" = "Add to Playlist";
"ADD_TO_PLAYLIST_HINT" = "Open the add to playlist menu";
"PLAYLIST_PLACEHOLDER" = "Playlist title";
"PLAYLIST_DESCRIPTION" = "Choose a title for your new playlist";
"PLAYLIST_CREATION" = "Create a new playlist";
"PLAYLIST_CREATION_HINT" = "Show an interactive action to create a playlist";
"ERROR_PLAYLIST_CREATION" = "Failed to create a playlist";
"ERROR_PLAYLIST_TRACKS" = "Failed to retrieve tracks";
"ERROR_RENAME_FAILED" = "Renaming failed";
"ERROR_EMPTY_NAME" = "The title can't be empty";
"SHARE_LABEL" = "Share";
"SHARE_HINT" = "Share selected files";
"RENAME_HINT" = "Rename selected files";
"DELETE_HINT" = "Delete selected files";
// Sort
"BUTTON_SORT" = "Sort";
"BUTTON_SORT_HINT" = "Display sort action sheet";
"HEADER_TITLE_SORT" = "Sort by";
"DESCENDING_LABEL" = "Descending Order";
"DESCENDING_SWITCH_LABEL" = "Ascending or descending order";
"DESCENDING_SWITCH_HINT" = "Sort context in ascending or descending order";
// VLCMediaLibraryKit - Sorting Criteria
"ALPHA" = "Alphanumerically";
"DURATION" = "مدت پخش";
"INSERTION_DATE" = "Insertion date";
"LAST_MODIFICATION_DATE" = "Last modification date";
"RELEASE_DATE" = "Release date";
"FILE_SIZE" = "File size";
"ARTIST" = "Artist";
"PLAY_COUNT" = "Play count";
"ALBUM" = "Album";
"FILENAME" = "Filename";
"TRACK_NUMBER" = "Track number";
"NB_AUDIO" = "Number of audio";
"NB_MEDIA" = "Number of media";
"NB_VIDEO" = "Number of video";
// VLCNetworkLoginTVViewController
"NO_SAVING_DATA" = "Nothing found";
// MediaCollectionViewCell
"UNKNOWN_ARTIST" = "Unknown Artist";
"VARIOUS_ARTIST" = "Various Artists";
"UNKNOWN_ALBUM" = "Unknown Album";
/* VideoSubControl */
"INTERFACE_LOCK_BUTTON" = "Lock interface";
"INTERFACE_LOCK_HINT" = "Disable interface controls";
"MORE_OPTIONS_BUTTON" = "More";
"MORE_OPTIONS_HINT" = "View more option controls";
"REPEAT_MODE_HINT" = "Change repeat mode of current item";
"VIDEO_ASPECT_RATIO_HINT" = "Change the aspect ratio of the current video";
/* MediaMoreOptionsActionSheet */
"EQUALIZER_CELL_TITLE" = "Equalizer";
"MORE_OPTIONS_HEADER_TITLE" = "Video Options";
/* Settings - Force rescan alert */
"FORCE_RESCAN_TITLE" = "Force media library rescan";
"FORCE_RESCAN_MESSAGE" = "Do you want to force VLC to rescan your media library?\nIt could take some time.";
// Local Network
"SMBV1_WARN_TITLE" = "SMBv1 Connection Warning";
"SMBV1_WARN_DESCRIPTION" = "We detected an old protocol (SMBv1).\nAre you really sure to continue with SMBv1?\nWe advise upgrading or changing your server settings.";
"SMBV1_CONTINUE" = "Continue with SMBv1";
"SMBV1_NEXT_PROTOCOL" = "Try SMBv2/v3";
/* Preview labels */
"ENCODING" = "Encoding";
/* Media groups */
"ADD_TO_MEDIA_GROUP" = "Add to media group";
"ADD_TO_MEDIA_GROUP_HINT" = "Open the add to media group menu";
"MEDIA_GROUPS" = "Media groups";
"MEDIA_GROUPS_DESCRIPTION" = "Choose a title for your new media group";
"MEDIA_GROUPS_PLACEHOLDER" = "Media group title";
"REMOVE_FROM_MEDIA_GROUP" = "Remove from media group";
"REMOVE_FROM_MEDIA_GROUP_HINT" = "Remove selection from the media group";
"MEDIA_GROUP_CREATION" = "New media group";
"MEDIA_GROUP_CREATION_HINT" = "Show alert to create a playlist";
"MEDIA_GROUP_MOVE_TO_ROOT" = "Move content to top level";
"MEDIA_GROUP_MOVE_TO_ROOT_HINT" = "Moves the content of the selection to the top level";
"BUTTON_REGROUP" = "Regroup";
"BUTTON_REGROUP_TITLE" = "Regroup selection";
"BUTTON_REGROUP_HINT" = "Attempt to regroup automatically single media.";
"BUTTON_REGROUP_DESCRIPTION" = "Are you sure to attempt to regroup automatically single media?\nThis can take some time.";
| {
"pile_set_name": "Github"
} |
/*
* fat.c
*
* R/O (V)FAT 12/16/32 filesystem implementation by Marcus Sundberg
*
* 2002-07-28 - [email protected] - ported to ppcboot v1.1.6
* 2003-03-10 - [email protected] - ported to uboot
*
* See file CREDITS for list of people who contributed to this
* project.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <config.h>
#include <exports.h>
#include <fat.h>
#include <asm/byteorder.h>
#include <part.h>
/*
* Convert a string to lowercase.
*/
static void downcase (char *str)
{
while (*str != '\0') {
TOLOWER(*str);
str++;
}
}
static block_dev_desc_t *cur_dev;
static unsigned int cur_part_nr;
static disk_partition_t cur_part_info;
#define DOS_BOOT_MAGIC_OFFSET 0x1fe
#define DOS_FS_TYPE_OFFSET 0x36
#define DOS_FS32_TYPE_OFFSET 0x52
static int disk_read(__u32 block, __u32 nr_blocks, void *buf)
{
if (!cur_dev || !cur_dev->block_read)
return -1;
return cur_dev->block_read(cur_dev->dev,
cur_part_info.start + block, nr_blocks, buf);
}
int fat_register_device (block_dev_desc_t * dev_desc, int part_no)
{
unsigned char buffer[dev_desc->blksz];
/* First close any currently found FAT filesystem */
cur_dev = NULL;
#if (CONFIG_COMMANDS & CFG_CMD_IDE) || \
(CONFIG_COMMANDS & CFG_CMD_SCSI)|| \
(CONFIG_COMMANDS & CFG_CMD_USB) || \
defined(CONFIG_SYSTEMACE)
/* Read the partition table, if present */
if (!get_partition_info(dev_desc, part_no, &cur_part_info)) {
cur_dev = dev_desc;
cur_part_nr = part_no;
}
#endif
/* Otherwise it might be a superfloppy (whole-disk FAT filesystem) */
if (!cur_dev) {
if (part_no != 1) {
printf("** Partition %d not valid on device %d **\n",
part_no, dev_desc->dev);
return -1;
}
cur_dev = dev_desc;
cur_part_nr = 1;
cur_part_info.start = 0;
cur_part_info.size = dev_desc->lba;
cur_part_info.blksz = dev_desc->blksz;
memset(cur_part_info.name, 0, sizeof(cur_part_info.name));
memset(cur_part_info.type, 0, sizeof(cur_part_info.type));
}
/* Make sure it has a valid FAT header */
if (disk_read(0, 1, buffer) != 1) {
cur_dev = NULL;
return -1;
}
/* Check if it's actually a DOS volume */
if (memcmp(buffer + DOS_BOOT_MAGIC_OFFSET, "\x55\xAA", 2)) {
cur_dev = NULL;
return -1;
}
/* Check for FAT12/FAT16/FAT32 filesystem */
if (!memcmp(buffer + DOS_FS_TYPE_OFFSET, "FAT", 3))
return 0;
if (!memcmp(buffer + DOS_FS32_TYPE_OFFSET, "FAT32", 5))
return 0;
cur_dev = NULL;
return -1;
}
/*
* Get the first occurence of a directory delimiter ('/' or '\') in a string.
* Return index into string if found, -1 otherwise.
*/
static int dirdelim (char *str)
{
char *start = str;
while (*str != '\0') {
if (ISDIRDELIM(*str))
return str - start;
str++;
}
return -1;
}
/*
* Extract zero terminated short name from a directory entry.
*/
static void get_name (dir_entry *dirent, char *s_name)
{
char *ptr;
memcpy(s_name, dirent->name, 8);
s_name[8] = '\0';
ptr = s_name;
while (*ptr && *ptr != ' ')
ptr++;
if (dirent->ext[0] && dirent->ext[0] != ' ') {
*ptr = '.';
ptr++;
memcpy(ptr, dirent->ext, 3);
ptr[3] = '\0';
while (*ptr && *ptr != ' ')
ptr++;
}
*ptr = '\0';
if (*s_name == DELETED_FLAG)
*s_name = '\0';
else if (*s_name == aRING)
*s_name = DELETED_FLAG;
downcase(s_name);
}
/*
* Get the entry at index 'entry' in a FAT (12/16/32) table.
* On failure 0x00 is returned.
*/
static __u32 get_fatent (fsdata *mydata, __u32 entry)
{
__u32 bufnum;
__u32 off16, offset;
__u32 ret = 0x00;
__u16 val1, val2;
switch (mydata->fatsize) {
case 32:
bufnum = entry / FAT32BUFSIZE;
offset = entry - bufnum * FAT32BUFSIZE;
break;
case 16:
bufnum = entry / FAT16BUFSIZE;
offset = entry - bufnum * FAT16BUFSIZE;
break;
case 12:
bufnum = entry / FAT12BUFSIZE;
offset = entry - bufnum * FAT12BUFSIZE;
break;
default:
/* Unsupported FAT size */
return ret;
}
debug("FAT%d: entry: 0x%04x = %d, offset: 0x%04x = %d\n",
mydata->fatsize, entry, entry, offset, offset);
/* Read a new block of FAT entries into the cache. */
if (bufnum != mydata->fatbufnum) {
__u32 getsize = FATBUFBLOCKS;
__u8 *bufptr = mydata->fatbuf;
__u32 fatlength = mydata->fatlength;
__u32 startblock = bufnum * FATBUFBLOCKS;
if (getsize > fatlength)
getsize = fatlength;
fatlength *= mydata->sect_size; /* We want it in bytes now */
startblock += mydata->fat_sect; /* Offset from start of disk */
if (disk_read(startblock, getsize, bufptr) < 0) {
debug("Error reading FAT blocks\n");
return ret;
}
mydata->fatbufnum = bufnum;
}
/* Get the actual entry from the table */
switch (mydata->fatsize) {
case 32:
ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
break;
case 16:
ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
break;
case 12:
off16 = (offset * 3) / 4;
switch (offset & 0x3) {
case 0:
ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[off16]);
ret &= 0xfff;
break;
case 1:
val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
val1 &= 0xf000;
val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
val2 &= 0x00ff;
ret = (val2 << 4) | (val1 >> 12);
break;
case 2:
val1 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
val1 &= 0xff00;
val2 = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16 + 1]);
val2 &= 0x000f;
ret = (val2 << 8) | (val1 >> 8);
break;
case 3:
ret = FAT2CPU16(((__u16 *)mydata->fatbuf)[off16]);
ret = (ret & 0xfff0) >> 4;
break;
default:
break;
}
break;
}
debug("FAT%d: ret: %08x, offset: %04x\n",
mydata->fatsize, ret, offset);
return ret;
}
/*
* Read at most 'size' bytes from the specified cluster into 'buffer'.
* Return 0 on success, -1 otherwise.
*/
static int
get_cluster (fsdata *mydata, __u32 clustnum, __u8 *buffer,
unsigned long size)
{
__u32 idx = 0;
__u32 startsect;
__u32 nr_sect;
int ret;
if (clustnum > 0) {
startsect = mydata->data_begin +
clustnum * mydata->clust_size;
} else {
startsect = mydata->rootdir_sect;
}
debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
nr_sect = size / mydata->sect_size;
ret = disk_read(startsect, nr_sect, buffer);
if (ret != nr_sect) {
debug("Error reading data (got %d)\n", ret);
return -1;
}
if (size % mydata->sect_size) {
__u8 tmpbuf[mydata->sect_size];
idx = size / mydata->sect_size;
ret = disk_read(startsect + idx, 1, tmpbuf);
if (ret != 1) {
debug("Error reading data (got %d)\n", ret);
return -1;
}
buffer += idx * mydata->sect_size;
memcpy(buffer, tmpbuf, size % mydata->sect_size);
return 0;
}
return 0;
}
/*
* Read at most 'maxsize' bytes from the file associated with 'dentptr'
* into 'buffer'.
* Return the number of bytes read or -1 on fatal errors.
*/
static long
get_contents (fsdata *mydata, dir_entry *dentptr, __u8 *buffer,
unsigned long maxsize)
{
unsigned long filesize = FAT2CPU32(dentptr->size), gotsize = 0;
unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
__u32 curclust = START(dentptr);
__u32 endclust, newclust;
unsigned long actsize;
debug("Filesize: %ld bytes\n", filesize);
if (maxsize > 0 && filesize > maxsize)
filesize = maxsize;
debug("%ld bytes\n", filesize);
actsize = bytesperclust;
endclust = curclust;
do {
/* search for consecutive clusters */
while (actsize < filesize) {
newclust = get_fatent(mydata, endclust);
if ((newclust - 1) != endclust)
goto getit;
if (CHECK_CLUST(newclust, mydata->fatsize)) {
debug("curclust: 0x%x\n", newclust);
debug("Invalid FAT entry\n");
return gotsize;
}
endclust = newclust;
actsize += bytesperclust;
}
/* actsize >= file size */
actsize -= bytesperclust;
/* get remaining clusters */
if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
printf("Error reading cluster\n");
return -1;
}
/* get remaining bytes */
gotsize += (int)actsize;
filesize -= actsize;
buffer += actsize;
actsize = filesize;
if (get_cluster(mydata, endclust, buffer, (int)actsize) != 0) {
printf("Error reading cluster\n");
return -1;
}
gotsize += actsize;
return gotsize;
getit:
if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
printf("Error reading cluster\n");
return -1;
}
gotsize += (int)actsize;
filesize -= actsize;
buffer += actsize;
curclust = get_fatent(mydata, endclust);
if (CHECK_CLUST(curclust, mydata->fatsize)) {
debug("curclust: 0x%x\n", curclust);
printf("Invalid FAT entry\n");
return gotsize;
}
actsize = bytesperclust;
endclust = curclust;
} while (1);
}
#ifdef CONFIG_SUPPORT_VFAT
/*
* Extract the file name information from 'slotptr' into 'l_name',
* starting at l_name[*idx].
* Return 1 if terminator (zero byte) is found, 0 otherwise.
*/
static int slot2str (dir_slot *slotptr, char *l_name, int *idx)
{
int j;
for (j = 0; j <= 8; j += 2) {
l_name[*idx] = slotptr->name0_4[j];
if (l_name[*idx] == 0x00)
return 1;
(*idx)++;
}
for (j = 0; j <= 10; j += 2) {
l_name[*idx] = slotptr->name5_10[j];
if (l_name[*idx] == 0x00)
return 1;
(*idx)++;
}
for (j = 0; j <= 2; j += 2) {
l_name[*idx] = slotptr->name11_12[j];
if (l_name[*idx] == 0x00)
return 1;
(*idx)++;
}
return 0;
}
/*
* Extract the full long filename starting at 'retdent' (which is really
* a slot) into 'l_name'. If successful also copy the real directory entry
* into 'retdent'
* Return 0 on success, -1 otherwise.
*/
__attribute__ ((__aligned__ (__alignof__ (dir_entry))))
__u8 get_vfatname_block[MAX_CLUSTSIZE];
static int
get_vfatname (fsdata *mydata, int curclust, __u8 *cluster,
dir_entry *retdent, char *l_name)
{
dir_entry *realdent;
dir_slot *slotptr = (dir_slot *)retdent;
__u8 *buflimit = cluster + mydata->sect_size * ((curclust == 0) ?
PREFETCH_BLOCKS :
mydata->clust_size);
__u8 counter = (slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff;
int idx = 0;
if (counter > VFAT_MAXSEQ) {
debug("Error: VFAT name is too long\n");
return -1;
}
while ((__u8 *)slotptr < buflimit) {
if (counter == 0)
break;
if (((slotptr->id & ~LAST_LONG_ENTRY_MASK) & 0xff) != counter)
return -1;
slotptr++;
counter--;
}
if ((__u8 *)slotptr >= buflimit) {
dir_slot *slotptr2;
if (curclust == 0)
return -1;
curclust = get_fatent(mydata, curclust);
if (CHECK_CLUST(curclust, mydata->fatsize)) {
debug("curclust: 0x%x\n", curclust);
printf("Invalid FAT entry\n");
return -1;
}
if (get_cluster(mydata, curclust, get_vfatname_block,
mydata->clust_size * mydata->sect_size) != 0) {
debug("Error: reading directory block\n");
return -1;
}
slotptr2 = (dir_slot *)get_vfatname_block;
while (counter > 0) {
if (((slotptr2->id & ~LAST_LONG_ENTRY_MASK)
& 0xff) != counter)
return -1;
slotptr2++;
counter--;
}
/* Save the real directory entry */
realdent = (dir_entry *)slotptr2;
while ((__u8 *)slotptr2 > get_vfatname_block) {
slotptr2--;
slot2str(slotptr2, l_name, &idx);
}
} else {
/* Save the real directory entry */
realdent = (dir_entry *)slotptr;
}
do {
slotptr--;
if (slot2str(slotptr, l_name, &idx))
break;
} while (!(slotptr->id & LAST_LONG_ENTRY_MASK));
l_name[idx] = '\0';
if (*l_name == DELETED_FLAG)
*l_name = '\0';
else if (*l_name == aRING)
*l_name = DELETED_FLAG;
downcase(l_name);
/* Return the real directory entry */
memcpy(retdent, realdent, sizeof(dir_entry));
return 0;
}
/* Calculate short name checksum */
static __u8 mkcksum (const char *str)
{
int i;
__u8 ret = 0;
for (i = 0; i < 11; i++) {
ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + str[i];
}
return ret;
}
#endif /* CONFIG_SUPPORT_VFAT */
/*
* Get the directory entry associated with 'filename' from the directory
* starting at 'startsect'
*/
__attribute__ ((__aligned__ (__alignof__ (dir_entry))))
__u8 get_dentfromdir_block[MAX_CLUSTSIZE];
static dir_entry *get_dentfromdir (fsdata *mydata, int startsect,
char *filename, dir_entry *retdent,
int dols)
{
__u16 prevcksum = 0xffff;
__u32 curclust = START(retdent);
int files = 0, dirs = 0;
debug("get_dentfromdir: %s\n", filename);
while (1) {
dir_entry *dentptr;
int i;
if (get_cluster(mydata, curclust, get_dentfromdir_block,
mydata->clust_size * mydata->sect_size) != 0) {
debug("Error: reading directory block\n");
return NULL;
}
dentptr = (dir_entry *)get_dentfromdir_block;
for (i = 0; i < DIRENTSPERCLUST; i++) {
char s_name[14], l_name[VFAT_MAXLEN_BYTES];
l_name[0] = '\0';
if (dentptr->name[0] == DELETED_FLAG) {
dentptr++;
continue;
}
if ((dentptr->attr & ATTR_VOLUME)) {
#ifdef CONFIG_SUPPORT_VFAT
if ((dentptr->attr & ATTR_VFAT) == ATTR_VFAT &&
(dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
prevcksum = ((dir_slot *)dentptr)->alias_checksum;
get_vfatname(mydata, curclust,
get_dentfromdir_block,
dentptr, l_name);
if (dols) {
int isdir;
char dirc;
int doit = 0;
isdir = (dentptr->attr & ATTR_DIR);
if (isdir) {
dirs++;
dirc = '/';
doit = 1;
} else {
dirc = ' ';
if (l_name[0] != 0) {
files++;
doit = 1;
}
}
if (doit) {
if (dirc == ' ') {
printf(" %8ld %s%c\n",
(long)FAT2CPU32(dentptr->size),
l_name,
dirc);
} else {
printf(" %s%c\n",
l_name,
dirc);
}
}
dentptr++;
continue;
}
debug("vfatname: |%s|\n", l_name);
} else
#endif
{
/* Volume label or VFAT entry */
dentptr++;
continue;
}
}
if (dentptr->name[0] == 0) {
if (dols) {
printf("\n%d file(s), %d dir(s)\n\n",
files, dirs);
}
debug("Dentname == NULL - %d\n", i);
return NULL;
}
#ifdef CONFIG_SUPPORT_VFAT
if (dols && mkcksum(dentptr->name) == prevcksum) {
prevcksum = 0xffff;
dentptr++;
continue;
}
#endif
get_name(dentptr, s_name);
if (dols) {
int isdir = (dentptr->attr & ATTR_DIR);
char dirc;
int doit = 0;
if (isdir) {
dirs++;
dirc = '/';
doit = 1;
} else {
dirc = ' ';
if (s_name[0] != 0) {
files++;
doit = 1;
}
}
if (doit) {
if (dirc == ' ') {
printf(" %8ld %s%c\n",
(long)FAT2CPU32(dentptr->size),
s_name, dirc);
} else {
printf(" %s%c\n",
s_name, dirc);
}
}
dentptr++;
continue;
}
if (strcmp(filename, s_name)
&& strcmp(filename, l_name)) {
debug("Mismatch: |%s|%s|\n", s_name, l_name);
dentptr++;
continue;
}
memcpy(retdent, dentptr, sizeof(dir_entry));
debug("DentName: %s", s_name);
debug(", start: 0x%x", START(dentptr));
debug(", size: 0x%x %s\n",
FAT2CPU32(dentptr->size),
(dentptr->attr & ATTR_DIR) ? "(DIR)" : "");
return retdent;
}
curclust = get_fatent(mydata, curclust);
if (CHECK_CLUST(curclust, mydata->fatsize)) {
debug("curclust: 0x%x\n", curclust);
printf("Invalid FAT entry\n");
return NULL;
}
}
return NULL;
}
/*
* Read boot sector and volume info from a FAT filesystem
*/
static int
read_bootsectandvi (boot_sector *bs, volume_info *volinfo, int *fatsize)
{
__u8 *block;
volume_info *vistart;
int ret = 0;
if (cur_dev == NULL) {
debug("Error: no device selected\n");
return -1;
}
block = malloc(cur_dev->blksz);
if (block == NULL) {
debug("Error: allocating block\n");
return -1;
}
if (disk_read (0, 1, block) < 0) {
debug("Error: reading block\n");
goto fail;
}
memcpy(bs, block, sizeof(boot_sector));
bs->reserved = FAT2CPU16(bs->reserved);
bs->fat_length = FAT2CPU16(bs->fat_length);
bs->secs_track = FAT2CPU16(bs->secs_track);
bs->heads = FAT2CPU16(bs->heads);
bs->total_sect = FAT2CPU32(bs->total_sect);
/* FAT32 entries */
if (bs->fat_length == 0) {
/* Assume FAT32 */
bs->fat32_length = FAT2CPU32(bs->fat32_length);
bs->flags = FAT2CPU16(bs->flags);
bs->root_cluster = FAT2CPU32(bs->root_cluster);
bs->info_sector = FAT2CPU16(bs->info_sector);
bs->backup_boot = FAT2CPU16(bs->backup_boot);
vistart = (volume_info *)(block + sizeof(boot_sector));
*fatsize = 32;
} else {
vistart = (volume_info *)&(bs->fat32_length);
*fatsize = 0;
}
memcpy(volinfo, vistart, sizeof(volume_info));
if (*fatsize == 32) {
if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0)
goto exit;
} else {
if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) {
*fatsize = 12;
goto exit;
}
if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) {
*fatsize = 16;
goto exit;
}
}
debug("Error: broken fs_type sign\n");
fail:
ret = -1;
exit:
free(block);
return ret;
}
__attribute__ ((__aligned__ (__alignof__ (dir_entry))))
__u8 do_fat_read_block[MAX_CLUSTSIZE];
long
do_fat_read (const char *filename, void *buffer, unsigned long maxsize,
int dols)
{
char fnamecopy[2048];
boot_sector bs;
volume_info volinfo;
fsdata datablock;
fsdata *mydata = &datablock;
dir_entry *dentptr;
__u16 prevcksum = 0xffff;
char *subname = "";
__u32 cursect;
int idx, isdir = 0;
int files = 0, dirs = 0;
long ret = -1;
int firsttime;
__u32 root_cluster = 0;
int rootdir_size = 0;
int j;
if (read_bootsectandvi(&bs, &volinfo, &mydata->fatsize)) {
debug("Error: reading boot sector\n");
return -1;
}
if (mydata->fatsize == 32) {
root_cluster = bs.root_cluster;
mydata->fatlength = bs.fat32_length;
} else {
mydata->fatlength = bs.fat_length;
}
mydata->fat_sect = bs.reserved;
cursect = mydata->rootdir_sect
= mydata->fat_sect + mydata->fatlength * bs.fats;
mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
mydata->clust_size = bs.cluster_size;
if (mydata->sect_size != cur_part_info.blksz) {
printf("Error: FAT sector size mismatch (fs=%hu, dev=%lu)\n",
mydata->sect_size, cur_part_info.blksz);
return -1;
}
if (mydata->fatsize == 32) {
mydata->data_begin = mydata->rootdir_sect -
(mydata->clust_size * 2);
} else {
rootdir_size = ((bs.dir_entries[1] * (int)256 +
bs.dir_entries[0]) *
sizeof(dir_entry)) /
mydata->sect_size;
mydata->data_begin = mydata->rootdir_sect +
rootdir_size -
(mydata->clust_size * 2);
}
mydata->fatbufnum = -1;
mydata->fatbuf = malloc(FATBUFSIZE);
if (mydata->fatbuf == NULL) {
debug("Error: allocating memory\n");
return -1;
}
#ifdef CONFIG_SUPPORT_VFAT
debug("VFAT Support enabled\n");
#endif
debug("FAT%d, fat_sect: %d, fatlength: %d\n",
mydata->fatsize, mydata->fat_sect, mydata->fatlength);
debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
"Data begins at: %d\n",
root_cluster,
mydata->rootdir_sect,
mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
mydata->clust_size);
/* "cwd" is always the root... */
while (ISDIRDELIM(*filename))
filename++;
/* Make a copy of the filename and convert it to lowercase */
strcpy(fnamecopy, filename);
downcase(fnamecopy);
if (*fnamecopy == '\0') {
if (!dols)
goto exit;
dols = LS_ROOT;
} else if ((idx = dirdelim(fnamecopy)) >= 0) {
isdir = 1;
fnamecopy[idx] = '\0';
subname = fnamecopy + idx + 1;
/* Handle multiple delimiters */
while (ISDIRDELIM(*subname))
subname++;
} else if (dols) {
isdir = 1;
}
j = 0;
while (1) {
int i;
debug("FAT read sect=%d, clust_size=%d, DIRENTSPERBLOCK=%d\n",
cursect, mydata->clust_size, DIRENTSPERBLOCK);
if (disk_read(cursect,
(mydata->fatsize == 32) ?
(mydata->clust_size) :
PREFETCH_BLOCKS,
do_fat_read_block) < 0) {
debug("Error: reading rootdir block\n");
goto exit;
}
dentptr = (dir_entry *) do_fat_read_block;
for (i = 0; i < DIRENTSPERBLOCK; i++) {
char s_name[14], l_name[VFAT_MAXLEN_BYTES];
l_name[0] = '\0';
if (dentptr->name[0] == DELETED_FLAG) {
dentptr++;
continue;
}
if ((dentptr->attr & ATTR_VOLUME)) {
#ifdef CONFIG_SUPPORT_VFAT
if ((dentptr->attr & ATTR_VFAT) == ATTR_VFAT &&
(dentptr->name[0] & LAST_LONG_ENTRY_MASK)) {
prevcksum =
((dir_slot *)dentptr)->alias_checksum;
get_vfatname(mydata,
root_cluster,
do_fat_read_block,
dentptr, l_name);
if (dols == LS_ROOT) {
char dirc;
int doit = 0;
int isdir =
(dentptr->attr & ATTR_DIR);
if (isdir) {
dirs++;
dirc = '/';
doit = 1;
} else {
dirc = ' ';
if (l_name[0] != 0) {
files++;
doit = 1;
}
}
if (doit) {
if (dirc == ' ') {
printf(" %8ld %s%c\n",
(long)FAT2CPU32(dentptr->size),
l_name,
dirc);
} else {
printf(" %s%c\n",
l_name,
dirc);
}
}
dentptr++;
continue;
}
debug("Rootvfatname: |%s|\n",
l_name);
} else
#endif
{
/* Volume label or VFAT entry */
dentptr++;
continue;
}
} else if (dentptr->name[0] == 0) {
debug("RootDentname == NULL - %d\n", i);
if (dols == LS_ROOT) {
printf("\n%d file(s), %d dir(s)\n\n",
files, dirs);
ret = 0;
}
goto exit;
}
#ifdef CONFIG_SUPPORT_VFAT
else if (dols == LS_ROOT &&
mkcksum(dentptr->name) == prevcksum) {
prevcksum = 0xffff;
dentptr++;
continue;
}
#endif
get_name(dentptr, s_name);
if (dols == LS_ROOT) {
int isdir = (dentptr->attr & ATTR_DIR);
char dirc;
int doit = 0;
if (isdir) {
dirc = '/';
if (s_name[0] != 0) {
dirs++;
doit = 1;
}
} else {
dirc = ' ';
if (s_name[0] != 0) {
files++;
doit = 1;
}
}
if (doit) {
if (dirc == ' ') {
printf(" %8ld %s%c\n",
(long)FAT2CPU32(dentptr->size),
s_name, dirc);
} else {
printf(" %s%c\n",
s_name, dirc);
}
}
dentptr++;
continue;
}
if (strcmp(fnamecopy, s_name)
&& strcmp(fnamecopy, l_name)) {
debug("RootMismatch: |%s|%s|\n", s_name,
l_name);
dentptr++;
continue;
}
if (isdir && !(dentptr->attr & ATTR_DIR))
goto exit;
debug("RootName: %s", s_name);
debug(", start: 0x%x", START(dentptr));
debug(", size: 0x%x %s\n",
FAT2CPU32(dentptr->size),
isdir ? "(DIR)" : "");
goto rootdir_done; /* We got a match */
}
debug("END LOOP: j=%d clust_size=%d\n", j,
mydata->clust_size);
/*
* On FAT32 we must fetch the FAT entries for the next
* root directory clusters when a cluster has been
* completely processed.
*/
++j;
int fat32_end = 0;
if ((mydata->fatsize == 32) && (j == mydata->clust_size)) {
int nxtsect = 0;
int nxt_clust = 0;
nxt_clust = get_fatent(mydata, root_cluster);
fat32_end = CHECK_CLUST(nxt_clust, 32);
nxtsect = mydata->data_begin +
(nxt_clust * mydata->clust_size);
root_cluster = nxt_clust;
cursect = nxtsect;
j = 0;
} else {
cursect++;
}
/* If end of rootdir reached */
if ((mydata->fatsize == 32 && fat32_end) ||
(mydata->fatsize != 32 && j == rootdir_size)) {
if (dols == LS_ROOT) {
printf("\n%d file(s), %d dir(s)\n\n",
files, dirs);
ret = 0;
}
goto exit;
}
}
rootdir_done:
firsttime = 1;
while (isdir) {
int startsect = mydata->data_begin
+ START(dentptr) * mydata->clust_size;
dir_entry dent;
char *nextname = NULL;
dent = *dentptr;
dentptr = &dent;
idx = dirdelim(subname);
if (idx >= 0) {
subname[idx] = '\0';
nextname = subname + idx + 1;
/* Handle multiple delimiters */
while (ISDIRDELIM(*nextname))
nextname++;
if (dols && *nextname == '\0')
firsttime = 0;
} else {
if (dols && firsttime) {
firsttime = 0;
} else {
isdir = 0;
}
}
if (get_dentfromdir(mydata, startsect, subname, dentptr,
isdir ? 0 : dols) == NULL) {
if (dols && !isdir)
ret = 0;
goto exit;
}
if (idx >= 0) {
if (!(dentptr->attr & ATTR_DIR))
goto exit;
subname = nextname;
}
}
ret = get_contents(mydata, dentptr, buffer, maxsize);
debug("Size: %d, got: %ld\n", FAT2CPU32(dentptr->size), ret);
exit:
free(mydata->fatbuf);
return ret;
}
int file_fat_detectfs (void)
{
boot_sector bs;
volume_info volinfo;
int fatsize;
char vol_label[12];
if (cur_dev == NULL) {
printf("No current device\n");
return 1;
}
#if (CONFIG_COMMANDS & CFG_CMD_IDE) || \
(CONFIG_COMMANDS & CFG_CMD_SCSI)|| \
(CONFIG_COMMANDS & CFG_CMD_USB)
printf("Interface: ");
switch (cur_dev->if_type) {
case IF_TYPE_IDE:
printf("IDE");
break;
/*
case IF_TYPE_SATA:
printf("SATA");
break;
*/
case IF_TYPE_SCSI:
printf("SCSI");
break;
/*
case IF_TYPE_ATAPI:
printf("ATAPI");
break;
*/
case IF_TYPE_USB:
printf("USB");
break;
/*
case IF_TYPE_DOC:
printf("DOC");
break;
case IF_TYPE_MMC:
printf("MMC");
break;
*/
default:
printf("Unknown");
}
printf("\n Device %d: ", cur_dev->dev);
dev_print(cur_dev);
#endif
if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
printf("\nNo valid FAT fs found\n");
return 1;
}
memcpy(vol_label, volinfo.volume_label, 11);
vol_label[11] = '\0';
volinfo.fs_type[5] = '\0';
printf("Partition %d: Filesystem: %s \"%s\"\n", cur_part_nr,
volinfo.fs_type, vol_label);
return 0;
}
int file_fat_ls (const char *dir)
{
return do_fat_read(dir, NULL, 0, LS_YES);
}
long file_fat_read (const char *filename, void *buffer, unsigned long maxsize)
{
printf("reading %s\n", filename);
return do_fat_read(filename, buffer, maxsize, LS_NO);
}
| {
"pile_set_name": "Github"
} |
package blkiodev
import "fmt"
// WeightDevice is a structure that holds device:weight pair
type WeightDevice struct {
Path string
Weight uint16
}
func (w *WeightDevice) String() string {
return fmt.Sprintf("%s:%d", w.Path, w.Weight)
}
// ThrottleDevice is a structure that holds device:rate_per_second pair
type ThrottleDevice struct {
Path string
Rate uint64
}
func (t *ThrottleDevice) String() string {
return fmt.Sprintf("%s:%d", t.Path, t.Rate)
}
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.db.metadata.model.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.modules.db.metadata.model.MetadataUtilities;
import org.netbeans.modules.db.metadata.model.api.Column;
import org.netbeans.modules.db.metadata.model.api.MetadataException;
import org.netbeans.modules.db.metadata.model.api.Schema;
import org.netbeans.modules.db.metadata.model.spi.ViewImplementation;
/**
* This class delegates to an underlying table implementation, as basically
* a view is a kind of table. I didn't do this as inheritance because I
* did not want to hard-code an inheritance relationship into the API. Who
* knows, for some implementations, a view is not a table.
*
* @author David Van Couvering
*/
public class JDBCView extends ViewImplementation {
private static final Logger LOGGER = Logger.getLogger(JDBCView.class.getName());
private final JDBCSchema jdbcSchema;
private final String name;
private Map<String, Column> columns;
public JDBCView(JDBCSchema jdbcSchema, String name) {
this.jdbcSchema = jdbcSchema;
this.name = name;
}
@Override
public String toString() {
return "JDBCView[name='" + getName() + "']"; // NOI18N
}
public final Schema getParent() {
return jdbcSchema.getSchema();
}
public final String getName() {
return name;
}
public final Collection<Column> getColumns() {
return initColumns().values();
}
public final Column getColumn(String name) {
return MetadataUtilities.find(name, initColumns());
}
protected JDBCColumn createJDBCColumn(ResultSet rs) throws SQLException {
int ordinalPosition = rs.getInt("ORDINAL_POSITION");
return new JDBCColumn(this.getView(), ordinalPosition, JDBCValue.createTableColumnValue(rs, this.getView()));
}
protected void createColumns() {
Map<String, Column> newColumns = new LinkedHashMap<String, Column>();
try {
ResultSet rs = jdbcSchema.getJDBCCatalog().getJDBCMetadata().getDmd().getColumns(jdbcSchema.getJDBCCatalog().getName(), jdbcSchema.getName(), name, "%"); // NOI18N
if (rs != null) {
try {
while (rs.next()) {
Column column = createJDBCColumn(rs).getColumn();
newColumns.put(column.getName(), column);
LOGGER.log(Level.FINE, "Created column {0}", column);
}
} finally {
rs.close();
}
}
} catch (SQLException e) {
throw new MetadataException(e);
}
columns = Collections.unmodifiableMap(newColumns);
}
private Map<String, Column> initColumns() {
if (columns != null) {
return columns;
}
LOGGER.log(Level.FINE, "Initializing columns in {0}", this);
createColumns();
return columns;
}
@Override
public final void refresh() {
columns = null;
}
}
| {
"pile_set_name": "Github"
} |
// =============================================================================
// Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
// Copyright (C) 2009 - DIGITEO - Clément DAVID
//
// This file is distributed under the same license as the Scilab package.
// =============================================================================
// <-- Non-regression test for bug 6541 -->
//
// <-- Bugzilla URL -->
// http://bugzilla.scilab.org/show_bug.cgi?id=6797
//
// <-- Short Description -->
// Calling importXcosDiagram without loading Scicos libs must not fail.
// The call of importXcosDiagram must not load scicos libs.
// Are scicos libs loaded ?
function result = isScicosLibLoaded()
result = isdef("BIGSOM_f");
endfunction
// Check that the simulation libraries are not loaded at startup
if isScicosLibLoaded() <> %f then pause,end
result = importXcosDiagram(SCI + "/modules/xcos/tests/nonreg_tests/bug_6797.zcos");
if result <> %t then pause,end
// Check that the simulation libraries are not loaded after the call
if isScicosLibLoaded() <> %f then pause,end
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.