text
stringlengths 2
99.5k
| meta
dict |
|---|---|
# coding: utf-8
describe PDF::Reader::Filter do
describe "#with" do
context "when passed :ASCII85Decode" do
it "returns the appropriate class" do
expect(PDF::Reader::Filter.with(:ASCII85Decode)).to be_a(PDF::Reader::Filter::Ascii85)
end
end
context "when passed :ASCIIHexDecode" do
it "returns the appropriate class" do
expect(PDF::Reader::Filter.with(:ASCIIHexDecode)).to be_a(PDF::Reader::Filter::AsciiHex)
end
end
context "when passed :CCITTFaxDecode" do
it "returns the appropriate class" do
expect(PDF::Reader::Filter.with(:CCITTFaxDecode)).to be_a(PDF::Reader::Filter::Null)
end
end
context "when passed :DCTDecode" do
it "returns the appropriate class" do
expect(PDF::Reader::Filter.with(:DCTDecode)).to be_a(PDF::Reader::Filter::Null)
end
end
context "when passed :ASCII85Decode" do
it "returns the appropriate class" do
expect(PDF::Reader::Filter.with(:ASCII85Decode)).to be_a(PDF::Reader::Filter::Ascii85)
end
end
context "when passed :FlateDecode" do
it "returns the appropriate class" do
expect(PDF::Reader::Filter.with(:FlateDecode)).to be_a(PDF::Reader::Filter::Flate)
end
end
context "when passed :JBIG2ecode" do
it "returns the appropriate class" do
expect(PDF::Reader::Filter.with(:JBIG2Decode)).to be_a(PDF::Reader::Filter::Null)
end
end
context "when passed :JPXDecode" do
it "returns the appropriate class" do
expect(PDF::Reader::Filter.with(:JPXDecode)).to be_a(PDF::Reader::Filter::Null)
end
end
context "when passed :LZWDecode" do
it "returns the appropriate class" do
expect(PDF::Reader::Filter.with(:LZWDecode)).to be_a(PDF::Reader::Filter::Lzw)
end
end
context "when passed :RunLengthDecode" do
it "returns the appropriate class" do
expect(PDF::Reader::Filter.with(:RunLengthDecode)).to be_a(PDF::Reader::Filter::RunLength)
end
end
context "when passed an unrecognised filter" do
it "raises an exception" do
expect {
PDF::Reader::Filter.with(:FooDecode)
}.to raise_error(PDF::Reader::UnsupportedFeatureError)
end
end
end
end
|
{
"pile_set_name": "Github"
}
|
cheats = 14
cheat0_desc = "Misc Codes"
cheat1_desc = "Disable AI"
cheat1_code = "02036440+E3A01000"
cheat1_enable = false
cheat2_desc = "AI Doesn't Attack"
cheat2_code = "02037328+E3A00000+02037338+E3A00000"
cheat2_enable = false
cheat3_desc = "Human Torch / Silver Surfer Codes"
cheat4_desc = "Infinite Health"
cheat4_code = "620D5010+00000000+B20D5010+00000000+20000150+00000096+D2000000+00000000"
cheat4_enable = false
cheat5_desc = "Invincible"
cheat5_code = "620D5010+00000000+B20D5010+00000000+00000158+0000FFFF+D2000000+00000000"
cheat5_enable = false
cheat6_desc = "Spaceship Codes"
cheat7_desc = "Infinite Health"
cheat7_code = "623AFDE8+00000000+B23AFDE8+00000000+B0000074+00000000+20000018+000000FF+D2000000+00000000"
cheat7_enable = false
cheat8_desc = "Invincible"
cheat8_code = "623AFDE8+00000000+B23AFDE8+00000000+B0000074+00000000+00000020+0000FFFF+D2000000+00000000"
cheat8_enable = false
cheat9_desc = "Boss Battle Codes"
cheat10_desc = "HP Never Decrease"
cheat10_code = "DA000000+020D9DE8+D7000000+020D9DE4+D2000000+00000000"
cheat10_enable = false
cheat11_desc = "1 hit KO boss battle"
cheat11_code = "94000130+FEFF0000+120D9DE0+00000001+D2000000+00000000"
cheat11_enable = false
cheat12_desc = "Backlight Codes"
cheat13_desc = "DS Lite Backlight Control"
cheat13_code = "94000130+FCFB0000+023FE074+012FFF11+E0000000+000000A8+E28F0001+E12FFF10+A21AB5F0+88234C24+80138811+D02A428B+25803490+F0002000+1C06F82A+F0002004+2703F826+21404007+D003420B+420B2180+E018D00C+4231210C+2F03D006+1C79D013+F0002004+E00EF816+E0094331+438E210C+2F001C31+1E79D004+F0002004+E002F80A+F0002000+BCF0F806+4718BC08+30800000+88222100+D1FC422A+80224A08+88208060+D1FC4228+80220C12+88228061+D1FC422A+21FF8860+47704008+04000130+80028802+023FE074+E3520003+D2000000+00000000"
cheat13_enable = false
|
{
"pile_set_name": "Github"
}
|
Pod::Spec.new do |s|
s.name = "KRLCollectionViewGridLayout"
s.version = "1.0.0"
s.summary = "A UICollectionViewLayout that specifies item size and location by number of columns."
s.description = <<-DESC
This layout is an alternative to UICollectionViewFlowLayout that positions and sizes items using a defined number of columns and an aspect ratio property which force the size of cells, rather than the cells' size telling the layout how to lay them out. By default, this will always show the same number of items in a row no matter how large or small the collection view is.
DESC
s.homepage = "http://github.com/klundberg/KRLCollectionViewGridLayout"
s.license = 'MIT'
s.author = { "Kevin Lundberg" => "kevin@klundberg.com" }
s.source = { :git => "https://github.com/klundberg/KRLCollectionViewGridLayout.git", :tag => "v#{s.version}" }
s.source_files = 'Classes/*.{h,m}'
s.ios.deployment_target = '6.0'
s.tvos.deployment_target = '9.0'
end
|
{
"pile_set_name": "Github"
}
|
[[_events_eventpublisher_transformation]]
= The @EventPublisher AST Transformation
Any component may gain the ability to publish events through an `{link_event_router}`
instance. You only need annotate the class with `{link_event_publisher_ast}`
and it will automatically gain all methods exposed by `{link_event_publisher}`.
The following example shows a trivial usage of this feature:
[source,groovy,linenums,options="nowrap"]
----
@griffon.transform.core.EventPublisher
class Publisher {
void doit(String name) {
publishEvent('arg', [name])
}
void doit() {
publishEvent('empty')
}
}
----
The application's event router will be used by default. If you'd like your custom
event publisher to use a private `{link_event_router}`, then you must define a binding
for it using a specific name, like this:
[source,groovy,linenums,options="nowrap"]
----
import griffon.core.injection.Module
import griffon.core.event.EventRouter
import org.kordamp.jipsy.ServiceProviderFor
import org.codehaus.griffon.runtime.core.injection.AbstractModule
import org.codehaus.griffon.runtime.core.event.DefaultEventRouter
import javax.inject.Named
import static griffon.util.AnnotationUtils.named
@ServiceProviderFor(Module)
@Named
class ApplicationModule extends AbstractModule {
@Override
protected void doConfigure() {
bind(EventRouter)
.withClassifier(named('my-private-event-router'))
.to(DefaultEventRouter)
.asSingleton()
}
}
----
Next, specify the named `{link_event_router}` as a parameter on the `{link_event_publisher_ast}`
transformation:
[source,groovy,linenums,options="nowrap"]
----
@griffon.transform.core.EventPublisher('my-private-event-router')
class Publisher {
void doit(String name) {
publishEvent('arg', [name])
}
void doit() {
publishEvent('empty')
}
}
----
|
{
"pile_set_name": "Github"
}
|
package com.gentics.mesh.core.data.service.transformation;
import java.util.Comparator;
import com.gentics.mesh.core.rest.common.AbstractResponse;
/**
* Comparator for rest model objects.
*
* @param <T>
*/
public class UuidRestModelComparator<T extends AbstractResponse> implements Comparator<T> {
@Override
public int compare(T o1, T o2) {
// TODO use order and sorting here?
String uuid1 = o1.getUuid();
String uuid2 = o2.getUuid();
if (uuid1 == null) {
uuid1 = "";
}
if (uuid2 == null) {
uuid2 = "";
}
return uuid1.compareTo(uuid2);
}
}
|
{
"pile_set_name": "Github"
}
|
// hex.h - originally written and placed in the public domain by Wei Dai
/// \file hex.h
/// \brief Classes for HexEncoder and HexDecoder
#ifndef CRYPTOPP_HEX_H
#define CRYPTOPP_HEX_H
#include "cryptlib.h"
#include "basecode.h"
NAMESPACE_BEGIN(CryptoPP)
/// \brief Converts given data to base 16
class CRYPTOPP_DLL HexEncoder : public SimpleProxyFilter
{
public:
/// \brief Construct a HexEncoder
/// \param attachment a BufferedTrasformation to attach to this object
/// \param uppercase a flag indicating uppercase output
/// \param groupSize the size of the output grouping
/// \param separator the separator to use between groups
/// \param terminator the terminator append after processing
HexEncoder(BufferedTransformation *attachment = NULLPTR, bool uppercase = true, int groupSize = 0, const std::string &separator = ":", const std::string &terminator = "")
: SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment)
{
IsolatedInitialize(MakeParameters(Name::Uppercase(), uppercase)(Name::GroupSize(), groupSize)(Name::Separator(), ConstByteArrayParameter(separator))(Name::Terminator(), ConstByteArrayParameter(terminator)));
}
void IsolatedInitialize(const NameValuePairs ¶meters);
};
/// \brief Decode base 16 data back to bytes
class CRYPTOPP_DLL HexDecoder : public BaseN_Decoder
{
public:
/// \brief Construct a HexDecoder
/// \param attachment a BufferedTrasformation to attach to this object
HexDecoder(BufferedTransformation *attachment = NULLPTR)
: BaseN_Decoder(GetDefaultDecodingLookupArray(), 4, attachment) {}
void IsolatedInitialize(const NameValuePairs ¶meters);
private:
static const int * CRYPTOPP_API GetDefaultDecodingLookupArray();
};
NAMESPACE_END
#endif
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.ballerinalang.net.http.websocket.client;
import java.util.List;
/**
* Represents a failover client connector config.
*
* @since 1.2.0
*/
public class FailoverContext {
private int currentIndex = 0;
private int failoverInterval = 0;
private boolean firstConnectionEstablished = false;
private List<String> targetUrls = null;
private int initialIndex = 0;
/**
* Gets the index.
*
* @return currentIndex
*/
public int getCurrentIndex() {
return currentIndex;
}
/**
* Assigns the index of the `FailoverContext` to the variable index.
*
* @param currentIndex - a current index
*/
public void setCurrentIndex(int currentIndex) {
this.currentIndex = currentIndex;
}
/**
* Gets the target URLs.
*
* @return targetUrls
*/
public List<String> getTargetUrls() {
return targetUrls;
}
/**
* Assigns the target URLs of the `FailoverContext` to the `targetUrls` variable.
*
* @param targetUrls - target URLs
*/
void setTargetUrls(List<String> targetUrls) {
this.targetUrls = targetUrls;
}
/**
* Assigns the failover interval of the `FailoverContext` to the `failoverInterval` variable.
*
* @param failoverInterval - a failover interval
*/
void setFailoverInterval(int failoverInterval) {
this.failoverInterval = failoverInterval;
}
/**
* Assigns the failover interval of the `FailoverContext` to the `failoverInterval` variable.
* @return failoverInterval
*/
public int getFailoverInterval() {
return failoverInterval;
}
/**
* Gets the `firstConnectionEstablished`.
*
* @return firstConnectionEstablished
*/
public boolean isFirstConnectionEstablished() {
return firstConnectionEstablished;
}
/**
* Assigns the connection state of the `FailoverContext` to the `firstConnectionEstablished` variable.
*/
public void setFirstConnectionEstablished() {
this.firstConnectionEstablished = true;
}
/**
* Gets the initial index.
*
* @return initialIndex
*/
public int getInitialIndex() {
return initialIndex;
}
/**
* Assigns the `initialIndex` of the FailoverContext to the `initialIndex` variable.
*
* @param initialIndex - the initial index
*/
public void setInitialIndex(int initialIndex) {
this.initialIndex = initialIndex;
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright 2008 - 2019 The Loon Game Engine 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.
*
* @project loon
* @author cping
* @email:javachenpeng@yahoo.com
* @version 0.5
*/
package loon.utils.timer;
import loon.LRelease;
import loon.LSystem;
import loon.utils.MathUtils;
import loon.utils.TArray;
import loon.utils.processes.GameProcessType;
import loon.utils.processes.RealtimeProcess;
import loon.utils.processes.RealtimeProcessManager;
/**
* 一个简单的Interval游戏事务延迟管理器,可以在其中存储多个Interval并统一提交到游戏循环中,进行统一管理.
*
* 例如:
*
* <pre>
*
* // 构建一个延迟事务管理器(默认循环执行其中事务)
* final Scheduler s = new Scheduler();
* // 若removeTask项为true,则会删除已经执行过的事务,则只所有调度仅进行一次,不会循环执行
* // final Scheduler s = new Scheduler(true);
* // 添加事务1
* s.add(new Interval() {
*
* @Override
* public void loop() {
* System.out.println("a");
* // 跳到索引2(即第三个添加的事务)
* s.setIndex(2);
* }
* });
* // 添加事务2
* s.add(new Interval() {
*
* @Override
* public void loop() {
* System.out.println("b");
* }
* });
* // 添加事务3
* s.add(new Interval() {
*
* @Override
* public void loop() {
* System.out.println("c");
* }
* });
* // 延迟1秒
* s.setDelay(LSystem.SECOND);
* s.start();
* </pre>
*
*
*/
public class Scheduler implements LRelease {
private static class SchedulerProcess extends RealtimeProcess {
private Scheduler sched = null;
public SchedulerProcess(Scheduler s) {
this.sched = s;
this.setProcessType(GameProcessType.Time);
}
@Override
public void run(LTimerContext time) {
if (sched != null) {
sched.update(time);
if (sched.completed()) {
kill();
}
}
}
}
private final LTimer _loop_timer;
private SchedulerProcess _processScheduler;
private TArray<Interval> _scheduled = new TArray<Interval>(32);
private int _childIndex = 0;
private boolean _removeSequenceTask = false;
private boolean _forceWaitSequence = false;
private boolean _closed = false;
public Scheduler() {
this(0L);
}
public Scheduler(long delay) {
this(LSystem.UNKNOWN, delay);
}
public Scheduler(boolean removeTask) {
this(LSystem.UNKNOWN, removeTask);
}
public Scheduler(String name, boolean removeTask) {
this(name, 0, removeTask, true);
}
public Scheduler(String name, long delay) {
this(name, delay, false);
}
public Scheduler(boolean removeTask, boolean sequence) {
this(LSystem.UNKNOWN, 0L, removeTask, sequence);
}
public Scheduler(String name, boolean removeTask, boolean sequence) {
this(name, 0L, removeTask, sequence);
}
public Scheduler(String name, long delay, boolean removeTask) {
this(name, delay, removeTask, true);
}
/**
* Scheduler事务管理器
*
* @param name
* 事务调度管理器名称
* @param delay
* 延迟时间(默认0)
* @param removeTask
* 是否删除已运行的任务
* @param sequence
* 是否循环播放管理器中事务(此项为true,当前事务不完成不会进行下一个,若想同步进行可改为false)
*/
public Scheduler(String name, long delay, boolean removeTask, boolean sequence) {
this._loop_timer = new LTimer(name, delay);
this._removeSequenceTask = removeTask;
this._forceWaitSequence = sequence;
this._closed = false;
_forceWaitSequence = sequence;
}
public boolean isActive() {
return this._loop_timer.isActive();
}
public Scheduler start() {
this.unpause();
synchronized (RealtimeProcessManager.class) {
if (_processScheduler != null) {
RealtimeProcessManager.get().delete(_processScheduler);
}
if (_processScheduler == null || _processScheduler.isDead()) {
_processScheduler = new SchedulerProcess(this);
}
_processScheduler.setDelay(0);
RealtimeProcessManager.get().addProcess(_processScheduler);
}
return this;
}
public Scheduler kill() {
if (_processScheduler != null) {
_processScheduler.kill();
}
return this;
}
public Scheduler stop() {
this.pause();
this.kill();
return this;
}
public Scheduler pause() {
this._loop_timer.pause();
return this;
}
public Scheduler unpause() {
this._loop_timer.unpause();
return this;
}
public boolean paused() {
return !isActive();
}
public boolean add(Interval sched) {
return _scheduled.add(sched);
}
public boolean remove(Interval sched) {
return _scheduled.remove(sched);
}
public Interval removeIndex(int idx) {
return _scheduled.removeIndex(idx);
}
public Interval getIndex(int idx) {
return _scheduled.get(idx);
}
public TArray<Interval> findName(String name) {
TArray<Interval> result = new TArray<Interval>();
for (int i = _scheduled.size - 1; i > -1; i--) {
Interval u = _scheduled.get(i);
if (u != null && name.equals(u.getName())) {
result.add(u);
}
}
return result.reverse();
}
public Scheduler removeName(String name) {
for (int i = _scheduled.size - 1; i > -1; i--) {
Interval u = _scheduled.get(i);
if (u != null && name.equals(u.getName())) {
_scheduled.removeIndex(i);
}
}
return this;
}
public Scheduler clear() {
_scheduled.clear();
return this;
}
public boolean completed() {
boolean c = _scheduled.isEmpty();
if (c) {
return true;
} else {
final int size = _scheduled.size;
int count = 0;
for (int i = _scheduled.size - 1; i > -1; i--) {
Interval u = _scheduled.get(i);
if (u != null && u.completed()) {
count++;
}
}
c = (count >= size);
}
return c;
}
public void update(LTimerContext context) {
if (_closed) {
return;
}
if (_loop_timer.action(context)) {
if (_scheduled.size > 0) {
final boolean seq = (_forceWaitSequence && _removeSequenceTask);
int index = seq ? 0 : MathUtils.max(0, _childIndex);
Interval i = _scheduled.get(index);
if (i != null) {
if (i._loop_timer.action(context)) {
i.loop();
}
if (_forceWaitSequence) {
if (i.completed()) {
if (_removeSequenceTask) {
_scheduled.removeFirst();
} else {
_childIndex++;
}
} else if (i.completed() && !seq) {
_childIndex++;
}
} else {
if (_removeSequenceTask) {
_scheduled.removeFirst();
} else {
_childIndex++;
}
}
}
if (_childIndex >= _scheduled.size) {
_childIndex = 0;
}
}
}
}
public Scheduler reset() {
_childIndex = 0;
_loop_timer.reset();
for (int i = _scheduled.size - 1; i > -1; i--) {
Interval u = _scheduled.get(i);
if (u != null) {
u._loop_timer.reset();
}
}
return this;
}
public Scheduler setIndex(int idx) {
this._childIndex = idx;
this._forceWaitSequence = false;
return this;
}
public int getIndex() {
return this._childIndex;
}
public int size() {
return _scheduled.size;
}
public long getDelay() {
return _loop_timer.getDelay();
}
public Scheduler setDelay(long delay) {
_loop_timer.setDelay(delay);
return this;
}
public String getName() {
return this._loop_timer.getName();
}
public LTimer currentTimer() {
return _loop_timer;
}
public boolean isClosed() {
return this._closed;
}
@Override
public void close() {
clear();
stop();
_closed = true;
}
}
|
{
"pile_set_name": "Github"
}
|
Sequel.migration do
change do
create_table :geocodings do
primary_key :id
Integer :user_id
Text :table_name
Integer :total_rows
Integer :processed_rows
DateTime :created_at, default: Sequel::CURRENT_TIMESTAMP
DateTime :updated_at, default: Sequel::CURRENT_TIMESTAMP
end
end
end
|
{
"pile_set_name": "Github"
}
|
`timescale 1ns / 1ps
module rp_dma_s2mm_upsize
#(parameter AXI_DATA_BITS = 64,
parameter AXIS_DATA_BITS = 16,
parameter AXI_BURST_LEN = 16)(
input wire clk,
input wire rst,
output reg [7:0] req_data,
output reg req_we,
input wire [AXIS_DATA_BITS-1:0] s_axis_tdata,
input wire s_axis_tvalid,
output wire s_axis_tready,
input wire s_axis_tlast,
output reg [AXI_DATA_BITS-1:0] m_axis_tdata,
output reg m_axis_tvalid,
input wire m_axis_tready
);
localparam MUX_MAX = AXI_DATA_BITS/AXIS_DATA_BITS;
reg [1:0] mux_sel;
reg [6:0] xfer_cnt;
wire [6:0] req_len;
reg tlast;
genvar i;
assign s_axis_tready = 1'b1;
assign req_len = xfer_cnt+1;
////////////////////////////////////////////////////////////
// Name :
//
////////////////////////////////////////////////////////////
always @(posedge clk)
begin
if (rst == 1) begin
xfer_cnt <= 0;
end else begin
if ((m_axis_tvalid == 1) && (m_axis_tready == 1)) begin
if (xfer_cnt == AXI_BURST_LEN-1) begin
xfer_cnt <= 0;
end else begin
xfer_cnt <= xfer_cnt + 1;
end
end
end
end
////////////////////////////////////////////////////////////
// Name : Request Data
// Sends the transfer count and indicates if this is the
// last transfer.
////////////////////////////////////////////////////////////
always @(posedge clk)
begin
req_data <= {tlast, req_len};
end
////////////////////////////////////////////////////////////
// Name :
//
////////////////////////////////////////////////////////////
always @(posedge clk)
begin
if (rst == 1) begin
req_we <= 0;
end else begin
if (((m_axis_tvalid == 1) && (m_axis_tready == 1) && ((tlast == 1) || (xfer_cnt == AXI_BURST_LEN-1)))) begin
req_we <= 1;
end else begin
req_we <= 0;
end
end
end
////////////////////////////////////////////////////////////
// Name : Mux Select
// Selects which part of the output data should have the
// input sample assigned.
////////////////////////////////////////////////////////////
always @(posedge clk)
begin
if (rst == 1) begin
mux_sel <= 0;
end else begin
if ((s_axis_tvalid == 1) && (s_axis_tready == 1)) begin
if (mux_sel == MUX_MAX-1) begin
mux_sel <= 0;
end else begin
mux_sel <= mux_sel + 1;
end
end
end
end
////////////////////////////////////////////////////////////
// Name : TDATA
//
////////////////////////////////////////////////////////////
generate
for (i=0; i<MUX_MAX; i=i+1) begin : gen_data
always @(posedge clk)
begin
if (mux_sel == i) begin
m_axis_tdata[i*AXIS_DATA_BITS +: AXIS_DATA_BITS] <= s_axis_tdata;
end
end
end
endgenerate
////////////////////////////////////////////////////////////
// Name : TVALID
// Set the valid signal if all samples are assigned to the
// ouput data or the last sample has arrived.
////////////////////////////////////////////////////////////
always @(posedge clk)
begin
if (rst == 1) begin
m_axis_tvalid <= 0;
end else begin
if (((mux_sel == MUX_MAX-1) || (s_axis_tlast == 1)) && (s_axis_tvalid == 1) && (s_axis_tready == 1)) begin
m_axis_tvalid <= 1;
end else begin
m_axis_tvalid <= 0;
end
end
end
////////////////////////////////////////////////////////////
// Name : TLAST
// Indicates that the last sample has been sent.
////////////////////////////////////////////////////////////
always @(posedge clk)
begin
if (rst == 1) begin
tlast <= 0;
end else begin
if ((s_axis_tlast == 1) && (s_axis_tvalid == 1) && (s_axis_tready == 1)) begin
tlast <= 1;
end
end
end
endmodule
|
{
"pile_set_name": "Github"
}
|
import {
composeButton,
composeModalPostPrivacyButton,
getNthPostPrivacyOptionInDialog,
postPrivacyButton, postPrivacyDialogButtonUnlisted,
scrollToStatus,
sleep
} from '../utils'
import { loginAsFoobar } from '../roles'
fixture`014-compose-post-privacy.js`
.page`http://localhost:4002`
test('Changes post privacy', async t => {
await loginAsFoobar(t)
await sleep(2000)
await t
.expect(postPrivacyButton.getAttribute('aria-label')).eql('Adjust privacy (currently Public)')
.click(postPrivacyButton)
.expect(getNthPostPrivacyOptionInDialog(2).exists).ok({ timeout: 30000 })
.click(getNthPostPrivacyOptionInDialog(2))
.expect(postPrivacyButton.getAttribute('aria-label')).eql('Adjust privacy (currently Unlisted)')
.click(postPrivacyButton)
.expect(getNthPostPrivacyOptionInDialog(1).exists).ok({ timeout: 30000 })
.click(getNthPostPrivacyOptionInDialog(1))
.expect(postPrivacyButton.getAttribute('aria-label')).eql('Adjust privacy (currently Public)')
})
test('can use privacy dialog within compose dialog', async t => {
await loginAsFoobar(t)
await scrollToStatus(t, 16)
await t.expect(composeButton.getAttribute('aria-label')).eql('Compose')
await sleep(2000)
await t.click(composeButton)
.click(composeModalPostPrivacyButton)
.click(postPrivacyDialogButtonUnlisted)
.expect(composeModalPostPrivacyButton.getAttribute('aria-label')).eql('Adjust privacy (currently Unlisted)')
})
|
{
"pile_set_name": "Github"
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// 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/.
#ifndef EIGEN_CXX11_TENSOR_TENSOR_BASE_H
#define EIGEN_CXX11_TENSOR_TENSOR_BASE_H
// clang-format off
namespace Eigen {
/** \class TensorBase
* \ingroup CXX11_Tensor_Module
*
* \brief The tensor base class.
*
* This class is the common parent of the Tensor and TensorMap class, thus
* making it possible to use either class interchangably in expressions.
*/
template<typename Derived>
class TensorBase<Derived, ReadOnlyAccessors>
{
public:
typedef internal::traits<Derived> DerivedTraits;
typedef typename DerivedTraits::Scalar Scalar;
typedef typename DerivedTraits::Index Index;
typedef typename internal::remove_const<Scalar>::type CoeffReturnType;
static const int NumDimensions = DerivedTraits::NumDimensions;
// Generic nullary operation support.
template <typename CustomNullaryOp> EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseNullaryOp<CustomNullaryOp, const Derived>
nullaryExpr(const CustomNullaryOp& func) const {
return TensorCwiseNullaryOp<CustomNullaryOp, const Derived>(derived(), func);
}
// Coefficient-wise nullary operators
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived>
constant(const Scalar& value) const {
return nullaryExpr(internal::scalar_constant_op<Scalar>(value));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseNullaryOp<internal::UniformRandomGenerator<Scalar>, const Derived>
random() const {
return nullaryExpr(internal::UniformRandomGenerator<Scalar>());
}
template <typename RandomGenerator> EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseNullaryOp<RandomGenerator, const Derived>
random(const RandomGenerator& gen = RandomGenerator()) const {
return nullaryExpr(gen);
}
// Tensor generation
template <typename Generator> EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorGeneratorOp<Generator, const Derived>
generate(const Generator& generator) const {
return TensorGeneratorOp<Generator, const Derived>(derived(), generator);
}
// Generic unary operation support.
template <typename CustomUnaryOp> EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<CustomUnaryOp, const Derived>
unaryExpr(const CustomUnaryOp& func) const {
return TensorCwiseUnaryOp<CustomUnaryOp, const Derived>(derived(), func);
}
// Coefficient-wise unary operators
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_opposite_op<Scalar>, const Derived>
operator-() const {
return unaryExpr(internal::scalar_opposite_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_sqrt_op<Scalar>, const Derived>
sqrt() const {
return unaryExpr(internal::scalar_sqrt_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_sign_op<Scalar>, const Derived>
sign() const {
return unaryExpr(internal::scalar_sign_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_rsqrt_op<Scalar>, const Derived>
rsqrt() const {
return unaryExpr(internal::scalar_rsqrt_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_square_op<Scalar>, const Derived>
square() const {
return unaryExpr(internal::scalar_square_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_cube_op<Scalar>, const Derived>
cube() const {
return unaryExpr(internal::scalar_cube_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_inverse_op<Scalar>, const Derived>
inverse() const {
return unaryExpr(internal::scalar_inverse_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_tanh_op<Scalar>, const Derived>
tanh() const {
return unaryExpr(internal::scalar_tanh_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_lgamma_op<Scalar>, const Derived>
lgamma() const {
return unaryExpr(internal::scalar_lgamma_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_digamma_op<Scalar>, const Derived>
digamma() const {
return unaryExpr(internal::scalar_digamma_op<Scalar>());
}
// igamma(a = this, x = other)
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_igamma_op<Scalar>, const Derived, const OtherDerived>
igamma(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_igamma_op<Scalar>());
}
// igammac(a = this, x = other)
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_igammac_op<Scalar>, const Derived, const OtherDerived>
igammac(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_igammac_op<Scalar>());
}
// zeta(x = this, q = other)
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_zeta_op<Scalar>, const Derived, const OtherDerived>
zeta(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_zeta_op<Scalar>());
}
// polygamma(n = this, x = other)
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_polygamma_op<Scalar>, const Derived, const OtherDerived>
polygamma(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_polygamma_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_erf_op<Scalar>, const Derived>
erf() const {
return unaryExpr(internal::scalar_erf_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_erfc_op<Scalar>, const Derived>
erfc() const {
return unaryExpr(internal::scalar_erfc_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_sigmoid_op<Scalar>, const Derived>
sigmoid() const {
return unaryExpr(internal::scalar_sigmoid_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_exp_op<Scalar>, const Derived>
exp() const {
return unaryExpr(internal::scalar_exp_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_expm1_op<Scalar>, const Derived>
expm1() const {
return unaryExpr(internal::scalar_expm1_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_log_op<Scalar>, const Derived>
log() const {
return unaryExpr(internal::scalar_log_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_log1p_op<Scalar>, const Derived>
log1p() const {
return unaryExpr(internal::scalar_log1p_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_abs_op<Scalar>, const Derived>
abs() const {
return unaryExpr(internal::scalar_abs_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_conjugate_op<Scalar>, const Derived>
conjugate() const {
return unaryExpr(internal::scalar_conjugate_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::bind2nd_op<internal::scalar_pow_op<Scalar,Scalar> >, const Derived>
pow(Scalar exponent) const {
return unaryExpr(internal::bind2nd_op<internal::scalar_pow_op<Scalar,Scalar> >(exponent));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_real_op<Scalar>, const Derived>
real() const {
return unaryExpr(internal::scalar_real_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_imag_op<Scalar>, const Derived>
imag() const {
return unaryExpr(internal::scalar_imag_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::bind2nd_op<internal::scalar_sum_op<Scalar,Scalar> >, const Derived>
operator+ (Scalar rhs) const {
return unaryExpr(internal::bind2nd_op<internal::scalar_sum_op<Scalar,Scalar> >(rhs));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE friend
const TensorCwiseUnaryOp<internal::bind1st_op<internal::scalar_sum_op<Scalar> >, const Derived>
operator+ (Scalar lhs, const Derived& rhs) {
return rhs.unaryExpr(internal::bind1st_op<internal::scalar_sum_op<Scalar> >(lhs));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::bind2nd_op<internal::scalar_difference_op<Scalar,Scalar> >, const Derived>
operator- (Scalar rhs) const {
EIGEN_STATIC_ASSERT((NumTraits<Scalar>::IsSigned || internal::is_same<Scalar, const std::complex<float> >::value), YOU_MADE_A_PROGRAMMING_MISTAKE);
return unaryExpr(internal::bind2nd_op<internal::scalar_difference_op<Scalar,Scalar> >(rhs));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE friend
const TensorCwiseUnaryOp<internal::bind1st_op<internal::scalar_difference_op<Scalar> >, const Derived>
operator- (Scalar lhs, const Derived& rhs) {
return rhs.unaryExpr(internal::bind1st_op<internal::scalar_difference_op<Scalar> >(lhs));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::bind2nd_op<internal::scalar_product_op<Scalar,Scalar> >, const Derived>
operator* (Scalar rhs) const {
return unaryExpr(internal::bind2nd_op<internal::scalar_product_op<Scalar,Scalar> >(rhs));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE friend
const TensorCwiseUnaryOp<internal::bind1st_op<internal::scalar_product_op<Scalar> >, const Derived>
operator* (Scalar lhs, const Derived& rhs) {
return rhs.unaryExpr(internal::bind1st_op<internal::scalar_product_op<Scalar> >(lhs));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::bind2nd_op<internal::scalar_quotient_op<Scalar,Scalar> >, const Derived>
operator/ (Scalar rhs) const {
return unaryExpr(internal::bind2nd_op<internal::scalar_quotient_op<Scalar,Scalar> >(rhs));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE friend
const TensorCwiseUnaryOp<internal::bind1st_op<internal::scalar_quotient_op<Scalar> >, const Derived>
operator/ (Scalar lhs, const Derived& rhs) {
return rhs.unaryExpr(internal::bind1st_op<internal::scalar_quotient_op<Scalar> >(lhs));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_mod_op<Scalar>, const Derived>
operator% (Scalar rhs) const {
EIGEN_STATIC_ASSERT(NumTraits<Scalar>::IsInteger, YOU_MADE_A_PROGRAMMING_MISTAKE_TRY_MOD);
return unaryExpr(internal::scalar_mod_op<Scalar>(rhs));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_max_op<Scalar>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
cwiseMax(Scalar threshold) const {
return cwiseMax(constant(threshold));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_min_op<Scalar>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
cwiseMin(Scalar threshold) const {
return cwiseMin(constant(threshold));
}
template <typename NewType> EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorConversionOp<NewType, const Derived>
cast() const {
return TensorConversionOp<NewType, const Derived>(derived());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_round_op<Scalar>, const Derived>
round() const {
return unaryExpr(internal::scalar_round_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_ceil_op<Scalar>, const Derived>
ceil() const {
return unaryExpr(internal::scalar_ceil_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_floor_op<Scalar>, const Derived>
floor() const {
return unaryExpr(internal::scalar_floor_op<Scalar>());
}
// Generic binary operation support.
template <typename CustomBinaryOp, typename OtherDerived> EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<CustomBinaryOp, const Derived, const OtherDerived>
binaryExpr(const OtherDerived& other, const CustomBinaryOp& func) const {
return TensorCwiseBinaryOp<CustomBinaryOp, const Derived, const OtherDerived>(derived(), other, func);
}
// Coefficient-wise binary operators.
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_sum_op<Scalar>, const Derived, const OtherDerived>
operator+(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_sum_op<Scalar>());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_difference_op<Scalar>, const Derived, const OtherDerived>
operator-(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_difference_op<Scalar>());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_product_op<Scalar>, const Derived, const OtherDerived>
operator*(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_product_op<Scalar>());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_quotient_op<Scalar>, const Derived, const OtherDerived>
operator/(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_quotient_op<Scalar>());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_max_op<Scalar>, const Derived, const OtherDerived>
cwiseMax(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_max_op<Scalar>());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_min_op<Scalar>, const Derived, const OtherDerived>
cwiseMin(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_min_op<Scalar>());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_boolean_and_op, const Derived, const OtherDerived>
operator&&(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_boolean_and_op());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_boolean_or_op, const Derived, const OtherDerived>
operator||(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_boolean_or_op());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_boolean_xor_op, const Derived, const OtherDerived>
operator^(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_boolean_xor_op());
}
// Comparisons and tests.
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LT>, const Derived, const OtherDerived>
operator<(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LT>());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LE>, const Derived, const OtherDerived>
operator<=(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LE>());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GT>, const Derived, const OtherDerived>
operator>(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GT>());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GE>, const Derived, const OtherDerived>
operator>=(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GE>());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_EQ>, const Derived, const OtherDerived>
operator==(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_EQ>());
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_NEQ>, const Derived, const OtherDerived>
operator!=(const OtherDerived& other) const {
return binaryExpr(other.derived(), internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_NEQ>());
}
// comparisons and tests for Scalars
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LT>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
operator<(Scalar threshold) const {
return operator<(constant(threshold));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_LE>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
operator<=(Scalar threshold) const {
return operator<=(constant(threshold));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GT>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
operator>(Scalar threshold) const {
return operator>(constant(threshold));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_GE>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
operator>=(Scalar threshold) const {
return operator>=(constant(threshold));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_EQ>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
operator==(Scalar threshold) const {
return operator==(constant(threshold));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseBinaryOp<internal::scalar_cmp_op<Scalar, Scalar, internal::cmp_NEQ>, const Derived, const TensorCwiseNullaryOp<internal::scalar_constant_op<Scalar>, const Derived> >
operator!=(Scalar threshold) const {
return operator!=(constant(threshold));
}
// Checks
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_isnan_op<Scalar>, const Derived>
(isnan)() const {
return unaryExpr(internal::scalar_isnan_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_isinf_op<Scalar>, const Derived>
(isinf)() const {
return unaryExpr(internal::scalar_isinf_op<Scalar>());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const TensorCwiseUnaryOp<internal::scalar_isfinite_op<Scalar>, const Derived>
(isfinite)() const {
return unaryExpr(internal::scalar_isfinite_op<Scalar>());
}
// Coefficient-wise ternary operators.
template<typename ThenDerived, typename ElseDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorSelectOp<const Derived, const ThenDerived, const ElseDerived>
select(const ThenDerived& thenTensor, const ElseDerived& elseTensor) const {
return TensorSelectOp<const Derived, const ThenDerived, const ElseDerived>(derived(), thenTensor.derived(), elseTensor.derived());
}
// Contractions.
typedef Eigen::IndexPair<Index> DimensionPair;
template<typename OtherDerived, typename Dimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorContractionOp<const Dimensions, const Derived, const OtherDerived>
contract(const OtherDerived& other, const Dimensions& dims) const {
return TensorContractionOp<const Dimensions, const Derived, const OtherDerived>(derived(), other.derived(), dims);
}
// Convolutions.
template<typename KernelDerived, typename Dimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorConvolutionOp<const Dimensions, const Derived, const KernelDerived>
convolve(const KernelDerived& kernel, const Dimensions& dims) const {
return TensorConvolutionOp<const Dimensions, const Derived, const KernelDerived>(derived(), kernel.derived(), dims);
}
// Fourier transforms
template <int FFTDataType, int FFTDirection, typename FFT> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorFFTOp<const FFT, const Derived, FFTDataType, FFTDirection>
fft(const FFT& fft) const {
return TensorFFTOp<const FFT, const Derived, FFTDataType, FFTDirection>(derived(), fft);
}
// Scan.
typedef TensorScanOp<internal::SumReducer<CoeffReturnType>, const Derived> TensorScanSumOp;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorScanSumOp
cumsum(const Index& axis, bool exclusive = false) const {
return TensorScanSumOp(derived(), axis, exclusive);
}
typedef TensorScanOp<internal::ProdReducer<CoeffReturnType>, const Derived> TensorScanProdOp;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorScanProdOp
cumprod(const Index& axis, bool exclusive = false) const {
return TensorScanProdOp(derived(), axis, exclusive);
}
template <typename Reducer>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorScanOp<Reducer, const Derived>
scan(const Index& axis, const Reducer& reducer, bool exclusive = false) const {
return TensorScanOp<Reducer, const Derived>(derived(), axis, exclusive, reducer);
}
// Reductions.
template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReductionOp<internal::SumReducer<CoeffReturnType>, const Dims, const Derived>
sum(const Dims& dims) const {
return TensorReductionOp<internal::SumReducer<CoeffReturnType>, const Dims, const Derived>(derived(), dims, internal::SumReducer<CoeffReturnType>());
}
const TensorReductionOp<internal::SumReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>
sum() const {
DimensionList<Index, NumDimensions> in_dims;
return TensorReductionOp<internal::SumReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>(derived(), in_dims, internal::SumReducer<CoeffReturnType>());
}
template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReductionOp<internal::MeanReducer<CoeffReturnType>, const Dims, const Derived>
mean(const Dims& dims) const {
return TensorReductionOp<internal::MeanReducer<CoeffReturnType>, const Dims, const Derived>(derived(), dims, internal::MeanReducer<CoeffReturnType>());
}
const TensorReductionOp<internal::MeanReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>
mean() const {
DimensionList<Index, NumDimensions> in_dims;
return TensorReductionOp<internal::MeanReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>(derived(), in_dims, internal::MeanReducer<CoeffReturnType>());
}
template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReductionOp<internal::ProdReducer<CoeffReturnType>, const Dims, const Derived>
prod(const Dims& dims) const {
return TensorReductionOp<internal::ProdReducer<CoeffReturnType>, const Dims, const Derived>(derived(), dims, internal::ProdReducer<CoeffReturnType>());
}
const TensorReductionOp<internal::ProdReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>
prod() const {
DimensionList<Index, NumDimensions> in_dims;
return TensorReductionOp<internal::ProdReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>(derived(), in_dims, internal::ProdReducer<CoeffReturnType>());
}
template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReductionOp<internal::MaxReducer<CoeffReturnType>, const Dims, const Derived>
maximum(const Dims& dims) const {
return TensorReductionOp<internal::MaxReducer<CoeffReturnType>, const Dims, const Derived>(derived(), dims, internal::MaxReducer<CoeffReturnType>());
}
const TensorReductionOp<internal::MaxReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>
maximum() const {
DimensionList<Index, NumDimensions> in_dims;
return TensorReductionOp<internal::MaxReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>(derived(), in_dims, internal::MaxReducer<CoeffReturnType>());
}
template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReductionOp<internal::MinReducer<CoeffReturnType>, const Dims, const Derived>
minimum(const Dims& dims) const {
return TensorReductionOp<internal::MinReducer<CoeffReturnType>, const Dims, const Derived>(derived(), dims, internal::MinReducer<CoeffReturnType>());
}
const TensorReductionOp<internal::MinReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>
minimum() const {
DimensionList<Index, NumDimensions> in_dims;
return TensorReductionOp<internal::MinReducer<CoeffReturnType>, const DimensionList<Index, NumDimensions>, const Derived>(derived(), in_dims, internal::MinReducer<CoeffReturnType>());
}
template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReductionOp<internal::AndReducer, const Dims, const TensorConversionOp<bool, const Derived> >
all(const Dims& dims) const {
return cast<bool>().reduce(dims, internal::AndReducer());
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReductionOp<internal::AndReducer, const DimensionList<Index, NumDimensions>, const TensorConversionOp<bool, const Derived> >
all() const {
DimensionList<Index, NumDimensions> in_dims;
return cast<bool>().reduce(in_dims, internal::AndReducer());
}
template <typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReductionOp<internal::OrReducer, const Dims, const TensorConversionOp<bool, const Derived> >
any(const Dims& dims) const {
return cast<bool>().reduce(dims, internal::OrReducer());
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReductionOp<internal::OrReducer, const DimensionList<Index, NumDimensions>, const TensorConversionOp<bool, const Derived> >
any() const {
DimensionList<Index, NumDimensions> in_dims;
return cast<bool>().reduce(in_dims, internal::OrReducer());
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorTupleReducerOp<
internal::ArgMaxTupleReducer<Tuple<Index, CoeffReturnType> >,
const array<Index, NumDimensions>, const Derived>
argmax() const {
array<Index, NumDimensions> in_dims;
for (Index d = 0; d < NumDimensions; ++d) in_dims[d] = d;
return TensorTupleReducerOp<
internal::ArgMaxTupleReducer<Tuple<Index, CoeffReturnType> >,
const array<Index, NumDimensions>,
const Derived>(derived(), internal::ArgMaxTupleReducer<Tuple<Index, CoeffReturnType> >(), -1, in_dims);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorTupleReducerOp<
internal::ArgMinTupleReducer<Tuple<Index, CoeffReturnType> >,
const array<Index, NumDimensions>, const Derived>
argmin() const {
array<Index, NumDimensions> in_dims;
for (Index d = 0; d < NumDimensions; ++d) in_dims[d] = d;
return TensorTupleReducerOp<
internal::ArgMinTupleReducer<Tuple<Index, CoeffReturnType> >,
const array<Index, NumDimensions>,
const Derived>(derived(), internal::ArgMinTupleReducer<Tuple<Index, CoeffReturnType> >(), -1, in_dims);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorTupleReducerOp<
internal::ArgMaxTupleReducer<Tuple<Index, CoeffReturnType> >,
const array<Index, 1>, const Derived>
argmax(const Index return_dim) const {
array<Index, 1> in_dims;
in_dims[0] = return_dim;
return TensorTupleReducerOp<
internal::ArgMaxTupleReducer<Tuple<Index, CoeffReturnType> >,
const array<Index, 1>,
const Derived>(derived(), internal::ArgMaxTupleReducer<Tuple<Index, CoeffReturnType> >(), return_dim, in_dims);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorTupleReducerOp<
internal::ArgMinTupleReducer<Tuple<Index, CoeffReturnType> >,
const array<Index, 1>, const Derived>
argmin(const Index return_dim) const {
array<Index, 1> in_dims;
in_dims[0] = return_dim;
return TensorTupleReducerOp<
internal::ArgMinTupleReducer<Tuple<Index, CoeffReturnType> >,
const array<Index, 1>,
const Derived>(derived(), internal::ArgMinTupleReducer<Tuple<Index, CoeffReturnType> >(), return_dim, in_dims);
}
template <typename Reducer, typename Dims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReductionOp<Reducer, const Dims, const Derived>
reduce(const Dims& dims, const Reducer& reducer) const {
return TensorReductionOp<Reducer, const Dims, const Derived>(derived(), dims, reducer);
}
template <typename Broadcast> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorBroadcastingOp<const Broadcast, const Derived>
broadcast(const Broadcast& broadcast) const {
return TensorBroadcastingOp<const Broadcast, const Derived>(derived(), broadcast);
}
template <typename Axis, typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorConcatenationOp<Axis, const Derived, const OtherDerived>
concatenate(const OtherDerived& other, Axis axis) const {
return TensorConcatenationOp<Axis, const Derived, const OtherDerived>(derived(), other.derived(), axis);
}
template <typename PatchDims> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorPatchOp<const PatchDims, const Derived>
extract_patches(const PatchDims& patch_dims) const {
return TensorPatchOp<const PatchDims, const Derived>(derived(), patch_dims);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorImagePatchOp<Dynamic, Dynamic, const Derived>
extract_image_patches(const Index patch_rows = 1, const Index patch_cols = 1,
const Index row_stride = 1, const Index col_stride = 1,
const Index in_row_stride = 1, const Index in_col_stride = 1,
const PaddingType padding_type = PADDING_SAME, const Scalar padding_value = Scalar(0)) const {
return TensorImagePatchOp<Dynamic, Dynamic, const Derived>(derived(), patch_rows, patch_cols, row_stride, col_stride,
in_row_stride, in_col_stride, 1, 1, padding_type, padding_value);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorImagePatchOp<Dynamic, Dynamic, const Derived>
extract_image_patches(const Index patch_rows, const Index patch_cols,
const Index row_stride, const Index col_stride,
const Index in_row_stride, const Index in_col_stride,
const Index row_inflate_stride, const Index col_inflate_stride,
const Index padding_top, const Index padding_bottom,
const Index padding_left,const Index padding_right,
const Scalar padding_value) const {
return TensorImagePatchOp<Dynamic, Dynamic, const Derived>(derived(), patch_rows, patch_cols, row_stride, col_stride,
in_row_stride, in_col_stride, row_inflate_stride, col_inflate_stride,
padding_top, padding_bottom, padding_left, padding_right, padding_value);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorVolumePatchOp<Dynamic, Dynamic, Dynamic, const Derived>
extract_volume_patches(const Index patch_planes, const Index patch_rows, const Index patch_cols,
const Index plane_stride = 1, const Index row_stride = 1, const Index col_stride = 1,
const PaddingType padding_type = PADDING_SAME, const Scalar padding_value = Scalar(0)) const {
return TensorVolumePatchOp<Dynamic, Dynamic, Dynamic, const Derived>(derived(), patch_planes, patch_rows, patch_cols, plane_stride, row_stride, col_stride, 1, 1, 1, 1, 1, 1, padding_type, padding_value);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorVolumePatchOp<Dynamic, Dynamic, Dynamic, const Derived>
extract_volume_patches(const Index patch_planes, const Index patch_rows, const Index patch_cols,
const Index plane_stride, const Index row_stride, const Index col_stride,
const Index plane_inflate_stride, const Index row_inflate_stride, const Index col_inflate_stride,
const Index padding_top_z, const Index padding_bottom_z,
const Index padding_top, const Index padding_bottom,
const Index padding_left, const Index padding_right, const Scalar padding_value = Scalar(0)) const {
return TensorVolumePatchOp<Dynamic, Dynamic, Dynamic, const Derived>(derived(), patch_planes, patch_rows, patch_cols, plane_stride, row_stride, col_stride, 1, 1, 1, plane_inflate_stride, row_inflate_stride, col_inflate_stride, padding_top_z, padding_bottom_z, padding_top, padding_bottom, padding_left, padding_right, padding_value);
}
// Morphing operators.
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorLayoutSwapOp<const Derived>
swap_layout() const {
return TensorLayoutSwapOp<const Derived>(derived());
}
template <typename NewDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReshapingOp<const NewDimensions, const Derived>
reshape(const NewDimensions& newDimensions) const {
return TensorReshapingOp<const NewDimensions, const Derived>(derived(), newDimensions);
}
template <typename StartIndices, typename Sizes> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorSlicingOp<const StartIndices, const Sizes, const Derived>
slice(const StartIndices& startIndices, const Sizes& sizes) const {
return TensorSlicingOp<const StartIndices, const Sizes, const Derived>(derived(), startIndices, sizes);
}
template <typename StartIndices, typename StopIndices, typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides, const Derived>
stridedSlice(const StartIndices& startIndices, const StopIndices& stopIndices, const Strides& strides) const {
return TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides,
const Derived>(derived(), startIndices, stopIndices, strides);
}
template <Index DimId> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorChippingOp<DimId, const Derived>
chip(const Index offset) const {
return TensorChippingOp<DimId, const Derived>(derived(), offset, DimId);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorChippingOp<Dynamic, const Derived>
chip(const Index offset, const Index dim) const {
return TensorChippingOp<Dynamic, const Derived>(derived(), offset, dim);
}
template <typename ReverseDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReverseOp<const ReverseDimensions, const Derived>
reverse(const ReverseDimensions& rev) const {
return TensorReverseOp<const ReverseDimensions, const Derived>(derived(), rev);
}
template <typename PaddingDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorPaddingOp<const PaddingDimensions, const Derived>
pad(const PaddingDimensions& padding) const {
return TensorPaddingOp<const PaddingDimensions, const Derived>(derived(), padding, internal::scalar_cast_op<int, Scalar>()(0));
}
template <typename PaddingDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorPaddingOp<const PaddingDimensions, const Derived>
pad(const PaddingDimensions& padding, const Scalar padding_value) const {
return TensorPaddingOp<const PaddingDimensions, const Derived>(derived(), padding, padding_value);
}
template <typename Shuffle> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorShufflingOp<const Shuffle, const Derived>
shuffle(const Shuffle& shuffle) const {
return TensorShufflingOp<const Shuffle, const Derived>(derived(), shuffle);
}
template <typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorStridingOp<const Strides, const Derived>
stride(const Strides& strides) const {
return TensorStridingOp<const Strides, const Derived>(derived(), strides);
}
template <typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorInflationOp<const Strides, const Derived>
inflate(const Strides& strides) const {
return TensorInflationOp<const Strides, const Derived>(derived(), strides);
}
// Returns a tensor containing index/value tuples
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorIndexTupleOp<const Derived>
index_tuples() const {
return TensorIndexTupleOp<const Derived>(derived());
}
// Support for custom unary and binary operations
template <typename CustomUnaryFunc>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCustomUnaryOp<const CustomUnaryFunc, const Derived> customOp(const CustomUnaryFunc& op) const {
return TensorCustomUnaryOp<const CustomUnaryFunc, const Derived>(derived(), op);
}
template <typename OtherDerived, typename CustomBinaryFunc>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorCustomBinaryOp<const CustomBinaryFunc, const Derived, const OtherDerived> customOp(const OtherDerived& other, const CustomBinaryFunc& op) const {
return TensorCustomBinaryOp<const CustomBinaryFunc, const Derived, const OtherDerived>(derived(), other, op);
}
// Force the evaluation of the expression.
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorForcedEvalOp<const Derived> eval() const {
return TensorForcedEvalOp<const Derived>(derived());
}
protected:
template <typename Scalar, int NumIndices, int Options, typename IndexType> friend class Tensor;
template <typename Scalar, typename Dimensions, int Option, typename IndexTypes> friend class TensorFixedSize;
template <typename OtherDerived, int AccessLevel> friend class TensorBase;
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const Derived& derived() const { return *static_cast<const Derived*>(this); }
};
template<typename Derived, int AccessLevel = internal::accessors_level<Derived>::value>
class TensorBase : public TensorBase<Derived, ReadOnlyAccessors> {
public:
typedef internal::traits<Derived> DerivedTraits;
typedef typename DerivedTraits::Scalar Scalar;
typedef typename DerivedTraits::Index Index;
typedef Scalar CoeffReturnType;
static const int NumDimensions = DerivedTraits::NumDimensions;
template <typename Scalar, int NumIndices, int Options, typename IndexType> friend class Tensor;
template <typename Scalar, typename Dimensions, int Option, typename IndexTypes> friend class TensorFixedSize;
template <typename OtherDerived, int OtherAccessLevel> friend class TensorBase;
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Derived& setZero() {
return setConstant(Scalar(0));
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Derived& setConstant(const Scalar& val) {
return derived() = this->constant(val);
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Derived& setRandom() {
return derived() = this->random();
}
template <typename RandomGenerator> EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Derived& setRandom() {
return derived() = this->template random<RandomGenerator>();
}
#if EIGEN_HAS_VARIADIC_TEMPLATES
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Derived& setValues(
const typename internal::Initializer<Derived, NumDimensions>::InitList& vals) {
TensorEvaluator<Derived, DefaultDevice> eval(derived(), DefaultDevice());
internal::initialize_tensor<Derived, NumDimensions>(eval, vals);
return derived();
}
#endif // EIGEN_HAS_VARIADIC_TEMPLATES
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator+=(const OtherDerived& other) {
return derived() = derived() + other.derived();
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator-=(const OtherDerived& other) {
return derived() = derived() - other.derived();
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator*=(const OtherDerived& other) {
return derived() = derived() * other.derived();
}
template<typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator/=(const OtherDerived& other) {
return derived() = derived() / other.derived();
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorLayoutSwapOp<const Derived>
swap_layout() const {
return TensorLayoutSwapOp<const Derived>(derived());
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
TensorLayoutSwapOp<Derived>
swap_layout() {
return TensorLayoutSwapOp<Derived>(derived());
}
template <typename Axis, typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorConcatenationOp<const Axis, const Derived, const OtherDerived>
concatenate(const OtherDerived& other, const Axis& axis) const {
return TensorConcatenationOp<const Axis, const Derived, const OtherDerived>(derived(), other, axis);
}
template <typename Axis, typename OtherDerived> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
TensorConcatenationOp<const Axis, Derived, OtherDerived>
concatenate(const OtherDerived& other, const Axis& axis) {
return TensorConcatenationOp<const Axis, Derived, OtherDerived>(derived(), other, axis);
}
template <typename NewDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReshapingOp<const NewDimensions, const Derived>
reshape(const NewDimensions& newDimensions) const {
return TensorReshapingOp<const NewDimensions, const Derived>(derived(), newDimensions);
}
template <typename NewDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
TensorReshapingOp<const NewDimensions, Derived>
reshape(const NewDimensions& newDimensions) {
return TensorReshapingOp<const NewDimensions, Derived>(derived(), newDimensions);
}
template <typename StartIndices, typename Sizes> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorSlicingOp<const StartIndices, const Sizes, const Derived>
slice(const StartIndices& startIndices, const Sizes& sizes) const {
return TensorSlicingOp<const StartIndices, const Sizes, const Derived>(derived(), startIndices, sizes);
}
template <typename StartIndices, typename Sizes> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
TensorSlicingOp<const StartIndices, const Sizes, Derived>
slice(const StartIndices& startIndices, const Sizes& sizes) {
return TensorSlicingOp<const StartIndices, const Sizes, Derived>(derived(), startIndices, sizes);
}
template <typename StartIndices, typename StopIndices, typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides, const Derived>
stridedSlice(const StartIndices& startIndices, const StopIndices& stopIndices, const Strides& strides) const {
return TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides,
const Derived>(derived(), startIndices, stopIndices, strides);
}
template <typename StartIndices, typename StopIndices, typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides, Derived>
stridedSlice(const StartIndices& startIndices, const StopIndices& stopIndices, const Strides& strides) {
return TensorStridingSlicingOp<const StartIndices, const StopIndices, const Strides,
Derived>(derived(), startIndices, stopIndices, strides);
}
template <DenseIndex DimId> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorChippingOp<DimId, const Derived>
chip(const Index offset) const {
return TensorChippingOp<DimId, const Derived>(derived(), offset, DimId);
}
template <Index DimId> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
TensorChippingOp<DimId, Derived>
chip(const Index offset) {
return TensorChippingOp<DimId, Derived>(derived(), offset, DimId);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorChippingOp<Dynamic, const Derived>
chip(const Index offset, const Index dim) const {
return TensorChippingOp<Dynamic, const Derived>(derived(), offset, dim);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
TensorChippingOp<Dynamic, Derived>
chip(const Index offset, const Index dim) {
return TensorChippingOp<Dynamic, Derived>(derived(), offset, dim);
}
template <typename ReverseDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorReverseOp<const ReverseDimensions, const Derived>
reverse(const ReverseDimensions& rev) const {
return TensorReverseOp<const ReverseDimensions, const Derived>(derived(), rev);
}
template <typename ReverseDimensions> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
TensorReverseOp<const ReverseDimensions, Derived>
reverse(const ReverseDimensions& rev) {
return TensorReverseOp<const ReverseDimensions, Derived>(derived(), rev);
}
template <typename Shuffle> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorShufflingOp<const Shuffle, const Derived>
shuffle(const Shuffle& shuffle) const {
return TensorShufflingOp<const Shuffle, const Derived>(derived(), shuffle);
}
template <typename Shuffle> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
TensorShufflingOp<const Shuffle, Derived>
shuffle(const Shuffle& shuffle) {
return TensorShufflingOp<const Shuffle, Derived>(derived(), shuffle);
}
template <typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const TensorStridingOp<const Strides, const Derived>
stride(const Strides& strides) const {
return TensorStridingOp<const Strides, const Derived>(derived(), strides);
}
template <typename Strides> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
TensorStridingOp<const Strides, Derived>
stride(const Strides& strides) {
return TensorStridingOp<const Strides, Derived>(derived(), strides);
}
// Select the device on which to evaluate the expression.
template <typename DeviceType>
TensorDevice<Derived, DeviceType> device(const DeviceType& device) {
return TensorDevice<Derived, DeviceType>(device, derived());
}
protected:
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Derived& derived() { return *static_cast<Derived*>(this); }
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const Derived& derived() const { return *static_cast<const Derived*>(this); }
};
} // end namespace Eigen
#endif // EIGEN_CXX11_TENSOR_TENSOR_BASE_H
|
{
"pile_set_name": "Github"
}
|
#
# Copyright (C) 2007-2016 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=curl
PKG_VERSION:=7.60.0
PKG_RELEASE:=3
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.xz
PKG_SOURCE_URL:=https://dl.uxnr.de/mirror/curl/ \
http://curl.mirror.anstey.ca/ \
http://curl.askapache.com/download/ \
https://curl.haxx.se/download/
PKG_HASH:=8736ff8ded89ddf7e926eec7b16f82597d029fc1469f3a551f1fafaac164e6a0
PKG_LICENSE:=MIT
PKG_LICENSE_FILES:=COPYING
PKG_CPE_ID:=cpe:/a:haxx:libcurl
PKG_FIXUP:=autoreconf
PKG_BUILD_PARALLEL:=1
PKG_CONFIG_DEPENDS:= \
CONFIG_IPV6 \
\
CONFIG_LIBCURL_WOLFSSL \
CONFIG_LIBCURL_GNUTLS \
CONFIG_LIBCURL_OPENSSL \
CONFIG_LIBCURL_MBEDTLS \
CONFIG_LIBCURL_NOSSL \
\
CONFIG_LIBCURL_LIBIDN2 \
CONFIG_LIBCURL_SSH2 \
CONFIG_LIBCURL_ZLIB \
\
CONFIG_LIBCURL_DICT \
CONFIG_LIBCURL_FILE \
CONFIG_LIBCURL_FTP \
CONFIG_LIBCURL_GOPHER \
CONFIG_LIBCURL_HTTP \
CONFIG_LIBCURL_IMAP \
CONFIG_LIBCURL_LDAP \
CONFIG_LIBCURL_LDAPS \
CONFIG_LIBCURL_POP3 \
CONFIG_LIBCURL_RTSP \
CONFIG_LIBCURL_NO_RTSP \
CONFIG_LIBCURL_SMB \
CONFIG_LIBCURL_NO_SMB \
CONFIG_LIBCURL_SMTP \
CONFIG_LIBCURL_TELNET \
CONFIG_LIBCURL_TFTP \
CONFIG_LIBCURL_NGHTTP2 \
\
CONFIG_LIBCURL_COOKIES \
CONFIG_LIBCURL_CRYPTO_AUTH \
CONFIG_LIBCURL_LIBCURL_OPTION \
CONFIG_LIBCURL_PROXY \
CONFIG_LIBCURL_THREADED_RESOLVER \
CONFIG_LIBCURL_TLS_SRP \
CONFIG_LIBCURL_UNIX_SOCKETS \
CONFIG_LIBCURL_VERBOSE \
CONFIG_LIBCURL_NTLM
include $(INCLUDE_DIR)/package.mk
define Package/curl/Default
SECTION:=net
CATEGORY:=Network
URL:=http://curl.haxx.se/
MAINTAINER:=Imre Kaloz <kaloz@openwrt.org>
endef
define Package/curl
$(call Package/curl/Default)
SUBMENU:=File Transfer
DEPENDS:=+libcurl
TITLE:=A client-side URL transfer utility
endef
define Package/libcurl
$(call Package/curl/Default)
SECTION:=libs
CATEGORY:=Libraries
DEPENDS:= +LIBCURL_WOLFSSL:libwolfssl +LIBCURL_OPENSSL:libopenssl +LIBCURL_GNUTLS:libgnutls +LIBCURL_MBEDTLS:libmbedtls
DEPENDS += +LIBCURL_ZLIB:zlib +LIBCURL_THREADED_RESOLVER:libpthread +LIBCURL_LDAP:libopenldap +LIBCURL_LIBIDN2:libidn2
DEPENDS += +LIBCURL_SSH2:libssh2 +LIBCURL_NGHTTP2:libnghttp2 +ca-bundle
TITLE:=A client-side URL transfer library
MENU:=1
endef
define Package/libcurl/config
source "$(SOURCE)/Config.in"
endef
TARGET_CFLAGS += $(FPIC) -ffunction-sections -fdata-sections
TARGET_CPPFLAGS += $(if $(CONFIG_LIBCURL_NTLM),,-DCURL_DISABLE_NTLM)
TARGET_LDFLAGS += -Wl,--gc-sections
CONFIGURE_ARGS += \
--disable-debug \
--disable-ares \
--enable-shared \
--enable-static \
--disable-manual \
--without-nss \
--without-libmetalink \
--without-librtmp \
--without-libidn \
--without-ca-path \
--with-ca-bundle=/etc/ssl/certs/ca-certificates.crt \
\
$(call autoconf_bool,CONFIG_IPV6,ipv6) \
\
$(if $(CONFIG_LIBCURL_WOLFSSL),--with-cyassl="$(STAGING_DIR)/usr",--without-cyassl) \
$(if $(CONFIG_LIBCURL_GNUTLS),--with-gnutls="$(STAGING_DIR)/usr",--without-gnutls) \
$(if $(CONFIG_LIBCURL_OPENSSL),--with-ssl="$(STAGING_DIR)/usr",--without-ssl) \
$(if $(CONFIG_LIBCURL_MBEDTLS),--with-mbedtls="$(STAGING_DIR)/usr",--without-mbedtls) \
\
$(if $(CONFIG_LIBCURL_LIBIDN2),--with-libidn2="$(STAGING_DIR)/usr",--without-libidn2) \
$(if $(CONFIG_LIBCURL_SSH2),--with-libssh2="$(STAGING_DIR)/usr",--without-libssh2) \
$(if $(CONFIG_LIBCURL_ZLIB),--with-zlib="$(STAGING_DIR)/usr",--without-zlib) \
$(if $(CONFIG_LIBCURL_NGHTTP2),--with-nghttp2="$(STAGING_DIR)/usr",--without-nghttp2) \
\
$(call autoconf_bool,CONFIG_LIBCURL_DICT,dict) \
$(call autoconf_bool,CONFIG_LIBCURL_FILE,file) \
$(call autoconf_bool,CONFIG_LIBCURL_FTP,ftp) \
$(call autoconf_bool,CONFIG_LIBCURL_GOPHER,gopher) \
$(call autoconf_bool,CONFIG_LIBCURL_HTTP,http) \
$(call autoconf_bool,CONFIG_LIBCURL_IMAP,imap) \
$(call autoconf_bool,CONFIG_LIBCURL_LDAP,ldap) \
$(call autoconf_bool,CONFIG_LIBCURL_LDAPS,ldaps) \
$(call autoconf_bool,CONFIG_LIBCURL_POP3,pop3) \
$(call autoconf_bool,CONFIG_LIBCURL_RTSP,rtsp) \
$(call autoconf_bool,CONFIG_LIBCURL_SMB,smb) \
$(call autoconf_bool,CONFIG_LIBCURL_SMTP,smtp) \
$(call autoconf_bool,CONFIG_LIBCURL_TELNET,telnet) \
$(call autoconf_bool,CONFIG_LIBCURL_TFTP,tftp) \
\
$(call autoconf_bool,CONFIG_LIBCURL_COOKIES,cookies) \
$(call autoconf_bool,CONFIG_LIBCURL_CRYPTO_AUTH,crypto-auth) \
$(call autoconf_bool,CONFIG_LIBCURL_LIBCURL_OPTION,libcurl-option) \
$(call autoconf_bool,CONFIG_LIBCURL_PROXY,proxy) \
$(call autoconf_bool,CONFIG_LIBCURL_THREADED_RESOLVER,threaded-resolver) \
$(call autoconf_bool,CONFIG_LIBCURL_TLS_SRP,tls-srp) \
$(call autoconf_bool,CONFIG_LIBCURL_UNIX_SOCKETS,unix-sockets) \
$(call autoconf_bool,CONFIG_LIBCURL_VERBOSE,verbose) \
define Build/Compile
+$(MAKE) $(PKG_JOBS) -C $(PKG_BUILD_DIR) \
DESTDIR="$(PKG_INSTALL_DIR)" \
CC="$(TARGET_CC)" \
install
endef
define Build/InstallDev
$(INSTALL_DIR) $(2)/bin $(1)/usr/bin $(1)/usr/include $(1)/usr/lib $(1)/usr/lib/pkgconfig
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/curl-config $(1)/usr/bin/
$(CP) $(PKG_INSTALL_DIR)/usr/include/curl $(1)/usr/include/
$(CP) $(PKG_INSTALL_DIR)/usr/lib/libcurl.{a,so*} $(1)/usr/lib/
$(CP) $(PKG_BUILD_DIR)/libcurl.pc $(1)/usr/lib/pkgconfig/
$(SED) 's,-L$$$${exec_prefix}/lib,,g' $(1)/usr/bin/curl-config
[ -n "$(TARGET_LDFLAGS)" ] && $(SED) 's#$(TARGET_LDFLAGS)##g' $(1)/usr/lib/pkgconfig/libcurl.pc || true
$(LN) $(STAGING_DIR)/usr/bin/curl-config $(2)/bin/
endef
define Package/curl/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/curl $(1)/usr/bin/
endef
define Package/libcurl/install
$(INSTALL_DIR) $(1)/usr/lib
$(CP) $(PKG_INSTALL_DIR)/usr/lib/libcurl.so.* $(1)/usr/lib/
endef
$(eval $(call BuildPackage,curl))
$(eval $(call BuildPackage,libcurl))
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env bash
# Copyright 2009 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Generate Go code listing errors and other #defined constant
# values (ENAMETOOLONG etc.), by asking the preprocessor
# about the definitions.
unset LANG
export LC_ALL=C
export LC_CTYPE=C
if test -z "$GOARCH" -o -z "$GOOS"; then
echo 1>&2 "GOARCH or GOOS not defined in environment"
exit 1
fi
# Check that we are using the new build system if we should
if [[ "$GOOS" = "linux" ]] && [[ "$GOARCH" != "sparc64" ]]; then
if [[ "$GOLANG_SYS_BUILD" != "docker" ]]; then
echo 1>&2 "In the new build system, mkerrors should not be called directly."
echo 1>&2 "See README.md"
exit 1
fi
fi
if [[ "$GOOS" = "aix" ]]; then
CC=${CC:-gcc}
else
CC=${CC:-cc}
fi
if [[ "$GOOS" = "solaris" ]]; then
# Assumes GNU versions of utilities in PATH.
export PATH=/usr/gnu/bin:$PATH
fi
uname=$(uname)
includes_AIX='
#include <net/if.h>
#include <net/netopt.h>
#include <netinet/ip_mroute.h>
#include <sys/protosw.h>
#include <sys/stropts.h>
#include <sys/mman.h>
#include <sys/poll.h>
#include <sys/termio.h>
#include <termios.h>
#include <fcntl.h>
#define AF_LOCAL AF_UNIX
'
includes_Darwin='
#define _DARWIN_C_SOURCE
#define KERNEL
#define _DARWIN_USE_64_BIT_INODE
#include <stdint.h>
#include <sys/attr.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/ptrace.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <sys/xattr.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <termios.h>
'
includes_DragonFly='
#include <sys/types.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <net/ip_mroute/ip_mroute.h>
'
includes_FreeBSD='
#include <sys/capability.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <sys/extattr.h>
#if __FreeBSD__ >= 10
#define IFT_CARP 0xf8 // IFT_CARP is deprecated in FreeBSD 10
#undef SIOCAIFADDR
#define SIOCAIFADDR _IOW(105, 26, struct oifaliasreq) // ifaliasreq contains if_data
#undef SIOCSIFPHYADDR
#define SIOCSIFPHYADDR _IOW(105, 70, struct oifaliasreq) // ifaliasreq contains if_data
#endif
'
includes_Linux='
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#ifndef __LP64__
#define _FILE_OFFSET_BITS 64
#endif
#define _GNU_SOURCE
// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of
// these structures. We just include them copied from <bits/termios.h>.
#if defined(__powerpc__)
struct sgttyb {
char sg_ispeed;
char sg_ospeed;
char sg_erase;
char sg_kill;
short sg_flags;
};
struct tchars {
char t_intrc;
char t_quitc;
char t_startc;
char t_stopc;
char t_eofc;
char t_brkc;
};
struct ltchars {
char t_suspc;
char t_dsuspc;
char t_rprntc;
char t_flushc;
char t_werasc;
char t_lnextc;
};
#endif
#include <bits/sockaddr.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/xattr.h>
#include <linux/if.h>
#include <linux/if_alg.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/if_tun.h>
#include <linux/if_packet.h>
#include <linux/if_addr.h>
#include <linux/falloc.h>
#include <linux/filter.h>
#include <linux/fs.h>
#include <linux/kexec.h>
#include <linux/keyctl.h>
#include <linux/magic.h>
#include <linux/memfd.h>
#include <linux/module.h>
#include <linux/netfilter/nfnetlink.h>
#include <linux/netlink.h>
#include <linux/net_namespace.h>
#include <linux/perf_event.h>
#include <linux/random.h>
#include <linux/reboot.h>
#include <linux/rtnetlink.h>
#include <linux/ptrace.h>
#include <linux/sched.h>
#include <linux/seccomp.h>
#include <linux/sockios.h>
#include <linux/wait.h>
#include <linux/icmpv6.h>
#include <linux/serial.h>
#include <linux/can.h>
#include <linux/vm_sockets.h>
#include <linux/taskstats.h>
#include <linux/genetlink.h>
#include <linux/watchdog.h>
#include <linux/hdreg.h>
#include <linux/rtc.h>
#include <linux/if_xdp.h>
#include <mtd/ubi-user.h>
#include <net/route.h>
#include <asm/termbits.h>
#ifndef MSG_FASTOPEN
#define MSG_FASTOPEN 0x20000000
#endif
#ifndef PTRACE_GETREGS
#define PTRACE_GETREGS 0xc
#endif
#ifndef PTRACE_SETREGS
#define PTRACE_SETREGS 0xd
#endif
#ifndef SOL_NETLINK
#define SOL_NETLINK 270
#endif
#ifdef SOL_BLUETOOTH
// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h
// but it is already in bluetooth_linux.go
#undef SOL_BLUETOOTH
#endif
// Certain constants are missing from the fs/crypto UAPI
#define FS_KEY_DESC_PREFIX "fscrypt:"
#define FS_KEY_DESC_PREFIX_SIZE 8
#define FS_MAX_KEY_SIZE 64
// XDP socket constants do not appear to be picked up otherwise.
// Copied from samples/bpf/xdpsock_user.c.
#ifndef SOL_XDP
#define SOL_XDP 283
#endif
#ifndef AF_XDP
#define AF_XDP 44
#endif
'
includes_NetBSD='
#include <sys/types.h>
#include <sys/param.h>
#include <sys/event.h>
#include <sys/extattr.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/termios.h>
#include <sys/ttycom.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <netinet/if_ether.h>
// Needed since <sys/param.h> refers to it...
#define schedppq 1
'
includes_OpenBSD='
#include <sys/types.h>
#include <sys/param.h>
#include <sys/event.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/termios.h>
#include <sys/ttycom.h>
#include <sys/unistd.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/if_var.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <netinet/if_ether.h>
#include <net/if_bridge.h>
// We keep some constants not supported in OpenBSD 5.5 and beyond for
// the promise of compatibility.
#define EMUL_ENABLED 0x1
#define EMUL_NATIVE 0x2
#define IPV6_FAITH 0x1d
#define IPV6_OPTIONS 0x1
#define IPV6_RTHDR_STRICT 0x1
#define IPV6_SOCKOPT_RESERVED1 0x3
#define SIOCGIFGENERIC 0xc020693a
#define SIOCSIFGENERIC 0x80206939
#define WALTSIG 0x4
'
includes_SunOS='
#include <limits.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/mkdev.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
'
includes='
#include <sys/types.h>
#include <sys/file.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <sys/signal.h>
#include <signal.h>
#include <sys/resource.h>
#include <time.h>
'
ccflags="$@"
# Write go tool cgo -godefs input.
(
echo package unix
echo
echo '/*'
indirect="includes_$(uname)"
echo "${!indirect} $includes"
echo '*/'
echo 'import "C"'
echo 'import "syscall"'
echo
echo 'const ('
# The gcc command line prints all the #defines
# it encounters while processing the input
echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags |
awk '
$1 != "#define" || $2 ~ /\(/ || $3 == "" {next}
$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next} # 386 registers
$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}
$2 ~ /^(SCM_SRCRT)$/ {next}
$2 ~ /^(MAP_FAILED)$/ {next}
$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.
$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||
$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}
$2 !~ /^ECCAPBITS/ &&
$2 !~ /^ETH_/ &&
$2 !~ /^EPROC_/ &&
$2 !~ /^EQUIV_/ &&
$2 !~ /^EXPR_/ &&
$2 ~ /^E[A-Z0-9_]+$/ ||
$2 ~ /^B[0-9_]+$/ ||
$2 ~ /^(OLD|NEW)DEV$/ ||
$2 == "BOTHER" ||
$2 ~ /^CI?BAUD(EX)?$/ ||
$2 == "IBSHIFT" ||
$2 ~ /^V[A-Z0-9]+$/ ||
$2 ~ /^CS[A-Z0-9]/ ||
$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||
$2 ~ /^IGN/ ||
$2 ~ /^IX(ON|ANY|OFF)$/ ||
$2 ~ /^IN(LCR|PCK)$/ ||
$2 !~ "X86_CR3_PCID_NOFLUSH" &&
$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||
$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||
$2 == "BRKINT" ||
$2 == "HUPCL" ||
$2 == "PENDIN" ||
$2 == "TOSTOP" ||
$2 == "XCASE" ||
$2 == "ALTWERASE" ||
$2 == "NOKERNINFO" ||
$2 ~ /^PAR/ ||
$2 ~ /^SIG[^_]/ ||
$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||
$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||
$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||
$2 ~ /^O?XTABS$/ ||
$2 ~ /^TC[IO](ON|OFF)$/ ||
$2 ~ /^IN_/ ||
$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||
$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||
$2 ~ /^TP_STATUS_/ ||
$2 ~ /^FALLOC_/ ||
$2 == "ICMPV6_FILTER" ||
$2 == "SOMAXCONN" ||
$2 == "NAME_MAX" ||
$2 == "IFNAMSIZ" ||
$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||
$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||
$2 ~ /^HW_MACHINE$/ ||
$2 ~ /^SYSCTL_VERS/ ||
$2 !~ "MNT_BITS" &&
$2 ~ /^(MS|MNT|UMOUNT)_/ ||
$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||
$2 ~ /^(O|F|E?FD|NAME|S|PTRACE|PT)_/ ||
$2 ~ /^KEXEC_/ ||
$2 ~ /^LINUX_REBOOT_CMD_/ ||
$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||
$2 ~ /^MODULE_INIT_/ ||
$2 !~ "NLA_TYPE_MASK" &&
$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||
$2 ~ /^SIOC/ ||
$2 ~ /^TIOC/ ||
$2 ~ /^TCGET/ ||
$2 ~ /^TCSET/ ||
$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||
$2 !~ "RTF_BITS" &&
$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||
$2 ~ /^BIOC/ ||
$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||
$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||
$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||
$2 ~ /^CLONE_[A-Z_]+/ ||
$2 !~ /^(BPF_TIMEVAL)$/ &&
$2 ~ /^(BPF|DLT)_/ ||
$2 ~ /^CLOCK_/ ||
$2 ~ /^CAN_/ ||
$2 ~ /^CAP_/ ||
$2 ~ /^ALG_/ ||
$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||
$2 ~ /^GRND_/ ||
$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||
$2 ~ /^KEYCTL_/ ||
$2 ~ /^PERF_EVENT_IOC_/ ||
$2 ~ /^SECCOMP_MODE_/ ||
$2 ~ /^SPLICE_/ ||
$2 ~ /^SYNC_FILE_RANGE_/ ||
$2 !~ /^AUDIT_RECORD_MAGIC/ &&
$2 !~ /IOC_MAGIC/ &&
$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||
$2 ~ /^(VM|VMADDR)_/ ||
$2 ~ /^IOCTL_VM_SOCKETS_/ ||
$2 ~ /^(TASKSTATS|TS)_/ ||
$2 ~ /^CGROUPSTATS_/ ||
$2 ~ /^GENL_/ ||
$2 ~ /^STATX_/ ||
$2 ~ /^RENAME/ ||
$2 ~ /^UBI_IOC[A-Z]/ ||
$2 ~ /^UTIME_/ ||
$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||
$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||
$2 ~ /^FSOPT_/ ||
$2 ~ /^WDIOC_/ ||
$2 ~ /^NFN/ ||
$2 ~ /^XDP_/ ||
$2 ~ /^(HDIO|WIN|SMART)_/ ||
$2 !~ "WMESGLEN" &&
$2 ~ /^W[A-Z0-9]+$/ ||
$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf("\t%s = C.%s\n", $2, $2)}
$2 ~ /^__WCOREFLAG$/ {next}
$2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)}
{next}
' | sort
echo ')'
) >_const.go
# Pull out the error names for later.
errors=$(
echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |
sort
)
# Pull out the signal names for later.
signals=$(
echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |
egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |
sort
)
# Again, writing regexps to a file.
echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' |
sort >_error.grep
echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' |
egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |
sort >_signal.grep
echo '// mkerrors.sh' "$@"
echo '// Code generated by the command above; see README.md. DO NOT EDIT.'
echo
echo "// +build ${GOARCH},${GOOS}"
echo
go tool cgo -godefs -- "$@" _const.go >_error.out
cat _error.out | grep -vf _error.grep | grep -vf _signal.grep
echo
echo '// Errors'
echo 'const ('
cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= syscall.Errno(\1)/'
echo ')'
echo
echo '// Signals'
echo 'const ('
cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= syscall.Signal(\1)/'
echo ')'
# Run C program to print error and syscall strings.
(
echo -E "
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include <signal.h>
#define nelem(x) (sizeof(x)/sizeof((x)[0]))
enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below
struct tuple {
int num;
const char *name;
};
struct tuple errors[] = {
"
for i in $errors
do
echo -E ' {'$i', "'$i'" },'
done
echo -E "
};
struct tuple signals[] = {
"
for i in $signals
do
echo -E ' {'$i', "'$i'" },'
done
# Use -E because on some systems bash builtin interprets \n itself.
echo -E '
};
static int
tuplecmp(const void *a, const void *b)
{
return ((struct tuple *)a)->num - ((struct tuple *)b)->num;
}
int
main(void)
{
int i, e;
char buf[1024], *p;
printf("\n\n// Error table\n");
printf("var errorList = [...]struct {\n");
printf("\tnum syscall.Errno\n");
printf("\tname string\n");
printf("\tdesc string\n");
printf("} {\n");
qsort(errors, nelem(errors), sizeof errors[0], tuplecmp);
for(i=0; i<nelem(errors); i++) {
e = errors[i].num;
if(i > 0 && errors[i-1].num == e)
continue;
strcpy(buf, strerror(e));
// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
buf[0] += a - A;
printf("\t{ %d, \"%s\", \"%s\" },\n", e, errors[i].name, buf);
}
printf("}\n\n");
printf("\n\n// Signal table\n");
printf("var signalList = [...]struct {\n");
printf("\tnum syscall.Signal\n");
printf("\tname string\n");
printf("\tdesc string\n");
printf("} {\n");
qsort(signals, nelem(signals), sizeof signals[0], tuplecmp);
for(i=0; i<nelem(signals); i++) {
e = signals[i].num;
if(i > 0 && signals[i-1].num == e)
continue;
strcpy(buf, strsignal(e));
// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
buf[0] += a - A;
// cut trailing : number.
p = strrchr(buf, ":"[0]);
if(p)
*p = '\0';
printf("\t{ %d, \"%s\", \"%s\" },\n", e, signals[i].name, buf);
}
printf("}\n\n");
return 0;
}
'
) >_errors.c
$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out
|
{
"pile_set_name": "Github"
}
|
/**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* 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 the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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.apereo.portal.groups.smartldap;
import java.util.Collections;
import java.util.List;
import org.apereo.portal.groups.IEntityGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class LdapRecord {
private static final Logger logger = LoggerFactory.getLogger(LdapRecord.class);
// Instance Members.
private final IEntityGroup group;
private final List<String> keysOfChildren;
/*
* Public API.
*/
public LdapRecord(IEntityGroup group, List<String> keysOfChildren) {
// Assertions.
if (group == null) {
String msg = "Argument 'group' cannot be null.";
throw new IllegalArgumentException(msg);
}
if (keysOfChildren == null) {
String msg = "Argument 'keysOfChildren' cannot be null.";
throw new IllegalArgumentException(msg);
}
if (logger.isDebugEnabled()) {
String keys = String.join(",", keysOfChildren);
logger.debug(
"Instantiating LdapRecord for group: {}/{} with children: {}",
group.getLocalKey(),
group.getName(),
keys);
}
// Instance Members.
this.group = group;
this.keysOfChildren = Collections.unmodifiableList(keysOfChildren);
}
/**
* <strong>NOTE</strong> two instances of {@link LdapRecord} are equal if the groups they
* contain share the same key.
*/
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof LdapRecord)) {
return false;
}
LdapRecord lr = (LdapRecord) o;
// NB: There is code that relies on this definition of equals()
return lr.getGroup().getKey().equals(getGroup().getKey());
}
public IEntityGroup getGroup() {
return group;
}
public List<String> getKeysOfChildren() {
return keysOfChildren;
}
@Override
public int hashCode() {
return getGroup().getKey().hashCode();
}
}
|
{
"pile_set_name": "Github"
}
|
# created by tools/tclZIC.tcl - do not edit
set TZData(:Asia/Ust-Nera) {
{-9223372036854775808 34374 0 LMT}
{-1579426374 28800 0 YAKT}
{354898800 43200 0 MAGST}
{370699200 39600 0 MAGT}
{386427600 43200 1 MAGST}
{402235200 39600 0 MAGT}
{417963600 43200 1 MAGST}
{433771200 39600 0 MAGT}
{449586000 43200 1 MAGST}
{465318000 39600 0 MAGT}
{481042800 43200 1 MAGST}
{496767600 39600 0 MAGT}
{512492400 43200 1 MAGST}
{528217200 39600 0 MAGT}
{543942000 43200 1 MAGST}
{559666800 39600 0 MAGT}
{575391600 43200 1 MAGST}
{591116400 39600 0 MAGT}
{606841200 43200 1 MAGST}
{622566000 39600 0 MAGT}
{638290800 43200 1 MAGST}
{654620400 39600 0 MAGT}
{670345200 36000 0 MAGMMTT}
{670348800 39600 1 MAGST}
{686073600 36000 0 MAGT}
{695750400 39600 0 MAGMMTT}
{701794800 43200 1 MAGST}
{717519600 39600 0 MAGT}
{733244400 43200 1 MAGST}
{748969200 39600 0 MAGT}
{764694000 43200 1 MAGST}
{780418800 39600 0 MAGT}
{796143600 43200 1 MAGST}
{811868400 39600 0 MAGT}
{828198000 43200 1 MAGST}
{846342000 39600 0 MAGT}
{859647600 43200 1 MAGST}
{877791600 39600 0 MAGT}
{891097200 43200 1 MAGST}
{909241200 39600 0 MAGT}
{922546800 43200 1 MAGST}
{941295600 39600 0 MAGT}
{953996400 43200 1 MAGST}
{972745200 39600 0 MAGT}
{985446000 43200 1 MAGST}
{1004194800 39600 0 MAGT}
{1017500400 43200 1 MAGST}
{1035644400 39600 0 MAGT}
{1048950000 43200 1 MAGST}
{1067094000 39600 0 MAGT}
{1080399600 43200 1 MAGST}
{1099148400 39600 0 MAGT}
{1111849200 43200 1 MAGST}
{1130598000 39600 0 MAGT}
{1143298800 43200 1 MAGST}
{1162047600 39600 0 MAGT}
{1174748400 43200 1 MAGST}
{1193497200 39600 0 MAGT}
{1206802800 43200 1 MAGST}
{1224946800 39600 0 MAGT}
{1238252400 43200 1 MAGST}
{1256396400 39600 0 MAGT}
{1269702000 43200 1 MAGST}
{1288450800 39600 0 MAGT}
{1301151600 43200 0 MAGT}
{1315828800 39600 0 VLAT}
{1414249200 36000 0 VLAT}
}
|
{
"pile_set_name": "Github"
}
|
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright 2015 CANAL+ Group
*
* 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 AssertionError from "../assertion_error";
import EncryptedMediaError from "../encrypted_media_error";
import isKnownError from "../is_known_error";
import MediaError from "../media_error";
import NetworkError from "../network_error";
import OtherError from "../other_error";
import RequestError from "../request_error";
describe("Errors - isKnownError", () => {
it("should return false for a regular error", () => {
expect(isKnownError(new Error("nope")))
.toBe(false);
});
it("should return false for a RequestError", () => {
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com");
const requestError = new RequestError("foo", 23, "TIMEOUT", xhr);
expect(isKnownError(requestError)).toBe(false);
});
it("should return false for an AssertionError", () => {
const assertionError = new AssertionError("foo");
expect(isKnownError(assertionError)).toBe(false);
});
it("should return true for an OtherError", () => {
const otherError = new OtherError("NONE", "tata");
expect(isKnownError(otherError)).toBe(true);
});
it("should return true for a NetworkError", () => {
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com");
const requestError = new RequestError("foo", 44, "ERROR_HTTP_CODE", xhr);
const networkError = new NetworkError("PIPELINE_LOAD_ERROR", requestError);
expect(isKnownError(networkError)).toBe(true);
});
it("should return true for a MediaError", () => {
const mediaError = new MediaError("MEDIA_ERR_DECODE", "toto");
expect(isKnownError(mediaError)).toBe(true);
});
it("should return true for an EncryptedMediaError", () => {
const encryptedMediaError = new EncryptedMediaError("KEY_UPDATE_ERROR", "toto");
expect(isKnownError(encryptedMediaError)).toBe(true);
});
});
|
{
"pile_set_name": "Github"
}
|
## Domain resolution
|
{
"pile_set_name": "Github"
}
|
//
// StrassenMatmulComputor.cpp
// MNN
//
// Created by MNN on 2019/02/11.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "StrassenMatmulComputor.hpp"
#include "backend/cpu/CPUBackend.hpp"
#include <string.h>
#include "ConvOpt.h"
#include <limits.h>
#include "CommonOptFunction.h"
#include "core/Macro.h"
#include "core/Concurrency.h"
//#define MNN_OPEN_TIME_TRACE
#include <MNN/AutoTime.hpp>
#include "math/Vec4.hpp"
#include "math/Matrix.hpp"
using namespace MNN::Math;
extern "C" {
void MNNStrassenMergeCFunction(float* c11, float* c12, float* c21, float* c22, float* xAddr, size_t cStride,
size_t eSub, size_t hSub);
}
#ifndef MNN_USE_NEON
void MNNStrassenMergeCFunction(float* c11, float* c12, float* c21, float* c22, float* xAddr, size_t cStride,
size_t eSub, size_t hSub) {
for (int y=0; y<hSub; ++y) {
auto c11Y = c11 + y * cStride;
auto c12Y = c12 + y * cStride;
auto c22Y = c22 + y * cStride;
auto c21Y = c21 + y * cStride;
auto xY = xAddr + y * eSub * 4;
for (int x=0; x<eSub; ++x) {
auto xv = Vec4::load(xY + 4*x);
auto c21v = Vec4::load(c21Y + 4*x);
auto c11v = Vec4::load(c11Y + 4*x);
auto c22v = Vec4::load(c22Y + 4*x);
auto c12v = Vec4::load(c12Y + 4*x);
c12v = c12v + xv;
c21v = c12v + c21v;
c12v = c22v + c12v;
c22v = c22v + c21v;
c12v = c11v + c12v;
Vec4::save(c12Y + 4*x, c12v);
Vec4::save(c22Y + 4*x, c22v);
Vec4::save(c21Y + 4*x, c21v);
}
}
}
#endif
namespace MNN {
typedef std::shared_ptr<Tensor> PTensor;
class StrassenMatrixComputor::AddTensor {
public:
AddTensor(Tensor* t, Backend* bn, Backend::StorageType storageType = Backend::DYNAMIC) {
mTensor.reset(t);
mValid = bn->onAcquireBuffer(t, storageType);
mBackend = bn;
mStorageType = storageType;
}
inline bool valid() const {
return mValid;
}
~AddTensor() {
mBackend->onReleaseBuffer(mTensor.get(), mStorageType);
}
const Tensor* operator->() const {
return mTensor.get();
}
const Tensor* get() const {
return mTensor.get();
}
private:
std::shared_ptr<Tensor> mTensor;
Backend* mBackend;
bool mValid = false;
Backend::StorageType mStorageType;
};
StrassenMatrixComputor::StrassenMatrixComputor(Backend* bn, bool multithread, int maxDepth) : mBackend(bn) {
mMaxDepth = maxDepth;
mSupportMultiThread = multithread;
};
StrassenMatrixComputor::~StrassenMatrixComputor() {
// Do nothing
}
ErrorCode StrassenMatrixComputor::_generateTrivalMatMul(const Tensor* AT, const Tensor* BT, const Tensor* CT, const Tensor* COT, const std::vector<float>& active) {
// Generate Trival Matrix Multiply
auto e = AT->length(1);
MNN_ASSERT(e > 0);
auto aHost = AT->host<float>();
auto bHost = BT->host<float>();
auto cHost = CT->host<float>();
auto aStride = AT->stride(0);
auto bStride = BT->stride(0);
auto cStride = CT->stride(0);
int eP, lP, hP;
MNNGetMatMulPackMode(&eP, &lP, &hP);
auto numberThread = mSupportMultiThread ? ((CPUBackend*)backend())->threadNumber() : 1;
auto CONVOLUTION_TILED_NUMBER = eP;
auto bExtraStride = bStride - BT->length(1) * BT->length(2);
AddTensor tileBuffer(Tensor::createDevice<float>(std::vector<int>{numberThread, BT->length(1), CONVOLUTION_TILED_NUMBER}), backend());
std::vector<float*> cachePtr(numberThread, nullptr);
if (hP % 4 != 0) {
auto hDiv = MNNGetC4DivNumber(hP);
AddTensor matmulTempBuffer(Tensor::createDevice<float>(std::vector<int>{numberThread, eP * hDiv * 4 + CT->length(0) * eP * 4}), backend());
for (int i=0; i<numberThread; ++i) {
cachePtr[i] = matmulTempBuffer->host<float>() + i * matmulTempBuffer->stride(0);
}
}
auto tileHostOrigin = tileBuffer->host<float>();
int unitNumber = e / CONVOLUTION_TILED_NUMBER;
int xCount = e - unitNumber * CONVOLUTION_TILED_NUMBER;
std::vector<size_t> parameters(6);
auto hMin = std::min(CT->length(0) * 4, BT->length(0) * hP);
parameters[0] = xCount * sizeof(float);
parameters[1] = BT->length(1);
parameters[2] = hMin;
parameters[3] = cStride * sizeof(float);
parameters[4] = 0;
parameters[5] = bExtraStride * sizeof(float);
auto eReal = aStride / AT->length(2);
const float* biasPtr = nullptr;
if (nullptr != COT) {
if (COT != CT) {
biasPtr = COT->host<float>();
}
}
mFunctions.emplace_back(
std::make_pair([xCount, aHost, bHost, cHost, tileHostOrigin, unitNumber, bExtraStride, numberThread, parameters, eReal, CONVOLUTION_TILED_NUMBER, cachePtr, biasPtr, active](int tId) {
auto tileHost = tileHostOrigin + CONVOLUTION_TILED_NUMBER * parameters[1] * tId;
const float* postParametersPtr = nullptr;
if (!active.empty()) {
postParametersPtr = active.data();
}
auto cache = cachePtr[tId];
for (int i = tId; i < unitNumber; i+=numberThread) {
int xStart = i * CONVOLUTION_TILED_NUMBER;
auto aStart = aHost + xStart * 4;
MNNPackC4ForMatMul_A(tileHost, aStart, CONVOLUTION_TILED_NUMBER, parameters[1], eReal);
MNNPackedMatMul(cHost + 4 * xStart, tileHost, bHost, parameters.data(), cache, postParametersPtr, biasPtr);
}
if (tId != numberThread -1) {
return;
}
if (xCount > 0) {
int xStart = unitNumber * CONVOLUTION_TILED_NUMBER;
auto aStart = aHost + xStart * 4;
// Copy
MNNPackC4ForMatMul_A(tileHost, aStart, xCount, parameters[1], eReal);
MNNPackedMatMulRemain(cHost + 4 * xStart, tileHost, bHost, xCount, parameters.data(), cache, postParametersPtr, biasPtr);
}
}, numberThread));
return NO_ERROR;
}
#define MNNMATRIX_SUB_MULTITHREAD(c, a, b, widthC4, cStride, aStride, bStride, lSub) \
for (int y = tId; y < lSub; y+=numberThread) {\
MNNMatrixSub(c + y * cStride, a + y * aStride, b + y * bStride, widthC4, 0, 0, 0, 1);\
}\
#define MNNMATRIX_ADD_MULTITHREAD(c, a, b, widthC4, cStride, aStride, bStride, lSub) \
for (int y = tId; y < lSub; y+=numberThread) {\
MNNMatrixAdd(c + y * cStride, a + y * aStride, b + y * bStride, widthC4, 0, 0, 0, 1);\
}\
ErrorCode StrassenMatrixComputor::_generateMatMul(const Tensor* AT, const Tensor* BT, const Tensor* CT, const Tensor* COT, int currentDepth, const std::vector<float>& postParameters) {
auto l = AT->length(0);
auto e = AT->length(1);
auto h = CT->length(0);
auto lReal = BT->length(1);
static const int aUnit = 4;
auto numberThread = mSupportMultiThread ? ((CPUBackend*)backend())->threadNumber() : 1;
int eP, lP, hP;
MNNGetMatMulPackMode(&eP, &lP, &hP);
auto hDiv = MNNGetC4DivNumber(hP);
auto eSub = (e / eP) / 2 * eP;
auto lSub = l / 2;
auto hSub = (h / hDiv) / 2 * hDiv;
auto remainH = h - hSub * 2;
auto remainE = e - eSub * 2;
if (currentDepth >= mMaxDepth || eSub == 0 || hSub == 0 || lReal % 8 != 0) {
return _generateTrivalMatMul(AT, BT, CT, COT, postParameters);
}
/*
Compute the memory read / write cost for expand
*/
auto bLSub = lSub * 4;
auto bHSub = (hSub * 4) / hP;
float AComputeCost = 4 * ((float)eSub * lSub) * aUnit;
float BComputeCost = 4 * (float)bLSub * bHSub * hP;
float CComputeCost = 7 * (float)eSub * hSub * aUnit;
float saveMatMulCost = (e / eP) * (aUnit * eP * hSub + lSub * eP * aUnit + bLSub * bHSub * hP);
const float pernaty = 1.5f;//FIXME: Find beter way to set it
//MNN_PRINT("%f - %f, %f, %f\n", saveMatMulCost, AComputeCost, BComputeCost, CComputeCost);
float saveCost = saveMatMulCost - (AComputeCost + BComputeCost + CComputeCost) * pernaty;
if (saveCost <= 0.0f) {
return _generateTrivalMatMul(AT, BT, CT, COT, postParameters);
}
// Strassen Construct
auto bn = backend();
currentDepth += 1;
auto bUnit = hP;
auto AS = std::vector<int>{lSub, eSub, aUnit};
auto BS = std::vector<int>{bHSub, bLSub, bUnit};
auto CS = std::vector<int>{hSub, eSub, aUnit};
auto ACS = AS;
if (CS[0] > ACS[0]) {
ACS[0] = CS[0];
}
// Use XReal to contain both AX and CX, that's two cache
AddTensor XReal(Tensor::createDevice<float>(ACS), bn);
AddTensor Y(Tensor::createDevice<float>(BS), bn);
if (!XReal.valid() || !Y.valid()) {
return OUT_OF_MEMORY;
}
PTensor X(Tensor::create<float>(AS, XReal->host<float>()));
PTensor CX(Tensor::create<float>(CS, XReal->host<float>()));
auto xAddr = X->host<float>();
auto yAddr = Y->host<float>();
auto aStride = AT->stride(0);
auto a11 = AT->host<float>() + 0 * aUnit * eSub + 0 * aStride * lSub;
auto a12 = AT->host<float>() + 0 * aUnit * eSub + 1 * aStride * lSub;
auto a21 = AT->host<float>() + 1 * aUnit * eSub + 0 * aStride * lSub;
auto a22 = AT->host<float>() + 1 * aUnit * eSub + 1 * aStride * lSub;
auto bStride = BT->stride(0);
auto b11 = BT->host<float>() + 0 * bUnit * bLSub + 0 * bStride * bHSub;
auto b12 = BT->host<float>() + 0 * bUnit * bLSub + 1 * bStride * bHSub;
auto b21 = BT->host<float>() + 1 * bUnit * bLSub + 0 * bStride * bHSub;
auto b22 = BT->host<float>() + 1 * bUnit * bLSub + 1 * bStride * bHSub;
auto cStride = CT->stride(0);
auto c11 = CT->host<float>() + 0 * aUnit * eSub + 0 * cStride * hSub;
auto c12 = CT->host<float>() + 0 * aUnit * eSub + 1 * cStride * hSub;
auto c21 = CT->host<float>() + 1 * aUnit * eSub + 0 * cStride * hSub;
auto c22 = CT->host<float>() + 1 * aUnit * eSub + 1 * cStride * hSub;
PTensor A11(Tensor::create<float>(AS, a11));
A11->setStride(0, aStride);
PTensor A12(Tensor::create<float>(AS, a12));
A12->setStride(0, aStride);
PTensor A21(Tensor::create<float>(AS, a21));
A21->setStride(0, aStride);
PTensor A22(Tensor::create<float>(AS, a22));
A22->setStride(0, aStride);
PTensor B11(Tensor::create<float>(BS, b11));
B11->setStride(0, bStride);
PTensor B12(Tensor::create<float>(BS, b12));
B12->setStride(0, bStride);
PTensor B21(Tensor::create<float>(BS, b21));
B21->setStride(0, bStride);
PTensor B22(Tensor::create<float>(BS, b22));
B22->setStride(0, bStride);
PTensor C11(Tensor::create<float>(CS, c11));
C11->setStride(0, cStride);
PTensor C12(Tensor::create<float>(CS, c12));
C12->setStride(0, cStride);
PTensor C21(Tensor::create<float>(CS, c21));
C21->setStride(0, cStride);
PTensor C22(Tensor::create<float>(CS, c22));
C22->setStride(0, cStride);
{
// S3=A11-A21, T3=B22-B12, P7=S3*T3
auto f = [a11, a21, b22, b12, xAddr, yAddr, eSub, lSub, hSub, aStride, bStride, numberThread, bUnit, bLSub, bHSub](int tId) {
MNNMATRIX_SUB_MULTITHREAD(xAddr, a11, a21, eSub * aUnit / 4, eSub * aUnit, aStride, aStride, lSub);
MNNMATRIX_SUB_MULTITHREAD(yAddr, b22, b12, bLSub * bUnit / 4, bLSub * bUnit, bStride, bStride, bHSub);
};
mFunctions.emplace_back(std::make_pair(f, numberThread));
auto code = _generateMatMul(X.get(), Y.get(), C21.get(), nullptr, currentDepth, {});
if (code != NO_ERROR) {
return code;
}
}
{
// S1=A21+A22, T1=B12-B11, P5=S1T1
auto f = [a22, a21, b11, b12, xAddr, yAddr, eSub, lSub, hSub, aStride, bStride, numberThread, bUnit, bLSub, bHSub](int tId) {
MNNMATRIX_ADD_MULTITHREAD(xAddr, a21, a22, eSub * aUnit / 4, eSub * aUnit, aStride, aStride, lSub);
MNNMATRIX_SUB_MULTITHREAD(yAddr, b12, b11, bLSub * bUnit / 4, bLSub * bUnit, bStride, bStride, bHSub);
};
mFunctions.emplace_back(std::make_pair(f, numberThread));
auto code = _generateMatMul(X.get(), Y.get(), C22.get(), nullptr, currentDepth, {});
if (code != NO_ERROR) {
return code;
}
}
{
// S2=S1-A11, T2=B22-T1, P6=S2T2
auto f = [a11, b22, xAddr, yAddr, eSub, lSub, hSub, aStride, bStride, numberThread, bUnit, bLSub, bHSub](int tId) {
MNNMATRIX_SUB_MULTITHREAD(xAddr, xAddr, a11, eSub * aUnit / 4, eSub * aUnit, eSub * aUnit, aStride, lSub);
MNNMATRIX_SUB_MULTITHREAD(yAddr, b22, yAddr, bLSub * bUnit / 4, bLSub * bUnit, bStride, bLSub * bUnit, bHSub);
};
mFunctions.emplace_back(std::make_pair(f, numberThread));
auto code = _generateMatMul(X.get(), Y.get(), C12.get(), nullptr, currentDepth, {});
if (code != NO_ERROR) {
return code;
}
}
{
// S4=A12-S2, P3=S4*B22, P1=A11*B11
auto f = [a12, xAddr, eSub, lSub, aStride, numberThread](int tId) {
MNNMATRIX_SUB_MULTITHREAD(xAddr, a12, xAddr, eSub * aUnit / 4, eSub * aUnit, aStride, eSub * aUnit, lSub);
};
mFunctions.emplace_back(std::make_pair(f, numberThread));
auto code = _generateMatMul(X.get(), B22.get(), C11.get(), nullptr, currentDepth, {});
if (code != NO_ERROR) {
return code;
}
code = _generateMatMul(A11.get(), B11.get(), CX.get(), nullptr, currentDepth, {});
if (code != NO_ERROR) {
return code;
}
}
{
// U2=P1+P6, U3=U2+P7, U4=U2+P5, U7=U3+P5
// U5=U4+P3, T4=T2-B21, P4=A22*T4
auto f = [c11, c12, c21, c22, b21, xAddr, yAddr, eSub, lSub, hSub, bStride, cStride, numberThread, bUnit, bHSub, bLSub](int tId) {
for (int y = tId; y < hSub; y+=numberThread) {
MNNStrassenMergeCFunction(c11 + y * cStride, c12 + y * cStride, c21 + y * cStride, c22 + y * cStride, xAddr + y * eSub * 4, 0, eSub, 1);
}
MNNMATRIX_SUB_MULTITHREAD(yAddr, yAddr, b21, bLSub * bUnit / 4, bLSub * bUnit, bLSub * bUnit, bStride, bHSub);
};
mFunctions.emplace_back(std::make_pair(f, numberThread));
auto code = _generateMatMul(A22.get(), Y.get(), C11.get(), nullptr, currentDepth, {});
if (code != NO_ERROR) {
return code;
}
}
{
// U6=U3-P4, P2=A12*B21, U1=P1+P2
auto f0 = [c11, c21, eSub, hSub, cStride, numberThread](int tId) {
auto cw = eSub * aUnit / 4;
MNNMATRIX_SUB_MULTITHREAD(c21, c21, c11, cw, cStride, cStride, cStride, hSub);
};
mFunctions.emplace_back(std::make_pair(f0, numberThread));
auto code = _generateMatMul(A12.get(), B21.get(), C11.get(), nullptr, currentDepth, {});
if (code != NO_ERROR) {
return code;
}
auto f1 = [c11, xAddr, eSub, hSub, cStride, numberThread](int tId) {
auto cw = eSub * aUnit / 4;
MNNMATRIX_ADD_MULTITHREAD(c11, c11, xAddr, cw, cStride, cStride, eSub * aUnit, hSub);
};
mFunctions.emplace_back(std::make_pair(f1, numberThread));
if (!postParameters.empty() && nullptr != COT) {
auto biasPtr = COT->host<float>();
if (1 == numberThread) {
auto postFunction = [c11, eSub, hSub, cStride, numberThread, biasPtr, postParameters](int tId) {
auto width = eSub * 2;
auto height = hSub * 2;
MNNAxByClampBroadcastC4(c11, c11, biasPtr, width, cStride, cStride, height, postParameters.data());
};
mFunctions.emplace_back(std::make_pair(postFunction, numberThread));
} else {
auto postFunction = [c11, eSub, hSub, cStride, numberThread, biasPtr, postParameters](int tId) {
auto width = eSub * 2;
auto height = hSub * 2;
for (int y = tId; y < height; y+=numberThread) {
MNNAxByClampBroadcastC4(c11 + y * cStride, c11 + y * cStride, biasPtr + y * 4, width, 0, 0, 1, postParameters.data());
}
};
mFunctions.emplace_back(std::make_pair(postFunction, numberThread));
}
}
}
if (remainH > 0) {
auto lastH = hSub * 2;
auto cLast = CT->host<float>() + cStride * lastH;
auto lastHB = bHSub * 2;
auto bLast = BT->host<float>() + bStride * lastHB;
PTensor BLast(Tensor::create<float>(std::vector<int>{BT->length(0) - lastHB, BT->length(1), bUnit}, bLast));
PTensor CLast(Tensor::create<float>(std::vector<int>{remainH, eSub * 2, aUnit}, cLast));
PTensor ALast(Tensor::create<float>(std::vector<int>{l, eSub * 2, aUnit}, AT->host<float>()));
PTensor biasWrap;
const Tensor* bias = COT;
if (nullptr != bias) {
biasWrap.reset(Tensor::create<float>(std::vector<int>{remainH, 1, aUnit}, COT->host<float>() + 4 * lastH));
bias = biasWrap.get();
}
BLast->setStride(0, bStride);
CLast->setStride(0, cStride);
ALast->setStride(0, aStride);
auto code = _generateTrivalMatMul(AT, BLast.get(), CLast.get(), bias, postParameters);
if (NO_ERROR != code) {
return code;
}
}
if (remainE > 0) {
auto aLast = AT->host<float>() + eSub * 2 * aUnit;
auto cLast = CT->host<float>() + eSub * 2 * aUnit;
PTensor ALast(Tensor::create<float>(std::vector<int>{l, remainE, aUnit}, aLast));
PTensor CLast(Tensor::create<float>(std::vector<int>{h, remainE, aUnit}, cLast));
ALast->setStride(0, aStride);
CLast->setStride(0, cStride);
auto code = _generateTrivalMatMul(ALast.get(), BT, CLast.get(), COT, postParameters);
if (NO_ERROR != code) {
return code;
}
}
return NO_ERROR;
}
void StrassenMatrixComputor::onReset() {
mFunctions.clear();
}
ErrorCode StrassenMatrixComputor::onEncode(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, const std::vector<float>& postParameters) {
MNN_ASSERT(inputs.size() == 2 || inputs.size() == 3);
MNN_ASSERT(outputs.size() == 1);
auto A = inputs[0];
auto BT = inputs[1];
auto C = outputs[0];
Tensor* CO = nullptr;
if (inputs.size() > 2) {
CO = inputs[2];
}
return _generateMatMul(A, BT, C, CO, 0, postParameters);
}
void StrassenMatrixComputor::onExecute() {
// All is done in onResize, just execute it
for (auto& f : mFunctions) {
MNN_CONCURRENCY_BEGIN(tId, f.second) {
f.first(tId);
}
MNN_CONCURRENCY_END();
}
}
} // namespace MNN
|
{
"pile_set_name": "Github"
}
|
StartChar: uni0477
Encoding: 1143 1143 2227
Width: 1000
VWidth: 0
Flags: M
LayerCount: 2
Fore
Refer: 2018 783 N 1 0 0 1 145 0 2
Refer: 2121 1141 N 1 0 0 1 0 0 3
EndChar
|
{
"pile_set_name": "Github"
}
|
package ch.cyberduck.core.dav;
/*
* Copyright (c) 2002-2016 iterate GmbH. All rights reserved.
* https://cyberduck.io/
*
* 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.
*/
import ch.cyberduck.core.DefaultIOExceptionMappingService;
import ch.cyberduck.core.Path;
import ch.cyberduck.core.exception.BackgroundException;
import ch.cyberduck.core.features.Quota;
import ch.cyberduck.core.shared.DefaultHomeFinderService;
import ch.cyberduck.core.worker.DefaultExceptionMappingService;
import java.io.IOException;
import com.github.sardine.DavQuota;
import com.github.sardine.impl.SardineException;
public class DAVQuotaFeature implements Quota {
private final DAVSession session;
public DAVQuotaFeature(final DAVSession session) {
this.session = session;
}
@Override
public Space get() throws BackgroundException {
final Path home = new DefaultHomeFinderService(session).find();
try {
final DavQuota quota = session.getClient().getQuota(new DAVPathEncoder().encode(home));
return new Space(
quota.getQuotaUsedBytes() > 0 ? quota.getQuotaUsedBytes() : 0,
quota.getQuotaAvailableBytes() >= 0 ? quota.getQuotaAvailableBytes() : Long.MAX_VALUE
);
}
catch(SardineException e) {
throw new DAVExceptionMappingService().map("Failure to read attributes of {0}", e, home);
}
catch(IOException e) {
throw new DefaultIOExceptionMappingService().map(e, home);
}
catch(NumberFormatException e) {
throw new DefaultExceptionMappingService().map(e);
}
}
}
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env escript
%%! -pz ./deps/amqp_client/ebin ./deps/rabbit_common/ebin ./deps/amqp_client/ebin ./deps/rabbit_common/ebin ./deps/recon/ebin ./deps/lager/ebin ./deps/goldrush/ebin ./deps/jsx/ebin ./deps/ranch/ebin
-include_lib("amqp_client/include/amqp_client.hrl").
main(Argv) ->
{ok, Connection} =
amqp_connection:start(#amqp_params_network{host = "localhost"}),
{ok, Channel} = amqp_connection:open_channel(Connection),
amqp_channel:call(Channel, #'exchange.declare'{exchange = <<"direct_logs">>,
type = <<"direct">>}),
#'queue.declare_ok'{queue = Queue} =
amqp_channel:call(Channel, #'queue.declare'{exclusive = true}),
[amqp_channel:call(Channel, #'queue.bind'{exchange = <<"direct_logs">>,
routing_key = list_to_binary(Severity),
queue = Queue})
|| Severity <- Argv],
io:format(" [*] Waiting for logs. To exit press CTRL+C~n"),
amqp_channel:subscribe(Channel, #'basic.consume'{queue = Queue,
no_ack = true}, self()),
receive
#'basic.consume_ok'{} -> ok
end,
loop(Channel).
loop(Channel) ->
receive
{#'basic.deliver'{routing_key = RoutingKey}, #amqp_msg{payload = Body}} ->
io:format(" [x] ~p:~p~n", [RoutingKey, Body]),
loop(Channel)
end.
|
{
"pile_set_name": "Github"
}
|
#ifndef STD_TCG_H
#define STD_TCG_H
#include "types.h"
#define SHA1_BUFSIZE 20
#define SHA256_BUFSIZE 32
#define SHA384_BUFSIZE 48
#define SHA512_BUFSIZE 64
#define SM3_256_BUFSIZE 32
/****************************************************************
* 16bit BIOS interface
****************************************************************/
/* Define for section 12.3 */
#define TCG_PC_OK 0x0
#define TCG_PC_TPMERROR 0x1
#define TCG_PC_LOGOVERFLOW 0x2
#define TCG_PC_UNSUPPORTED 0x3
#define TPM_ALG_SHA 0x4
#define TCG_MAGIC 0x41504354L
#define TCG_VERSION_MAJOR 1
#define TCG_VERSION_MINOR 2
#define TPM_OK 0x0
#define TPM_RET_BASE 0x1
#define TCG_GENERAL_ERROR (TPM_RET_BASE + 0x0)
#define TCG_TPM_IS_LOCKED (TPM_RET_BASE + 0x1)
#define TCG_NO_RESPONSE (TPM_RET_BASE + 0x2)
#define TCG_INVALID_RESPONSE (TPM_RET_BASE + 0x3)
#define TCG_INVALID_ACCESS_REQUEST (TPM_RET_BASE + 0x4)
#define TCG_FIRMWARE_ERROR (TPM_RET_BASE + 0x5)
#define TCG_INTEGRITY_CHECK_FAILED (TPM_RET_BASE + 0x6)
#define TCG_INVALID_DEVICE_ID (TPM_RET_BASE + 0x7)
#define TCG_INVALID_VENDOR_ID (TPM_RET_BASE + 0x8)
#define TCG_UNABLE_TO_OPEN (TPM_RET_BASE + 0x9)
#define TCG_UNABLE_TO_CLOSE (TPM_RET_BASE + 0xa)
#define TCG_RESPONSE_TIMEOUT (TPM_RET_BASE + 0xb)
#define TCG_INVALID_COM_REQUEST (TPM_RET_BASE + 0xc)
#define TCG_INVALID_ADR_REQUEST (TPM_RET_BASE + 0xd)
#define TCG_WRITE_BYTE_ERROR (TPM_RET_BASE + 0xe)
#define TCG_READ_BYTE_ERROR (TPM_RET_BASE + 0xf)
#define TCG_BLOCK_WRITE_TIMEOUT (TPM_RET_BASE + 0x10)
#define TCG_CHAR_WRITE_TIMEOUT (TPM_RET_BASE + 0x11)
#define TCG_CHAR_READ_TIMEOUT (TPM_RET_BASE + 0x12)
#define TCG_BLOCK_READ_TIMEOUT (TPM_RET_BASE + 0x13)
#define TCG_TRANSFER_ABORT (TPM_RET_BASE + 0x14)
#define TCG_INVALID_DRV_FUNCTION (TPM_RET_BASE + 0x15)
#define TCG_OUTPUT_BUFFER_TOO_SHORT (TPM_RET_BASE + 0x16)
#define TCG_FATAL_COM_ERROR (TPM_RET_BASE + 0x17)
#define TCG_INVALID_INPUT_PARA (TPM_RET_BASE + 0x18)
#define TCG_TCG_COMMAND_ERROR (TPM_RET_BASE + 0x19)
#define TCG_INTERFACE_SHUTDOWN (TPM_RET_BASE + 0x20)
//define TCG_PC_UNSUPPORTED (TPM_RET_BASE + 0x21)
#define TCG_PC_TPM_NOT_PRESENT (TPM_RET_BASE + 0x22)
#define TCG_PC_TPM_DEACTIVATED (TPM_RET_BASE + 0x23)
/* interrupt identifiers (al register) */
enum irq_ids {
TCG_StatusCheck = 0,
TCG_HashLogExtendEvent = 1,
TCG_PassThroughToTPM = 2,
TCG_ShutdownPreBootInterface = 3,
TCG_HashLogEvent = 4,
TCG_HashAll = 5,
TCG_TSS = 6,
TCG_CompactHashLogExtendEvent = 7,
};
/* Input and Output blocks for the TCG BIOS commands */
struct hleei_short
{
u16 ipblength;
u16 reserved;
const void *hashdataptr;
u32 hashdatalen;
u32 pcrindex;
const void *logdataptr;
u32 logdatalen;
} PACKED;
struct hleei_long
{
u16 ipblength;
u16 reserved;
void *hashdataptr;
u32 hashdatalen;
u32 pcrindex;
u32 reserved2;
void *logdataptr;
u32 logdatalen;
} PACKED;
struct hleeo
{
u16 opblength;
u16 reserved;
u32 eventnumber;
u8 digest[SHA1_BUFSIZE];
} PACKED;
struct pttti
{
u16 ipblength;
u16 reserved;
u16 opblength;
u16 reserved2;
u8 tpmopin[0];
} PACKED;
struct pttto
{
u16 opblength;
u16 reserved;
u8 tpmopout[0];
};
struct hlei
{
u16 ipblength;
u16 reserved;
const void *hashdataptr;
u32 hashdatalen;
u32 pcrindex;
u32 logeventtype;
const void *logdataptr;
u32 logdatalen;
} PACKED;
struct hleo
{
u16 opblength;
u16 reserved;
u32 eventnumber;
} PACKED;
struct hai
{
u16 ipblength;
u16 reserved;
const void *hashdataptr;
u32 hashdatalen;
u32 algorithmid;
} PACKED;
struct ti
{
u16 ipblength;
u16 reserved;
u16 opblength;
u16 reserved2;
u8 tssoperandin[0];
} PACKED;
struct to
{
u16 opblength;
u16 reserved;
u8 tssoperandout[0];
} PACKED;
struct pcpes
{
u32 pcrindex;
u32 eventtype;
u8 digest[SHA1_BUFSIZE];
u32 eventdatasize;
u8 event[0];
} PACKED;
/****************************************************************
* TPM v1.2 hardware commands
****************************************************************/
#define TPM_ORD_SelfTestFull 0x00000050
#define TPM_ORD_ForceClear 0x0000005d
#define TPM_ORD_GetCapability 0x00000065
#define TPM_ORD_PhysicalEnable 0x0000006f
#define TPM_ORD_PhysicalDisable 0x00000070
#define TPM_ORD_SetOwnerInstall 0x00000071
#define TPM_ORD_PhysicalSetDeactivated 0x00000072
#define TPM_ORD_SetTempDeactivated 0x00000073
#define TPM_ORD_Startup 0x00000099
#define TPM_ORD_PhysicalPresence 0x4000000a
#define TPM_ORD_Extend 0x00000014
#define TSC_ORD_ResetEstablishmentBit 0x4000000b
#define TPM_ST_CLEAR 0x0001
#define TPM_ST_STATE 0x0002
#define TPM_ST_DEACTIVATED 0x0003
#define TPM_PP_CMD_ENABLE 0x0020
#define TPM_PP_PRESENT 0x0008
#define TPM_PP_NOT_PRESENT_LOCK 0x0014
/* TPM command error codes */
#define TPM_INVALID_POSTINIT 0x26
#define TPM_BAD_LOCALITY 0x3d
/* TPM command tags */
#define TPM_TAG_RQU_CMD 0x00c1
#define TPM_TAG_RQU_AUTH1_CMD 0x00c2
#define TPM_TAG_RQU_AUTH2_CMD 0x00c3
struct tpm_req_header {
u16 tag;
u32 totlen;
u32 ordinal;
} PACKED;
struct tpm_rsp_header {
u16 tag;
u32 totlen;
u32 errcode;
} PACKED;
struct tpm_req_extend {
struct tpm_req_header hdr;
u32 pcrindex;
u8 digest[SHA1_BUFSIZE];
} PACKED;
struct tpm_rsp_extend {
struct tpm_rsp_header hdr;
u8 digest[SHA1_BUFSIZE];
} PACKED;
struct tpm_req_getcap {
struct tpm_req_header hdr;
u32 capArea;
u32 subCapSize;
u32 subCap;
} PACKED;
#define TPM_CAP_FLAG 0x04
#define TPM_CAP_PROPERTY 0x05
#define TPM_CAP_FLAG_PERMANENT 0x108
#define TPM_CAP_FLAG_VOLATILE 0x109
#define TPM_CAP_PROP_OWNER 0x111
#define TPM_CAP_PROP_TIS_TIMEOUT 0x115
#define TPM_CAP_PROP_DURATION 0x120
struct tpm_permanent_flags {
u16 tag;
u8 flags[20];
} PACKED;
enum permFlagsIndex {
PERM_FLAG_IDX_DISABLE = 0,
PERM_FLAG_IDX_OWNERSHIP,
PERM_FLAG_IDX_DEACTIVATED,
PERM_FLAG_IDX_READPUBEK,
PERM_FLAG_IDX_DISABLEOWNERCLEAR,
PERM_FLAG_IDX_ALLOW_MAINTENANCE,
PERM_FLAG_IDX_PHYSICAL_PRESENCE_LIFETIME_LOCK,
PERM_FLAG_IDX_PHYSICAL_PRESENCE_HW_ENABLE,
PERM_FLAG_IDX_PHYSICAL_PRESENCE_CMD_ENABLE,
};
struct tpm_res_getcap_perm_flags {
struct tpm_rsp_header hdr;
u32 size;
struct tpm_permanent_flags perm_flags;
} PACKED;
struct tpm_stclear_flags {
u16 tag;
u8 flags[5];
} PACKED;
#define STCLEAR_FLAG_IDX_DEACTIVATED 0
#define STCLEAR_FLAG_IDX_DISABLE_FORCE_CLEAR 1
#define STCLEAR_FLAG_IDX_PHYSICAL_PRESENCE 2
#define STCLEAR_FLAG_IDX_PHYSICAL_PRESENCE_LOCK 3
#define STCLEAR_FLAG_IDX_GLOBAL_LOCK 4
struct tpm_res_getcap_stclear_flags {
struct tpm_rsp_header hdr;
u32 size;
struct tpm_stclear_flags stclear_flags;
} PACKED;
struct tpm_res_getcap_ownerauth {
struct tpm_rsp_header hdr;
u32 size;
u8 flag;
} PACKED;
struct tpm_res_getcap_timeouts {
struct tpm_rsp_header hdr;
u32 size;
u32 timeouts[4];
} PACKED;
struct tpm_res_getcap_durations {
struct tpm_rsp_header hdr;
u32 size;
u32 durations[3];
} PACKED;
struct tpm_res_sha1start {
struct tpm_rsp_header hdr;
u32 max_num_bytes;
} PACKED;
struct tpm_res_sha1complete {
struct tpm_rsp_header hdr;
u8 hash[20];
} PACKED;
/****************************************************************
* TPM v2.0 hardware commands
****************************************************************/
#define TPM2_NO 0
#define TPM2_YES 1
#define TPM2_SU_CLEAR 0x0000
#define TPM2_SU_STATE 0x0001
#define TPM2_RH_OWNER 0x40000001
#define TPM2_RS_PW 0x40000009
#define TPM2_RH_ENDORSEMENT 0x4000000b
#define TPM2_RH_PLATFORM 0x4000000c
#define TPM2_ALG_SHA1 0x0004
#define TPM2_ALG_SHA256 0x000b
#define TPM2_ALG_SHA384 0x000c
#define TPM2_ALG_SHA512 0x000d
#define TPM2_ALG_SM3_256 0x0012
/* TPM 2 command tags */
#define TPM2_ST_NO_SESSIONS 0x8001
#define TPM2_ST_SESSIONS 0x8002
/* TPM 2 commands */
#define TPM2_CC_HierarchyControl 0x121
#define TPM2_CC_Clear 0x126
#define TPM2_CC_ClearControl 0x127
#define TPM2_CC_HierarchyChangeAuth 0x129
#define TPM2_CC_SelfTest 0x143
#define TPM2_CC_Startup 0x144
#define TPM2_CC_StirRandom 0x146
#define TPM2_CC_GetCapability 0x17a
#define TPM2_CC_GetRandom 0x17b
#define TPM2_CC_PCR_Extend 0x182
/* TPM 2 error codes */
#define TPM2_RC_INITIALIZE 0x100
/* TPM 2 Capabilities */
#define TPM2_CAP_PCRS 0x00000005
/* TPM 2 data structures */
struct tpm2_req_stirrandom {
struct tpm_req_header hdr;
u16 size;
u64 stir;
} PACKED;
struct tpm2_req_getrandom {
struct tpm_req_header hdr;
u16 bytesRequested;
} PACKED;
struct tpm2b_20 {
u16 size;
u8 buffer[20];
} PACKED;
struct tpm2_res_getrandom {
struct tpm_rsp_header hdr;
struct tpm2b_20 rnd;
} PACKED;
struct tpm2_authblock {
u32 handle;
u16 noncesize; /* always 0 */
u8 contsession; /* always TPM2_YES */
u16 pwdsize; /* always 0 */
} PACKED;
struct tpm2_req_hierarchychangeauth {
struct tpm_req_header hdr;
u32 authhandle;
u32 authblocksize;
struct tpm2_authblock authblock;
struct tpm2b_20 newAuth;
} PACKED;
struct tpm2_req_extend {
struct tpm_req_header hdr;
u32 pcrindex;
u32 authblocksize;
struct tpm2_authblock authblock;
u8 digest[0];
} PACKED;
struct tpm2_req_clearcontrol {
struct tpm_req_header hdr;
u32 authhandle;
u32 authblocksize;
struct tpm2_authblock authblock;
u8 disable;
} PACKED;
struct tpm2_req_clear {
struct tpm_req_header hdr;
u32 authhandle;
u32 authblocksize;
struct tpm2_authblock authblock;
} PACKED;
struct tpm2_req_hierarchycontrol {
struct tpm_req_header hdr;
u32 authhandle;
u32 authblocksize;
struct tpm2_authblock authblock;
u32 enable;
u8 state;
} PACKED;
struct tpm2_req_getcapability {
struct tpm_req_header hdr;
u32 capability;
u32 property;
u32 propertycount;
} PACKED;
struct tpm2_res_getcapability {
struct tpm_rsp_header hdr;
u8 moreData;
u32 capability;
u8 data[0]; /* capability dependent data */
} PACKED;
struct tpms_pcr_selection {
u16 hashAlg;
u8 sizeOfSelect;
u8 pcrSelect[0];
} PACKED;
struct tpml_pcr_selection {
u32 count;
struct tpms_pcr_selection selections[0];
} PACKED;
/****************************************************************
* ACPI TCPA table interface
****************************************************************/
/* event types: 10.4.1 / table 11 */
#define EV_POST_CODE 1
#define EV_NO_ACTION 3
#define EV_SEPARATOR 4
#define EV_ACTION 5
#define EV_EVENT_TAG 6
#define EV_COMPACT_HASH 12
#define EV_IPL 13
#define EV_IPL_PARTITION_DATA 14
struct tpm2_digest_value {
u16 hashAlg;
u8 hash[0]; /* size depends on hashAlg */
} PACKED;
struct tpm2_digest_values {
u32 count;
struct tpm2_digest_value digest[0];
} PACKED;
// Each entry in the TPM log contains: a tpm_log_header, a variable
// length digest, a tpm_log_trailer, and a variable length event. The
// 'digest' matches what is sent to the TPM hardware via the Extend
// command. On TPM1.2 the digest is a SHA1 hash; on TPM2.0 the digest
// contains a tpm2_digest_values struct followed by a variable number
// of tpm2_digest_value structs (as specified by the hardware via the
// TPM2_CAP_PCRS request).
struct tpm_log_header {
u32 pcrindex;
u32 eventtype;
u8 digest[0];
} PACKED;
struct tpm_log_trailer {
u32 eventdatasize;
u8 event[0];
} PACKED;
struct TCG_EfiSpecIdEventStruct {
u8 signature[16];
u32 platformClass;
u8 specVersionMinor;
u8 specVersionMajor;
u8 specErrata;
u8 uintnSize;
u32 numberOfAlgorithms;
struct TCG_EfiSpecIdEventAlgorithmSize {
u16 algorithmId;
u16 digestSize;
} digestSizes[0];
/*
u8 vendorInfoSize;
u8 vendorInfo[0];
*/
} PACKED;
#define TPM_TCPA_ACPI_CLASS_CLIENT 0
struct pcctes
{
u32 eventid;
u32 eventdatasize;
u8 digest[SHA1_BUFSIZE];
} PACKED;
struct pcctes_romex
{
u32 eventid;
u32 eventdatasize;
u16 reserved;
u16 pfa;
u8 digest[SHA1_BUFSIZE];
} PACKED;
/****************************************************************
* Physical presence interface
****************************************************************/
#define TPM_STATE_ENABLED 1
#define TPM_STATE_ACTIVE 2
#define TPM_STATE_OWNED 4
#define TPM_STATE_OWNERINSTALL 8
#define TPM_PPI_OP_NOOP 0
#define TPM_PPI_OP_ENABLE 1
#define TPM_PPI_OP_DISABLE 2
#define TPM_PPI_OP_ACTIVATE 3
#define TPM_PPI_OP_DEACTIVATE 4
#define TPM_PPI_OP_CLEAR 5
#define TPM_PPI_OP_SET_OWNERINSTALL_TRUE 8
#define TPM_PPI_OP_SET_OWNERINSTALL_FALSE 9
#endif // tcg.h
|
{
"pile_set_name": "Github"
}
|
#pragma once
#include <Common/HashTable/HashTable.h>
namespace DB
{
namespace ErrorCodes
{
extern const int NO_AVAILABLE_DATA;
}
}
template <typename Key, typename TState = HashTableNoState>
struct FixedHashTableCell
{
using State = TState;
using value_type = Key;
using mapped_type = VoidMapped;
bool full;
FixedHashTableCell() {}
FixedHashTableCell(const Key &, const State &) : full(true) {}
const VoidKey getKey() const { return {}; }
VoidMapped getMapped() const { return {}; }
bool isZero(const State &) const { return !full; }
void setZero() { full = false; }
static constexpr bool need_zero_value_storage = false;
/// This Cell is only stored inside an iterator. It's used to accommodate the fact
/// that the iterator based API always provide a reference to a continuous memory
/// containing the Key. As a result, we have to instantiate a real Key field.
/// All methods that return a mutable reference to the Key field are named with
/// -Mutable suffix, indicating this is uncommon usage. As this is only for lookup
/// tables, it's totally fine to discard the Key mutations.
struct CellExt
{
Key key;
const VoidKey getKey() const { return {}; }
VoidMapped getMapped() const { return {}; }
const value_type & getValue() const { return key; }
void update(Key && key_, FixedHashTableCell *) { key = key_; }
};
};
/// How to obtain the size of the table.
template <typename Cell>
struct FixedHashTableStoredSize
{
size_t m_size = 0;
size_t getSize(const Cell *, const typename Cell::State &, size_t) const { return m_size; }
bool isEmpty(const Cell *, const typename Cell::State &, size_t) const { return m_size == 0; }
void increaseSize() { ++m_size; }
void clearSize() { m_size = 0; }
void setSize(size_t to) { m_size = to; }
};
template <typename Cell>
struct FixedHashTableCalculatedSize
{
size_t getSize(const Cell * buf, const typename Cell::State & state, size_t num_cells) const
{
size_t res = 0;
for (const Cell * end = buf + num_cells; buf != end; ++buf)
if (!buf->isZero(state))
++res;
return res;
}
bool isEmpty(const Cell * buf, const typename Cell::State & state, size_t num_cells) const
{
for (const Cell * end = buf + num_cells; buf != end; ++buf)
if (!buf->isZero(state))
return false;
return true;
}
void increaseSize() {}
void clearSize() {}
void setSize(size_t) {}
};
/** Used as a lookup table for small keys such as UInt8, UInt16. It's different
* than a HashTable in that keys are not stored in the Cell buf, but inferred
* inside each iterator. There are a bunch of to make it faster than using
* HashTable: a) It doesn't have a conflict chain; b) There is no key
* comparison; c) The number of cycles for checking cell empty is halved; d)
* Memory layout is tighter, especially the Clearable variants.
*
* NOTE: For Set variants this should always be better. For Map variants
* however, as we need to assemble the real cell inside each iterator, there
* might be some cases we fall short.
*
* TODO: Deprecate the cell API so that end users don't rely on the structure
* of cell. Instead iterator should be used for operations such as cell
* transfer, key updates (f.g. StringRef) and serde. This will allow
* TwoLevelHashSet(Map) to contain different type of sets(maps).
*/
template <typename Key, typename Cell, typename Size, typename Allocator>
class FixedHashTable : private boost::noncopyable, protected Allocator, protected Cell::State, protected Size
{
static constexpr size_t NUM_CELLS = 1ULL << (sizeof(Key) * 8);
protected:
friend class const_iterator;
friend class iterator;
friend class Reader;
using Self = FixedHashTable;
Cell * buf; /// A piece of memory for all elements.
void alloc() { buf = reinterpret_cast<Cell *>(Allocator::alloc(NUM_CELLS * sizeof(Cell))); }
void free()
{
if (buf)
{
Allocator::free(buf, getBufferSizeInBytes());
buf = nullptr;
}
}
void destroyElements()
{
if (!std::is_trivially_destructible_v<Cell>)
for (iterator it = begin(), it_end = end(); it != it_end; ++it)
it.ptr->~Cell();
}
template <typename Derived, bool is_const>
class iterator_base
{
using Container = std::conditional_t<is_const, const Self, Self>;
using cell_type = std::conditional_t<is_const, const Cell, Cell>;
Container * container;
cell_type * ptr;
friend class FixedHashTable;
public:
iterator_base() {}
iterator_base(Container * container_, cell_type * ptr_) : container(container_), ptr(ptr_)
{
cell.update(ptr - container->buf, ptr);
}
bool operator==(const iterator_base & rhs) const { return ptr == rhs.ptr; }
bool operator!=(const iterator_base & rhs) const { return ptr != rhs.ptr; }
Derived & operator++()
{
++ptr;
/// Skip empty cells in the main buffer.
auto buf_end = container->buf + container->NUM_CELLS;
while (ptr < buf_end && ptr->isZero(*container))
++ptr;
return static_cast<Derived &>(*this);
}
auto & operator*()
{
if (cell.key != ptr - container->buf)
cell.update(ptr - container->buf, ptr);
return cell;
}
auto * operator-> ()
{
if (cell.key != ptr - container->buf)
cell.update(ptr - container->buf, ptr);
return &cell;
}
auto getPtr() const { return ptr; }
size_t getHash() const { return ptr - container->buf; }
size_t getCollisionChainLength() const { return 0; }
typename cell_type::CellExt cell;
};
public:
using key_type = Key;
using mapped_type = typename Cell::mapped_type;
using value_type = typename Cell::value_type;
using cell_type = Cell;
using LookupResult = Cell *;
using ConstLookupResult = const Cell *;
size_t hash(const Key & x) const { return x; }
FixedHashTable() { alloc(); }
FixedHashTable(FixedHashTable && rhs) : buf(nullptr) { *this = std::move(rhs); }
~FixedHashTable()
{
destroyElements();
free();
}
FixedHashTable & operator=(FixedHashTable && rhs)
{
destroyElements();
free();
std::swap(buf, rhs.buf);
this->setSize(rhs.size());
Allocator::operator=(std::move(rhs));
Cell::State::operator=(std::move(rhs));
return *this;
}
class Reader final : private Cell::State
{
public:
Reader(DB::ReadBuffer & in_) : in(in_) {}
Reader(const Reader &) = delete;
Reader & operator=(const Reader &) = delete;
bool next()
{
if (!is_initialized)
{
Cell::State::read(in);
DB::readVarUInt(size, in);
is_initialized = true;
}
if (read_count == size)
{
is_eof = true;
return false;
}
cell.read(in);
++read_count;
return true;
}
inline const value_type & get() const
{
if (!is_initialized || is_eof)
throw DB::Exception("No available data", DB::ErrorCodes::NO_AVAILABLE_DATA);
return cell.getValue();
}
private:
DB::ReadBuffer & in;
Cell cell;
size_t read_count = 0;
size_t size;
bool is_eof = false;
bool is_initialized = false;
};
class iterator : public iterator_base<iterator, false>
{
public:
using iterator_base<iterator, false>::iterator_base;
};
class const_iterator : public iterator_base<const_iterator, true>
{
public:
using iterator_base<const_iterator, true>::iterator_base;
};
const_iterator begin() const
{
if (!buf)
return end();
const Cell * ptr = buf;
auto buf_end = buf + NUM_CELLS;
while (ptr < buf_end && ptr->isZero(*this))
++ptr;
return const_iterator(this, ptr);
}
const_iterator cbegin() const { return begin(); }
iterator begin()
{
if (!buf)
return end();
Cell * ptr = buf;
auto buf_end = buf + NUM_CELLS;
while (ptr < buf_end && ptr->isZero(*this))
++ptr;
return iterator(this, ptr);
}
const_iterator end() const
{
/// Avoid UBSan warning about adding zero to nullptr. It is valid in C++20 (and earlier) but not valid in C.
return const_iterator(this, buf ? buf + NUM_CELLS : buf);
}
const_iterator cend() const
{
return end();
}
iterator end()
{
return iterator(this, buf ? buf + NUM_CELLS : buf);
}
public:
/// The last parameter is unused but exists for compatibility with HashTable interface.
void ALWAYS_INLINE emplace(const Key & x, LookupResult & it, bool & inserted, size_t /* hash */ = 0)
{
it = &buf[x];
if (!buf[x].isZero(*this))
{
inserted = false;
return;
}
new (&buf[x]) Cell(x, *this);
inserted = true;
this->increaseSize();
}
std::pair<LookupResult, bool> ALWAYS_INLINE insert(const value_type & x)
{
std::pair<LookupResult, bool> res;
emplace(Cell::getKey(x), res.first, res.second);
if (res.second)
insertSetMapped(res.first->getMapped(), x);
return res;
}
LookupResult ALWAYS_INLINE find(const Key & x) { return !buf[x].isZero(*this) ? &buf[x] : nullptr; }
ConstLookupResult ALWAYS_INLINE find(const Key & x) const { return const_cast<std::decay_t<decltype(*this)> *>(this)->find(x); }
LookupResult ALWAYS_INLINE find(const Key &, size_t hash_value) { return !buf[hash_value].isZero(*this) ? &buf[hash_value] : nullptr; }
ConstLookupResult ALWAYS_INLINE find(const Key & key, size_t hash_value) const
{
return const_cast<std::decay_t<decltype(*this)> *>(this)->find(key, hash_value);
}
bool ALWAYS_INLINE has(const Key & x) const { return !buf[x].isZero(*this); }
bool ALWAYS_INLINE has(const Key &, size_t hash_value) const { return !buf[hash_value].isZero(*this); }
void write(DB::WriteBuffer & wb) const
{
Cell::State::write(wb);
DB::writeVarUInt(size(), wb);
if (!buf)
return;
for (auto ptr = buf, buf_end = buf + NUM_CELLS; ptr < buf_end; ++ptr)
{
if (!ptr->isZero(*this))
{
DB::writeVarUInt(ptr - buf);
ptr->write(wb);
}
}
}
void writeText(DB::WriteBuffer & wb) const
{
Cell::State::writeText(wb);
DB::writeText(size(), wb);
if (!buf)
return;
for (auto ptr = buf, buf_end = buf + NUM_CELLS; ptr < buf_end; ++ptr)
{
if (!ptr->isZero(*this))
{
DB::writeChar(',', wb);
DB::writeText(ptr - buf, wb);
DB::writeChar(',', wb);
ptr->writeText(wb);
}
}
}
void read(DB::ReadBuffer & rb)
{
Cell::State::read(rb);
destroyElements();
size_t m_size;
DB::readVarUInt(m_size, rb);
this->setSize(m_size);
free();
alloc();
for (size_t i = 0; i < m_size; ++i)
{
size_t place_value = 0;
DB::readVarUInt(place_value, rb);
Cell x;
x.read(rb);
new (&buf[place_value]) Cell(x, *this);
}
}
void readText(DB::ReadBuffer & rb)
{
Cell::State::readText(rb);
destroyElements();
size_t m_size;
DB::readText(m_size, rb);
this->setSize(m_size);
free();
alloc();
for (size_t i = 0; i < m_size; ++i)
{
size_t place_value = 0;
DB::assertChar(',', rb);
DB::readText(place_value, rb);
Cell x;
DB::assertChar(',', rb);
x.readText(rb);
new (&buf[place_value]) Cell(x, *this);
}
}
size_t size() const { return this->getSize(buf, *this, NUM_CELLS); }
bool empty() const { return this->isEmpty(buf, *this, NUM_CELLS); }
void clear()
{
destroyElements();
this->clearSize();
memset(static_cast<void *>(buf), 0, NUM_CELLS * sizeof(*buf));
}
/// After executing this function, the table can only be destroyed,
/// and also you can use the methods `size`, `empty`, `begin`, `end`.
void clearAndShrink()
{
destroyElements();
this->clearSize();
free();
}
size_t getBufferSizeInBytes() const { return NUM_CELLS * sizeof(Cell); }
size_t getBufferSizeInCells() const { return NUM_CELLS; }
const Cell * data() const { return buf; }
Cell * data() { return buf; }
#ifdef DBMS_HASH_MAP_COUNT_COLLISIONS
size_t getCollisions() const { return 0; }
#endif
};
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardBackgroundColor="@color/color_white"
app:cardCornerRadius="@dimen/space_18"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="@dimen/space_40"
android:padding="@dimen/space_10">
<TextView
android:id="@+id/header_title"
style="@style/text_14_333333"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginStart="@dimen/space_10"
tools:text="标题" />
<TextView
android:id="@+id/header_options"
style="@style/text_14_333333"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="@dimen/space_10"
tools:text="操作" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>com.sadun.${EXECUTABLE_NAME}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
</dict>
</plist>
|
{
"pile_set_name": "Github"
}
|
#include "farversion.hpp"
#define PLUGIN_BUILD 110
#define PLUGIN_DESC L"Temporary Panel for Far Manager"
#define PLUGIN_NAME L"TmpPanel"
#define PLUGIN_FILENAME L"TmpPanel.dll"
#define PLUGIN_AUTHOR FARCOMPANYNAME
#define PLUGIN_VERSION MAKEFARVERSION(FARMANAGERVERSION_MAJOR,FARMANAGERVERSION_MINOR,FARMANAGERVERSION_REVISION,PLUGIN_BUILD,VS_RELEASE)
|
{
"pile_set_name": "Github"
}
|
//===-- sanitizer_posix.cpp -----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries and implements POSIX-specific functions from
// sanitizer_posix.h.
//===----------------------------------------------------------------------===//
#include "sanitizer_platform.h"
#if SANITIZER_POSIX
#include "sanitizer_common.h"
#include "sanitizer_file.h"
#include "sanitizer_flags.h"
#include "sanitizer_libc.h"
#include "sanitizer_posix.h"
#include "sanitizer_procmaps.h"
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/mman.h>
#if SANITIZER_FREEBSD
// The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
// that, it was never implemented. So just define it to zero.
#undef MAP_NORESERVE
#define MAP_NORESERVE 0
#endif
namespace __sanitizer {
// ------------- sanitizer_common.h
uptr GetMmapGranularity() {
return GetPageSize();
}
void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
size = RoundUpTo(size, GetPageSizeCached());
uptr res = MmapNamed(nullptr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, mem_type);
int reserrno;
if (UNLIKELY(internal_iserror(res, &reserrno)))
ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno, raw_report);
IncreaseTotalMmap(size);
return (void *)res;
}
void UnmapOrDie(void *addr, uptr size) {
if (!addr || !size) return;
uptr res = internal_munmap(addr, size);
if (UNLIKELY(internal_iserror(res))) {
Report("ERROR: %s failed to deallocate 0x%zx (%zd) bytes at address %p\n",
SanitizerToolName, size, size, addr);
CHECK("unable to unmap" && 0);
}
DecreaseTotalMmap(size);
}
void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
size = RoundUpTo(size, GetPageSizeCached());
uptr res = MmapNamed(nullptr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, mem_type);
int reserrno;
if (UNLIKELY(internal_iserror(res, &reserrno))) {
if (reserrno == ENOMEM)
return nullptr;
ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno);
}
IncreaseTotalMmap(size);
return (void *)res;
}
// We want to map a chunk of address space aligned to 'alignment'.
// We do it by mapping a bit more and then unmapping redundant pieces.
// We probably can do it with fewer syscalls in some OS-dependent way.
void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
const char *mem_type) {
CHECK(IsPowerOfTwo(size));
CHECK(IsPowerOfTwo(alignment));
uptr map_size = size + alignment;
uptr map_res = (uptr)MmapOrDieOnFatalError(map_size, mem_type);
if (UNLIKELY(!map_res))
return nullptr;
uptr map_end = map_res + map_size;
uptr res = map_res;
if (!IsAligned(res, alignment)) {
res = (map_res + alignment - 1) & ~(alignment - 1);
UnmapOrDie((void*)map_res, res - map_res);
}
uptr end = res + size;
if (end != map_end)
UnmapOrDie((void*)end, map_end - end);
return (void*)res;
}
void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
size = RoundUpTo(size, GetPageSizeCached());
uptr p = MmapNamed(nullptr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, mem_type);
int reserrno;
if (UNLIKELY(internal_iserror(p, &reserrno)))
ReportMmapFailureAndDie(size, mem_type, "allocate noreserve", reserrno);
IncreaseTotalMmap(size);
return (void *)p;
}
static void *MmapFixedImpl(uptr fixed_addr, uptr size, bool tolerate_enomem,
const char *name) {
size = RoundUpTo(size, GetPageSizeCached());
fixed_addr = RoundDownTo(fixed_addr, GetPageSizeCached());
uptr p = MmapNamed((void *)fixed_addr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON | MAP_FIXED, name);
int reserrno;
if (UNLIKELY(internal_iserror(p, &reserrno))) {
if (tolerate_enomem && reserrno == ENOMEM)
return nullptr;
char mem_type[40];
internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
fixed_addr);
ReportMmapFailureAndDie(size, mem_type, "allocate", reserrno);
}
IncreaseTotalMmap(size);
return (void *)p;
}
void *MmapFixedOrDie(uptr fixed_addr, uptr size, const char *name) {
return MmapFixedImpl(fixed_addr, size, false /*tolerate_enomem*/, name);
}
void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size, const char *name) {
return MmapFixedImpl(fixed_addr, size, true /*tolerate_enomem*/, name);
}
bool MprotectNoAccess(uptr addr, uptr size) {
return 0 == internal_mprotect((void*)addr, size, PROT_NONE);
}
bool MprotectReadOnly(uptr addr, uptr size) {
return 0 == internal_mprotect((void *)addr, size, PROT_READ);
}
#if !SANITIZER_MAC
void MprotectMallocZones(void *addr, int prot) {}
#endif
fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *errno_p) {
if (ShouldMockFailureToOpen(filename))
return kInvalidFd;
int flags;
switch (mode) {
case RdOnly: flags = O_RDONLY; break;
case WrOnly: flags = O_WRONLY | O_CREAT | O_TRUNC; break;
case RdWr: flags = O_RDWR | O_CREAT; break;
}
fd_t res = internal_open(filename, flags, 0660);
if (internal_iserror(res, errno_p))
return kInvalidFd;
return ReserveStandardFds(res);
}
void CloseFile(fd_t fd) {
internal_close(fd);
}
bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
error_t *error_p) {
uptr res = internal_read(fd, buff, buff_size);
if (internal_iserror(res, error_p))
return false;
if (bytes_read)
*bytes_read = res;
return true;
}
bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
error_t *error_p) {
uptr res = internal_write(fd, buff, buff_size);
if (internal_iserror(res, error_p))
return false;
if (bytes_written)
*bytes_written = res;
return true;
}
void *MapFileToMemory(const char *file_name, uptr *buff_size) {
fd_t fd = OpenFile(file_name, RdOnly);
CHECK(fd != kInvalidFd);
uptr fsize = internal_filesize(fd);
CHECK_NE(fsize, (uptr)-1);
CHECK_GT(fsize, 0);
*buff_size = RoundUpTo(fsize, GetPageSizeCached());
uptr map = internal_mmap(nullptr, *buff_size, PROT_READ, MAP_PRIVATE, fd, 0);
return internal_iserror(map) ? nullptr : (void *)map;
}
void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
uptr flags = MAP_SHARED;
if (addr) flags |= MAP_FIXED;
uptr p = internal_mmap(addr, size, PROT_READ | PROT_WRITE, flags, fd, offset);
int mmap_errno = 0;
if (internal_iserror(p, &mmap_errno)) {
Printf("could not map writable file (%d, %lld, %zu): %zd, errno: %d\n",
fd, (long long)offset, size, p, mmap_errno);
return nullptr;
}
return (void *)p;
}
static inline bool IntervalsAreSeparate(uptr start1, uptr end1,
uptr start2, uptr end2) {
CHECK(start1 <= end1);
CHECK(start2 <= end2);
return (end1 < start2) || (end2 < start1);
}
#if SANITIZER_EMSCRIPTEN
bool MemoryRangeIsAvailable(uptr /*range_start*/, uptr /*range_end*/) {
// TODO: actually implement this.
return true;
}
void DumpProcessMap() {
Report("Cannot dump memory map on emscripten");
}
#else
// FIXME: this is thread-unsafe, but should not cause problems most of the time.
// When the shadow is mapped only a single thread usually exists (plus maybe
// several worker threads on Mac, which aren't expected to map big chunks of
// memory).
bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
MemoryMappingLayout proc_maps(/*cache_enabled*/true);
if (proc_maps.Error())
return true; // and hope for the best
MemoryMappedSegment segment;
while (proc_maps.Next(&segment)) {
if (segment.start == segment.end) continue; // Empty range.
CHECK_NE(0, segment.end);
if (!IntervalsAreSeparate(segment.start, segment.end - 1, range_start,
range_end))
return false;
}
return true;
}
void DumpProcessMap() {
MemoryMappingLayout proc_maps(/*cache_enabled*/true);
const sptr kBufSize = 4095;
char *filename = (char*)MmapOrDie(kBufSize, __func__);
MemoryMappedSegment segment(filename, kBufSize);
Report("Process memory map follows:\n");
while (proc_maps.Next(&segment)) {
Printf("\t%p-%p\t%s\n", (void *)segment.start, (void *)segment.end,
segment.filename);
}
Report("End of process memory map.\n");
UnmapOrDie(filename, kBufSize);
}
#endif
const char *GetPwd() {
return GetEnv("PWD");
}
bool IsPathSeparator(const char c) {
return c == '/';
}
bool IsAbsolutePath(const char *path) {
return path != nullptr && IsPathSeparator(path[0]);
}
void ReportFile::Write(const char *buffer, uptr length) {
SpinMutexLock l(mu);
ReopenIfNecessary();
internal_write(fd, buffer, length);
}
bool GetCodeRangeForFile(const char *module, uptr *start, uptr *end) {
#if SANITIZER_EMSCRIPTEN
// Code is not mapped in memory in Emscripten, so this operation is meaningless
// and thus always fails.
#else
MemoryMappingLayout proc_maps(/*cache_enabled*/false);
InternalScopedString buff(kMaxPathLength);
MemoryMappedSegment segment(buff.data(), kMaxPathLength);
while (proc_maps.Next(&segment)) {
if (segment.IsExecutable() &&
internal_strcmp(module, segment.filename) == 0) {
*start = segment.start;
*end = segment.end;
return true;
}
}
#endif
return false;
}
uptr SignalContext::GetAddress() const {
auto si = static_cast<const siginfo_t *>(siginfo);
return (uptr)si->si_addr;
}
bool SignalContext::IsMemoryAccess() const {
auto si = static_cast<const siginfo_t *>(siginfo);
return si->si_signo == SIGSEGV;
}
int SignalContext::GetType() const {
return static_cast<const siginfo_t *>(siginfo)->si_signo;
}
const char *SignalContext::Describe() const {
switch (GetType()) {
case SIGFPE:
return "FPE";
case SIGILL:
return "ILL";
case SIGABRT:
return "ABRT";
case SIGSEGV:
return "SEGV";
case SIGBUS:
return "BUS";
case SIGTRAP:
return "TRAP";
}
return "UNKNOWN SIGNAL";
}
fd_t ReserveStandardFds(fd_t fd) {
CHECK_GE(fd, 0);
if (fd > 2)
return fd;
bool used[3];
internal_memset(used, 0, sizeof(used));
while (fd <= 2) {
used[fd] = true;
fd = internal_dup(fd);
}
for (int i = 0; i <= 2; ++i)
if (used[i])
internal_close(i);
return fd;
}
bool ShouldMockFailureToOpen(const char *path) {
return common_flags()->test_only_emulate_no_memorymap &&
internal_strncmp(path, "/proc/", 6) == 0;
}
#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_GO
int GetNamedMappingFd(const char *name, uptr size, int *flags) {
if (!common_flags()->decorate_proc_maps || !name)
return -1;
char shmname[200];
CHECK(internal_strlen(name) < sizeof(shmname) - 10);
internal_snprintf(shmname, sizeof(shmname), "/dev/shm/%zu [%s]",
internal_getpid(), name);
int fd = ReserveStandardFds(
internal_open(shmname, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRWXU));
CHECK_GE(fd, 0);
int res = internal_ftruncate(fd, size);
CHECK_EQ(0, res);
res = internal_unlink(shmname);
CHECK_EQ(0, res);
*flags &= ~(MAP_ANON | MAP_ANONYMOUS);
return fd;
}
#else
int GetNamedMappingFd(const char *name, uptr size, int *flags) {
return -1;
}
#endif
#if SANITIZER_ANDROID
#define PR_SET_VMA 0x53564d41
#define PR_SET_VMA_ANON_NAME 0
void DecorateMapping(uptr addr, uptr size, const char *name) {
if (!common_flags()->decorate_proc_maps || !name)
return;
internal_prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, addr, size, (uptr)name);
}
#else
void DecorateMapping(uptr addr, uptr size, const char *name) {
}
#endif
uptr MmapNamed(void *addr, uptr length, int prot, int flags, const char *name) {
int fd = GetNamedMappingFd(name, length, &flags);
uptr res = internal_mmap(addr, length, prot, flags, fd, 0);
if (!internal_iserror(res))
DecorateMapping(res, length, name);
return res;
}
} // namespace __sanitizer
#endif // SANITIZER_POSIX
|
{
"pile_set_name": "Github"
}
|
<transition_graph cluster-delay="60s" stonith-timeout="60s" failed-stop-offset="INFINITY" failed-start-offset="INFINITY" transition_id="0">
<synapse id="0">
<action_set>
<rsc_op id="7" operation="start" operation_key="rsc1_start_0" on_node="host2" on_node_uuid="host2">
<primitive id="rsc1" class="ocf" provider="pacemaker" type="Dummy"/>
<attributes CRM_meta_on_node="host2" CRM_meta_on_node_uuid="host2" CRM_meta_timeout="20000" />
</rsc_op>
</action_set>
<inputs>
<trigger>
<pseudo_event id="2" operation="load_stopped_host2" operation_key="load_stopped_host2"/>
</trigger>
<trigger>
<rsc_op id="3" operation="monitor" operation_key="rsc1_monitor_0" on_node="host1" on_node_uuid="host1"/>
</trigger>
<trigger>
<rsc_op id="5" operation="monitor" operation_key="rsc1_monitor_0" on_node="host2" on_node_uuid="host2"/>
</trigger>
</inputs>
</synapse>
<synapse id="1">
<action_set>
<rsc_op id="5" operation="monitor" operation_key="rsc1_monitor_0" on_node="host2" on_node_uuid="host2">
<primitive id="rsc1" class="ocf" provider="pacemaker" type="Dummy"/>
<attributes CRM_meta_on_node="host2" CRM_meta_on_node_uuid="host2" CRM_meta_op_target_rc="7" CRM_meta_timeout="20000" />
</rsc_op>
</action_set>
<inputs/>
</synapse>
<synapse id="2">
<action_set>
<rsc_op id="3" operation="monitor" operation_key="rsc1_monitor_0" on_node="host1" on_node_uuid="host1">
<primitive id="rsc1" class="ocf" provider="pacemaker" type="Dummy"/>
<attributes CRM_meta_on_node="host1" CRM_meta_on_node_uuid="host1" CRM_meta_op_target_rc="7" CRM_meta_timeout="20000" />
</rsc_op>
</action_set>
<inputs/>
</synapse>
<synapse id="3">
<action_set>
<rsc_op id="8" operation="start" operation_key="rsc2_start_0" on_node="host1" on_node_uuid="host1">
<primitive id="rsc2" class="ocf" provider="pacemaker" type="Dummy"/>
<attributes CRM_meta_on_node="host1" CRM_meta_on_node_uuid="host1" CRM_meta_timeout="20000" />
</rsc_op>
</action_set>
<inputs>
<trigger>
<pseudo_event id="1" operation="load_stopped_host1" operation_key="load_stopped_host1"/>
</trigger>
<trigger>
<rsc_op id="4" operation="monitor" operation_key="rsc2_monitor_0" on_node="host1" on_node_uuid="host1"/>
</trigger>
<trigger>
<rsc_op id="6" operation="monitor" operation_key="rsc2_monitor_0" on_node="host2" on_node_uuid="host2"/>
</trigger>
</inputs>
</synapse>
<synapse id="4">
<action_set>
<rsc_op id="6" operation="monitor" operation_key="rsc2_monitor_0" on_node="host2" on_node_uuid="host2">
<primitive id="rsc2" class="ocf" provider="pacemaker" type="Dummy"/>
<attributes CRM_meta_on_node="host2" CRM_meta_on_node_uuid="host2" CRM_meta_op_target_rc="7" CRM_meta_timeout="20000" />
</rsc_op>
</action_set>
<inputs/>
</synapse>
<synapse id="5">
<action_set>
<rsc_op id="4" operation="monitor" operation_key="rsc2_monitor_0" on_node="host1" on_node_uuid="host1">
<primitive id="rsc2" class="ocf" provider="pacemaker" type="Dummy"/>
<attributes CRM_meta_on_node="host1" CRM_meta_on_node_uuid="host1" CRM_meta_op_target_rc="7" CRM_meta_timeout="20000" />
</rsc_op>
</action_set>
<inputs/>
</synapse>
<synapse id="6">
<action_set>
<pseudo_event id="2" operation="load_stopped_host2" operation_key="load_stopped_host2">
<attributes />
</pseudo_event>
</action_set>
<inputs/>
</synapse>
<synapse id="7">
<action_set>
<pseudo_event id="1" operation="load_stopped_host1" operation_key="load_stopped_host1">
<attributes />
</pseudo_event>
</action_set>
<inputs/>
</synapse>
</transition_graph>
|
{
"pile_set_name": "Github"
}
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class UsagesOperations(object):
"""UsagesOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: The API version to use for this operation. Constant value: "2019-06-01".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2019-06-01"
self.config = config
def list_by_location(
self, location, custom_headers=None, raw=False, **operation_config):
"""Gets the current usage count and the limit for the resources of the
location under the subscription.
:param location: The location of the Azure Storage resource.
:type location: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of Usage
:rtype:
~azure.mgmt.storage.v2019_06_01.models.UsagePaged[~azure.mgmt.storage.v2019_06_01.models.Usage]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
def prepare_request(next_link=None):
if not next_link:
# Construct URL
url = self.list_by_location.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str', min_length=1),
'location': self._serialize.url("location", location, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str', min_length=1)
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
return request
def internal_paging(next_link=None):
request = prepare_request(next_link)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
# Deserialize response
header_dict = None
if raw:
header_dict = {}
deserialized = models.UsagePaged(internal_paging, self._deserialize.dependencies, header_dict)
return deserialized
list_by_location.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Storage/locations/{location}/usages'}
|
{
"pile_set_name": "Github"
}
|
/*
* Really Slick XScreenSavers
* Copyright (C) 2002-2006 Michael Chapman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 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 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
*
*****************************************************************************
*
* This is a Linux port of the Really Slick Screensavers,
* Copyright (C) 2002 Terence M. Welsh, available from www.reallyslick.com
*/
#include <common.hh>
#include <color.hh>
#include <oggsound.hh>
#include <pngimage.hh>
#include <resources.hh>
#include <skyrocket.hh>
#include <vector.hh>
#define STARTEXSIZE 512
#define MOONGLOWTEXSIZE 128
#define FLARESIZE 128
#define STARMESH 12
namespace Resources {
namespace Sounds {
Sound* boom1;
Sound* boom2;
Sound* boom3;
Sound* boom4;
Sound* launch1;
Sound* launch2;
Sound* nuke;
Sound* popper;
Sound* suck;
Sound* whistle;
void _init();
};
namespace Textures {
GLuint cloud;
GLuint stars;
GLuint moon;
GLuint moonGlow;
GLuint sunset;
GLuint earthNear;
GLuint earthFar;
GLuint earthLight;
GLuint smoke[5];
GLuint flare[4];
void makeHeights(unsigned int, unsigned int, unsigned int*);
void _init();
};
namespace DisplayLists {
GLuint flares;
GLuint rocket;
GLuint smokes;
GLuint stars;
GLuint moon;
GLuint moonGlow;
GLuint sunset;
GLuint earthNear;
GLuint earthFar;
GLuint earthLight;
void _init();
};
void init(float, const Vector&, const Vector&, const UnitQuat&);
};
void Resources::Sounds::_init() {
boom1 = new OGG("boom1.ogg", 1000.0f); Common::resources->manage(boom1);
boom2 = new OGG("boom2.ogg", 1000.0f); Common::resources->manage(boom2);
boom3 = new OGG("boom3.ogg", 1000.0f); Common::resources->manage(boom3);
boom4 = new OGG("boom4.ogg", 1200.0f); Common::resources->manage(boom4);
launch1 = new OGG("launch1.ogg", 10.0f); Common::resources->manage(launch1);
launch2 = new OGG("launch2.ogg", 10.0f); Common::resources->manage(launch2);
nuke = new OGG("nuke.ogg", 2000.0f); Common::resources->manage(nuke);
popper = new OGG("popper.ogg", 700.0f, 2.5f); Common::resources->manage(popper);
suck = new OGG("suck.ogg", 1500.0f); Common::resources->manage(suck);
whistle = new OGG("whistle.ogg", 700.0f); Common::resources->manage(whistle);
}
void Resources::Textures::makeHeights(unsigned int first, unsigned int last,
unsigned int* h) {
unsigned int diff = last - first;
if (diff <= 1) return;
unsigned int middle = first + (last - first) / 2;
int newHeight = (int(h[first]) + int(h[last])) / 2 +
Common::randomInt(diff / 2) - (diff / 4);
h[middle] = (newHeight < 1) ? 1 : newHeight;
makeHeights(first, middle, h);
makeHeights(middle, last, h);
}
void Resources::Textures::_init() {
// Initialize cloud texture object even if clouds are not turned on.
// Sunsets and shockwaves can also use cloud texture.
PNG cloudPNG("cloud.png");
cloud = Common::resources->genTexture(
GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT,
cloudPNG
);
if (Hack::starDensity > 0) {
stdx::dim3<float, 3, STARTEXSIZE> starMap(STARTEXSIZE);
for (unsigned int i = 0; i < (Hack::starDensity * 20); ++i) {
unsigned int u = Common::randomInt(STARTEXSIZE - 4) + 2;
unsigned int v = Common::randomInt(STARTEXSIZE - 4) + 2;
RGBColor RGB(
0.8627f + Common::randomFloat(0.1373f),
0.8627f + Common::randomFloat(0.1373f),
0.8627f + Common::randomFloat(0.1373f)
);
switch (Common::randomInt(3)) {
case 0: RGB.r() = 1.0f; break;
case 1: RGB.g() = 1.0f; break;
case 2: RGB.b() = 1.0f; break;
}
switch (Common::randomInt(6)) { // different stars
case 0: case 1: case 2: // small
starMap(u, v, 0) = RGB.r() / 2.0f;
starMap(u, v, 1) = RGB.g() / 2.0f;
starMap(u, v, 2) = RGB.b() / 2.0f;
RGB /= 3 + Common::randomInt(6);
starMap(u + 1, v, 0) = starMap(u - 1, v, 0) =
starMap(u, v + 1, 0) = starMap(u, v - 1, 0) = RGB.r();
starMap(u + 1, v, 1) = starMap(u - 1, v, 1) =
starMap(u, v + 1, 1) = starMap(u, v - 1, 1) = RGB.g();
starMap(u + 1, v, 2) = starMap(u - 1, v, 2) =
starMap(u, v + 1, 2) = starMap(u, v - 1, 2) = RGB.b();
break;
case 3: case 4: // medium
starMap(u, v, 0) = RGB.r();
starMap(u, v, 1) = RGB.g();
starMap(u, v, 2) = RGB.b();
RGB /= 2;
starMap(u + 1, v, 0) = starMap(u - 1, v, 0) =
starMap(u, v + 1, 0) = starMap(u, v - 1, 0) = RGB.r();
starMap(u + 1, v, 1) = starMap(u - 1, v, 1) =
starMap(u, v + 1, 1) = starMap(u, v - 1, 1) = RGB.g();
starMap(u + 1, v, 2) = starMap(u - 1, v, 2) =
starMap(u, v + 1, 2) = starMap(u, v - 1, 2) = RGB.b();
break;
case 5: // large
starMap(u, v, 0) = RGB.r();
starMap(u, v, 1) = RGB.g();
starMap(u, v, 2) = RGB.b();
starMap(u + 1, v + 1, 0) = starMap(u - 1, v + 1, 0) =
starMap(u + 1, v - 1, 0) = starMap(u - 1, v - 1, 0) =
RGB.r() / 4.0f;
starMap(u + 1, v + 1, 1) = starMap(u - 1, v + 1, 1) =
starMap(u + 1, v - 1, 1) = starMap(u - 1, v - 1, 1) =
RGB.g() / 4.0f;
starMap(u + 1, v + 1, 2) = starMap(u - 1, v + 1, 2) =
starMap(u + 1, v - 1, 2) = starMap(u - 1, v - 1, 2) =
RGB.b() / 4.0f;
RGB *= 0.75;
starMap(u + 1, v, 0) = starMap(u - 1, v, 0) =
starMap(u, v + 1, 0) = starMap(u, v - 1, 0) = RGB.r();
starMap(u + 1, v, 1) = starMap(u - 1, v, 1) =
starMap(u, v + 1, 1) = starMap(u, v - 1, 1) = RGB.g();
starMap(u + 1, v, 2) = starMap(u - 1, v, 2) =
starMap(u, v + 1, 2) = starMap(u, v - 1, 2) = RGB.b();
}
}
stars = Common::resources->genTexture(
GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT,
3, STARTEXSIZE, STARTEXSIZE, GL_RGB, GL_FLOAT, &starMap.front()
);
}
if (Hack::drawMoon) {
moon = Common::resources->genTexture(
GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT,
PNG("moon.png")
);
if (Hack::moonGlow > 0.0f) {
stdx::dim3<float, 4, MOONGLOWTEXSIZE> moonGlowMap(MOONGLOWTEXSIZE);
for (unsigned int i = 0; i < MOONGLOWTEXSIZE; ++i) {
for (unsigned int j = 0; j < MOONGLOWTEXSIZE; ++j) {
float u = 2 * float(i) / float(MOONGLOWTEXSIZE) - 1;
float v = 2 * float(j) / float(MOONGLOWTEXSIZE) - 1;
float temp1 = Common::clamp(
4.0f * ((u * u) + (v * v)) * (1.0f - ((u * u) + (v * v))),
0.0f, 1.0f
);
temp1 = temp1 * temp1 * temp1 * temp1;
u *= 1.2f;
v *= 1.2f;
float temp2 = Common::clamp(
4.0f * ((u * u) + (v * v)) * (1.0f - ((u * u) + (v * v))),
0.0f, 1.0f
);
temp2 = temp2 * temp2 * temp2 * temp2;
u *= 1.25f;
v *= 1.25f;
float temp3 = Common::clamp(
4.0f * ((u * u) + (v * v)) * (1.0f - ((u * u) + (v * v))),
0.0f, 1.0f
);
temp3 = temp3 * temp3 * temp3 * temp3;
moonGlowMap(i, j, 0) = temp1 * 0.4f + temp2 * 0.4f + temp3 * 0.48f;
moonGlowMap(i, j, 1) = temp1 * 0.4f + temp2 * 0.48f + temp3 * 0.38f;
moonGlowMap(i, j, 2) = temp1 * 0.48f + temp2 * 0.4f + temp3 * 0.38f;
moonGlowMap(i, j, 3) = temp1 * 0.48f + temp2 * 0.48f + temp3 * 0.48f;
}
}
moonGlow = Common::resources->genTexture(
GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT,
4, MOONGLOWTEXSIZE, MOONGLOWTEXSIZE, GL_RGBA, GL_FLOAT,
&moonGlowMap.front()
);
}
}
if (Hack::drawSunset) {
RGBColor RGB;
if (Common::randomInt(3))
RGB.r() = 0.2353f + Common::randomFloat(0.1647f);
else
RGB.r() = Common::randomFloat(0.4f);
RGB.g() = Common::randomFloat(RGB.r());
if (RGB.g() < 0.0196f)
RGB.b() = 0.0392f - Common::randomFloat(RGB.r());
stdx::dim3<float, 3> sunsetMap(cloudPNG.width(), cloudPNG.height());
for (unsigned int i = 0; i < cloudPNG.width(); ++i) {
for (unsigned int j = 0; j < cloudPNG.height(); ++j) {
sunsetMap(i, j, 0) = RGB.r();
sunsetMap(i, j, 1) = RGB.g();
sunsetMap(i, j, 2) = RGB.b();
}
}
// Maybe clouds in sunset
if (Common::randomInt(3)) {
unsigned int xOffset = Common::randomInt(cloudPNG.width());
unsigned int yOffset = Common::randomInt(cloudPNG.height());
for (unsigned int i = 0; i < cloudPNG.width(); ++i) {
for (unsigned int j = 0; j < cloudPNG.height(); ++j) {
unsigned int x = (i + xOffset) % cloudPNG.width();
unsigned int y = (j + yOffset) % cloudPNG.height();
float cloudInfluence = cloudPNG(x, y).g();
sunsetMap(i, j, 0) *= cloudInfluence;
cloudInfluence *= cloudPNG(x, y).r();
sunsetMap(i, j, 1) *= cloudInfluence;
}
}
}
std::vector<unsigned int> mountains(cloudPNG.width() + 1);
mountains[0] = mountains[cloudPNG.width()] = Common::randomInt(10) + 5;
makeHeights(0, cloudPNG.width(), &mountains.front());
for (unsigned int i = 0; i < cloudPNG.width(); ++i) {
for (unsigned int j = 0; j <= mountains[i]; ++j)
sunsetMap(i, j, 0) = sunsetMap(i, j, 1) = sunsetMap(i, j, 2) = 0.0f;
sunsetMap(i, mountains[i] + 1, 0) /= 4.0f;
sunsetMap(i, mountains[i] + 1, 1) /= 4.0f;
sunsetMap(i, mountains[i] + 1, 2) /= 4.0f;
sunsetMap(i, mountains[i] + 2, 0) /= 2.0f;
sunsetMap(i, mountains[i] + 2, 1) /= 2.0f;
sunsetMap(i, mountains[i] + 2, 2) /= 2.0f;
sunsetMap(i, mountains[i] + 3, 0) *= 0.75f;
sunsetMap(i, mountains[i] + 3, 1) *= 0.75f;
sunsetMap(i, mountains[i] + 3, 2) *= 0.75f;
}
sunset = Common::resources->genTexture(
GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP, GL_CLAMP,
3, cloudPNG.width(), cloudPNG.height(), GL_RGB, GL_FLOAT,
&sunsetMap.front()
);
}
if (Hack::drawEarth) {
earthNear = Common::resources->genTexture(
GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP, GL_CLAMP,
PNG("earth-near.png")
);
earthFar = Common::resources->genTexture(
GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP, GL_CLAMP,
PNG("earth-far.png")
);
earthLight = Common::resources->genTexture(
GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP, GL_CLAMP,
PNG("earth-light.png")
);
}
for (unsigned int i = 0; i < 5; i++) {
smoke[i] = Common::resources->genTexture(
GL_NEAREST, GL_LINEAR, GL_REPEAT, GL_REPEAT,
PNG(stdx::oss() << "smoke" << (char)(i + '1') << ".png")
);
}
stdx::dim3<GLubyte, 4, FLARESIZE> flareMap[4];
for (unsigned int i = 0; i < 4; ++i)
flareMap[i].resize(FLARESIZE);
for (int i = 0; i < FLARESIZE; ++i) {
for (int j = 0; j < FLARESIZE; ++j) {
float x = float(i - FLARESIZE / 2) / float(FLARESIZE / 2);
float y = float(j - FLARESIZE / 2) / float(FLARESIZE / 2);
float temp;
// Basic flare
flareMap[0](i, j, 0) = 255;
flareMap[0](i, j, 1) = 255;
flareMap[0](i, j, 2) = 255;
temp = Common::clamp(
1.0f - ((x * x) + (y * y)),
0.0f, 1.0f
);
flareMap[0](i, j, 3) = GLubyte(255.0f * temp * temp);
// Flattened sphere
flareMap[1](i, j, 0) = 255;
flareMap[1](i, j, 1) = 255;
flareMap[1](i, j, 2) = 255;
temp = Common::clamp(
2.5f * (1.0f - ((x * x) + (y * y))),
0.0f, 1.0f
);
flareMap[1](i, j, 3) = GLubyte(255.0f * temp);
// Torus
flareMap[2](i, j, 0) = 255;
flareMap[2](i, j, 1) = 255;
flareMap[2](i, j, 2) = 255;
temp = Common::clamp(
4.0f * ((x * x) + (y * y)) * (1.0f - ((x * x) + (y * y))),
0.0f, 1.0f
);
temp = temp * temp * temp * temp;
flareMap[2](i, j, 3) = GLubyte(255.0f * temp);
// Kick-ass!
x = std::abs(x);
y = std::abs(y);
float xy = x * y;
flareMap[3](i, j, 0) = 255;
flareMap[3](i, j, 1) = 255;
temp = Common::clamp(
0.14f * (1.0f - ((x > y) ? x : y)) / ((xy > 0.05f) ? xy : 0.05f),
0.0f, 1.0f
);
flareMap[3](i, j, 2) = GLubyte(255.0f * temp);
temp = Common::clamp(
0.1f * (1.0f - ((x > y) ? x : y)) / ((xy > 0.1f) ? xy : 0.1f),
0.0f, 1.0f
);
flareMap[3](i, j, 3) = GLubyte(255.0f * temp);
}
}
for (unsigned int i = 0; i < 4; ++i)
flare[i] = Common::resources->genTexture(
GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT,
4, FLARESIZE, FLARESIZE, GL_RGBA, GL_UNSIGNED_BYTE,
&flareMap[i].front(), false
);
}
void Resources::DisplayLists::_init() {
flares = Common::resources->genLists(4);
for (unsigned int i = 0; i < 4; ++i) {
glNewList(flares + i, GL_COMPILE);
glBindTexture(GL_TEXTURE_2D, Resources::Textures::flare[i]);
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-0.5f, -0.5f, 0.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(0.5f, -0.5f, 0.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-0.5f, 0.5f, 0.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(0.5f, 0.5f, 0.0f);
glEnd();
glEndList();
}
rocket = Common::resources->genLists(1);
glNewList(rocket, GL_COMPILE);
// Draw rocket (10-sided cylinder)
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(0.075f, 0.0f, 0.0f);
glVertex3f(0.075f, 1.0f, 0.0f);
glVertex3f(0.060676f, 0.0f, 0.033504f);
glVertex3f(0.060676f, 1.0f, 0.033504f);
glVertex3f(0.023176f, 0.0f, 0.071329f);
glVertex3f(0.023176f, 1.0f, 0.071329f);
glVertex3f(-0.023176f, 0.0f, 0.071329f);
glVertex3f(-0.023176f, 1.0f, 0.071329f);
glVertex3f(-0.060676f, 0.0f, 0.033504f);
glVertex3f(-0.060676f, 1.0f, 0.033504f);
glVertex3f(-0.075f, 0.0f, 0.0f);
glVertex3f(-0.075f, 1.0f, 0.0f);
glVertex3f(-0.060676f, 0.0f, -0.033504f);
glVertex3f(-0.060676f, 1.0f, -0.033504f);
glVertex3f(-0.023176f, 0.0f, -0.071329f);
glVertex3f(-0.023176f, 1.0f, -0.071329f);
glVertex3f(0.023176f, 0.0f, -0.071329f);
glVertex3f(0.023176f, 1.0f, -0.071329f);
glVertex3f(0.060676f, 0.0f, -0.033504f);
glVertex3f(0.060676f, 1.0f, -0.033504f);
glVertex3f(0.075f, 0.0f, 0.0f);
glVertex3f(0.075f, 1.0f, 0.0f);
glEnd();
// bottom of rocket
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(0.075f, 0.0f, 0.0f);
glVertex3f(0.060676f, 0.0f, 0.033504f);
glVertex3f(0.060676f, 0.0f, -0.033504f);
glVertex3f(0.023176f, 0.0f, 0.071329f);
glVertex3f(0.023176f, 0.0f, -0.071329f);
glVertex3f(-0.023176f, 0.0f, 0.071329f);
glVertex3f(-0.023176f, 0.0f, -0.071329f);
glVertex3f(-0.060676f, 0.0f, 0.033504f);
glVertex3f(-0.060676f, 0.0f, -0.033504f);
glVertex3f(-0.075f, 0.0f, 0.0f);
glEnd();
// top of rocket
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(0.075f, 1.0f, 0.0f);
glVertex3f(0.060676f, 1.0f, -0.033504f);
glVertex3f(0.060676f, 1.0f, 0.033504f);
glVertex3f(0.023176f, 1.0f, -0.071329f);
glVertex3f(0.023176f, 1.0f, 0.071329f);
glVertex3f(-0.023176f, 1.0f, -0.071329f);
glVertex3f(-0.023176f, 1.0f, 0.071329f);
glVertex3f(-0.060676f, 1.0f, -0.033504f);
glVertex3f(-0.060676f, 1.0f, 0.033504f);
glVertex3f(-0.075f, 1.0f, 0.0f);
glEnd();
glEndList();
smokes = Common::resources->genLists(5);
for (unsigned int i = 0; i < 5; i++) {
glNewList(smokes + i, GL_COMPILE);
glBindTexture(GL_TEXTURE_2D, Resources::Textures::smoke[i]);
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-0.5f, -0.5f, 0.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(0.5f, -0.5f, 0.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-0.5f, 0.5f, 0.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(0.5f, 0.5f, 0.0f);
glEnd();
glEndList();
}
if (Hack::starDensity > 0) {
Vector starPos[STARMESH + 1][STARMESH / 2];
float starCoord[STARMESH + 1][STARMESH / 2][2];
float starBrightness[STARMESH + 1][STARMESH / 2];
for (unsigned int j = 0; j < STARMESH / 2; ++j) {
float y = std::sin(M_PI_2 * float(j) / float(STARMESH / 2));
for (unsigned int i = 0; i <= STARMESH; ++i) {
float x = std::cos(M_PI * 2 * float(i) / float(STARMESH)) *
std::cos(M_PI_2 * float(j) / float(STARMESH / 2));
float z = std::sin(M_PI * 2 * float(i) / float(STARMESH)) *
std::cos(M_PI_2 * float(j) / float(STARMESH / 2));
starPos[i][j].set(
x * 20000.0f,
1500.0f + 18500.0f * y,
z * 20000.0f
);
starCoord[i][j][0] = 1.2f * x * (2.5f - y);
starCoord[i][j][1] = 1.2f * z * (2.5f - y);
starBrightness[i][j] = (starPos[i][j].y() < 1501.0f) ? 0.0f : 1.0f;
}
}
stars = Common::resources->genLists(1);
glNewList(stars, GL_COMPILE);
glBindTexture(GL_TEXTURE_2D, Resources::Textures::stars);
for (unsigned int j = 0; j < (STARMESH / 2 - 1); ++j) {
glBegin(GL_TRIANGLE_STRIP);
for (unsigned int i = 0; i <= STARMESH; ++i) {
glColor3f(
starBrightness[i][j + 1],
starBrightness[i][j + 1],
starBrightness[i][j + 1]
);
glTexCoord2fv(starCoord[i][j + 1]);
glVertex3fv(starPos[i][j + 1].get());
glColor3f(
starBrightness[i][j],
starBrightness[i][j],
starBrightness[i][j]
);
glTexCoord2fv(starCoord[i][j]);
glVertex3fv(starPos[i][j].get());
}
glEnd();
}
glBegin(GL_TRIANGLE_FAN);
glColor3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(0.0f, 20000.0f, 0.0f);
for (unsigned int i = 0; i <= STARMESH; ++i) {
glColor3f(
starBrightness[i][STARMESH / 2 - 1],
starBrightness[i][STARMESH / 2 - 1],
starBrightness[i][STARMESH / 2 - 1]
);
glTexCoord2fv(starCoord[i][STARMESH / 2 - 1]);
glVertex3fv(starPos[i][STARMESH / 2 - 1].get());
}
glEnd();
glEndList();
}
if (Hack::drawMoon) {
moon = Common::resources->genLists(1);
glNewList(moon, GL_COMPILE);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glBindTexture(GL_TEXTURE_2D, Resources::Textures::moon);
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-800.0f, -800.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(800.0f, -800.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-800.0f, 800.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(800.0f, 800.0f, 0.0f);
glEnd();
glEndList();
if (Hack::moonGlow > 0.0f) {
moonGlow = Common::resources->genLists(1);
glNewList(moonGlow, GL_COMPILE);
glBindTexture(GL_TEXTURE_2D, Resources::Textures::moonGlow);
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-7000.0f, -7000.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(7000.0f, -7000.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-7000.0f, 7000.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(7000.0f, 7000.0f, 0.0f);
glEnd();
glEndList();
}
}
if (Hack::drawSunset) {
float vert[6] = { 0.0f, 7654.0f, 8000.0f, 14142.0f, 18448.0f, 20000.0f };
sunset = Common::resources->genLists(1);
glNewList(sunset, GL_COMPILE);
glBindTexture(GL_TEXTURE_2D, Resources::Textures::sunset);
glBegin(GL_TRIANGLE_STRIP);
glColor3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(vert[0], vert[2], vert[5]);
glColor3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(vert[0], vert[0], vert[5]);
glColor3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.125f);
glVertex3f(-vert[1], vert[2], vert[4]);
glColor3f(0.25f, 0.25f, 0.25f);
glTexCoord2f(0.0f, 0.125f);
glVertex3f(-vert[1], vert[0], vert[4]);
glColor3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.25f);
glVertex3f(-vert[3], vert[2], vert[3]);
glColor3f(0.5f, 0.5f, 0.5f);
glTexCoord2f(0.0f, 0.25f);
glVertex3f(-vert[3], vert[0], vert[3]);
glColor3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.375f);
glVertex3f(-vert[4], vert[2], vert[1]);
glColor3f(0.75f, 0.75f, 0.75f);
glTexCoord2f(0.0f, 0.375f);
glVertex3f(-vert[4], vert[0], vert[1]);
glColor3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.5f);
glVertex3f(-vert[5], vert[2], vert[0]);
glColor3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 0.5f);
glVertex3f(-vert[5], vert[0], vert[0]);
glColor3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.625f);
glVertex3f(-vert[4], vert[2], -vert[1]);
glColor3f(0.75f, 0.75f, 0.75f);
glTexCoord2f(0.0f, 0.625f);
glVertex3f(-vert[4], vert[0], -vert[1]);
glColor3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.75f);
glVertex3f(-vert[3], vert[2], -vert[3]);
glColor3f(0.5f, 0.5f, 0.5f);
glTexCoord2f(0.0f, 0.75f);
glVertex3f(-vert[3], vert[0], -vert[3]);
glColor3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.875f);
glVertex3f(-vert[1], vert[2], -vert[4]);
glColor3f(0.25f, 0.25f, 0.25f);
glTexCoord2f(0.0f, 0.875f);
glVertex3f(-vert[1], vert[0], -vert[4]);
glColor3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(vert[0], vert[2], -vert[5]);
glColor3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(vert[0], vert[0], -vert[5]);
glEnd();
glEndList();
}
if (Hack::drawEarth) {
float lit[] = {
Hack::ambient * 0.01f,
Hack::ambient * 0.01f,
Hack::ambient * 0.01f
};
float unlit[] = { 0.0f, 0.0f, 0.0f };
float vert[] = { 839.68f, 8396.8f };
float tex[] = { 0.0f, 0.45f, 0.55f, 1.0f };
earthNear = Common::resources->genLists(1);
glNewList(earthNear, GL_COMPILE);
glColor3fv(lit);
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(tex[0], tex[0]);
glVertex3f(-vert[0], 0.0f, -vert[0]);
glTexCoord2f(tex[0], tex[3]);
glVertex3f(-vert[0], 0.0f, vert[0]);
glTexCoord2f(tex[3], tex[0]);
glVertex3f(vert[0], 0.0f, -vert[0]);
glTexCoord2f(tex[3], tex[3]);
glVertex3f(vert[0], 0.0f, vert[0]);
glEnd();
glEndList();
earthFar = Common::resources->genLists(1);
glNewList(earthFar, GL_COMPILE);
glBegin(GL_TRIANGLE_STRIP);
glColor3fv(lit);
glTexCoord2f(tex[1], tex[1]);
glVertex3f(-vert[0], 0.0f, -vert[0]);
glTexCoord2f(tex[2], tex[1]);
glVertex3f(vert[0], 0.0f, -vert[0]);
glColor3fv(unlit);
glTexCoord2f(tex[0], tex[0]);
glVertex3f(-vert[1], 0.0f, -vert[1]);
glTexCoord2f(tex[3], tex[0]);
glVertex3f(vert[1], 0.0f, -vert[1]);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor3fv(lit);
glTexCoord2f(tex[1], tex[2]);
glVertex3f(-vert[0], 0.0f, vert[0]);
glTexCoord2f(tex[1], tex[1]);
glVertex3f(-vert[0], 0.0f, -vert[0]);
glColor3fv(unlit);
glTexCoord2f(tex[0], tex[3]);
glVertex3f(-vert[1], 0.0f, vert[1]);
glTexCoord2f(tex[0], tex[0]);
glVertex3f(-vert[1], 0.0f, -vert[1]);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor3fv(lit);
glTexCoord2f(tex[2], tex[2]);
glVertex3f(vert[0], 0.0f, vert[0]);
glTexCoord2f(tex[1], tex[2]);
glVertex3f(-vert[0], 0.0f, vert[0]);
glColor3fv(unlit);
glTexCoord2f(tex[3], tex[3]);
glVertex3f(vert[1], 0.0f, vert[1]);
glTexCoord2f(tex[0], tex[3]);
glVertex3f(-vert[1], 0.0f, vert[1]);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor3fv(lit);
glTexCoord2f(tex[2], tex[1]);
glVertex3f(vert[0], 0.0f, -vert[0]);
glTexCoord2f(tex[2], tex[2]);
glVertex3f(vert[0], 0.0f, vert[0]);
glColor3fv(unlit);
glTexCoord2f(tex[3], tex[0]);
glVertex3f(vert[1], 0.0f, -vert[1]);
glTexCoord2f(tex[3], tex[3]);
glVertex3f(vert[1], 0.0f, vert[1]);
glEnd();
glEndList();
earthLight = Common::resources->genLists(1);
glNewList(earthLight, GL_COMPILE);
lit[0] = lit[1] = lit[2] = 0.4f;
glColor3fv(lit);
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(tex[1], tex[1]);
glVertex3f(-vert[0], 0.0f, -vert[0]);
glTexCoord2f(tex[1], tex[2]);
glVertex3f(-vert[0], 0.0f, vert[0]);
glTexCoord2f(tex[2], tex[1]);
glVertex3f(vert[0], 0.0f, -vert[0]);
glTexCoord2f(tex[2], tex[2]);
glVertex3f(vert[0], 0.0f, vert[0]);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor3fv(lit);
glTexCoord2f(tex[1], tex[1]);
glVertex3f(-vert[0], 0.0f, -vert[0]);
glTexCoord2f(tex[2], tex[1]);
glVertex3f(vert[0], 0.0f, -vert[0]);
glColor3fv(unlit);
glTexCoord2f(tex[0], tex[0]);
glVertex3f(-vert[1], 0.0f, -vert[1]);
glTexCoord2f(tex[3], tex[0]);
glVertex3f(vert[1], 0.0f, -vert[1]);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor3fv(lit);
glTexCoord2f(tex[1], tex[2]);
glVertex3f(-vert[0], 0.0f, vert[0]);
glTexCoord2f(tex[1], tex[1]);
glVertex3f(-vert[0], 0.0f, -vert[0]);
glColor3fv(unlit);
glTexCoord2f(tex[0], tex[3]);
glVertex3f(-vert[1], 0.0f, vert[1]);
glTexCoord2f(tex[0], tex[0]);
glVertex3f(-vert[1], 0.0f, -vert[1]);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor3fv(lit);
glTexCoord2f(tex[2], tex[2]);
glVertex3f(vert[0], 0.0f, vert[0]);
glTexCoord2f(tex[1], tex[2]);
glVertex3f(-vert[0], 0.0f, vert[0]);
glColor3fv(unlit);
glTexCoord2f(tex[3], tex[3]);
glVertex3f(vert[1], 0.0f, vert[1]);
glTexCoord2f(tex[0], tex[3]);
glVertex3f(-vert[1], 0.0f, vert[1]);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor3fv(lit);
glTexCoord2f(tex[2], tex[1]);
glVertex3f(vert[0], 0.0f, -vert[0]);
glTexCoord2f(tex[2], tex[2]);
glVertex3f(vert[0], 0.0f, vert[0]);
glColor3fv(unlit);
glTexCoord2f(tex[3], tex[0]);
glVertex3f(vert[1], 0.0f, -vert[1]);
glTexCoord2f(tex[3], tex[3]);
glVertex3f(vert[1], 0.0f, vert[1]);
glEnd();
glEndList();
}
}
void Resources::init() {
if (Hack::volume > 0.0f) {
try {
Sound::init(
Hack::openalSpec, Hack::volume, Hack::speedOfSound,
&Hack::cameraPos, &Hack::cameraVel, &Hack::cameraDir
);
} catch (Sound::Unavailable e) {
Hack::volume = 0.0f;
} catch (Common::Exception e) {
WARN(e);
Hack::volume = 0.0f;
}
}
if (Hack::volume > 0.0f) {
try {
Sounds::_init();
} catch (Sound::Unavailable e) {
Hack::volume = 0.0f;
}
}
Textures::_init();
DisplayLists::_init();
}
|
{
"pile_set_name": "Github"
}
|
/**
* \file
*
* \brief Linker script for running in internal FLASH on the SAMD21G18A
*
* Copyright (c) 2017 Microchip Technology Inc.
*
* \asf_license_start
*
* \page License
*
* SPDX-License-Identifier: Apache-2.0
*
* 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 Licence 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.
*
* \asf_license_stop
*
*/
OUTPUT_FORMAT("elf32-littlearm", "elf32-littlearm", "elf32-littlearm")
OUTPUT_ARCH(arm)
SEARCH_DIR(.)
/* Memory Spaces Definitions */
MEMORY
{
rom (rx) : ORIGIN = 0x00000000 + 8K, LENGTH = 0x00040000 - 8K /* 8K offset to preserve bootloader */
ram (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}
/* The stack size used by the application. NOTE: you need to adjust according to your application. */
STACK_SIZE = DEFINED(STACK_SIZE) ? STACK_SIZE : DEFINED(__stack_size__) ? __stack_size__ : 0x2000;
ENTRY(Reset_Handler)
/* Section Definitions */
SECTIONS
{
.text :
{
. = ALIGN(4);
_sfixed = .;
KEEP(*(.vectors .vectors.*))
*(.text .text.* .gnu.linkonce.t.*)
*(.glue_7t) *(.glue_7)
*(.rodata .rodata* .gnu.linkonce.r.*)
*(.ARM.extab* .gnu.linkonce.armextab.*)
/* Support C constructors, and C destructors in both user code
and the C library. This also provides support for C++ code. */
. = ALIGN(4);
KEEP(*(.init))
. = ALIGN(4);
__preinit_array_start = .;
KEEP (*(.preinit_array))
__preinit_array_end = .;
. = ALIGN(4);
__init_array_start = .;
KEEP (*(SORT(.init_array.*)))
KEEP (*(.init_array))
__init_array_end = .;
. = ALIGN(4);
KEEP (*crtbegin.o(.ctors))
KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors))
KEEP (*(SORT(.ctors.*)))
KEEP (*crtend.o(.ctors))
. = ALIGN(4);
KEEP(*(.fini))
. = ALIGN(4);
__fini_array_start = .;
KEEP (*(.fini_array))
KEEP (*(SORT(.fini_array.*)))
__fini_array_end = .;
KEEP (*crtbegin.o(.dtors))
KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors))
KEEP (*(SORT(.dtors.*)))
KEEP (*crtend.o(.dtors))
. = ALIGN(4);
_efixed = .; /* End of text section */
} > rom
/* .ARM.exidx is sorted, so has to go in its own output section. */
PROVIDE_HIDDEN (__exidx_start = .);
.ARM.exidx :
{
*(.ARM.exidx* .gnu.linkonce.armexidx.*)
} > rom
PROVIDE_HIDDEN (__exidx_end = .);
. = ALIGN(4);
_etext = .;
.relocate : AT (_etext)
{
. = ALIGN(4);
_srelocate = .;
*(.ramfunc .ramfunc.*);
*(.data .data.*);
. = ALIGN(4);
_erelocate = .;
} > ram
/* .bss section which is used for uninitialized data */
.bss (NOLOAD) :
{
. = ALIGN(4);
_sbss = . ;
_szero = .;
*(.bss .bss.*)
*(COMMON)
. = ALIGN(4);
_ebss = . ;
_ezero = .;
end = .;
} > ram
/* stack section */
.stack (NOLOAD):
{
. = ALIGN(8);
_sstack = .;
. = . + STACK_SIZE;
. = ALIGN(8);
_estack = .;
} > ram
. = ALIGN(4);
_end = . ;
}
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
**
** Copyright (C) 2014-2019 Dinu SV.
** (contact: mail@dinusv.com)
** This file is part of Livekeys Application.
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
****************************************************************************/
#include "live/libraryloadpath.h"
#include "live/visuallog.h"
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QDebug>
namespace lv{
namespace{
bool assertLinkPathExists(const QString& linkPath){
if ( !QDir(linkPath).exists() )
return QDir().mkdir(linkPath);
return true;
}
}// namespace
void LibraryLoadPath::addImpl(const QString& path, const QString& linkPath, bool recursive){
if ( !assertLinkPathExists(linkPath) ){
qCritical("Failed to create link directory. Some library dependencies may fail to load.");
return;
}
QDirIterator dit(path);
while ( dit.hasNext() ){
dit.next();
QFileInfo info = dit.fileInfo();
if ( info.fileName() == "." || info.fileName() == ".." )
continue;
if ( (info.isFile() || info.isSymLink()) &&
info.fileName().startsWith("lib") &&
( info.fileName().contains(".so") || info.fileName().contains(".dylib") )
)
{
QFile f(dit.filePath());
f.link(linkPath + "/" + info.fileName());
vlog_debug("libraryloadpath", "Added \'" + linkPath + "/" + info.fileName() + "\' -> \'" + f.fileName() + "\'");
} else if ( info.isDir() && recursive ){
addImpl(info.filePath(), linkPath, recursive);
}
}
}
}// namespace
|
{
"pile_set_name": "Github"
}
|
/*
* picodlp panel driver
* picodlp_i2c_driver: i2c_client driver
*
* Copyright (C) 2009-2011 Texas Instruments
* Author: Mythri P K <mythripk@ti.com>
* Mayuresh Janorkar <mayur@ti.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/module.h>
#include <linux/input.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/i2c.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <video/omapdss.h>
#include <video/omap-panel-picodlp.h>
#include "panel-picodlp.h"
struct picodlp_data {
struct mutex lock;
struct i2c_client *picodlp_i2c_client;
};
static struct i2c_board_info picodlp_i2c_board_info = {
I2C_BOARD_INFO("picodlp_i2c_driver", 0x1b),
};
struct picodlp_i2c_data {
struct mutex xfer_lock;
};
static struct i2c_device_id picodlp_i2c_id[] = {
{ "picodlp_i2c_driver", 0 },
};
struct picodlp_i2c_command {
u8 reg;
u32 value;
};
static struct omap_video_timings pico_ls_timings = {
.x_res = 864,
.y_res = 480,
.hsw = 7,
.hfp = 11,
.hbp = 7,
.pixel_clock = 19200,
.vsw = 2,
.vfp = 3,
.vbp = 14,
};
static inline struct picodlp_panel_data
*get_panel_data(const struct omap_dss_device *dssdev)
{
return (struct picodlp_panel_data *) dssdev->data;
}
static u32 picodlp_i2c_read(struct i2c_client *client, u8 reg)
{
u8 read_cmd[] = {READ_REG_SELECT, reg}, data[4];
struct picodlp_i2c_data *picodlp_i2c_data = i2c_get_clientdata(client);
struct i2c_msg msg[2];
mutex_lock(&picodlp_i2c_data->xfer_lock);
msg[0].addr = client->addr;
msg[0].flags = 0;
msg[0].len = 2;
msg[0].buf = read_cmd;
msg[1].addr = client->addr;
msg[1].flags = I2C_M_RD;
msg[1].len = 4;
msg[1].buf = data;
i2c_transfer(client->adapter, msg, 2);
mutex_unlock(&picodlp_i2c_data->xfer_lock);
return (data[3] | (data[2] << 8) | (data[1] << 16) | (data[0] << 24));
}
static int picodlp_i2c_write_block(struct i2c_client *client,
u8 *data, int len)
{
struct i2c_msg msg;
int i, r, msg_count = 1;
struct picodlp_i2c_data *picodlp_i2c_data = i2c_get_clientdata(client);
if (len < 1 || len > 32) {
dev_err(&client->dev,
"too long syn_write_block len %d\n", len);
return -EIO;
}
mutex_lock(&picodlp_i2c_data->xfer_lock);
msg.addr = client->addr;
msg.flags = 0;
msg.len = len;
msg.buf = data;
r = i2c_transfer(client->adapter, &msg, msg_count);
mutex_unlock(&picodlp_i2c_data->xfer_lock);
/*
* i2c_transfer returns:
* number of messages sent in case of success
* a negative error number in case of failure
*/
if (r != msg_count)
goto err;
/* In case of success */
for (i = 0; i < len; i++)
dev_dbg(&client->dev,
"addr %x bw 0x%02x[%d]: 0x%02x\n",
client->addr, data[0] + i, i, data[i]);
return 0;
err:
dev_err(&client->dev, "picodlp_i2c_write error\n");
return r;
}
static int picodlp_i2c_write(struct i2c_client *client, u8 reg, u32 value)
{
u8 data[5];
int i;
data[0] = reg;
for (i = 1; i < 5; i++)
data[i] = (value >> (32 - (i) * 8)) & 0xFF;
return picodlp_i2c_write_block(client, data, 5);
}
static int picodlp_i2c_write_array(struct i2c_client *client,
const struct picodlp_i2c_command commands[],
int count)
{
int i, r = 0;
for (i = 0; i < count; i++) {
r = picodlp_i2c_write(client, commands[i].reg,
commands[i].value);
if (r)
return r;
}
return r;
}
static int picodlp_wait_for_dma_done(struct i2c_client *client)
{
u8 trial = 100;
do {
msleep(1);
if (!trial--)
return -ETIMEDOUT;
} while (picodlp_i2c_read(client, MAIN_STATUS) & DMA_STATUS);
return 0;
}
/**
* picodlp_i2c_init: i2c_initialization routine
* client: i2c_client for communication
*
* return
* 0 : Success, no error
* error code : Failure
*/
static int picodlp_i2c_init(struct i2c_client *client)
{
int r;
static const struct picodlp_i2c_command init_cmd_set1[] = {
{SOFT_RESET, 1},
{DMD_PARK_TRIGGER, 1},
{MISC_REG, 5},
{SEQ_CONTROL, 0},
{SEQ_VECTOR, 0x100},
{DMD_BLOCK_COUNT, 7},
{DMD_VCC_CONTROL, 0x109},
{DMD_PARK_PULSE_COUNT, 0xA},
{DMD_PARK_PULSE_WIDTH, 0xB},
{DMD_PARK_DELAY, 0x2ED},
{DMD_SHADOW_ENABLE, 0},
{FLASH_OPCODE, 0xB},
{FLASH_DUMMY_BYTES, 1},
{FLASH_ADDR_BYTES, 3},
{PBC_CONTROL, 0},
{FLASH_START_ADDR, CMT_LUT_0_START_ADDR},
{FLASH_READ_BYTES, CMT_LUT_0_SIZE},
{CMT_SPLASH_LUT_START_ADDR, 0},
{CMT_SPLASH_LUT_DEST_SELECT, CMT_LUT_ALL},
{PBC_CONTROL, 1},
};
static const struct picodlp_i2c_command init_cmd_set2[] = {
{PBC_CONTROL, 0},
{CMT_SPLASH_LUT_DEST_SELECT, 0},
{PBC_CONTROL, 0},
{FLASH_START_ADDR, SEQUENCE_0_START_ADDR},
{FLASH_READ_BYTES, SEQUENCE_0_SIZE},
{SEQ_RESET_LUT_START_ADDR, 0},
{SEQ_RESET_LUT_DEST_SELECT, SEQ_SEQ_LUT},
{PBC_CONTROL, 1},
};
static const struct picodlp_i2c_command init_cmd_set3[] = {
{PBC_CONTROL, 0},
{SEQ_RESET_LUT_DEST_SELECT, 0},
{PBC_CONTROL, 0},
{FLASH_START_ADDR, DRC_TABLE_0_START_ADDR},
{FLASH_READ_BYTES, DRC_TABLE_0_SIZE},
{SEQ_RESET_LUT_START_ADDR, 0},
{SEQ_RESET_LUT_DEST_SELECT, SEQ_DRC_LUT_ALL},
{PBC_CONTROL, 1},
};
static const struct picodlp_i2c_command init_cmd_set4[] = {
{PBC_CONTROL, 0},
{SEQ_RESET_LUT_DEST_SELECT, 0},
{SDC_ENABLE, 1},
{AGC_CTRL, 7},
{CCA_C1A, 0x100},
{CCA_C1B, 0x0},
{CCA_C1C, 0x0},
{CCA_C2A, 0x0},
{CCA_C2B, 0x100},
{CCA_C2C, 0x0},
{CCA_C3A, 0x0},
{CCA_C3B, 0x0},
{CCA_C3C, 0x100},
{CCA_C7A, 0x100},
{CCA_C7B, 0x100},
{CCA_C7C, 0x100},
{CCA_ENABLE, 1},
{CPU_IF_MODE, 1},
{SHORT_FLIP, 1},
{CURTAIN_CONTROL, 0},
{DMD_PARK_TRIGGER, 0},
{R_DRIVE_CURRENT, 0x298},
{G_DRIVE_CURRENT, 0x298},
{B_DRIVE_CURRENT, 0x298},
{RGB_DRIVER_ENABLE, 7},
{SEQ_CONTROL, 0},
{ACTGEN_CONTROL, 0x10},
{SEQUENCE_MODE, SEQ_LOCK},
{DATA_FORMAT, RGB888},
{INPUT_RESOLUTION, WVGA_864_LANDSCAPE},
{INPUT_SOURCE, PARALLEL_RGB},
{CPU_IF_SYNC_METHOD, 1},
{SEQ_CONTROL, 1}
};
r = picodlp_i2c_write_array(client, init_cmd_set1,
ARRAY_SIZE(init_cmd_set1));
if (r)
return r;
r = picodlp_wait_for_dma_done(client);
if (r)
return r;
r = picodlp_i2c_write_array(client, init_cmd_set2,
ARRAY_SIZE(init_cmd_set2));
if (r)
return r;
r = picodlp_wait_for_dma_done(client);
if (r)
return r;
r = picodlp_i2c_write_array(client, init_cmd_set3,
ARRAY_SIZE(init_cmd_set3));
if (r)
return r;
r = picodlp_wait_for_dma_done(client);
if (r)
return r;
r = picodlp_i2c_write_array(client, init_cmd_set4,
ARRAY_SIZE(init_cmd_set4));
if (r)
return r;
return 0;
}
static int picodlp_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct picodlp_i2c_data *picodlp_i2c_data;
picodlp_i2c_data = kzalloc(sizeof(struct picodlp_i2c_data), GFP_KERNEL);
if (!picodlp_i2c_data)
return -ENOMEM;
mutex_init(&picodlp_i2c_data->xfer_lock);
i2c_set_clientdata(client, picodlp_i2c_data);
return 0;
}
static int picodlp_i2c_remove(struct i2c_client *client)
{
struct picodlp_i2c_data *picodlp_i2c_data =
i2c_get_clientdata(client);
kfree(picodlp_i2c_data);
return 0;
}
static struct i2c_driver picodlp_i2c_driver = {
.driver = {
.name = "picodlp_i2c_driver",
},
.probe = picodlp_i2c_probe,
.remove = picodlp_i2c_remove,
.id_table = picodlp_i2c_id,
};
static int picodlp_panel_power_on(struct omap_dss_device *dssdev)
{
int r, trial = 100;
struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev);
struct picodlp_panel_data *picodlp_pdata = get_panel_data(dssdev);
if (dssdev->platform_enable) {
r = dssdev->platform_enable(dssdev);
if (r)
return r;
}
gpio_set_value(picodlp_pdata->pwrgood_gpio, 0);
msleep(1);
gpio_set_value(picodlp_pdata->pwrgood_gpio, 1);
while (!gpio_get_value(picodlp_pdata->emu_done_gpio)) {
if (!trial--) {
dev_err(&dssdev->dev, "emu_done signal not"
" going high\n");
return -ETIMEDOUT;
}
msleep(5);
}
/*
* As per dpp2600 programming guide,
* it is required to sleep for 1000ms after emu_done signal goes high
* then only i2c commands can be successfully sent to dpp2600
*/
msleep(1000);
r = omapdss_dpi_display_enable(dssdev);
if (r) {
dev_err(&dssdev->dev, "failed to enable DPI\n");
goto err1;
}
r = picodlp_i2c_init(picod->picodlp_i2c_client);
if (r)
goto err;
dssdev->state = OMAP_DSS_DISPLAY_ACTIVE;
return r;
err:
omapdss_dpi_display_disable(dssdev);
err1:
if (dssdev->platform_disable)
dssdev->platform_disable(dssdev);
return r;
}
static void picodlp_panel_power_off(struct omap_dss_device *dssdev)
{
struct picodlp_panel_data *picodlp_pdata = get_panel_data(dssdev);
omapdss_dpi_display_disable(dssdev);
gpio_set_value(picodlp_pdata->emu_done_gpio, 0);
gpio_set_value(picodlp_pdata->pwrgood_gpio, 0);
if (dssdev->platform_disable)
dssdev->platform_disable(dssdev);
}
static int picodlp_panel_probe(struct omap_dss_device *dssdev)
{
struct picodlp_data *picod;
struct picodlp_panel_data *picodlp_pdata = get_panel_data(dssdev);
struct i2c_adapter *adapter;
struct i2c_client *picodlp_i2c_client;
int r = 0, picodlp_adapter_id;
dssdev->panel.config = OMAP_DSS_LCD_TFT | OMAP_DSS_LCD_ONOFF |
OMAP_DSS_LCD_IHS | OMAP_DSS_LCD_IVS;
dssdev->panel.acb = 0x0;
dssdev->panel.timings = pico_ls_timings;
picod = kzalloc(sizeof(struct picodlp_data), GFP_KERNEL);
if (!picod)
return -ENOMEM;
mutex_init(&picod->lock);
picodlp_adapter_id = picodlp_pdata->picodlp_adapter_id;
adapter = i2c_get_adapter(picodlp_adapter_id);
if (!adapter) {
dev_err(&dssdev->dev, "can't get i2c adapter\n");
r = -ENODEV;
goto err;
}
picodlp_i2c_client = i2c_new_device(adapter, &picodlp_i2c_board_info);
if (!picodlp_i2c_client) {
dev_err(&dssdev->dev, "can't add i2c device::"
" picodlp_i2c_client is NULL\n");
r = -ENODEV;
goto err;
}
picod->picodlp_i2c_client = picodlp_i2c_client;
dev_set_drvdata(&dssdev->dev, picod);
return r;
err:
kfree(picod);
return r;
}
static void picodlp_panel_remove(struct omap_dss_device *dssdev)
{
struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev);
i2c_unregister_device(picod->picodlp_i2c_client);
dev_set_drvdata(&dssdev->dev, NULL);
dev_dbg(&dssdev->dev, "removing picodlp panel\n");
kfree(picod);
}
static int picodlp_panel_enable(struct omap_dss_device *dssdev)
{
struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev);
int r;
dev_dbg(&dssdev->dev, "enabling picodlp panel\n");
mutex_lock(&picod->lock);
if (dssdev->state != OMAP_DSS_DISPLAY_DISABLED) {
mutex_unlock(&picod->lock);
return -EINVAL;
}
r = picodlp_panel_power_on(dssdev);
mutex_unlock(&picod->lock);
return r;
}
static void picodlp_panel_disable(struct omap_dss_device *dssdev)
{
struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev);
mutex_lock(&picod->lock);
/* Turn off DLP Power */
if (dssdev->state == OMAP_DSS_DISPLAY_ACTIVE)
picodlp_panel_power_off(dssdev);
dssdev->state = OMAP_DSS_DISPLAY_DISABLED;
mutex_unlock(&picod->lock);
dev_dbg(&dssdev->dev, "disabling picodlp panel\n");
}
static int picodlp_panel_suspend(struct omap_dss_device *dssdev)
{
struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev);
mutex_lock(&picod->lock);
/* Turn off DLP Power */
if (dssdev->state != OMAP_DSS_DISPLAY_ACTIVE) {
mutex_unlock(&picod->lock);
dev_err(&dssdev->dev, "unable to suspend picodlp panel,"
" panel is not ACTIVE\n");
return -EINVAL;
}
picodlp_panel_power_off(dssdev);
dssdev->state = OMAP_DSS_DISPLAY_SUSPENDED;
mutex_unlock(&picod->lock);
dev_dbg(&dssdev->dev, "suspending picodlp panel\n");
return 0;
}
static int picodlp_panel_resume(struct omap_dss_device *dssdev)
{
struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev);
int r;
mutex_lock(&picod->lock);
if (dssdev->state != OMAP_DSS_DISPLAY_SUSPENDED) {
mutex_unlock(&picod->lock);
dev_err(&dssdev->dev, "unable to resume picodlp panel,"
" panel is not ACTIVE\n");
return -EINVAL;
}
r = picodlp_panel_power_on(dssdev);
mutex_unlock(&picod->lock);
dev_dbg(&dssdev->dev, "resuming picodlp panel\n");
return r;
}
static void picodlp_get_resolution(struct omap_dss_device *dssdev,
u16 *xres, u16 *yres)
{
*xres = dssdev->panel.timings.x_res;
*yres = dssdev->panel.timings.y_res;
}
static struct omap_dss_driver picodlp_driver = {
.probe = picodlp_panel_probe,
.remove = picodlp_panel_remove,
.enable = picodlp_panel_enable,
.disable = picodlp_panel_disable,
.get_resolution = picodlp_get_resolution,
.suspend = picodlp_panel_suspend,
.resume = picodlp_panel_resume,
.driver = {
.name = "picodlp_panel",
.owner = THIS_MODULE,
},
};
static int __init picodlp_init(void)
{
int r = 0;
r = i2c_add_driver(&picodlp_i2c_driver);
if (r) {
printk(KERN_WARNING "picodlp_i2c_driver" \
" registration failed\n");
return r;
}
r = omap_dss_register_driver(&picodlp_driver);
if (r)
i2c_del_driver(&picodlp_i2c_driver);
return r;
}
static void __exit picodlp_exit(void)
{
i2c_del_driver(&picodlp_i2c_driver);
omap_dss_unregister_driver(&picodlp_driver);
}
module_init(picodlp_init);
module_exit(picodlp_exit);
MODULE_AUTHOR("Mythri P K <mythripk@ti.com>");
MODULE_DESCRIPTION("picodlp driver");
MODULE_LICENSE("GPL");
|
{
"pile_set_name": "Github"
}
|
import fs from 'graceful-fs';
import { promisify } from 'util';
export const copyFile = promisify(fs.copyFile);
export const mkdir = promisify(fs.mkdir);
export const readdir = promisify(fs.readdir);
export const readFile = promisify(fs.readFile);
export const stat = promisify(fs.stat);
|
{
"pile_set_name": "Github"
}
|
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_plot_spectrogram.h"
#include "qwt_painter.h"
#include "qwt_interval.h"
#include "qwt_scale_map.h"
#include "qwt_color_map.h"
#include <qimage.h>
#include <qpen.h>
#include <qpainter.h>
#include <qmath.h>
#include <qalgorithms.h>
#if QT_VERSION >= 0x040400
#include <qthread.h>
#include <qfuture.h>
#include <qtconcurrentrun.h>
#endif
#define DEBUG_RENDER 0
#if DEBUG_RENDER
#include <QElapsedTimer>
#endif
class QwtPlotSpectrogram::PrivateData
{
public:
PrivateData():
data( NULL )
{
colorMap = new QwtLinearColorMap();
displayMode = ImageMode;
conrecFlags = QwtRasterData::IgnoreAllVerticesOnLevel;
#if 0
conrecFlags |= QwtRasterData::IgnoreOutOfRange;
#endif
}
~PrivateData()
{
delete data;
delete colorMap;
}
QwtRasterData *data;
QwtColorMap *colorMap;
DisplayModes displayMode;
QList<double> contourLevels;
QPen defaultContourPen;
QwtRasterData::ConrecFlags conrecFlags;
};
/*!
Sets the following item attributes:
- QwtPlotItem::AutoScale: true
- QwtPlotItem::Legend: false
The z value is initialized by 8.0.
\param title Title
\sa QwtPlotItem::setItemAttribute(), QwtPlotItem::setZ()
*/
QwtPlotSpectrogram::QwtPlotSpectrogram( const QString &title ):
QwtPlotRasterItem( title )
{
d_data = new PrivateData();
setItemAttribute( QwtPlotItem::AutoScale, true );
setItemAttribute( QwtPlotItem::Legend, false );
setZ( 8.0 );
}
//! Destructor
QwtPlotSpectrogram::~QwtPlotSpectrogram()
{
delete d_data;
}
//! \return QwtPlotItem::Rtti_PlotSpectrogram
int QwtPlotSpectrogram::rtti() const
{
return QwtPlotItem::Rtti_PlotSpectrogram;
}
/*!
The display mode controls how the raster data will be represented.
\param mode Display mode
\param on On/Off
The default setting enables ImageMode.
\sa DisplayMode, displayMode()
*/
void QwtPlotSpectrogram::setDisplayMode( DisplayMode mode, bool on )
{
if ( on != bool( mode & d_data->displayMode ) )
{
if ( on )
d_data->displayMode |= mode;
else
d_data->displayMode &= ~mode;
}
legendChanged();
itemChanged();
}
/*!
The display mode controls how the raster data will be represented.
\param mode Display mode
\return true if mode is enabled
*/
bool QwtPlotSpectrogram::testDisplayMode( DisplayMode mode ) const
{
return ( d_data->displayMode & mode );
}
/*!
Change the color map
Often it is useful to display the mapping between intensities and
colors as an additional plot axis, showing a color bar.
\param colorMap Color Map
\sa colorMap(), QwtScaleWidget::setColorBarEnabled(),
QwtScaleWidget::setColorMap()
*/
void QwtPlotSpectrogram::setColorMap( QwtColorMap *colorMap )
{
if ( d_data->colorMap != colorMap )
{
delete d_data->colorMap;
d_data->colorMap = colorMap;
}
invalidateCache();
legendChanged();
itemChanged();
}
/*!
\return Color Map used for mapping the intensity values to colors
\sa setColorMap()
*/
const QwtColorMap *QwtPlotSpectrogram::colorMap() const
{
return d_data->colorMap;
}
/*!
Build and assign the default pen for the contour lines
In Qt5 the default pen width is 1.0 ( 0.0 in Qt4 ) what makes it
non cosmetic ( see QPen::isCosmetic() ). This method has been introduced
to hide this incompatibility.
\param color Pen color
\param width Pen width
\param style Pen style
\sa pen(), brush()
*/
void QwtPlotSpectrogram::setDefaultContourPen(
const QColor &color, qreal width, Qt::PenStyle style )
{
setDefaultContourPen( QPen( color, width, style ) );
}
/*!
\brief Set the default pen for the contour lines
If the spectrogram has a valid default contour pen
a contour line is painted using the default contour pen.
Otherwise (pen.style() == Qt::NoPen) the pen is calculated
for each contour level using contourPen().
\sa defaultContourPen(), contourPen()
*/
void QwtPlotSpectrogram::setDefaultContourPen( const QPen &pen )
{
if ( pen != d_data->defaultContourPen )
{
d_data->defaultContourPen = pen;
legendChanged();
itemChanged();
}
}
/*!
\return Default contour pen
\sa setDefaultContourPen()
*/
QPen QwtPlotSpectrogram::defaultContourPen() const
{
return d_data->defaultContourPen;
}
/*!
\brief Calculate the pen for a contour line
The color of the pen is the color for level calculated by the color map
\param level Contour level
\return Pen for the contour line
\note contourPen is only used if defaultContourPen().style() == Qt::NoPen
\sa setDefaultContourPen(), setColorMap(), setContourLevels()
*/
QPen QwtPlotSpectrogram::contourPen( double level ) const
{
if ( d_data->data == NULL || d_data->colorMap == NULL )
return QPen();
const QwtInterval intensityRange = d_data->data->interval(Qt::ZAxis);
const QColor c( d_data->colorMap->rgb( intensityRange, level ) );
return QPen( c );
}
/*!
Modify an attribute of the CONREC algorithm, used to calculate
the contour lines.
\param flag CONREC flag
\param on On/Off
\sa testConrecFlag(), renderContourLines(),
QwtRasterData::contourLines()
*/
void QwtPlotSpectrogram::setConrecFlag(
QwtRasterData::ConrecFlag flag, bool on )
{
if ( bool( d_data->conrecFlags & flag ) == on )
return;
if ( on )
d_data->conrecFlags |= flag;
else
d_data->conrecFlags &= ~flag;
itemChanged();
}
/*!
Test an attribute of the CONREC algorithm, used to calculate
the contour lines.
\param flag CONREC flag
\return true, is enabled
The default setting enables QwtRasterData::IgnoreAllVerticesOnLevel
\sa setConrecClag(), renderContourLines(),
QwtRasterData::contourLines()
*/
bool QwtPlotSpectrogram::testConrecFlag(
QwtRasterData::ConrecFlag flag ) const
{
return d_data->conrecFlags & flag;
}
/*!
Set the levels of the contour lines
\param levels Values of the contour levels
\sa contourLevels(), renderContourLines(),
QwtRasterData::contourLines()
\note contourLevels returns the same levels but sorted.
*/
void QwtPlotSpectrogram::setContourLevels( const QList<double> &levels )
{
d_data->contourLevels = levels;
qSort( d_data->contourLevels );
legendChanged();
itemChanged();
}
/*!
\return Levels of the contour lines.
The levels are sorted in increasing order.
\sa contourLevels(), renderContourLines(),
QwtRasterData::contourLines()
*/
QList<double> QwtPlotSpectrogram::contourLevels() const
{
return d_data->contourLevels;
}
/*!
Set the data to be displayed
\param data Spectrogram Data
\sa data()
*/
void QwtPlotSpectrogram::setData( QwtRasterData *data )
{
if ( data != d_data->data )
{
delete d_data->data;
d_data->data = data;
invalidateCache();
itemChanged();
}
}
/*!
\return Spectrogram data
\sa setData()
*/
const QwtRasterData *QwtPlotSpectrogram::data() const
{
return d_data->data;
}
/*!
\return Spectrogram data
\sa setData()
*/
QwtRasterData *QwtPlotSpectrogram::data()
{
return d_data->data;
}
/*!
\return Bounding interval for an axis
The default implementation returns the interval of the
associated raster data object.
\param axis X, Y, or Z axis
\sa QwtRasterData::interval()
*/
QwtInterval QwtPlotSpectrogram::interval(Qt::Axis axis) const
{
if ( d_data->data == NULL )
return QwtInterval();
return d_data->data->interval( axis );
}
/*!
\brief Pixel hint
The geometry of a pixel is used to calculated the resolution and
alignment of the rendered image.
The default implementation returns data()->pixelHint( rect );
\param area In most implementations the resolution of the data doesn't
depend on the requested area.
\return Bounding rectangle of a pixel
\sa QwtPlotRasterItem::pixelHint(), QwtRasterData::pixelHint(),
render(), renderImage()
*/
QRectF QwtPlotSpectrogram::pixelHint( const QRectF &area ) const
{
if ( d_data->data == NULL )
return QRectF();
return d_data->data->pixelHint( area );
}
/*!
\brief Render an image from data and color map.
For each pixel of area the value is mapped into a color.
\param xMap X-Scale Map
\param yMap Y-Scale Map
\param area Requested area for the image in scale coordinates
\param imageSize Size of the requested image
\return A QImage::Format_Indexed8 or QImage::Format_ARGB32 depending
on the color map.
\sa QwtRasterData::value(), QwtColorMap::rgb(),
QwtColorMap::colorIndex()
*/
QImage QwtPlotSpectrogram::renderImage(
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRectF &area, const QSize &imageSize ) const
{
if ( imageSize.isEmpty() || d_data->data == NULL
|| d_data->colorMap == NULL )
{
return QImage();
}
const QwtInterval intensityRange = d_data->data->interval( Qt::ZAxis );
if ( !intensityRange.isValid() )
return QImage();
QImage::Format format = ( d_data->colorMap->format() == QwtColorMap::RGB )
? QImage::Format_ARGB32 : QImage::Format_Indexed8;
QImage image( imageSize, format );
if ( d_data->colorMap->format() == QwtColorMap::Indexed )
image.setColorTable( d_data->colorMap->colorTable( intensityRange ) );
d_data->data->initRaster( area, image.size() );
#if DEBUG_RENDER
QElapsedTimer time;
time.start();
#endif
#if QT_VERSION >= 0x040400 && !defined(QT_NO_QFUTURE)
uint numThreads = renderThreadCount();
if ( numThreads <= 0 )
numThreads = QThread::idealThreadCount();
if ( numThreads <= 0 )
numThreads = 1;
const int numRows = imageSize.height() / numThreads;
QList< QFuture<void> > futures;
for ( uint i = 0; i < numThreads; i++ )
{
QRect tile( 0, i * numRows, image.width(), numRows );
if ( i == numThreads - 1 )
{
tile.setHeight( image.height() - i * numRows );
renderTile( xMap, yMap, tile, &image );
}
else
{
futures += QtConcurrent::run(
this, &QwtPlotSpectrogram::renderTile,
xMap, yMap, tile, &image );
}
}
for ( int i = 0; i < futures.size(); i++ )
futures[i].waitForFinished();
#else // QT_VERSION < 0x040400
const QRect tile( 0, 0, image.width(), image.height() );
renderTile( xMap, yMap, tile, &image );
#endif
#if DEBUG_RENDER
const qint64 elapsed = time.elapsed();
qDebug() << "renderImage" << imageSize << elapsed;
#endif
d_data->data->discardRaster();
return image;
}
/*!
\brief Render a tile of an image.
Rendering in tiles can be used to composite an image in parallel
threads.
\param xMap X-Scale Map
\param yMap Y-Scale Map
\param tile Geometry of the tile in image coordinates
\param image Image to be rendered
*/
void QwtPlotSpectrogram::renderTile(
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRect &tile, QImage *image ) const
{
const QwtInterval range = d_data->data->interval( Qt::ZAxis );
if ( !range.isValid() )
return;
if ( d_data->colorMap->format() == QwtColorMap::RGB )
{
for ( int y = tile.top(); y <= tile.bottom(); y++ )
{
const double ty = yMap.invTransform( y );
QRgb *line = reinterpret_cast<QRgb *>( image->scanLine( y ) );
line += tile.left();
for ( int x = tile.left(); x <= tile.right(); x++ )
{
const double tx = xMap.invTransform( x );
*line++ = d_data->colorMap->rgb( range,
d_data->data->value( tx, ty ) );
}
}
}
else if ( d_data->colorMap->format() == QwtColorMap::Indexed )
{
for ( int y = tile.top(); y <= tile.bottom(); y++ )
{
const double ty = yMap.invTransform( y );
unsigned char *line = image->scanLine( y );
line += tile.left();
for ( int x = tile.left(); x <= tile.right(); x++ )
{
const double tx = xMap.invTransform( x );
*line++ = d_data->colorMap->colorIndex( range,
d_data->data->value( tx, ty ) );
}
}
}
}
/*!
\brief Return the raster to be used by the CONREC contour algorithm.
A larger size will improve the precision of the CONREC algorithm,
but will slow down the time that is needed to calculate the lines.
The default implementation returns rect.size() / 2 bounded to
the resolution depending on pixelSize().
\param area Rectangle, where to calculate the contour lines
\param rect Rectangle in pixel coordinates, where to paint the contour lines
\return Raster to be used by the CONREC contour algorithm.
\note The size will be bounded to rect.size().
\sa drawContourLines(), QwtRasterData::contourLines()
*/
QSize QwtPlotSpectrogram::contourRasterSize(
const QRectF &area, const QRect &rect ) const
{
QSize raster = rect.size() / 2;
const QRectF pixelRect = pixelHint( area );
if ( !pixelRect.isEmpty() )
{
const QSize res( qCeil( rect.width() / pixelRect.width() ),
qCeil( rect.height() / pixelRect.height() ) );
raster = raster.boundedTo( res );
}
return raster;
}
/*!
Calculate contour lines
\param rect Rectangle, where to calculate the contour lines
\param raster Raster, used by the CONREC algorithm
\return Calculated contour lines
\sa contourLevels(), setConrecFlag(),
QwtRasterData::contourLines()
*/
QwtRasterData::ContourLines QwtPlotSpectrogram::renderContourLines(
const QRectF &rect, const QSize &raster ) const
{
if ( d_data->data == NULL )
return QwtRasterData::ContourLines();
return d_data->data->contourLines( rect, raster,
d_data->contourLevels, d_data->conrecFlags );
}
/*!
Paint the contour lines
\param painter Painter
\param xMap Maps x-values into pixel coordinates.
\param yMap Maps y-values into pixel coordinates.
\param contourLines Contour lines
\sa renderContourLines(), defaultContourPen(), contourPen()
*/
void QwtPlotSpectrogram::drawContourLines( QPainter *painter,
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QwtRasterData::ContourLines &contourLines ) const
{
if ( d_data->data == NULL )
return;
const int numLevels = d_data->contourLevels.size();
for ( int l = 0; l < numLevels; l++ )
{
const double level = d_data->contourLevels[l];
QPen pen = defaultContourPen();
if ( pen.style() == Qt::NoPen )
pen = contourPen( level );
if ( pen.style() == Qt::NoPen )
continue;
painter->setPen( pen );
const QPolygonF &lines = contourLines[level];
for ( int i = 0; i < lines.size(); i += 2 )
{
const QPointF p1( xMap.transform( lines[i].x() ),
yMap.transform( lines[i].y() ) );
const QPointF p2( xMap.transform( lines[i+1].x() ),
yMap.transform( lines[i+1].y() ) );
QwtPainter::drawLine( painter, p1, p2 );
}
}
}
/*!
\brief Draw the spectrogram
\param painter Painter
\param xMap Maps x-values into pixel coordinates.
\param yMap Maps y-values into pixel coordinates.
\param canvasRect Contents rectangle of the canvas in painter coordinates
\sa setDisplayMode(), renderImage(),
QwtPlotRasterItem::draw(), drawContourLines()
*/
void QwtPlotSpectrogram::draw( QPainter *painter,
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRectF &canvasRect ) const
{
if ( d_data->displayMode & ImageMode )
QwtPlotRasterItem::draw( painter, xMap, yMap, canvasRect );
if ( d_data->displayMode & ContourMode )
{
// Add some pixels at the borders
const int margin = 2;
QRectF rasterRect( canvasRect.x() - margin, canvasRect.y() - margin,
canvasRect.width() + 2 * margin, canvasRect.height() + 2 * margin );
QRectF area = QwtScaleMap::invTransform( xMap, yMap, rasterRect );
const QRectF br = boundingRect();
if ( br.isValid() )
{
area &= br;
if ( area.isEmpty() )
return;
rasterRect = QwtScaleMap::transform( xMap, yMap, area );
}
QSize raster = contourRasterSize( area, rasterRect.toRect() );
raster = raster.boundedTo( rasterRect.toRect().size() );
if ( raster.isValid() )
{
const QwtRasterData::ContourLines lines =
renderContourLines( area, raster );
drawContourLines( painter, xMap, yMap, lines );
}
}
}
|
{
"pile_set_name": "Github"
}
|
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var DESC = "Vector initialization from constructor call, compare vector-init-1 and array-init-4.";
include "driver.as"
class C {
public var c:C = null;
}
function vector_init_C(): *
{
var t: Vector.<C>;
var c: C = new C;
for ( var i:int=0 ; i < 10000 ; i++ )
t = Vector.<C>([c, c, c]);
return t;
}
TEST(function () { vector_init_C(); }, "vector-init-4");
|
{
"pile_set_name": "Github"
}
|
import sys
from typing import Any, IO, Optional, Tuple, Callable, Dict, List, Union
from .decoder import JSONDecoder as JSONDecoder
from .encoder import JSONEncoder as JSONEncoder
if sys.version_info >= (3, 5):
from .decoder import JSONDecodeError as JSONDecodeError
def dumps(obj: Any,
skipkeys: bool = ...,
ensure_ascii: bool = ...,
check_circular: bool = ...,
allow_nan: bool = ...,
cls: Any = ...,
indent: Union[None, int, str] = ...,
separators: Optional[Tuple[str, str]] = ...,
default: Optional[Callable[[Any], Any]] = ...,
sort_keys: bool = ...,
**kwds: Any) -> str: ...
def dump(obj: Any,
fp: IO[str],
skipkeys: bool = ...,
ensure_ascii: bool = ...,
check_circular: bool = ...,
allow_nan: bool = ...,
cls: Any = ...,
indent: Union[None, int, str] = ...,
separators: Optional[Tuple[str, str]] = ...,
default: Optional[Callable[[Any], Any]] = ...,
sort_keys: bool = ...,
**kwds: Any) -> None: ...
def loads(s: Union[str, bytes, bytearray],
encoding: Any = ..., # ignored and deprecated
cls: Any = ...,
object_hook: Optional[Callable[[Dict], Any]] = ...,
parse_float: Optional[Callable[[str], Any]] = ...,
parse_int: Optional[Callable[[str], Any]] = ...,
parse_constant: Optional[Callable[[str], Any]] = ...,
object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ...,
**kwds: Any) -> Any: ...
if sys.version_info >= (3, 6):
_LoadIO = IO[Any]
else:
_LoadIO = IO[str]
def load(fp: _LoadIO,
cls: Any = ...,
object_hook: Optional[Callable[[Dict], Any]] = ...,
parse_float: Optional[Callable[[str], Any]] = ...,
parse_int: Optional[Callable[[str], Any]] = ...,
parse_constant: Optional[Callable[[str], Any]] = ...,
object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ...,
**kwds: Any) -> Any: ...
|
{
"pile_set_name": "Github"
}
|
// Copyright 2011 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#if !defined(JSON_IS_AMALGAMATION)
#include <json/writer.h>
#include "json_tool.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <iomanip>
#include <memory>
#include <sstream>
#include <utility>
#include <set>
#include <cassert>
#include <cstring>
#include <cstdio>
#if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0
#include <float.h>
#define isfinite _finite
#elif defined(__sun) && defined(__SVR4) //Solaris
#include <ieeefp.h>
#define isfinite finite
#else
#include <cmath>
#define isfinite std::isfinite
#endif
#if defined(_MSC_VER) && _MSC_VER < 1500 // VC++ 8.0 and below
#define snprintf _snprintf
#elif defined(__ANDROID__)
#define snprintf snprintf
#elif __cplusplus >= 201103L
#define snprintf std::snprintf
#endif
#if defined(__BORLANDC__)
#include <float.h>
#define isfinite _finite
#define snprintf _snprintf
#endif
#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
// Disable warning about strdup being deprecated.
#pragma warning(disable : 4996)
#endif
namespace Json {
#if __cplusplus >= 201103L
typedef std::unique_ptr<StreamWriter> StreamWriterPtr;
#else
typedef std::auto_ptr<StreamWriter> StreamWriterPtr;
#endif
static bool containsControlCharacter(const char* str) {
while (*str) {
if (isControlCharacter(*(str++)))
return true;
}
return false;
}
static bool containsControlCharacter0(const char* str, unsigned len) {
char const* end = str + len;
while (end != str) {
if (isControlCharacter(*str) || 0 == *str)
return true;
++str;
}
return false;
}
std::string valueToString(LargestInt value) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
if (value == Value::minLargestInt) {
uintToString(LargestUInt(Value::maxLargestInt) + 1, current);
*--current = '-';
}
else if (value < 0) {
uintToString(LargestUInt(-value), current);
*--current = '-';
}
else {
uintToString(LargestUInt(value), current);
}
assert(current >= buffer);
return current;
}
std::string valueToString(LargestUInt value) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
uintToString(value, current);
assert(current >= buffer);
return current;
}
#if defined(JSON_HAS_INT64)
std::string valueToString(Int value) {
return valueToString(LargestInt(value));
}
std::string valueToString(UInt value) {
return valueToString(LargestUInt(value));
}
#endif // # if defined(JSON_HAS_INT64)
std::string valueToString(double value) {
// Allocate a buffer that is more than large enough to store the 16 digits of
// precision requested below.
char buffer[32];
int len = -1;
// Print into the buffer. We need not request the alternative representation
// that always has a decimal point because JSON doesn't distingish the
// concepts of reals and integers.
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with
// visual studio 2005 to
// avoid warning.
#if defined(WINCE)
len = _snprintf(buffer, sizeof(buffer), "%.17g", value);
#else
len = sprintf_s(buffer, sizeof(buffer), "%.17g", value);
#endif
#else
if (isfinite(value)) {
len = snprintf(buffer, sizeof(buffer), "%.17g", value);
}
else {
// IEEE standard states that NaN values will not compare to themselves
if (value != value) {
len = snprintf(buffer, sizeof(buffer), "null");
}
else if (value < 0) {
len = snprintf(buffer, sizeof(buffer), "-1e+9999");
}
else {
len = snprintf(buffer, sizeof(buffer), "1e+9999");
}
// For those, we do not need to call fixNumLoc, but it is fast.
}
#endif
assert(len >= 0);
fixNumericLocale(buffer, buffer + len);
return buffer;
}
std::string valueToString(bool value) { return value ? "true" : "false"; }
std::string valueToQuotedString(const char* value) {
if (value == NULL)
return "";
// Not sure how to handle unicode...
if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL &&
!containsControlCharacter(value))
return std::string("\"") + value + "\"";
// We have to walk value and escape any special characters.
// Appending to std::string is not efficient, but this should be rare.
// (Note: forward slashes are *not* rare, but I am not escaping them.)
std::string::size_type maxsize =
strlen(value) * 2 + 3; // allescaped+quotes+NULL
std::string result;
result.reserve(maxsize); // to avoid lots of mallocs
result += "\"";
for (const char* c = value; *c != 0; ++c) {
switch (*c) {
case '\"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
// case '/':
// Even though \/ is considered a legal escape in JSON, a bare
// slash is also legal, so I see no reason to escape it.
// (I hope I am not misunderstanding something.
// blep notes: actually escaping \/ may be useful in javascript to avoid </
// sequence.
// Should add a flag to allow this compatibility mode and prevent this
// sequence from occurring.
default:
if (isControlCharacter(*c)) {
std::ostringstream oss;
oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
<< std::setw(4) << static_cast<int>(*c);
result += oss.str();
}
else {
result += *c;
}
break;
}
}
result += "\"";
return result;
}
// https://github.com/upcaste/upcaste/blob/master/src/upcore/src/cstring/strnpbrk.cpp
static char const* strnpbrk(char const* s, char const* accept, size_t n) {
assert((s || !n) && accept);
char const* const end = s + n;
for (char const* cur = s; cur < end; ++cur) {
int const c = *cur;
for (char const* a = accept; *a; ++a) {
if (*a == c) {
return cur;
}
}
}
return NULL;
}
static std::string valueToQuotedStringN(const char* value, unsigned length) {
if (value == NULL)
return "";
// Not sure how to handle unicode...
if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL &&
!containsControlCharacter0(value, length))
return std::string("\"") + value + "\"";
// We have to walk value and escape any special characters.
// Appending to std::string is not efficient, but this should be rare.
// (Note: forward slashes are *not* rare, but I am not escaping them.)
std::string::size_type maxsize =
length * 2 + 3; // allescaped+quotes+NULL
std::string result;
result.reserve(maxsize); // to avoid lots of mallocs
result += "\"";
char const* end = value + length;
for (const char* c = value; c != end; ++c) {
switch (*c) {
case '\"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
// case '/':
// Even though \/ is considered a legal escape in JSON, a bare
// slash is also legal, so I see no reason to escape it.
// (I hope I am not misunderstanding something.)
// blep notes: actually escaping \/ may be useful in javascript to avoid </
// sequence.
// Should add a flag to allow this compatibility mode and prevent this
// sequence from occurring.
default:
if ((isControlCharacter(*c)) || (*c == 0)) {
std::ostringstream oss;
oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
<< std::setw(4) << static_cast<int>(*c);
result += oss.str();
}
else {
result += *c;
}
break;
}
}
result += "\"";
return result;
}
// Class Writer
// //////////////////////////////////////////////////////////////////
Writer::~Writer() {}
// Class FastWriter
// //////////////////////////////////////////////////////////////////
FastWriter::FastWriter()
: yamlCompatiblityEnabled_(false), dropNullPlaceholders_(false),
omitEndingLineFeed_(false) {}
void FastWriter::enableYAMLCompatibility() { yamlCompatiblityEnabled_ = true; }
void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; }
void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; }
std::string FastWriter::write(const Value& root) {
document_ = "";
writeValue(root);
if (!omitEndingLineFeed_)
document_ += "\n";
return document_;
}
void FastWriter::writeValue(const Value& value) {
switch (value.type()) {
case nullValue:
if (!dropNullPlaceholders_)
document_ += "null";
break;
case intValue:
document_ += valueToString(value.asLargestInt());
break;
case uintValue:
document_ += valueToString(value.asLargestUInt());
break;
case realValue:
document_ += valueToString(value.asDouble());
break;
case stringValue:
{
// Is NULL possible for value.string_?
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) document_ += valueToQuotedStringN(str, static_cast<unsigned>(end - str));
break;
}
case booleanValue:
document_ += valueToString(value.asBool());
break;
case arrayValue: {
document_ += '[';
int size = value.size();
for (int index = 0; index < size; ++index) {
if (index > 0)
document_ += ',';
writeValue(value[index]);
}
document_ += ']';
} break;
case objectValue: {
Value::Members members(value.getMemberNames());
document_ += '{';
for (Value::Members::iterator it = members.begin(); it != members.end();
++it) {
const std::string& name = *it;
if (it != members.begin())
document_ += ',';
document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
document_ += yamlCompatiblityEnabled_ ? ": " : ":";
writeValue(value[name]);
}
document_ += '}';
} break;
}
}
// Class StyledWriter
// //////////////////////////////////////////////////////////////////
StyledWriter::StyledWriter()
: rightMargin_(74), indentSize_(3), addChildValues_() {}
std::string StyledWriter::write(const Value& root) {
document_ = "";
addChildValues_ = false;
indentString_ = "";
writeCommentBeforeValue(root);
writeValue(root);
writeCommentAfterValueOnSameLine(root);
document_ += "\n";
return document_;
}
void StyledWriter::writeValue(const Value& value) {
switch (value.type()) {
case nullValue:
pushValue("null");
break;
case intValue:
pushValue(valueToString(value.asLargestInt()));
break;
case uintValue:
pushValue(valueToString(value.asLargestUInt()));
break;
case realValue:
pushValue(valueToString(value.asDouble()));
break;
case stringValue:
{
// Is NULL possible for value.string_?
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str)));
else pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
case arrayValue:
writeArrayValue(value);
break;
case objectValue: {
Value::Members members(value.getMemberNames());
if (members.empty())
pushValue("{}");
else {
writeWithIndent("{");
indent();
Value::Members::iterator it = members.begin();
for (;;) {
const std::string& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
document_ += " : ";
writeValue(childValue);
if (++it == members.end()) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
document_ += ',';
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("}");
}
} break;
}
}
void StyledWriter::writeArrayValue(const Value& value) {
unsigned size = value.size();
if (size == 0)
pushValue("[]");
else {
bool isArrayMultiLine = isMultineArray(value);
if (isArrayMultiLine) {
writeWithIndent("[");
indent();
bool hasChildValue = !childValues_.empty();
unsigned index = 0;
for (;;) {
const Value& childValue = value[index];
writeCommentBeforeValue(childValue);
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
writeIndent();
writeValue(childValue);
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
document_ += ',';
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("]");
}
else // output on a single line
{
assert(childValues_.size() == size);
document_ += "[ ";
for (unsigned index = 0; index < size; ++index) {
if (index > 0)
document_ += ", ";
document_ += childValues_[index];
}
document_ += " ]";
}
}
}
bool StyledWriter::isMultineArray(const Value& value) {
int size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (int index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
isMultiLine =
isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0);
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (int index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += int(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
}
return isMultiLine;
}
void StyledWriter::pushValue(const std::string& value) {
if (addChildValues_)
childValues_.push_back(value);
else
document_ += value;
}
void StyledWriter::writeIndent() {
if (!document_.empty()) {
char last = document_[document_.length() - 1];
if (last == ' ') // already indented
return;
if (last != '\n') // Comments may add new-line
document_ += '\n';
}
document_ += indentString_;
}
void StyledWriter::writeWithIndent(const std::string& value) {
writeIndent();
document_ += value;
}
void StyledWriter::indent() { indentString_ += std::string(indentSize_, ' '); }
void StyledWriter::unindent() {
assert(int(indentString_.size()) >= indentSize_);
indentString_.resize(indentString_.size() - indentSize_);
}
void StyledWriter::writeCommentBeforeValue(const Value& root) {
if (!root.hasComment(commentBefore))
return;
document_ += "\n";
writeIndent();
const std::string& comment = root.getComment(commentBefore);
std::string::const_iterator iter = comment.begin();
while (iter != comment.end()) {
document_ += *iter;
if (*iter == '\n' &&
(iter != comment.end() && *(iter + 1) == '/'))
writeIndent();
++iter;
}
// Comments are stripped of trailing newlines, so add one here
document_ += "\n";
}
void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) {
if (root.hasComment(commentAfterOnSameLine))
document_ += " " + root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
document_ += "\n";
document_ += root.getComment(commentAfter);
document_ += "\n";
}
}
bool StyledWriter::hasCommentForValue(const Value& value) {
return value.hasComment(commentBefore) ||
value.hasComment(commentAfterOnSameLine) ||
value.hasComment(commentAfter);
}
// Class StyledStreamWriter
// //////////////////////////////////////////////////////////////////
StyledStreamWriter::StyledStreamWriter(std::string indentation)
: document_(NULL), rightMargin_(74), indentation_(indentation),
addChildValues_() {}
void StyledStreamWriter::write(std::ostream& out, const Value& root) {
document_ = &out;
addChildValues_ = false;
indentString_ = "";
indented_ = true;
writeCommentBeforeValue(root);
if (!indented_) writeIndent();
indented_ = true;
writeValue(root);
writeCommentAfterValueOnSameLine(root);
*document_ << "\n";
document_ = NULL; // Forget the stream, for safety.
}
void StyledStreamWriter::writeValue(const Value& value) {
switch (value.type()) {
case nullValue:
pushValue("null");
break;
case intValue:
pushValue(valueToString(value.asLargestInt()));
break;
case uintValue:
pushValue(valueToString(value.asLargestUInt()));
break;
case realValue:
pushValue(valueToString(value.asDouble()));
break;
case stringValue:
{
// Is NULL possible for value.string_?
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str)));
else pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
case arrayValue:
writeArrayValue(value);
break;
case objectValue: {
Value::Members members(value.getMemberNames());
if (members.empty())
pushValue("{}");
else {
writeWithIndent("{");
indent();
Value::Members::iterator it = members.begin();
for (;;) {
const std::string& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
*document_ << " : ";
writeValue(childValue);
if (++it == members.end()) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*document_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("}");
}
} break;
}
}
void StyledStreamWriter::writeArrayValue(const Value& value) {
unsigned size = value.size();
if (size == 0)
pushValue("[]");
else {
bool isArrayMultiLine = isMultineArray(value);
if (isArrayMultiLine) {
writeWithIndent("[");
indent();
bool hasChildValue = !childValues_.empty();
unsigned index = 0;
for (;;) {
const Value& childValue = value[index];
writeCommentBeforeValue(childValue);
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
if (!indented_) writeIndent();
indented_ = true;
writeValue(childValue);
indented_ = false;
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*document_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("]");
}
else // output on a single line
{
assert(childValues_.size() == size);
*document_ << "[ ";
for (unsigned index = 0; index < size; ++index) {
if (index > 0)
*document_ << ", ";
*document_ << childValues_[index];
}
*document_ << " ]";
}
}
}
bool StyledStreamWriter::isMultineArray(const Value& value) {
int size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (int index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
isMultiLine =
isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0);
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (int index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += int(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
}
return isMultiLine;
}
void StyledStreamWriter::pushValue(const std::string& value) {
if (addChildValues_)
childValues_.push_back(value);
else
*document_ << value;
}
void StyledStreamWriter::writeIndent() {
// blep intended this to look at the so-far-written string
// to determine whether we are already indented, but
// with a stream we cannot do that. So we rely on some saved state.
// The caller checks indented_.
*document_ << '\n' << indentString_;
}
void StyledStreamWriter::writeWithIndent(const std::string& value) {
if (!indented_) writeIndent();
*document_ << value;
indented_ = false;
}
void StyledStreamWriter::indent() { indentString_ += indentation_; }
void StyledStreamWriter::unindent() {
assert(indentString_.size() >= indentation_.size());
indentString_.resize(indentString_.size() - indentation_.size());
}
void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {
if (!root.hasComment(commentBefore))
return;
if (!indented_) writeIndent();
const std::string& comment = root.getComment(commentBefore);
std::string::const_iterator iter = comment.begin();
while (iter != comment.end()) {
*document_ << *iter;
if (*iter == '\n' &&
(iter != comment.end() && *(iter + 1) == '/'))
// writeIndent(); // would include newline
*document_ << indentString_;
++iter;
}
indented_ = false;
}
void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) {
if (root.hasComment(commentAfterOnSameLine))
*document_ << ' ' << root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
writeIndent();
*document_ << root.getComment(commentAfter);
}
indented_ = false;
}
bool StyledStreamWriter::hasCommentForValue(const Value& value) {
return value.hasComment(commentBefore) ||
value.hasComment(commentAfterOnSameLine) ||
value.hasComment(commentAfter);
}
//////////////////////////
// BuiltStyledStreamWriter
/// Scoped enums are not available until C++11.
struct CommentStyle {
/// Decide whether to write comments.
enum Enum {
None, ///< Drop all comments.
Most, ///< Recover odd behavior of previous versions (not implemented yet).
All ///< Keep all comments.
};
};
struct BuiltStyledStreamWriter : public StreamWriter
{
BuiltStyledStreamWriter(
std::string const& indentation,
CommentStyle::Enum cs,
std::string const& colonSymbol,
std::string const& nullSymbol,
std::string const& endingLineFeedSymbol);
virtual int write(Value const& root, std::ostream* sout);
private:
void writeValue(Value const& value);
void writeArrayValue(Value const& value);
bool isMultineArray(Value const& value);
void pushValue(std::string const& value);
void writeIndent();
void writeWithIndent(std::string const& value);
void indent();
void unindent();
void writeCommentBeforeValue(Value const& root);
void writeCommentAfterValueOnSameLine(Value const& root);
static bool hasCommentForValue(const Value& value);
typedef std::vector<std::string> ChildValues;
ChildValues childValues_;
std::string indentString_;
int rightMargin_;
std::string indentation_;
CommentStyle::Enum cs_;
std::string colonSymbol_;
std::string nullSymbol_;
std::string endingLineFeedSymbol_;
bool addChildValues_ : 1;
bool indented_ : 1;
};
BuiltStyledStreamWriter::BuiltStyledStreamWriter(
std::string const& indentation,
CommentStyle::Enum cs,
std::string const& colonSymbol,
std::string const& nullSymbol,
std::string const& endingLineFeedSymbol)
: rightMargin_(74)
, indentation_(indentation)
, cs_(cs)
, colonSymbol_(colonSymbol)
, nullSymbol_(nullSymbol)
, endingLineFeedSymbol_(endingLineFeedSymbol)
, addChildValues_(false)
, indented_(false)
{
}
int BuiltStyledStreamWriter::write(Value const& root, std::ostream* sout)
{
sout_ = sout;
addChildValues_ = false;
indented_ = true;
indentString_ = "";
writeCommentBeforeValue(root);
if (!indented_) writeIndent();
indented_ = true;
writeValue(root);
writeCommentAfterValueOnSameLine(root);
*sout_ << endingLineFeedSymbol_;
sout_ = NULL;
return 0;
}
void BuiltStyledStreamWriter::writeValue(Value const& value) {
switch (value.type()) {
case nullValue:
pushValue(nullSymbol_);
break;
case intValue:
pushValue(valueToString(value.asLargestInt()));
break;
case uintValue:
pushValue(valueToString(value.asLargestUInt()));
break;
case realValue:
pushValue(valueToString(value.asDouble()));
break;
case stringValue:
{
// Is NULL is possible for value.string_?
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str)));
else pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
case arrayValue:
writeArrayValue(value);
break;
case objectValue: {
Value::Members members(value.getMemberNames());
if (members.empty())
pushValue("{}");
else {
writeWithIndent("{");
indent();
Value::Members::iterator it = members.begin();
for (;;) {
std::string const& name = *it;
Value const& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())));
*sout_ << colonSymbol_;
writeValue(childValue);
if (++it == members.end()) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*sout_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("}");
}
} break;
}
}
void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
unsigned size = value.size();
if (size == 0)
pushValue("[]");
else {
bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value);
if (isMultiLine) {
writeWithIndent("[");
indent();
bool hasChildValue = !childValues_.empty();
unsigned index = 0;
for (;;) {
Value const& childValue = value[index];
writeCommentBeforeValue(childValue);
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
if (!indented_) writeIndent();
indented_ = true;
writeValue(childValue);
indented_ = false;
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*sout_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("]");
}
else // output on a single line
{
assert(childValues_.size() == size);
*sout_ << "[";
if (!indentation_.empty()) *sout_ << " ";
for (unsigned index = 0; index < size; ++index) {
if (index > 0)
*sout_ << ", ";
*sout_ << childValues_[index];
}
if (!indentation_.empty()) *sout_ << " ";
*sout_ << "]";
}
}
}
bool BuiltStyledStreamWriter::isMultineArray(Value const& value) {
int size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (int index = 0; index < size && !isMultiLine; ++index) {
Value const& childValue = value[index];
isMultiLine =
isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0);
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (int index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += int(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
}
return isMultiLine;
}
void BuiltStyledStreamWriter::pushValue(std::string const& value) {
if (addChildValues_)
childValues_.push_back(value);
else
*sout_ << value;
}
void BuiltStyledStreamWriter::writeIndent() {
// blep intended this to look at the so-far-written string
// to determine whether we are already indented, but
// with a stream we cannot do that. So we rely on some saved state.
// The caller checks indented_.
if (!indentation_.empty()) {
// In this case, drop newlines too.
*sout_ << '\n' << indentString_;
}
}
void BuiltStyledStreamWriter::writeWithIndent(std::string const& value) {
if (!indented_) writeIndent();
*sout_ << value;
indented_ = false;
}
void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; }
void BuiltStyledStreamWriter::unindent() {
assert(indentString_.size() >= indentation_.size());
indentString_.resize(indentString_.size() - indentation_.size());
}
void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
if (cs_ == CommentStyle::None) return;
if (!root.hasComment(commentBefore))
return;
if (!indented_) writeIndent();
const std::string& comment = root.getComment(commentBefore);
std::string::const_iterator iter = comment.begin();
while (iter != comment.end()) {
*sout_ << *iter;
if (*iter == '\n' &&
(iter != comment.end() && *(iter + 1) == '/'))
// writeIndent(); // would write extra newline
*sout_ << indentString_;
++iter;
}
indented_ = false;
}
void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(Value const& root) {
if (cs_ == CommentStyle::None) return;
if (root.hasComment(commentAfterOnSameLine))
*sout_ << " " + root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
writeIndent();
*sout_ << root.getComment(commentAfter);
}
}
// static
bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) {
return value.hasComment(commentBefore) ||
value.hasComment(commentAfterOnSameLine) ||
value.hasComment(commentAfter);
}
///////////////
// StreamWriter
StreamWriter::StreamWriter()
: sout_(NULL)
{
}
StreamWriter::~StreamWriter()
{
}
StreamWriter::Factory::~Factory()
{}
StreamWriterBuilder::StreamWriterBuilder()
{
setDefaults(&settings_);
}
StreamWriterBuilder::~StreamWriterBuilder()
{}
StreamWriter* StreamWriterBuilder::newStreamWriter() const
{
std::string indentation = settings_["indentation"].asString();
std::string cs_str = settings_["commentStyle"].asString();
bool eyc = settings_["enableYAMLCompatibility"].asBool();
bool dnp = settings_["dropNullPlaceholders"].asBool();
CommentStyle::Enum cs = CommentStyle::All;
if (cs_str == "All") {
cs = CommentStyle::All;
}
else if (cs_str == "None") {
cs = CommentStyle::None;
}
else {
throwRuntimeError("commentStyle must be 'All' or 'None'");
}
std::string colonSymbol = " : ";
if (eyc) {
colonSymbol = ": ";
}
else if (indentation.empty()) {
colonSymbol = ":";
}
std::string nullSymbol = "null";
if (dnp) {
nullSymbol = "";
}
std::string endingLineFeedSymbol = "";
return new BuiltStyledStreamWriter(
indentation, cs,
colonSymbol, nullSymbol, endingLineFeedSymbol);
}
static void getValidWriterKeys(std::set<std::string>* valid_keys)
{
valid_keys->clear();
valid_keys->insert("indentation");
valid_keys->insert("commentStyle");
valid_keys->insert("enableYAMLCompatibility");
valid_keys->insert("dropNullPlaceholders");
}
bool StreamWriterBuilder::validate(Json::Value* invalid) const
{
Json::Value my_invalid;
if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
Json::Value& inv = *invalid;
std::set<std::string> valid_keys;
getValidWriterKeys(&valid_keys);
Value::Members keys = settings_.getMemberNames();
size_t n = keys.size();
for (size_t i = 0; i < n; ++i) {
std::string const& key = keys[i];
if (valid_keys.find(key) == valid_keys.end()) {
inv[key] = settings_[key];
}
}
return 0u == inv.size();
}
Value& StreamWriterBuilder::operator[](std::string key)
{
return settings_[key];
}
// static
void StreamWriterBuilder::setDefaults(Json::Value* settings)
{
//! [StreamWriterBuilderDefaults]
(*settings)["commentStyle"] = "All";
(*settings)["indentation"] = "\t";
(*settings)["enableYAMLCompatibility"] = false;
(*settings)["dropNullPlaceholders"] = false;
//! [StreamWriterBuilderDefaults]
}
std::string writeString(StreamWriter::Factory const& builder, Value const& root) {
std::ostringstream sout;
StreamWriterPtr const writer(builder.newStreamWriter());
writer->write(root, &sout);
return sout.str();
}
std::ostream& operator<<(std::ostream& sout, Value const& root) {
StreamWriterBuilder builder;
StreamWriterPtr const writer(builder.newStreamWriter());
writer->write(root, &sout);
return sout;
}
} // namespace Json
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2004-2011 Atheros Communications Inc.
* Copyright (c) 2011-2012 Qualcomm Atheros, Inc.
*
* Permission to use, copy, modify, and/or 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.
*/
#include "core.h"
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/export.h>
#include <linux/vmalloc.h>
#include "debug.h"
#include "hif-ops.h"
#include "htc-ops.h"
#include "cfg80211.h"
unsigned int debug_mask;
static unsigned int suspend_mode;
static unsigned int wow_mode;
static unsigned int uart_debug;
static unsigned int uart_rate = 115200;
static unsigned int ath6kl_p2p;
static unsigned int testmode;
static unsigned int recovery_enable;
static unsigned int heart_beat_poll;
module_param(debug_mask, uint, 0644);
module_param(suspend_mode, uint, 0644);
module_param(wow_mode, uint, 0644);
module_param(uart_debug, uint, 0644);
module_param(uart_rate, uint, 0644);
module_param(ath6kl_p2p, uint, 0644);
module_param(testmode, uint, 0644);
module_param(recovery_enable, uint, 0644);
module_param(heart_beat_poll, uint, 0644);
MODULE_PARM_DESC(recovery_enable, "Enable recovery from firmware error");
MODULE_PARM_DESC(heart_beat_poll,
"Enable fw error detection periodic polling in msecs - Also set recovery_enable for this to be effective");
void ath6kl_core_tx_complete(struct ath6kl *ar, struct sk_buff *skb)
{
ath6kl_htc_tx_complete(ar, skb);
}
EXPORT_SYMBOL(ath6kl_core_tx_complete);
void ath6kl_core_rx_complete(struct ath6kl *ar, struct sk_buff *skb, u8 pipe)
{
ath6kl_htc_rx_complete(ar, skb, pipe);
}
EXPORT_SYMBOL(ath6kl_core_rx_complete);
int ath6kl_core_init(struct ath6kl *ar, enum ath6kl_htc_type htc_type)
{
struct ath6kl_bmi_target_info targ_info;
struct wireless_dev *wdev;
int ret = 0, i;
switch (htc_type) {
case ATH6KL_HTC_TYPE_MBOX:
ath6kl_htc_mbox_attach(ar);
break;
case ATH6KL_HTC_TYPE_PIPE:
ath6kl_htc_pipe_attach(ar);
break;
default:
WARN_ON(1);
return -ENOMEM;
}
ar->ath6kl_wq = create_singlethread_workqueue("ath6kl");
if (!ar->ath6kl_wq)
return -ENOMEM;
ret = ath6kl_bmi_init(ar);
if (ret)
goto err_wq;
/*
* Turn on power to get hardware (target) version and leave power
* on delibrately as we will boot the hardware anyway within few
* seconds.
*/
ret = ath6kl_hif_power_on(ar);
if (ret)
goto err_bmi_cleanup;
ret = ath6kl_bmi_get_target_info(ar, &targ_info);
if (ret)
goto err_power_off;
ar->version.target_ver = le32_to_cpu(targ_info.version);
ar->target_type = le32_to_cpu(targ_info.type);
ar->wiphy->hw_version = le32_to_cpu(targ_info.version);
ret = ath6kl_init_hw_params(ar);
if (ret)
goto err_power_off;
ar->htc_target = ath6kl_htc_create(ar);
if (!ar->htc_target) {
ret = -ENOMEM;
goto err_power_off;
}
ar->testmode = testmode;
ret = ath6kl_init_fetch_firmwares(ar);
if (ret)
goto err_htc_cleanup;
/* FIXME: we should free all firmwares in the error cases below */
/*
* Backwards compatibility support for older ar6004 firmware images
* which do not set these feature flags.
*/
if (ar->target_type == TARGET_TYPE_AR6004 &&
ar->fw_api <= 4) {
__set_bit(ATH6KL_FW_CAPABILITY_64BIT_RATES,
ar->fw_capabilities);
__set_bit(ATH6KL_FW_CAPABILITY_AP_INACTIVITY_MINS,
ar->fw_capabilities);
if (ar->hw.id == AR6004_HW_1_3_VERSION)
__set_bit(ATH6KL_FW_CAPABILITY_MAP_LP_ENDPOINT,
ar->fw_capabilities);
}
/* Indicate that WMI is enabled (although not ready yet) */
set_bit(WMI_ENABLED, &ar->flag);
ar->wmi = ath6kl_wmi_init(ar);
if (!ar->wmi) {
ath6kl_err("failed to initialize wmi\n");
ret = -EIO;
goto err_htc_cleanup;
}
ath6kl_dbg(ATH6KL_DBG_TRC, "%s: got wmi @ 0x%p.\n", __func__, ar->wmi);
/* setup access class priority mappings */
ar->ac_stream_pri_map[WMM_AC_BK] = 0; /* lowest */
ar->ac_stream_pri_map[WMM_AC_BE] = 1;
ar->ac_stream_pri_map[WMM_AC_VI] = 2;
ar->ac_stream_pri_map[WMM_AC_VO] = 3; /* highest */
/* allocate some buffers that handle larger AMSDU frames */
ath6kl_refill_amsdu_rxbufs(ar, ATH6KL_MAX_AMSDU_RX_BUFFERS);
ath6kl_cookie_init(ar);
ar->conf_flags = ATH6KL_CONF_IGNORE_ERP_BARKER |
ATH6KL_CONF_ENABLE_11N | ATH6KL_CONF_ENABLE_TX_BURST;
if (suspend_mode &&
suspend_mode >= WLAN_POWER_STATE_CUT_PWR &&
suspend_mode <= WLAN_POWER_STATE_WOW)
ar->suspend_mode = suspend_mode;
else
ar->suspend_mode = 0;
if (suspend_mode == WLAN_POWER_STATE_WOW &&
(wow_mode == WLAN_POWER_STATE_CUT_PWR ||
wow_mode == WLAN_POWER_STATE_DEEP_SLEEP))
ar->wow_suspend_mode = wow_mode;
else
ar->wow_suspend_mode = 0;
if (uart_debug)
ar->conf_flags |= ATH6KL_CONF_UART_DEBUG;
ar->hw.uarttx_rate = uart_rate;
set_bit(FIRST_BOOT, &ar->flag);
ath6kl_debug_init(ar);
ret = ath6kl_init_hw_start(ar);
if (ret) {
ath6kl_err("Failed to start hardware: %d\n", ret);
goto err_rxbuf_cleanup;
}
/* give our connected endpoints some buffers */
ath6kl_rx_refill(ar->htc_target, ar->ctrl_ep);
ath6kl_rx_refill(ar->htc_target, ar->ac2ep_map[WMM_AC_BE]);
ret = ath6kl_cfg80211_init(ar);
if (ret)
goto err_rxbuf_cleanup;
ret = ath6kl_debug_init_fs(ar);
if (ret) {
wiphy_unregister(ar->wiphy);
goto err_rxbuf_cleanup;
}
for (i = 0; i < ar->vif_max; i++)
ar->avail_idx_map |= BIT(i);
rtnl_lock();
/* Add an initial station interface */
wdev = ath6kl_interface_add(ar, "wlan%d", NET_NAME_ENUM,
NL80211_IFTYPE_STATION, 0, INFRA_NETWORK);
rtnl_unlock();
if (!wdev) {
ath6kl_err("Failed to instantiate a network device\n");
ret = -ENOMEM;
wiphy_unregister(ar->wiphy);
goto err_rxbuf_cleanup;
}
ath6kl_dbg(ATH6KL_DBG_TRC, "%s: name=%s dev=0x%p, ar=0x%p\n",
__func__, wdev->netdev->name, wdev->netdev, ar);
ar->fw_recovery.enable = !!recovery_enable;
if (!ar->fw_recovery.enable)
return ret;
if (heart_beat_poll &&
test_bit(ATH6KL_FW_CAPABILITY_HEART_BEAT_POLL,
ar->fw_capabilities))
ar->fw_recovery.hb_poll = heart_beat_poll;
ath6kl_recovery_init(ar);
return ret;
err_rxbuf_cleanup:
ath6kl_debug_cleanup(ar);
ath6kl_htc_flush_rx_buf(ar->htc_target);
ath6kl_cleanup_amsdu_rxbufs(ar);
ath6kl_wmi_shutdown(ar->wmi);
clear_bit(WMI_ENABLED, &ar->flag);
ar->wmi = NULL;
err_htc_cleanup:
ath6kl_htc_cleanup(ar->htc_target);
err_power_off:
ath6kl_hif_power_off(ar);
err_bmi_cleanup:
ath6kl_bmi_cleanup(ar);
err_wq:
destroy_workqueue(ar->ath6kl_wq);
return ret;
}
EXPORT_SYMBOL(ath6kl_core_init);
struct ath6kl *ath6kl_core_create(struct device *dev)
{
struct ath6kl *ar;
u8 ctr;
ar = ath6kl_cfg80211_create();
if (!ar)
return NULL;
ar->p2p = !!ath6kl_p2p;
ar->dev = dev;
ar->vif_max = 1;
ar->max_norm_iface = 1;
spin_lock_init(&ar->lock);
spin_lock_init(&ar->mcastpsq_lock);
spin_lock_init(&ar->list_lock);
init_waitqueue_head(&ar->event_wq);
sema_init(&ar->sem, 1);
INIT_LIST_HEAD(&ar->amsdu_rx_buffer_queue);
INIT_LIST_HEAD(&ar->vif_list);
clear_bit(WMI_ENABLED, &ar->flag);
clear_bit(SKIP_SCAN, &ar->flag);
clear_bit(DESTROY_IN_PROGRESS, &ar->flag);
ar->tx_pwr = 0;
ar->intra_bss = 1;
ar->lrssi_roam_threshold = DEF_LRSSI_ROAM_THRESHOLD;
ar->state = ATH6KL_STATE_OFF;
memset((u8 *)ar->sta_list, 0,
AP_MAX_NUM_STA * sizeof(struct ath6kl_sta));
/* Init the PS queues */
for (ctr = 0; ctr < AP_MAX_NUM_STA; ctr++) {
spin_lock_init(&ar->sta_list[ctr].psq_lock);
skb_queue_head_init(&ar->sta_list[ctr].psq);
skb_queue_head_init(&ar->sta_list[ctr].apsdq);
ar->sta_list[ctr].mgmt_psq_len = 0;
INIT_LIST_HEAD(&ar->sta_list[ctr].mgmt_psq);
ar->sta_list[ctr].aggr_conn =
kzalloc(sizeof(struct aggr_info_conn), GFP_KERNEL);
if (!ar->sta_list[ctr].aggr_conn) {
ath6kl_err("Failed to allocate memory for sta aggregation information\n");
ath6kl_core_destroy(ar);
return NULL;
}
}
skb_queue_head_init(&ar->mcastpsq);
memcpy(ar->ap_country_code, DEF_AP_COUNTRY_CODE, 3);
return ar;
}
EXPORT_SYMBOL(ath6kl_core_create);
void ath6kl_core_cleanup(struct ath6kl *ar)
{
ath6kl_hif_power_off(ar);
ath6kl_recovery_cleanup(ar);
destroy_workqueue(ar->ath6kl_wq);
if (ar->htc_target)
ath6kl_htc_cleanup(ar->htc_target);
ath6kl_cookie_cleanup(ar);
ath6kl_cleanup_amsdu_rxbufs(ar);
ath6kl_bmi_cleanup(ar);
ath6kl_debug_cleanup(ar);
kfree(ar->fw_board);
kfree(ar->fw_otp);
vfree(ar->fw);
kfree(ar->fw_patch);
kfree(ar->fw_testscript);
ath6kl_cfg80211_cleanup(ar);
}
EXPORT_SYMBOL(ath6kl_core_cleanup);
void ath6kl_core_destroy(struct ath6kl *ar)
{
ath6kl_cfg80211_destroy(ar);
}
EXPORT_SYMBOL(ath6kl_core_destroy);
MODULE_AUTHOR("Qualcomm Atheros");
MODULE_DESCRIPTION("Core module for AR600x SDIO and USB devices.");
MODULE_LICENSE("Dual BSD/GPL");
|
{
"pile_set_name": "Github"
}
|
<!--++ description-logic/Manifest642.rdf ** generated by SKB ++-->
<!--++ Created Tue Feb 25 15:57:05 2003 ++-->
<!--
Copyright World Wide Web Consortium, (Massachusetts Institute of
Technology, European Research Consortium for Informatics and
Mathematics, Keio University).
All Rights Reserved.
Please see the full Copyright clause at
<http://www.w3.org/Consortium/Legal/copyright-software.html>
$Id: Manifest642.rdf,v 1.5 2003/07/23 11:51:21 jcarroll Exp $
-->
<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'
xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema#'
xmlns:rtest='http://www.w3.org/2000/10/rdf-tests/rdfcore/testSchema#'
xmlns:otest='http://www.w3.org/2002/03owlt/testOntology#'
xmlns:dc='http://purl.org/dc/elements/1.0/'
xmlns='http://www.w3.org/1999/xhtml'
xmlns:owl='http://www.w3.org/2002/07/owl#'
xml:base='http://www.w3.org/2002/03owlt/description-logic/Manifest642'
>
<otest:InconsistencyTest rdf:ID='test'>
<otest:level rdf:resource='http://www.w3.org/2002/03owlt/testOntology#Full' />
<rtest:status>APPROVED</rtest:status> <rtest:approval rdf:resource="http://lists.w3.org/Archives/Public/www-webont-wg/2003May/0271"/> <otest:size rdf:resource='http://www.w3.org/2002/03owlt/testOntology#Large'/>
<dc:creator>Sean Bechhofer</dc:creator>
<otest:issuette rdf:resource='http://www.w3.org/TR/owl-test/#dl-600-harderlite' />
<otest:level rdf:resource='http://www.w3.org/2002/03owlt/testOntology#Lite' />
<rtest:description rdf:parseType='Literal'>
DL Test: heinsohn1.2
Tbox tests from <a href="#ref-Heinsohn_et_al.">[Heinsohn et al.]</a>
Tests incoherency caused by disjoint concept
</rtest:description>
<rtest:inputDocument>
<rtest:RDF-XML-Document rdf:about='inconsistent642' >
<otest:level rdf:resource='http://www.w3.org/2002/03owlt/testOntology#Lite' />
</rtest:RDF-XML-Document>
</rtest:inputDocument>
</otest:InconsistencyTest>
</rdf:RDF>
|
{
"pile_set_name": "Github"
}
|
//
// TRStatusBarStyle.swift
// TransitionTreasury
//
// Created by DianQK on 1/11/16.
// Copyright © 2016 TransitionTreasury. All rights reserved.
//
import UIKit
/**
TransitionTreasury Status Bar Style.
*/
public enum TRStatusBarStyle {
case `default`
@available(iOS 7.0, *)
case lightContent
case hide
func updateStatusBarStyle(_ animated: Bool = true) {
switch self {
case .default :
UIApplication.shared.setStatusBarHidden(false, with: .fade)
UIApplication.shared.setStatusBarStyle(.default, animated: animated)
case .lightContent :
UIApplication.shared.setStatusBarHidden(false, with: .fade)
UIApplication.shared.setStatusBarStyle(.lightContent, animated: animated)
case .hide :
UIApplication.shared.setStatusBarHidden(true, with: .fade)
}
}
static func convertTo(statusBarStyle: UIStatusBarStyle, statusBarHidden: Bool = UIApplication.shared.isStatusBarHidden) -> TRStatusBarStyle {
guard statusBarHidden == false else {
return .hide
}
switch statusBarStyle {
case .lightContent :
return .lightContent
case .default :
return .default
default :
fatalError("No support this status bar style")
}
}
static func currentlyTRStatusBarStyle() -> TRStatusBarStyle {
return convertTo(statusBarStyle: UIApplication.shared.statusBarStyle)
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array/>
</plist>
|
{
"pile_set_name": "Github"
}
|
namespace ClassLib079
{
public class Class083
{
public static string Property => "ClassLib079";
}
}
|
{
"pile_set_name": "Github"
}
|
<zoom>
<min>0.000000000</min>
<max>1.000000000</max>
</zoom>
|
{
"pile_set_name": "Github"
}
|
$01-00-01-08-4-1
[soundStopAll]
[bgm BGM_EVENT_2 0.1]
[scene 20300 0]
[charaSet A 8001000 1 マシュ]
[charaSet B 4017001 1 マリー・アントワネット]
[charaSet C 98014000 1 指揮官]
[charaSet D 9001001 1 ジャンヌ]
[charaSet E 98014000 1 兵士]
[charaSet F 1022001 1 ジル]
[charaSet G 7002001 1 ランスロット]
[charaSet H 6012001 1 サンソン]
[charaFace G 4]
[charaFadein G 0 1]
[fadein black 1]
[wait fade]
@ランスロット
……A……アー……サー……。
[k]
[charaFadeout G 0]
[charaTalk D]
[charaFadein G 0.1 0]
[charaFace D 4]
[charaFadein D 0.1 2]
@ジャンヌ
アーサー?[r]……それは、貴方の王アーサーのことですか?
[k]
@ジャンヌ
[line 2]残念ですが、私はジャンヌ・ダルク。[r]貴方が求めた王、アーサーではありません。
[k]
[charaFadeout G 0.1]
[charaFadeout D 0.1]
[charaFace A 12]
[charaFadein A 0.1 1]
@マシュ
……。[r]ああ、そうか。
[k]
?1:何?
?2:どうしたの?
?!
@マシュ
ランスロットがジャンヌさんに[#拘:こだわ]った理由が分かりました。[r]ジャンヌさんは、アーサー王に似ているんですね。
[k]
[charaFace A 13]
@マシュ
顔形ではなく、魂が[line 2]。
[k]
[charaFadeout A 0.1]
[charaFace G 4]
[charaFadein G 0.1 1]
@ランスロット
王……よ……私は……どうか……。
[k]
[messageOff]
[charaSpecialEffect G flashErasure 1 3]
[wt 1]
[se ba5]
[wait charaSpecialEffect G]
[charaFace D 4]
[charaFadein D 0.1 1]
@ジャンヌ
……。
[k]
[charaFadeout D 0.1]
[charaTalk A]
[charaFadein D 0.1 0]
[charaFace A 0]
[charaFadein A 0.1 2]
@マシュ
ジャンヌさん、行きましょう。
[k]
[charaFace D 0]
@ジャンヌ
はい!
[k]
[charaFadeout A 0.1]
[charaFadeout D 0.1]
[charaFace F 2]
[charaFadein F 0.1 1]
@ジル
ジャンヌ![r]お待ちを! 貴女は確かにジャンヌ・ダルク!
[k]
[charaFace F 1]
@ジル
“竜の魔女”ではない、[r]正真正銘の聖女……!
[k]
[charaFadeout F 0.1]
[charaFace B 4]
[charaFadein B 0.1 2]
[charaFace D 4]
[charaFadein D 0.1 0]
@ジャンヌ
……。
[k]
@マリー・アントワネット
……返答しなくていいのですか?
[k]
@ジャンヌ
私が返答すれば、ジルの立場が危うくなります。[r]現状、彼らに頼ることもないでしょう。
[k]
@ジャンヌ
何より、かつて共に戦った人々に憎まれるのは[r]さすがに堪えますから。
[k]
@マリー・アントワネット
でも……本当に彼らは、憎んでいるのでしょうか。
[k]
[charaFace D 0]
@ジャンヌ
[line 2]行きましょう。
[k]
[charaFadeout D 0.4]
[charaFadeout B 0.4]
[wt 0.3]
[charaFace F 0]
[charaFadein F 0.1 2]
[charaFace C 0]
[charaFadein C 0.1 0]
@指揮官
元帥。[r]今のは一体……。
[k]
[charaFace F 4]
@ジル
わからん。[r]わからんが……もう一度“竜の魔女”について調べ直せ。
[k]
@ジル
シャルル七世を討ったのが、本当にジャンヌ・ダルク[r]だったのか。悪質な偽物なのか。
[k]
[charaFace F 0]
@ジル
あるいは……ジャンヌ・ダルクはこの世界に[r]二人存在するのか。
[k]
[messageOff]
[fadeout black 0.5]
[bgmStop BGM_EVENT_2 0.4]
[wait fade]
[soundStopAll]
[end]
|
{
"pile_set_name": "Github"
}
|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example40-jquery</title>
<script src="../../components/jquery-2.1.1/jquery.js"></script>
<script src="../../../angular.js"></script>
<script src="script.js"></script>
</head>
<body >
<div ng-app="myApp">
<div>
{{ 'World' | greet }}
</div>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
fakeIpList = [
# https://zh.wikipedia.org/wiki/%E5%9F%9F%E5%90%8D%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%BC%93%E5%AD%98%E6%B1%A1%E6%9F%93
'4.36.66.178',
'8.7.198.45',
'23.89.5.60',
'37.61.54.158',
'46.82.174.68',
'49.2.123.56',
'54.76.135.1',
'59.24.3.173',
'64.33.88.161',
'64.33.99.47',
'64.66.163.251',
'65.104.202.252',
'65.160.219.113',
'66.45.252.237',
'72.14.205.99',
'72.14.205.104',
'77.4.7.92',
'78.16.49.15',
'93.46.8.89',
'118.5.49.6',
'128.121.126.139',
'159.106.121.75',
'169.132.13.103',
'188.5.4.96',
'189.163.17.5',
'192.67.198.6',
'197.4.4.12',
'202.106.1.2',
'202.181.7.85',
'203.98.7.65',
'203.161.230.171',
'207.12.88.98',
'208.56.31.43',
'209.36.73.33',
'209.145.54.50',
'209.220.30.174',
'211.94.66.147',
'213.169.251.35',
'216.221.188.182',
'216.234.179.13',
'243.185.187.39',
'249.129.46.48',
'253.157.14.165',
'74.125.31.113',
'74.125.39.102',
'74.125.39.113',
'74.125.127.102',
'74.125.130.47',
'74.125.155.102',
'209.85.229.138',
'210.242.125.20',
'0.0.0.0',
'2.1.1.2',
'4.193.80.0',
'8.105.84.0',
'12.87.133.0',
'16.63.155.0',
'20.139.56.0',
'24.51.184.0',
'28.121.126.139',
'28.13.216.0',
'46.20.126.252',
'46.38.24.209',
'61.54.28.6',
'66.206.11.194',
'74.117.57.138',
'89.31.55.106',
'113.11.194.190',
'122.218.101.190',
'123.50.49.171',
'123.126.249.238',
'125.230.148.48',
'127.0.0.2',
'173.201.216.6',
'203.199.57.81',
'208.109.138.55',
'211.5.133.18',
'211.8.69.27',
'213.186.33.5',
'216.139.213.144',
'221.8.69.27',
'243.185.187.3',
'243.185.187.30'
]
def ip2int(ipstr):
intlist = ipstr.split('.')
ret = 0
for i in range(4):
ret = ret * 256 + int(intlist[i])
return ret
def final_list():
fileobj = open("data/cn_ip_range.txt", "r")
content = ''
if fileobj:
list_result = []
lines_list = [line.rstrip('\n').split(' ') for line in fileobj]
#list_result = [ "0x%x:%s," % (int(line[0]),int(line[1])) for line in lines_list ]
#'''
list_result.append('{')
start_num = 0
comma = ''
for line in lines_list:
while (int(line[0]) >> 24) > start_num:
start_num += 1
list_result.append('},{')
comma = ''
list_result.append("%s0x%x:%s" % ( comma, int(line[0])/256, int(line[1])/256 ))
comma = ','
list_result.append('}')
#'''
content = ''.join(list_result)
content = '[\n' + content + "\n]"
return content
def center_list():
fileobj = open("data/cn_ip_range.txt", "r")
master_net = set()
content = ''
if fileobj:
list_result = []
lines_list = [line.rstrip('\n').split(' ') for line in fileobj]
for line in lines_list:
if int(line[1]) < (1 << 14):
master_net.add( int(int(line[0]) >> 14) )
master_net = list(master_net)
master_net.sort()
list_result = ['0x%x:1,' % s for s in master_net]
content = ''.join(list_result)
content = '{\n' + content[:-1] + "\n}"
return content
def fake_list():
content = ''
list_result = [ "0x%x," % int(ip2int(ip)) for ip in fakeIpList ]
content = ''.join(list_result)
content = '[\n' + content[:-1] + "\n]"
return content
def main():
print center_list()
if __name__ == '__main__':
main()
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2019 Qameta Software OÜ
*
* 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.qameta.allure.test;
import io.qameta.allure.Feature;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author charlie (Dmitry Baev).
*/
@SuppressWarnings({"JavadocType", "PMD.MissingStaticMethodInNonInstantiatableClass"})
@Target({})
public @interface AllureFeatures {
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Basic framework support")
@interface Base {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Parallel test execution support")
@interface Parallel {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Full name")
@interface FullName {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Display name")
@interface DisplayName {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Descriptions")
@interface Descriptions {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Timings")
@interface Timings {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Steps")
@interface Steps {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Attachments")
@interface Attachments {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Parameters")
@interface Parameters {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Fixtures")
@interface Fixtures {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Links")
@interface Links {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Marker annotations")
@interface MarkerAnnotations {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Failed tests")
@interface FailedTests {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Broken tests")
@interface BrokenTests {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Passed tests")
@interface PassedTests {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Skipped tests")
@interface SkippedTests {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Ignored tests")
@interface IgnoredTests {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Not implemented tests")
@interface NotImplementedTests {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("History")
@interface History {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Retries")
@interface Retries {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Stages")
@interface Stages {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Trees")
@interface Trees {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Timeline")
@interface Timeline {
}
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Feature("Timeline")
@interface Severity {
}
}
|
{
"pile_set_name": "Github"
}
|
import React from "react";
import { mount } from "enzyme";
import { TileWait } from "../tile_wait";
import { fakeSequence } from "../../../__test_support__/fake_state/resources";
import { emptyState } from "../../../resources/reducer";
import { StepParams } from "../../interfaces";
describe("<TileWait/>", () => {
const fakeProps = (): StepParams => ({
currentSequence: fakeSequence(),
currentStep: {
kind: "wait",
args: {
milliseconds: 100
}
},
dispatch: jest.fn(),
index: 0,
resources: emptyState().index,
});
it("renders inputs", () => {
const block = mount(<TileWait {...fakeProps()} />);
const inputs = block.find("input");
const labels = block.find("label");
expect(inputs.length).toEqual(2);
expect(labels.length).toEqual(1);
expect(inputs.first().props().placeholder).toEqual("Wait");
expect(labels.at(0).text()).toEqual("Time in milliseconds");
expect(inputs.at(1).props().value).toEqual(100);
});
});
|
{
"pile_set_name": "Github"
}
|
# -*- Mode: Python -*-
from scan_utxo import gen_utxo
from caesure.script import parse_script, pprint_script, ScriptError
from caesure._script import ScriptError
from caesure.bitcoin import bcrepr
def frob (name):
return name[::-1].encode ('hex')
n = 0
for txname, outputs in gen_utxo():
for (index, amt, script) in outputs:
try:
script = parse_script (script)
except ScriptError:
print frob(txname), index, bcrepr (amt), script.encode ('hex'), repr(script)
n += 1
print 'scanned %d scripts' % (n,)
|
{
"pile_set_name": "Github"
}
|
<?php
namespace Illuminate\Database;
use Illuminate\Support\Arr;
use InvalidArgumentException;
use Illuminate\Console\Command;
use Illuminate\Container\Container;
abstract class Seeder
{
/**
* The container instance.
*
* @var \Illuminate\Container\Container
*/
protected $container;
/**
* The console command instance.
*
* @var \Illuminate\Console\Command
*/
protected $command;
/**
* Seed the given connection from the given path.
*
* @param array|string $class
* @param bool $silent
* @return $this
*/
public function call($class, $silent = false)
{
$classes = Arr::wrap($class);
foreach ($classes as $class) {
$seeder = $this->resolve($class);
if ($silent === false && isset($this->command)) {
$this->command->getOutput()->writeln('<info>Seeding:</info> '.get_class($seeder));
}
$seeder->__invoke();
}
return $this;
}
/**
* Silently seed the given connection from the given path.
*
* @param array|string $class
* @return void
*/
public function callSilent($class)
{
$this->call($class, true);
}
/**
* Resolve an instance of the given seeder class.
*
* @param string $class
* @return \Illuminate\Database\Seeder
*/
protected function resolve($class)
{
if (isset($this->container)) {
$instance = $this->container->make($class);
$instance->setContainer($this->container);
} else {
$instance = new $class;
}
if (isset($this->command)) {
$instance->setCommand($this->command);
}
return $instance;
}
/**
* Set the IoC container instance.
*
* @param \Illuminate\Container\Container $container
* @return $this
*/
public function setContainer(Container $container)
{
$this->container = $container;
return $this;
}
/**
* Set the console command instance.
*
* @param \Illuminate\Console\Command $command
* @return $this
*/
public function setCommand(Command $command)
{
$this->command = $command;
return $this;
}
/**
* Run the database seeds.
*
* @return mixed
*
* @throws \InvalidArgumentException
*/
public function __invoke()
{
if (! method_exists($this, 'run')) {
throw new InvalidArgumentException('Method [run] missing from '.get_class($this));
}
return isset($this->container)
? $this->container->call([$this, 'run'])
: $this->run();
}
}
|
{
"pile_set_name": "Github"
}
|
---
layout: api
title: "v3.3.0 JavaScript Library: L.Browser"
categories: api
version: v3.3.0
permalink: /api/v3.3.0/l-browser/
---
<h2 id="browser">Browser</h2>
<p>A namespace with properties for browser/feature detection used by Leaflet internally.</p>
<pre><code>if (L.Browser.ie6) {
alert('Upgrade your browser, dude!');
}</code></pre>
<table data-id='browser'>
<tr>
<th class="width100">property</th>
<th class="width100">type</th>
<th>description</th>
</tr>
<tr>
<td><code><b>ie</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for all Internet Explorer versions.</td>
</tr>
<tr>
<td><code><b>ie6</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for Internet Explorer 6.</td>
</tr>
<tr>
<td><code><b>ie7</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for Internet Explorer 7.</td>
</tr>
<tr>
<td><code><b>webkit</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for webkit-based browsers like Chrome and Safari (including mobile versions).</td>
</tr>
<tr>
<td><code><b>webkit3d</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for webkit-based browsers that support CSS 3D transformations.</td>
</tr>
<!--<tr>
<td><code><b>gecko</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for Gecko-based browsers like Firefox and Mozilla.</td>
</tr>
<tr>
<td><code><b>opera</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for Opera.</td>
</tr>-->
<tr>
<td><code><b>android</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for Android mobile browser.</td>
</tr>
<tr>
<td><code><b>android23</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for old Android stock browsers (2 and 3).</td>
</tr>
<tr>
<td><code><b>mobile</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for modern mobile browsers (including iOS Safari and different Android browsers).</td>
</tr>
<tr>
<td><code><b>mobileWebkit</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for mobile webkit-based browsers.</td>
</tr>
<tr>
<td><code><b>mobileOpera</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for mobile Opera.</td>
</tr>
<tr>
<td><code><b>touch</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for all browsers on touch devices.</td>
</tr>
<tr>
<td><code><b>msTouch</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for browsers with Microsoft touch model (e.g. IE10).</td>
</tr>
<tr>
<td><code><b>retina</b></code></td>
<td><code>Boolean</code></td>
<td><code><span class="literal">true</span></code> for devices with Retina screens.</td>
</tr>
</table>
|
{
"pile_set_name": "Github"
}
|
媈
|
{
"pile_set_name": "Github"
}
|
---
layout: default
title: Level 18
cat: level
lang: en
number: 18
---
<p id="goal"><b>Goal:</b> Given a point A, a line, and a point B. Construct a circle that passes through A and is tangent to the line at B.
</p>
<p id="winningimg">
<img src="/img/Level{{page.number}}.png"/ >
</p>
<div id="hidden" style="display: none">
<p id="level">
Go to <a href="/Level19/">Level 19</a>.
</p>
</div>
<script type="text/javascript">
{% include parameters480p.js %}
parameters.customToolBar = "501 | 5 | 15 | 18 | 10 | 100001 | 100002 | 9 | 4 | 3 | 100003 | 53";
parameters.ggbBase64 = "{% base64 ggb/Level18.ggb %}" ;
</script>
<div id="applet_container">
</div>
<script type="text/javascript">
{% include testobjects.js %}
checkobject("target1");
LevelCompleted(drawn("target1"),4);
}
</script>
|
{
"pile_set_name": "Github"
}
|
export const meta = {
title: 'Prisma Admin',
position: 161
}
## Overview
Prisma Admin is currently in [Preview](oje2#preview-vs-final). You can find its announcement blog post [here](https://www.prisma.io/blog/prisma-admin-beta-pai5lah43soe/). We're looking for feedback, please share your ideas how to improve Prisma Admin [here](https://github.com/prisma/prisma-admin-feedback).
|
{
"pile_set_name": "Github"
}
|
<?php //[STAMP] a1362517a50ae530a4dd5bd96b2b52cf
namespace _generated;
// This class was automatically generated by build task
// You should not change it manually as it will be overwritten on next build
// @codingStandardsIgnoreFile
trait FunctionalTesterActions
{
/**
* @return \Codeception\Scenario
*/
abstract protected function getScenario();
}
|
{
"pile_set_name": "Github"
}
|
package varargs;
public class Parent {
public String concatenate(String... strings) {
StringBuilder builder = new StringBuilder();
for (String s : strings) {
builder.append(s);
}
return builder.toString();
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* TI OMAP L4 interconnect emulation.
*
* Copyright (C) 2007-2009 Nokia Corporation
* Written by Andrzej Zaborowski <andrew@openedhand.com>
*
* 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 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "hw.h"
#include "omap.h"
#ifdef L4_MUX_HACK
static int omap_l4_io_entries;
static int omap_cpu_io_entry;
static struct omap_l4_entry {
CPUReadMemoryFunc * const *mem_read;
CPUWriteMemoryFunc * const *mem_write;
void *opaque;
} *omap_l4_io_entry;
static CPUReadMemoryFunc * const *omap_l4_io_readb_fn;
static CPUReadMemoryFunc * const *omap_l4_io_readh_fn;
static CPUReadMemoryFunc * const *omap_l4_io_readw_fn;
static CPUWriteMemoryFunc * const *omap_l4_io_writeb_fn;
static CPUWriteMemoryFunc * const *omap_l4_io_writeh_fn;
static CPUWriteMemoryFunc * const *omap_l4_io_writew_fn;
static void **omap_l4_io_opaque;
int l4_register_io_memory(CPUReadMemoryFunc * const *mem_read,
CPUWriteMemoryFunc * const *mem_write, void *opaque)
{
omap_l4_io_entry[omap_l4_io_entries].mem_read = mem_read;
omap_l4_io_entry[omap_l4_io_entries].mem_write = mem_write;
omap_l4_io_entry[omap_l4_io_entries].opaque = opaque;
return omap_l4_io_entries ++;
}
static uint32_t omap_l4_io_readb(void *opaque, target_phys_addr_t addr)
{
unsigned int i = (addr - OMAP2_L4_BASE) >> TARGET_PAGE_BITS;
return omap_l4_io_readb_fn[i](omap_l4_io_opaque[i], addr);
}
static uint32_t omap_l4_io_readh(void *opaque, target_phys_addr_t addr)
{
unsigned int i = (addr - OMAP2_L4_BASE) >> TARGET_PAGE_BITS;
return omap_l4_io_readh_fn[i](omap_l4_io_opaque[i], addr);
}
static uint32_t omap_l4_io_readw(void *opaque, target_phys_addr_t addr)
{
unsigned int i = (addr - OMAP2_L4_BASE) >> TARGET_PAGE_BITS;
return omap_l4_io_readw_fn[i](omap_l4_io_opaque[i], addr);
}
static void omap_l4_io_writeb(void *opaque, target_phys_addr_t addr,
uint32_t value)
{
unsigned int i = (addr - OMAP2_L4_BASE) >> TARGET_PAGE_BITS;
return omap_l4_io_writeb_fn[i](omap_l4_io_opaque[i], addr, value);
}
static void omap_l4_io_writeh(void *opaque, target_phys_addr_t addr,
uint32_t value)
{
unsigned int i = (addr - OMAP2_L4_BASE) >> TARGET_PAGE_BITS;
return omap_l4_io_writeh_fn[i](omap_l4_io_opaque[i], addr, value);
}
static void omap_l4_io_writew(void *opaque, target_phys_addr_t addr,
uint32_t value)
{
unsigned int i = (addr - OMAP2_L4_BASE) >> TARGET_PAGE_BITS;
return omap_l4_io_writew_fn[i](omap_l4_io_opaque[i], addr, value);
}
static CPUReadMemoryFunc * const omap_l4_io_readfn[] = {
omap_l4_io_readb,
omap_l4_io_readh,
omap_l4_io_readw,
};
static CPUWriteMemoryFunc * const omap_l4_io_writefn[] = {
omap_l4_io_writeb,
omap_l4_io_writeh,
omap_l4_io_writew,
};
#else
int l4_register_io_memory(CPUReadMemoryFunc * const *mem_read,
CPUWriteMemoryFunc * const *mem_write,
void *opaque)
{
return cpu_register_io_memory(mem_read, mem_write, opaque,
DEVICE_NATIVE_ENDIAN);
}
#endif
struct omap_l4_s {
target_phys_addr_t base;
int ta_num;
struct omap_target_agent_s ta[0];
};
struct omap_l4_s *omap_l4_init(target_phys_addr_t base, int ta_num)
{
struct omap_l4_s *bus = g_malloc0(
sizeof(*bus) + ta_num * sizeof(*bus->ta));
bus->ta_num = ta_num;
bus->base = base;
#ifdef L4_MUX_HACK
omap_l4_io_entries = 1;
omap_l4_io_entry = g_malloc0(125 * sizeof(*omap_l4_io_entry));
omap_cpu_io_entry =
cpu_register_io_memory(omap_l4_io_readfn,
omap_l4_io_writefn, bus, DEVICE_NATIVE_ENDIAN);
# define L4_PAGES (0xb4000 / TARGET_PAGE_SIZE)
omap_l4_io_readb_fn = g_malloc0(sizeof(void *) * L4_PAGES);
omap_l4_io_readh_fn = g_malloc0(sizeof(void *) * L4_PAGES);
omap_l4_io_readw_fn = g_malloc0(sizeof(void *) * L4_PAGES);
omap_l4_io_writeb_fn = g_malloc0(sizeof(void *) * L4_PAGES);
omap_l4_io_writeh_fn = g_malloc0(sizeof(void *) * L4_PAGES);
omap_l4_io_writew_fn = g_malloc0(sizeof(void *) * L4_PAGES);
omap_l4_io_opaque = g_malloc0(sizeof(void *) * L4_PAGES);
#endif
return bus;
}
target_phys_addr_t omap_l4_region_base(struct omap_target_agent_s *ta,
int region)
{
return ta->bus->base + ta->start[region].offset;
}
static uint32_t omap_l4ta_read(void *opaque, target_phys_addr_t addr)
{
struct omap_target_agent_s *s = (struct omap_target_agent_s *) opaque;
switch (addr) {
case 0x00: /* COMPONENT */
return s->component;
case 0x20: /* AGENT_CONTROL */
return s->control;
case 0x28: /* AGENT_STATUS */
return s->status;
}
OMAP_BAD_REG(addr);
return 0;
}
static void omap_l4ta_write(void *opaque, target_phys_addr_t addr,
uint32_t value)
{
struct omap_target_agent_s *s = (struct omap_target_agent_s *) opaque;
switch (addr) {
case 0x00: /* COMPONENT */
case 0x28: /* AGENT_STATUS */
OMAP_RO_REG(addr);
break;
case 0x20: /* AGENT_CONTROL */
s->control = value & 0x01000700;
if (value & 1) /* OCP_RESET */
s->status &= ~1; /* REQ_TIMEOUT */
break;
default:
OMAP_BAD_REG(addr);
}
}
static CPUReadMemoryFunc * const omap_l4ta_readfn[] = {
omap_badwidth_read16,
omap_l4ta_read,
omap_badwidth_read16,
};
static CPUWriteMemoryFunc * const omap_l4ta_writefn[] = {
omap_badwidth_write32,
omap_badwidth_write32,
omap_l4ta_write,
};
struct omap_target_agent_s *omap_l4ta_get(struct omap_l4_s *bus,
const struct omap_l4_region_s *regions,
const struct omap_l4_agent_info_s *agents,
int cs)
{
int i, iomemtype;
struct omap_target_agent_s *ta = NULL;
const struct omap_l4_agent_info_s *info = NULL;
for (i = 0; i < bus->ta_num; i ++)
if (agents[i].ta == cs) {
ta = &bus->ta[i];
info = &agents[i];
break;
}
if (!ta) {
fprintf(stderr, "%s: bad target agent (%i)\n", __FUNCTION__, cs);
exit(-1);
}
ta->bus = bus;
ta->start = ®ions[info->region];
ta->regions = info->regions;
ta->component = ('Q' << 24) | ('E' << 16) | ('M' << 8) | ('U' << 0);
ta->status = 0x00000000;
ta->control = 0x00000200; /* XXX 01000200 for L4TAO */
iomemtype = l4_register_io_memory(omap_l4ta_readfn,
omap_l4ta_writefn, ta);
ta->base = omap_l4_attach(ta, info->ta_region, iomemtype);
return ta;
}
target_phys_addr_t omap_l4_attach(struct omap_target_agent_s *ta, int region,
int iotype)
{
target_phys_addr_t base;
ssize_t size;
#ifdef L4_MUX_HACK
int i;
#endif
if (region < 0 || region >= ta->regions) {
fprintf(stderr, "%s: bad io region (%i)\n", __FUNCTION__, region);
exit(-1);
}
base = ta->bus->base + ta->start[region].offset;
size = ta->start[region].size;
if (iotype) {
#ifndef L4_MUX_HACK
cpu_register_physical_memory(base, size, iotype);
#else
cpu_register_physical_memory(base, size, omap_cpu_io_entry);
i = (base - ta->bus->base) / TARGET_PAGE_SIZE;
for (; size > 0; size -= TARGET_PAGE_SIZE, i ++) {
omap_l4_io_readb_fn[i] = omap_l4_io_entry[iotype].mem_read[0];
omap_l4_io_readh_fn[i] = omap_l4_io_entry[iotype].mem_read[1];
omap_l4_io_readw_fn[i] = omap_l4_io_entry[iotype].mem_read[2];
omap_l4_io_writeb_fn[i] = omap_l4_io_entry[iotype].mem_write[0];
omap_l4_io_writeh_fn[i] = omap_l4_io_entry[iotype].mem_write[1];
omap_l4_io_writew_fn[i] = omap_l4_io_entry[iotype].mem_write[2];
omap_l4_io_opaque[i] = omap_l4_io_entry[iotype].opaque;
}
#endif
}
return base;
}
|
{
"pile_set_name": "Github"
}
|
% Copyright (C) 1996 Aladdin Enterprises. All rights reserved.
%
% This file is part of Aladdin Ghostscript.
%
% Aladdin Ghostscript is distributed with NO WARRANTY OF ANY KIND. No author
% or distributor accepts any responsibility for the consequences of using it,
% or for whether it serves any particular purpose or works at all, unless he
% or she says so in writing. Refer to the Aladdin Ghostscript Free Public
% License (the "License") for full details.
%
% Every copy of Aladdin Ghostscript must include a copy of the License,
% normally in a plain ASCII text file named PUBLIC. The License grants you
% the right to copy, modify and redistribute Aladdin Ghostscript, but only
% under certain conditions described in the License. Among other things, the
% License requires that the copyright notice and this notice be preserved on
% all copies.
% Fontmap - standard font catalog for Ghostscript.
% ----------------------------------------------------------------
% This file is a catalog of fonts known to Ghostscript. Any font
% that is to be loaded automatically when named must be in this catalog,
% except for fonts that Ghostscript finds automatically in directories
% named in the GS_FONTPATH environment variable.
% Each font has an entry consisting of three items:
%
% - The name by which the font is known inside Ghostscript
% (a Ghostscript name preceded by a `/', or a string enclosed
% in parentheses). This is used to find the file from which
% a font of a given name should be loaded.
%
% - Information depending on whether this is a real font or a
% font alias:
%
% - For real fonts, the name of the Ghostscript font
% file (a Ghostscript string, enclosed in parentheses).
% The filename should include the extension, which (by
% convention) is `.gsf'. `.pfa' and `.pfb' files are
% also usable as fonts for Ghostscript.
%
% - For font aliases, the name of the font which should
% be used when this one is requested, preceded by a
% `/'. See the entry for Charter below for an example.
% Note that an alias name cannot be enclosed in parentheses.
%
% - At least one space or tab, and a terminating semicolon.
% Because of limitations in the MS-DOS environment, Ghostscript font
% file names must be no more than 8 characters long, must consist only
% of LOWER CASE letters, digits, and underscores, and must start with a
% letter. Font names, on the other hand, need only obey the syntax of
% names in the Ghostscript language, which is much more liberal.
% The following table is actually a Ghostscript data structure.
% If you add new entries, be sure to copy the punctuation accurately;
% in particular, you must leave at least one space or tab between each
% field in the entry. Also, please read fonts.doc for important information
% about font names.
% Note that .pfa and .pfb fonts are compatible with Adobe Type Manager
% and other programs that don't include full PostScript interpreters,
% as well as with PostScript interpreters; .gsf fonts are compatible with
% PostScript interpreters, but not with ATM or similar programs.
%
%
% Fonts contributed by:
% URW++ Design and Development Incorporated
% Poppenbuetteler Bogen 29A
% D-22399 Hamburg
% Germany
% tel. +49 (40) 60 60 50
% fax +49 (40) 60 60 51 11
% http://www.urwpp.de
% for distribution under the GNU License and Aladdin Free Public License.
% See the notice at the head of this Fontmap file for licensing terms.
% Each of these fonts is individually covered by the license:
% for licensing purposes, they are not "part of" any larger entity.
% The following notice applies to these fonts:
%
% Copyright URW Software, Copyright 1994 by URW.
%
% Actual fonts
/URWBookmanL-DemiBold (b018015l.pfb) ;
/URWBookmanL-DemiBoldItal (b018035l.pfb) ;
/URWBookmanL-Ligh (b018012l.pfb) ;
/URWBookmanL-LighItal (b018032l.pfb) ;
/NimbusMonL-Regu (n022003l.pfb) ;
/NimbusMonL-ReguObli (n022023l.pfb) ;
/NimbusMonL-Bold (n022004l.pfb) ;
/NimbusMonL-BoldObli (n022024l.pfb) ;
/URWGothicL-Book (a010013l.pfb) ;
/URWGothicL-BookObli (a010033l.pfb) ;
/URWGothicL-Demi (a010015l.pfb) ;
/URWGothicL-DemiObli (a010035l.pfb) ;
/NimbusSanL-Regu (n019003l.pfb) ;
/NimbusSanL-ReguItal (n019023l.pfb) ;
/NimbusSanL-Bold (n019004l.pfb) ;
/NimbusSanL-BoldItal (n019024l.pfb) ;
/NimbusSanL-ReguCond (n019043l.pfb) ;
/NimbusSanL-ReguCondItal (n019063l.pfb) ;
/NimbusSanL-BoldCond (n019044l.pfb) ;
/NimbusSanL-BoldCondItal (n019064l.pfb) ;
/URWPalladioL-Roma (p052003l.pfb) ;
/URWPalladioL-Ital (p052023l.pfb) ;
/URWPalladioL-Bold (p052004l.pfb) ;
/URWPalladioL-BoldItal (p052024l.pfb) ;
/CenturySchL-Roma (c059013l.pfb) ;
/CenturySchL-Ital (c059033l.pfb) ;
/CenturySchL-Bold (c059016l.pfb) ;
/CenturySchL-BoldItal (c059036l.pfb) ;
/NimbusRomNo9L-Regu (n021003l.pfb) ;
/NimbusRomNo9L-ReguItal (n021023l.pfb) ;
/NimbusRomNo9L-Medi (n021004l.pfb) ;
/NimbusRomNo9L-MediItal (n021024l.pfb) ;
/StandardSymL (s050000l.pfb) ;
/URWChanceryL-MediItal (z003034l.pfb) ;
/Dingbats (d050000l.pfb) ;
% Aliases
/Bookman-Demi /URWBookmanL-DemiBold ;
/Bookman-DemiItalic /URWBookmanL-DemiBoldItal ;
/Bookman-Light /URWBookmanL-Ligh ;
/Bookman-LightItalic /URWBookmanL-LighItal ;
/Courier /NimbusMonL-Regu ;
/Courier-Oblique /NimbusMonL-ReguObli ;
/Courier-Bold /NimbusMonL-Bold ;
/Courier-BoldOblique /NimbusMonL-BoldObli ;
/AvantGarde-Book /URWGothicL-Book ;
/AvantGarde-BookOblique /URWGothicL-BookObli ;
/AvantGarde-Demi /URWGothicL-Demi ;
/AvantGarde-DemiOblique /URWGothicL-DemiObli ;
/Helvetica /NimbusSanL-Regu ;
/Helvetica-Oblique /NimbusSanL-ReguItal ;
/Helvetica-Bold /NimbusSanL-Bold ;
/Helvetica-BoldOblique /NimbusSanL-BoldItal ;
/Helvetica-Narrow /NimbusSanL-ReguCond ;
/Helvetica-Narrow-Oblique /NimbusSanL-ReguCondItal ;
/Helvetica-Narrow-Bold /NimbusSanL-BoldCond ;
/Helvetica-Narrow-BoldOblique /NimbusSanL-BoldCondItal ;
/Palatino-Roman /URWPalladioL-Roma ;
/Palatino-Italic /URWPalladioL-Ital ;
/Palatino-Bold /URWPalladioL-Bold ;
/Palatino-BoldItalic /URWPalladioL-BoldItal ;
/NewCenturySchlbk-Roman /CenturySchL-Roma ;
/NewCenturySchlbk-Italic /CenturySchL-Ital ;
/NewCenturySchlbk-Bold /CenturySchL-Bold ;
/NewCenturySchlbk-BoldItalic /CenturySchL-BoldItal ;
/Times-Roman /NimbusRomNo9L-Regu ;
/Times-Italic /NimbusRomNo9L-ReguItal ;
/Times-Bold /NimbusRomNo9L-Medi ;
/Times-BoldItalic /NimbusRomNo9L-MediItal ;
/Symbol /StandardSymL ;
/ZapfChancery-MediumItalic /URWChanceryL-MediItal ;
/ZapfDingbats /Dingbats ;
%
%
% Type 1 fonts contributed to the X11R5 distribution.
%
% The following notice accompanied the Charter fonts.
%
% (c) Copyright 1989-1992, Bitstream Inc., Cambridge, MA.
%
% You are hereby granted permission under all Bitstream propriety rights
% to use, copy, modify, sublicense, sell, and redistribute the 4 Bitstream
% Charter (r) Type 1 outline fonts and the 4 Courier Type 1 outline fonts
% for any purpose and without restriction; provided, that this notice is
% left intact on all copies of such fonts and that Bitstream's trademark
% is acknowledged as shown below on all unmodified copies of the 4 Charter
% Type 1 fonts.
%
% BITSTREAM CHARTER is a registered trademark of Bitstream Inc.
% The Bitstream Charter fonts have different names (CharterBT-
% instead of Charter-), but Ghostscript doesn't care.
/Charter-Roman (bchr.pfa) ;
/Charter-Italic (bchri.pfa) ;
/Charter-Bold (bchb.pfa) ;
/Charter-BoldItalic (bchbi.pfa) ;
% The following notice accompanied the Utopia font:
%
% Permission to use, reproduce, display and distribute the listed
% typefaces is hereby granted, provided that the Adobe Copyright notice
% appears in all whole and partial copies of the software and that the
% following trademark symbol and attribution appear in all unmodified
% copies of the software:
%
% Copyright (c) 1989 Adobe Systems Incorporated
% Utopia (R)
% Utopia is a registered trademark of Adobe Systems Incorporated
%
% The Adobe typefaces (Type 1 font program, bitmaps and Adobe Font
% Metric files) donated are:
%
% Utopia Regular
% Utopia Italic
% Utopia Bold
% Utopia Bold Italic
/Utopia-Regular (putr.pfa) ;
/Utopia-Italic (putri.pfa) ;
/Utopia-Bold (putb.pfa) ;
/Utopia-BoldItalic (putbi.pfa) ;
%
%
% Fonts contributed by URW GmbH for distribution under the GNU License.
% The following notice accompanied these fonts:
%
% U004006T URW Grotesk 2031 Bold PostScript Type 1 Font Program
% U003043T URW Antiqua 2051 Regular Condensed PostScript Type 1 Font Program
%
% Copyright (c) 1992 URW GmbH, Hamburg, Germany
%
% 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) later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; wihtout 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., 675 Mass Ave, Cambridge, MA 02139, USA.
%
% Address:
% URW GmbH
% PC Support
% Harksheider Strasse 102
% 2000 Hamburg 65
% Germany
% Phone: +49 40 60 60 50 (Reception)
% Phone: +49 40 60 60 52 30 (PC Support)
% Fax : +49 40 60 60 52 52
%
/URWAntiquaT-RegularCondensed (u003043t.gsf) ;
/URWGroteskT-Bold (u004006t.gsf) ;
%
%
% Shareware Kana fonts. These are subject to the following notice:
%
% These copyrighted fonts were developed by Kevin Hartig. Permission is
% granted to freely distribute them in entirety along with this statement.
% This is shareware. If you decide to use these fonts please contribute
% $10 US to help support further freeware and shareware software development.
% Questions and comments may be sent to:
%
% hartig@fsl.noaa.gov
% khartig@nyx.cs.du.edu
%
% Kevin Hartig
% 1126 Collyer Street
% Longmont, CO 80501 USA
%
% copyright 1993.
% Hiragana and Katakana fonts. The character names are inappropriate,
% and the encoding is probably not related to any known standard.
/Calligraphic-Hiragana (fhirw.gsf) ;
/Calligraphic-Katakana (fkarw.gsf) ;
%
%
% Public-domain fonts. These have no copyright, and are of unknown quality.
% Cyrillic fonts. The character names are inappropriate,
% and the encoding is probably not related to any known standard.
/Shareware-Cyrillic-Regular (fcyr.gsf) ;
/Shareware-Cyrillic-Italic (fcyri.gsf) ;
% Aliases
/Cyrillic /Cyrillic-Regular ;
/Cyrillic-Regular /Shareware-Cyrillic-Regular ;
/Cyrillic-Italic /Shareware-Cyrillic-Italic ;
%
%
% Fonts converted from Hershey outlines. These are constructed and
% maintained manually. These are also in the public domain.
%
% The suggested UniqueID's and filenames are constructed differently for
% these than for the ones above, because of the strange way that the Hershey
% fonts were constructed. The scheme for these looks like:
%
% 42TTXY0
%
% TT = typeface, X = ``class'', Y = variation
%
% The typeface names and numbers are listed in fonts.mak.
%
% class:
% 0 = normal = r
% 1 = simplex = s
% 2 = complex = c
% 3 = triplex = t
% 4 = duplex = d
%
% variation:
% 0 = normal (omitted)
% 1 = oblique = o
% 2 = italic = i
% 3 = bold = b
% 4 = bold oblique = bo
% 5 = bold italic = bi
%
% Fonts created by Thomas Wolff <wolff@inf.fu-berlin.de>, by adding
% accents, accented characters, and various other non-alphabetics
% to the original Hershey fonts. These are "freeware", not to be sold.
/Hershey-Gothic-English (hrger.pfa) ; % 5066533
/Hershey-Gothic-German (hrgrr.pfa) ;
/Hershey-Gothic-Italian (hritr.pfa) ;
/Hershey-Plain-Duplex (hrpld.pfa) ;
/Hershey-Plain-Duplex-Italic (hrpldi.pfa) ;
/Hershey-Plain-Triplex (hrplt.pfa) ;
/Hershey-Plain-Triplex-Italic (hrplti.pfa) ;
/Hershey-Script-Complex (hrscc.pfa) ;
/Hershey-Script-Simplex (hrscs.pfa) ; % 5066541
% Fonts created algorithmically from the above.
/Hershey-Gothic-English-Bold (hrgerb.gsf) ; % 5066542
/Hershey-Gothic-English-Oblique (hrgero.gsf) ;
/Hershey-Gothic-English-SemiBold (hrgerd.gsf) ;
/Hershey-Gothic-German-Bold (hrgrrb.gsf) ;
/Hershey-Gothic-German-Oblique (hrgrro.gsf) ;
/Hershey-Gothic-Italian-Bold (hritrb.gsf) ;
/Hershey-Gothic-Italian-Oblique (hritro.gsf) ;
/Hershey-Plain-Duplex-Bold (hrpldb.gsf) ;
/Hershey-Plain-Duplex-Bold-Italic (hrpldbi.gsf) ;
/Hershey-Plain-Triplex-Bold (hrpltb.gsf) ;
/Hershey-Plain-Triplex-Bold-Italic (hrpltbi.gsf) ;
/Hershey-Script-Complex-Bold (hrsccb.gsf) ;
/Hershey-Script-Complex-Oblique (hrscco.gsf) ;
/Hershey-Script-Simplex-Bold (hrscsb.gsf) ;
/Hershey-Script-Simplex-Oblique (hrscso.gsf) ; % 5066556
% Fonts consisting only of characters from the original Hershey
% distribution. These are Type 3 fonts.
/Hershey-Greek-Complex (hrgkc.gsf) ; % 5066557
/Hershey-Greek-Simplex (hrgks.gsf) ;
/Hershey-Plain (hrplr.gsf) ;
/Hershey-Plain-Simplex (hrpls.gsf) ; % 5066560
% Fonts created algorithmically from the above.
/Hershey-Plain-Bold (hrplrb.gsf) ; % 5066561
/Hershey-Plain-Bold-Oblique (hrplrbo.gsf) ;
/Hershey-Plain-Oblique (hrplro.gsf) ;
/Hershey-Plain-Simplex-Bold (hrplsb.gsf) ;
/Hershey-Plain-Simplex-Bold-Oblique (hrplsbo.gsf) ;
/Hershey-Plain-Simplex-Oblique (hrplso.gsf) ; % 5066566
% This font, and only this font among the Hershey fonts, uses
% the SymbolEncoding.
/Hershey-Symbol (hrsyr.gsf) ; % 5066567
%
% This section is all: Plan 9 Feb/98
% Fonts known to Plan 9
/LucidaSansUnicode00 (lsunr00.pfa) ;
/LucidaSansUnicode01 (lsunr01.pfa) ;
/LucidaSansUnicode02 (lsunr02.pfa) ;
/LucidaSansUnicode03 (lsunr03.pfa) ;
/LucidaSansUnicode04 (lsunr04.pfa) ;
/LucidaSansUnicode05 (lsunr05.pfa) ;
/LucidaSansUnicode20 (lsunr20.pfa) ;
/LucidaSansUnicode21 (lsunr21.pfa) ;
/LucidaSansUnicode22 (lsunr22.pfa) ;
/LucidaSansUnicode24 (lsunr24.pfa) ;
/LucidaSans-Demi (LucidaSansB) ;
/LucidaSans-Italic (LucidaSansI) ;
/LucidaTypewriter (LucidaCW) ;
/ACaslon-AltBold (ACaslon-AltBold) ;
/ACaslon-AltItalic (ACaslon-AltItalic) ;
/ACaslon-AltRegular (ACaslon-AltRegular) ;
/ACaslon-Bold (ACaslon-Bold) ;
/ACaslon-Italic (ACaslon-Italic) ;
/ACaslon-Regular (ACaslon-Regular) ;
/ACaslon-SwashItalic (ACaslon-SwashItalic) ;
/ACaslon-SwashSemiboldItalic (ACaslon-SwashSemiboldItalic) ;
/ATTLogoPlain (ATTLogoPlain) ;
/AvantGarde-Book (AvantGarde-Book) ;
/AvantGarde-BookOblique (AvantGarde-BookOblique) ;
/AvantGarde-Demi (AvantGarde-Demi) ;
/AvantGarde-DemiOblique (AvantGarde-DemiOblique) ;
/Bookman-Demi (Bookman-Demi) ;
/Bookman-DemiItalic (Bookman-DemiItalic) ;
/Bookman-Light (Bookman-Light) ;
/Bookman-LightItalic (Bookman-LightItalic) ;
/Courier (Courier) ;
/Courier-Bold (Courier-Bold) ;
/Courier-BoldOblique (Courier-BoldOblique) ;
/Courier-Oblique (Courier-Oblique) ;
/GalileoBold (GalileoBold) ;
/GalileoBoldItalic (GalileoBoldItalic) ;
/GalileoItalic (GalileoItalic) ;
/GalileoRoman (GalileoRoman) ;
/Garamond-Bold (Garamond-Bold) ;
/Garamond-BoldCondensed (Garamond-BoldCondensed) ;
/Garamond-BoldCondensedItalic (Garamond-BoldCondensedItali) ;
/Garamond-BoldItalic (Garamond-BoldItalic) ;
/Garamond-Book (Garamond-Book) ;
/Garamond-BookCondensed (Garamond-BookCondensed) ;
/Garamond-BookCondensedItalic (Garamond-BookCondensedItali) ;
/Garamond-BookItalic (Garamond-BookItalic) ;
/Garamond-Light (Garamond-Light) ;
/Garamond-LightCondensed (Garamond-LightCondensed) ;
/Garamond-LightCondensedItalic (Garamond-LightCondensedItal) ;
/Garamond-LightItalic (Garamond-LightItalic) ;
/Garamond-Ultra (Garamond-Ultra) ;
/Garamond-UltraCondensed (Garamond-UltraCondensed) ;
/Garamond-UltraCondensedItalic (Garamond-UltraCondensedItal) ;
/Garamond-UltraItalic (Garamond-UltraItalic) ;
/Helvetica (Helvetica) ;
/Helvetica-Bold (Helvetica-Bold) ;
/Helvetica-BoldOblique (Helvetica-BoldOblique) ;
/Helvetica-Narrow (Helvetica-Narrow) ;
/Helvetica-Narrow-Bold (Helvetica-Narrow-Bold) ;
/Helvetica-Narrow-BoldOblique (Helvetica-Narrow-BoldObliqu) ;
/Helvetica-Narrow-Oblique (Helvetica-Narrow-Oblique) ;
/Helvetica-Oblique (Helvetica-Oblique) ;
%/Helvetica-Condensed (Helvetica-Condensed) ;
%/Helvetica-Condensed-Light (Helvetica-Condensed-Light) ;
%/Helvetica-Condensed-Bold (Helvetica-Condensed-Bold) ;
%/Helvetica-Condensed-Black (Helvetica-Condensed-Black) ;
%/HelveticaNeue-Roman (Helvetica) ;
%/HelveticaNeue-Bold (Helvetica-Bold) ;
%/HelveticaNeue-Italic (Helvetica-Oblique) ;
/NewCenturySchlbk-Bold (NewCenturySchlbk-Bold) ;
/NewCenturySchlbk-BoldItalic (NewCenturySchlbk-BoldItalic) ;
/NewCenturySchlbk-Italic (NewCenturySchlbk-Italic) ;
/NewCenturySchlbk-Roman (NewCenturySchlbk-Roman) ;
/Optima (Optima) ;
/Palatino-Bold (Palatino-Bold) ;
/Palatino-BoldItalic (Palatino-BoldItalic) ;
/Palatino-Italic (Palatino-Italic) ;
/Palatino-Roman (Palatino-Roman) ;
/Symbol (Symbol) ;
/Tekton (Tekton) ;
/Tekton-Bold (Tekton-Bold) ;
/Tekton-BoldOblique (Tekton-BoldOblique) ;
/Tekton-Oblique (Tekton-Oblique) ;
/Times-Bold (Times-Bold) ;
/Times-BoldItalic (Times-BoldItalic) ;
/Times-Italic (Times-Italic) ;
/Times-Roman (Times-Roman) ;
/TrumpMediaeval-Bold (TrumpMediaeval-Bold) ;
/Univers-BoldExt (Univers-BoldExt) ;
/Univers-Condensed (Univers-Condensed) ;
/Univers-CondensedBold (Univers-CondensedBold) ;
/Univers-CondensedOblique (Univers-CondensedOblique) ;
/Univers-Extended (Univers-Extended) ;
/Univers-ExtendedObl (Univers-ExtendedObl) ;
/Walbaum-Bold (Walbaum-Bold) ;
/Walbaum-Italic (Walbaum-Italic) ;
/Walbaum-Roman (Walbaum-Roman) ;
/Weiss (Weiss) ;
/Weiss-Bold (Weiss-Bold) ;
/Weiss-Italic (Weiss-Italic) ;
/ZapfChancery-MediumItalic (ZapfChancery-MediumItalic) ;
/ZapfDingbats (ZapfDingbats) ;
|
{
"pile_set_name": "Github"
}
|
config TI_SOC_THERMAL
tristate "Texas Instruments SoCs temperature sensor driver"
help
If you say yes here you get support for the Texas Instruments
OMAP4460+ on die bandgap temperature sensor support. The register
set is part of system control module.
This includes alert interrupts generation and also the TSHUT
support.
config TI_THERMAL
bool "Texas Instruments SoCs thermal framework support"
depends on TI_SOC_THERMAL
help
If you say yes here you want to get support for generic thermal
framework for the Texas Instruments on die bandgap temperature sensor.
This includes trip points definitions, extrapolation rules and
CPU cooling device bindings.
config OMAP3_THERMAL
bool "Texas Instruments OMAP3 thermal support"
depends on TI_SOC_THERMAL
depends on ARCH_OMAP3 || COMPILE_TEST
help
If you say yes here you get thermal support for the Texas Instruments
OMAP3 SoC family. The current chips supported are:
- OMAP3430
OMAP3 chips normally don't need thermal management, and sensors in
this generation are not accurate, nor they are very close to
the important hotspots.
Say 'N' here.
config OMAP4_THERMAL
bool "Texas Instruments OMAP4 thermal support"
depends on TI_SOC_THERMAL
depends on ARCH_OMAP4 || COMPILE_TEST
help
If you say yes here you get thermal support for the Texas Instruments
OMAP4 SoC family. The current chip supported are:
- OMAP4430
- OMAP4460
- OMAP4470
This includes alert interrupts generation and also the TSHUT
support.
config OMAP5_THERMAL
bool "Texas Instruments OMAP5 thermal support"
depends on TI_SOC_THERMAL
depends on SOC_OMAP5 || COMPILE_TEST
help
If you say yes here you get thermal support for the Texas Instruments
OMAP5 SoC family. The current chip supported are:
- OMAP5430
This includes alert interrupts generation and also the TSHUT
support.
config DRA752_THERMAL
bool "Texas Instruments DRA752 thermal support"
depends on TI_SOC_THERMAL
depends on SOC_DRA7XX || COMPILE_TEST
help
If you say yes here you get thermal support for the Texas Instruments
DRA752 SoC family. The current chip supported are:
- DRA752
This includes alert interrupts generation and also the TSHUT
support.
|
{
"pile_set_name": "Github"
}
|
set error non-classified off
set error unknown_code off
set error memory off
set error stack off
set hw simif nas 0xffff
run
state
quit
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.common.logger;
/**
* Helper class for a list (or tree) of LoggerNodes.
*
* <p>When this is set as the head of the list,
* an instance of it can function as a drop-in replacement for {@link android.util.Log}.
* Most of the methods in this class server only to map a method call in Log to its equivalent
* in LogNode.</p>
*/
public class Log {
// Grabbing the native values from Android's native logging facilities,
// to make for easy migration and interop.
public static final int NONE = -1;
public static final int VERBOSE = android.util.Log.VERBOSE;
public static final int DEBUG = android.util.Log.DEBUG;
public static final int INFO = android.util.Log.INFO;
public static final int WARN = android.util.Log.WARN;
public static final int ERROR = android.util.Log.ERROR;
public static final int ASSERT = android.util.Log.ASSERT;
// Stores the beginning of the LogNode topology.
private static LogNode mLogNode;
/**
* Returns the next LogNode in the linked list.
*/
public static LogNode getLogNode() {
return mLogNode;
}
/**
* Sets the LogNode data will be sent to.
*/
public static void setLogNode(LogNode node) {
mLogNode = node;
}
/**
* Instructs the LogNode to print the log data provided. Other LogNodes can
* be chained to the end of the LogNode as desired.
*
* @param priority Log level of the data being logged. Verbose, Error, etc.
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void println(int priority, String tag, String msg, Throwable tr) {
if (mLogNode != null) {
mLogNode.println(priority, tag, msg, tr);
}
}
/**
* Instructs the LogNode to print the log data provided. Other LogNodes can
* be chained to the end of the LogNode as desired.
*
* @param priority Log level of the data being logged. Verbose, Error, etc.
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged. The actual message to be logged.
*/
public static void println(int priority, String tag, String msg) {
println(priority, tag, msg, null);
}
/**
* Prints a message at VERBOSE priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void v(String tag, String msg, Throwable tr) {
println(VERBOSE, tag, msg, tr);
}
/**
* Prints a message at VERBOSE priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void v(String tag, String msg) {
v(tag, msg, null);
}
/**
* Prints a message at DEBUG priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void d(String tag, String msg, Throwable tr) {
println(DEBUG, tag, msg, tr);
}
/**
* Prints a message at DEBUG priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void d(String tag, String msg) {
d(tag, msg, null);
}
/**
* Prints a message at INFO priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void i(String tag, String msg, Throwable tr) {
println(INFO, tag, msg, tr);
}
/**
* Prints a message at INFO priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void i(String tag, String msg) {
i(tag, msg, null);
}
/**
* Prints a message at WARN priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void w(String tag, String msg, Throwable tr) {
println(WARN, tag, msg, tr);
}
/**
* Prints a message at WARN priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void w(String tag, String msg) {
w(tag, msg, null);
}
/**
* Prints a message at WARN priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void w(String tag, Throwable tr) {
w(tag, null, tr);
}
/**
* Prints a message at ERROR priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void e(String tag, String msg, Throwable tr) {
println(ERROR, tag, msg, tr);
}
/**
* Prints a message at ERROR priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void e(String tag, String msg) {
e(tag, msg, null);
}
/**
* Prints a message at ASSERT priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void wtf(String tag, String msg, Throwable tr) {
println(ASSERT, tag, msg, tr);
}
/**
* Prints a message at ASSERT priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void wtf(String tag, String msg) {
wtf(tag, msg, null);
}
/**
* Prints a message at ASSERT priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void wtf(String tag, Throwable tr) {
wtf(tag, null, tr);
}
}
|
{
"pile_set_name": "Github"
}
|
package meghanada.analyze;
import com.google.common.base.MoreObjects;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import meghanada.reflect.CandidateUnit;
import meghanada.reflect.MemberDescriptor;
import meghanada.reflect.MethodDescriptor;
import meghanada.reflect.MethodParameter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.EntryMessage;
public class MethodScope extends BlockScope {
private static final Logger log = LogManager.getLogger(MethodScope.class);
private static final long serialVersionUID = -5255555840551352713L;
public static final String[] STRINGS = new String[0];
public final String declaringClass;
public final List<String> parameters = new ArrayList<>(3);
public boolean vararg;
public String modifier;
public final String name;
public String returnType;
public final Range nameRange;
private final boolean isConstructor;
private final List<String> exceptions = new ArrayList<>(1);
public MethodScope(
final String declaringClass,
final String name,
@Nullable final Range nameRange,
final int pos,
final Range range,
final boolean isConstructor) {
super(pos, range);
this.declaringClass = declaringClass;
this.name = name;
this.nameRange = nameRange;
this.isConstructor = isConstructor;
}
void addMethodParameter(final String fqcn) {
this.parameters.add(fqcn);
}
void addException(final String fqcn) {
this.exceptions.add(fqcn);
}
@Override
public void dumpVariable() {
final EntryMessage entryMessage =
log.traceEntry("**** {} {} return {}", this.getScopeType(), this.name, this.returnType);
super.dumpVariable(log);
for (final ExpressionScope expressionScope : this.expressions) {
expressionScope.dumpVariable();
}
for (final BlockScope blockScope : this.scopes) {
blockScope.dumpVariable();
}
log.traceExit(entryMessage);
}
@Override
public void dumpFieldAccess() {
final EntryMessage entryMessage =
log.traceEntry("**** {} {} return {}", this.getScopeType(), this.name, this.returnType);
super.dumpFieldAccess(log);
for (final ExpressionScope expressionScope : this.expressions) {
expressionScope.dumpFieldAccess();
}
for (final BlockScope blockScope : this.scopes) {
blockScope.dumpFieldAccess();
}
log.traceExit(entryMessage);
}
@Override
public void dump() {
final EntryMessage entryMessage =
log.traceEntry(
"**** {} {} return {} isParameter {}",
this.getScopeType(),
this.name,
this.returnType,
this.parameters);
super.dumpVariable(log);
for (final ExpressionScope expressionScope : this.expressions) {
expressionScope.dumpVariable();
}
for (final BlockScope blockScope : this.scopes) {
blockScope.dumpVariable();
}
super.dumpFieldAccess(log);
for (final ExpressionScope expressionScope : this.expressions) {
expressionScope.dumpFieldAccess();
}
for (final BlockScope blockScope : this.scopes) {
blockScope.dumpFieldAccess();
}
log.traceExit(entryMessage);
}
@Override
public String getName() {
return this.name;
}
public Range getNameRange() {
return nameRange;
}
public long getBeginLine() {
return range.begin.line;
}
@Override
public Map<String, Variable> getDeclaratorMap() {
final Map<String, Variable> declaratorMap = super.getDeclaratorMap();
for (final ExpressionScope es : this.expressions) {
declaratorMap.putAll(es.getDeclaratorMap());
}
return declaratorMap;
}
@Override
public Map<String, Variable> getVariableMap() {
final Map<String, Variable> variableMap = super.getVariableMap();
for (final ExpressionScope es : this.expressions) {
es.getVariableMap()
.forEach(
(k, v) -> {
if (v.isDecl()) {
variableMap.put(k, v);
} else {
variableMap.putIfAbsent(k, v);
}
});
}
return variableMap;
}
@Override
public Set<Variable> getVariables() {
final Set<Variable> variables = super.getVariables();
for (final ExpressionScope es : this.expressions) {
variables.addAll(es.getVariables());
}
return variables;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("nameRange", nameRange)
.add("isConstructor", isConstructor)
.add("returnType", returnType)
.add("parameters", parameters)
.toString();
}
public List<String> getParameters() {
return parameters;
}
public boolean isConstructor() {
return isConstructor;
}
public MemberDescriptor toMemberDescriptor() {
int size = this.parameters.size();
List<MethodParameter> mps = new ArrayList<>(size);
int i = 0;
for (String type : parameters) {
i++;
boolean v = this.vararg && i == size;
MethodParameter mp = new MethodParameter(type, "arg" + i, v);
mps.add(mp);
}
String[] exceptions = getExceptions();
return new MethodDescriptor(
this.declaringClass,
this.name,
this.modifier,
mps,
exceptions,
this.returnType,
false,
CandidateUnit.MemberType.METHOD);
}
private String[] getExceptions() {
return this.exceptions.toArray(STRINGS);
}
}
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <CloudKit/CKObject.h>
@class NSNumber, NSString;
__attribute__((visibility("hidden")))
@interface CKAssetHandle : CKObject
{
NSNumber *_itemID;
NSString *_UUID;
NSString *_path;
NSNumber *_deviceID;
NSNumber *_fileID;
NSNumber *_generationID;
NSNumber *_lastUsedTime;
}
@property(retain, nonatomic) NSNumber *lastUsedTime; // @synthesize lastUsedTime=_lastUsedTime;
@property(retain, nonatomic) NSNumber *generationID; // @synthesize generationID=_generationID;
@property(retain, nonatomic) NSNumber *fileID; // @synthesize fileID=_fileID;
@property(retain, nonatomic) NSNumber *deviceID; // @synthesize deviceID=_deviceID;
@property(retain, nonatomic) NSString *path; // @synthesize path=_path;
@property(retain, nonatomic) NSString *UUID; // @synthesize UUID=_UUID;
@property(retain, nonatomic) NSNumber *itemID; // @synthesize itemID=_itemID;
- (void).cxx_destruct;
- (id)initWithItemID:(id)arg1 UUID:(id)arg2 path:(id)arg3;
- (id)description;
- (id)CKPropertiesDescription;
@end
|
{
"pile_set_name": "Github"
}
|
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27213.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.StackTrace.Tests", "tests\System.Diagnostics.StackTrace.Tests.csproj", "{297A9116-1005-499D-A895-2063D03E4C94}"
ProjectSection(ProjectDependencies) = postProject
{02304469-722E-4723-92A1-820B9A37D275} = {02304469-722E-4723-92A1-820B9A37D275}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.StackTrace", "src\System.Diagnostics.StackTrace.csproj", "{02304469-722E-4723-92A1-820B9A37D275}"
ProjectSection(ProjectDependencies) = postProject
{C38217EF-88F4-4D56-9F58-780BE1DDAFF6} = {C38217EF-88F4-4D56-9F58-780BE1DDAFF6}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.StackTrace", "ref\System.Diagnostics.StackTrace.csproj", "{C38217EF-88F4-4D56-9F58-780BE1DDAFF6}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{1A2F9F4A-A032-433E-B914-ADD5992BB178}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{E107E9C1-E893-4E87-987E-04EF0DCEAEFD}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{2E666815-2EDB-464B-9DF6-380BF4789AD4}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{854C7BBD-8B87-44AE-B109-421647CD5959}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Collections.Concurrent", "..\System.Collections.Concurrent\src\System.Collections.Concurrent.csproj", "{ADDF4CDC-9F80-492C-85B5-908E34B64D74}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.IO.FileSystem", "..\System.IO.FileSystem\src\System.IO.FileSystem.csproj", "{6E4DEE24-716D-4E97-877B-83B138020091}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime", "..\System.Runtime\src\System.Runtime.csproj", "{20636DC7-EB9C-4E40-B10C-BC023B4AEEDF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.Extensions", "..\System.Runtime.Extensions\src\System.Runtime.Extensions.csproj", "{5D5B7D66-AEB4-41A1-AB8A-1AB884A65064}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Reflection.Metadata", "..\System.Reflection.Metadata\src\System.Reflection.Metadata.csproj", "{456DBDB3-EF0D-4517-8893-8D5087CA3254}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Collections.Immutable", "..\System.Collections.Immutable\src\System.Collections.Immutable.csproj", "{085360DE-8FF9-4725-8014-3C660BB36A25}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{297A9116-1005-499D-A895-2063D03E4C94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{297A9116-1005-499D-A895-2063D03E4C94}.Debug|Any CPU.Build.0 = Debug|Any CPU
{297A9116-1005-499D-A895-2063D03E4C94}.Release|Any CPU.ActiveCfg = Release|Any CPU
{297A9116-1005-499D-A895-2063D03E4C94}.Release|Any CPU.Build.0 = Release|Any CPU
{02304469-722E-4723-92A1-820B9A37D275}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{02304469-722E-4723-92A1-820B9A37D275}.Debug|Any CPU.Build.0 = Debug|Any CPU
{02304469-722E-4723-92A1-820B9A37D275}.Release|Any CPU.ActiveCfg = Release|Any CPU
{02304469-722E-4723-92A1-820B9A37D275}.Release|Any CPU.Build.0 = Release|Any CPU
{C38217EF-88F4-4D56-9F58-780BE1DDAFF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C38217EF-88F4-4D56-9F58-780BE1DDAFF6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C38217EF-88F4-4D56-9F58-780BE1DDAFF6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C38217EF-88F4-4D56-9F58-780BE1DDAFF6}.Release|Any CPU.Build.0 = Release|Any CPU
{854C7BBD-8B87-44AE-B109-421647CD5959}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{854C7BBD-8B87-44AE-B109-421647CD5959}.Debug|Any CPU.Build.0 = Debug|Any CPU
{854C7BBD-8B87-44AE-B109-421647CD5959}.Release|Any CPU.ActiveCfg = Release|Any CPU
{854C7BBD-8B87-44AE-B109-421647CD5959}.Release|Any CPU.Build.0 = Release|Any CPU
{ADDF4CDC-9F80-492C-85B5-908E34B64D74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ADDF4CDC-9F80-492C-85B5-908E34B64D74}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ADDF4CDC-9F80-492C-85B5-908E34B64D74}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ADDF4CDC-9F80-492C-85B5-908E34B64D74}.Release|Any CPU.Build.0 = Release|Any CPU
{6E4DEE24-716D-4E97-877B-83B138020091}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6E4DEE24-716D-4E97-877B-83B138020091}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6E4DEE24-716D-4E97-877B-83B138020091}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6E4DEE24-716D-4E97-877B-83B138020091}.Release|Any CPU.Build.0 = Release|Any CPU
{20636DC7-EB9C-4E40-B10C-BC023B4AEEDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{20636DC7-EB9C-4E40-B10C-BC023B4AEEDF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{20636DC7-EB9C-4E40-B10C-BC023B4AEEDF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{20636DC7-EB9C-4E40-B10C-BC023B4AEEDF}.Release|Any CPU.Build.0 = Release|Any CPU
{5D5B7D66-AEB4-41A1-AB8A-1AB884A65064}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5D5B7D66-AEB4-41A1-AB8A-1AB884A65064}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5D5B7D66-AEB4-41A1-AB8A-1AB884A65064}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5D5B7D66-AEB4-41A1-AB8A-1AB884A65064}.Release|Any CPU.Build.0 = Release|Any CPU
{456DBDB3-EF0D-4517-8893-8D5087CA3254}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{456DBDB3-EF0D-4517-8893-8D5087CA3254}.Debug|Any CPU.Build.0 = Debug|Any CPU
{456DBDB3-EF0D-4517-8893-8D5087CA3254}.Release|Any CPU.ActiveCfg = Release|Any CPU
{456DBDB3-EF0D-4517-8893-8D5087CA3254}.Release|Any CPU.Build.0 = Release|Any CPU
{085360DE-8FF9-4725-8014-3C660BB36A25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{085360DE-8FF9-4725-8014-3C660BB36A25}.Debug|Any CPU.Build.0 = Debug|Any CPU
{085360DE-8FF9-4725-8014-3C660BB36A25}.Release|Any CPU.ActiveCfg = Release|Any CPU
{085360DE-8FF9-4725-8014-3C660BB36A25}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{297A9116-1005-499D-A895-2063D03E4C94} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
{02304469-722E-4723-92A1-820B9A37D275} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD}
{C38217EF-88F4-4D56-9F58-780BE1DDAFF6} = {2E666815-2EDB-464B-9DF6-380BF4789AD4}
{854C7BBD-8B87-44AE-B109-421647CD5959} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
{ADDF4CDC-9F80-492C-85B5-908E34B64D74} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD}
{6E4DEE24-716D-4E97-877B-83B138020091} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD}
{20636DC7-EB9C-4E40-B10C-BC023B4AEEDF} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD}
{5D5B7D66-AEB4-41A1-AB8A-1AB884A65064} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD}
{456DBDB3-EF0D-4517-8893-8D5087CA3254} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD}
{085360DE-8FF9-4725-8014-3C660BB36A25} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {207AB5D6-FFD0-42E8-88DF-0A3C6DF24251}
EndGlobalSection
EndGlobal
|
{
"pile_set_name": "Github"
}
|
package fa_IR
import (
"math"
"strconv"
"time"
"github.com/go-playground/locales"
"github.com/go-playground/locales/currency"
)
type fa_IR struct {
locale string
pluralsCardinal []locales.PluralRule
pluralsOrdinal []locales.PluralRule
pluralsRange []locales.PluralRule
decimal string
group string
minus string
percent string
perMille string
timeSeparator string
inifinity string
currencies []string // idx = enum of currency code
currencyPositivePrefix string
currencyNegativePrefix string
monthsAbbreviated []string
monthsNarrow []string
monthsWide []string
daysAbbreviated []string
daysNarrow []string
daysShort []string
daysWide []string
periodsAbbreviated []string
periodsNarrow []string
periodsShort []string
periodsWide []string
erasAbbreviated []string
erasNarrow []string
erasWide []string
timezones map[string]string
}
// New returns a new instance of translator for the 'fa_IR' locale
func New() locales.Translator {
return &fa_IR{
locale: "fa_IR",
pluralsCardinal: []locales.PluralRule{2, 6},
pluralsOrdinal: []locales.PluralRule{6},
pluralsRange: []locales.PluralRule{6},
decimal: "٫",
group: "٬",
minus: "−",
percent: "٪",
perMille: "؉",
timeSeparator: ":",
inifinity: "∞",
currencies: []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNH", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "STN", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "USD", "USN", "USS", "UYI", "UYP", "UYU", "UZS", "VEB", "VEF", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"},
currencyPositivePrefix: "",
currencyNegativePrefix: "",
monthsAbbreviated: []string{"", "ژانویهٔ", "فوریهٔ", "مارس", "آوریل", "مهٔ", "ژوئن", "ژوئیهٔ", "اوت", "سپتامبر", "اکتبر", "نوامبر", "دسامبر"},
monthsNarrow: []string{"", "ژ", "ف", "م", "آ", "م", "ژ", "ژ", "ا", "س", "ا", "ن", "د"},
monthsWide: []string{"", "ژانویهٔ", "فوریهٔ", "مارس", "آوریل", "مهٔ", "ژوئن", "ژوئیهٔ", "اوت", "سپتامبر", "اکتبر", "نوامبر", "دسامبر"},
daysAbbreviated: []string{"یکشنبه", "دوشنبه", "سه\u200cشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه"},
daysNarrow: []string{"ی", "د", "س", "چ", "پ", "ج", "ش"},
daysShort: []string{"۱ش", "۲ش", "۳ش", "۴ش", "۵ش", "ج", "ش"},
daysWide: []string{"یکشنبه", "دوشنبه", "سه\u200cشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه"},
periodsAbbreviated: []string{"ق.ظ.", "ب.ظ."},
periodsNarrow: []string{"ق", "ب"},
periodsWide: []string{"قبل\u200cازظهر", "بعدازظهر"},
erasAbbreviated: []string{"ق.م.", "م."},
erasNarrow: []string{"ق", "م"},
erasWide: []string{"قبل از میلاد", "میلادی"},
timezones: map[string]string{"GMT": "وقت گرینویچ", "CHADT": "وقت تابستانی چت\u200cهام", "WART": "وقت عادی غرب آرژانتین", "SRT": "وقت سورینام", "HKST": "وقت تابستانی هنگ\u200cکنگ", "IST": "وقت هند", "GYT": "وقت گویان", "PDT": "وقت تابستانی غرب امریکا", "WAST": "وقت تابستانی غرب افریقا", "EST": "وقت عادی شرق امریکا", "MEZ": "وقت عادی مرکز اروپا", "UYT": "وقت عادی اروگوئه", "AWDT": "وقت تابستانی غرب استرالیا", "SGT": "وقت سنگاپور", "ACWST": "وقت عادی مرکز-غرب استرالیا", "ACWDT": "وقت تابستانی مرکز-غرب استرالیا", "HEPM": "وقت تابستانی سنت\u200cپیر و میکلون", "∅∅∅": "وقت تابستانی آمازون", "HADT": "وقت تابستانی هاوایی‐الوشن", "MYT": "وقت مالزی", "HEEG": "وقت تابستانی شرق گرینلند", "ACST": "وقت عادی مرکز استرالیا", "HEPMX": "وقت تابستانی شرق مکزیک", "ADT": "وقت تابستانی آتلانتیک", "NZDT": "وقت تابستانی زلاند نو", "HNOG": "وقت عادی غرب گرینلند", "HKT": "وقت عادی هنگ\u200cکنگ", "ARST": "وقت تابستانی آرژانتین", "HNCU": "وقت عادی کوبا", "HNPMX": "وقت عادی شرق مکزیک", "WAT": "وقت عادی غرب افریقا", "BOT": "وقت بولیوی", "LHST": "وقت عادی لردهو", "CAT": "وقت مرکز افریقا", "EAT": "وقت شرق افریقا", "HECU": "وقت تابستانی کوبا", "WESZ": "وقت تابستانی غرب اروپا", "EDT": "وقت تابستانی شرق امریکا", "WITA": "وقت مرکز اندونزی", "TMST": "وقت تابستانی ترکمنستان", "ART": "وقت عادی آرژانتین", "CHAST": "وقت عادی چت\u200cهام", "WEZ": "وقت عادی غرب اروپا", "HAT": "وقت تابستانی نیوفاندلند", "OEZ": "وقت عادی شرق اروپا", "AST": "وقت عادی آتلانتیک", "AEST": "وقت عادی شرق استرالیا", "JST": "وقت عادی ژاپن", "HNEG": "وقت عادی شرق گرینلند", "HAST": "وقت عادی هاوایی‐الوشن", "CDT": "وقت تابستانی مرکز امریکا", "JDT": "وقت تابستانی ژاپن", "HNPM": "وقت عادی سنت\u200cپیر و میکلون", "CLT": "وقت عادی شیلی", "AKDT": "وقت تابستانی آلاسکا", "HNT": "وقت عادی نیوفاندلند", "HNNOMX": "وقت عادی شمال غرب مکزیک", "ChST": "وقت عادی چامورو", "AWST": "وقت عادی غرب استرالیا", "MDT": "وقت تابستانی کوهستانی امریکا", "WIB": "وقت غرب اندونزی", "BT": "وقت بوتان", "CLST": "وقت تابستانی شیلی", "NZST": "وقت عادی زلاند نو", "TMT": "وقت عادی ترکمنستان", "CST": "وقت عادی مرکز امریکا", "PST": "وقت عادی غرب امریکا", "AEDT": "وقت تابستانی شرق استرالیا", "MESZ": "وقت تابستانی مرکز اروپا", "ACDT": "وقت تابستانی مرکز استرالیا", "LHDT": "وقت تابستانی لردهو", "WARST": "وقت تابستانی غرب آرژانتین", "COST": "وقت تابستانی کلمبیا", "OESZ": "وقت تابستانی شرق اروپا", "SAST": "وقت عادی جنوب افریقا", "GFT": "وقت گویان فرانسه", "ECT": "وقت اکوادور", "VET": "وقت ونزوئلا", "MST": "وقت عادی کوهستانی امریکا", "HEOG": "وقت تابستانی غرب گرینلند", "HENOMX": "وقت تابستانی شمال غرب مکزیک", "WIT": "وقت شرق اندونزی", "COT": "وقت عادی کلمبیا", "UYST": "وقت تابستانی اروگوئه", "AKST": "وقت عادی آلاسکا"},
}
}
// Locale returns the current translators string locale
func (fa *fa_IR) Locale() string {
return fa.locale
}
// PluralsCardinal returns the list of cardinal plural rules associated with 'fa_IR'
func (fa *fa_IR) PluralsCardinal() []locales.PluralRule {
return fa.pluralsCardinal
}
// PluralsOrdinal returns the list of ordinal plural rules associated with 'fa_IR'
func (fa *fa_IR) PluralsOrdinal() []locales.PluralRule {
return fa.pluralsOrdinal
}
// PluralsRange returns the list of range plural rules associated with 'fa_IR'
func (fa *fa_IR) PluralsRange() []locales.PluralRule {
return fa.pluralsRange
}
// CardinalPluralRule returns the cardinal PluralRule given 'num' and digits/precision of 'v' for 'fa_IR'
func (fa *fa_IR) CardinalPluralRule(num float64, v uint64) locales.PluralRule {
n := math.Abs(num)
i := int64(n)
if (i == 0) || (n == 1) {
return locales.PluralRuleOne
}
return locales.PluralRuleOther
}
// OrdinalPluralRule returns the ordinal PluralRule given 'num' and digits/precision of 'v' for 'fa_IR'
func (fa *fa_IR) OrdinalPluralRule(num float64, v uint64) locales.PluralRule {
return locales.PluralRuleOther
}
// RangePluralRule returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for 'fa_IR'
func (fa *fa_IR) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) locales.PluralRule {
return locales.PluralRuleOther
}
// MonthAbbreviated returns the locales abbreviated month given the 'month' provided
func (fa *fa_IR) MonthAbbreviated(month time.Month) string {
return fa.monthsAbbreviated[month]
}
// MonthsAbbreviated returns the locales abbreviated months
func (fa *fa_IR) MonthsAbbreviated() []string {
return fa.monthsAbbreviated[1:]
}
// MonthNarrow returns the locales narrow month given the 'month' provided
func (fa *fa_IR) MonthNarrow(month time.Month) string {
return fa.monthsNarrow[month]
}
// MonthsNarrow returns the locales narrow months
func (fa *fa_IR) MonthsNarrow() []string {
return fa.monthsNarrow[1:]
}
// MonthWide returns the locales wide month given the 'month' provided
func (fa *fa_IR) MonthWide(month time.Month) string {
return fa.monthsWide[month]
}
// MonthsWide returns the locales wide months
func (fa *fa_IR) MonthsWide() []string {
return fa.monthsWide[1:]
}
// WeekdayAbbreviated returns the locales abbreviated weekday given the 'weekday' provided
func (fa *fa_IR) WeekdayAbbreviated(weekday time.Weekday) string {
return fa.daysAbbreviated[weekday]
}
// WeekdaysAbbreviated returns the locales abbreviated weekdays
func (fa *fa_IR) WeekdaysAbbreviated() []string {
return fa.daysAbbreviated
}
// WeekdayNarrow returns the locales narrow weekday given the 'weekday' provided
func (fa *fa_IR) WeekdayNarrow(weekday time.Weekday) string {
return fa.daysNarrow[weekday]
}
// WeekdaysNarrow returns the locales narrow weekdays
func (fa *fa_IR) WeekdaysNarrow() []string {
return fa.daysNarrow
}
// WeekdayShort returns the locales short weekday given the 'weekday' provided
func (fa *fa_IR) WeekdayShort(weekday time.Weekday) string {
return fa.daysShort[weekday]
}
// WeekdaysShort returns the locales short weekdays
func (fa *fa_IR) WeekdaysShort() []string {
return fa.daysShort
}
// WeekdayWide returns the locales wide weekday given the 'weekday' provided
func (fa *fa_IR) WeekdayWide(weekday time.Weekday) string {
return fa.daysWide[weekday]
}
// WeekdaysWide returns the locales wide weekdays
func (fa *fa_IR) WeekdaysWide() []string {
return fa.daysWide
}
// Decimal returns the decimal point of number
func (fa *fa_IR) Decimal() string {
return fa.decimal
}
// Group returns the group of number
func (fa *fa_IR) Group() string {
return fa.group
}
// Group returns the minus sign of number
func (fa *fa_IR) Minus() string {
return fa.minus
}
// FmtNumber returns 'num' with digits/precision of 'v' for 'fa_IR' and handles both Whole and Real numbers based on 'v'
func (fa *fa_IR) FmtNumber(num float64, v uint64) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
l := len(s) + 8 + 2*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
for j := len(fa.decimal) - 1; j >= 0; j-- {
b = append(b, fa.decimal[j])
}
inWhole = true
continue
}
if inWhole {
if count == 3 {
for j := len(fa.group) - 1; j >= 0; j-- {
b = append(b, fa.group[j])
}
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
for j := len(fa.minus) - 1; j >= 0; j-- {
b = append(b, fa.minus[j])
}
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
// FmtPercent returns 'num' with digits/precision of 'v' for 'fa_IR' and handles both Whole and Real numbers based on 'v'
// NOTE: 'num' passed into FmtPercent is assumed to be in percent already
func (fa *fa_IR) FmtPercent(num float64, v uint64) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
l := len(s) + 10
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
for j := len(fa.decimal) - 1; j >= 0; j-- {
b = append(b, fa.decimal[j])
}
continue
}
b = append(b, s[i])
}
if num < 0 {
for j := len(fa.minus) - 1; j >= 0; j-- {
b = append(b, fa.minus[j])
}
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
b = append(b, fa.percent...)
return string(b)
}
// FmtCurrency returns the currency representation of 'num' with digits/precision of 'v' for 'fa_IR'
func (fa *fa_IR) FmtCurrency(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := fa.currencies[currency]
l := len(s) + len(symbol) + 11 + 2*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
for j := len(fa.decimal) - 1; j >= 0; j-- {
b = append(b, fa.decimal[j])
}
inWhole = true
continue
}
if inWhole {
if count == 3 {
for j := len(fa.group) - 1; j >= 0; j-- {
b = append(b, fa.group[j])
}
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
for j := len(symbol) - 1; j >= 0; j-- {
b = append(b, symbol[j])
}
for j := len(fa.currencyPositivePrefix) - 1; j >= 0; j-- {
b = append(b, fa.currencyPositivePrefix[j])
}
if num < 0 {
for j := len(fa.minus) - 1; j >= 0; j-- {
b = append(b, fa.minus[j])
}
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
if int(v) < 2 {
if v == 0 {
b = append(b, fa.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
return string(b)
}
// FmtAccounting returns the currency representation of 'num' with digits/precision of 'v' for 'fa_IR'
// in accounting notation.
func (fa *fa_IR) FmtAccounting(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := fa.currencies[currency]
l := len(s) + len(symbol) + 11 + 2*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
for j := len(fa.decimal) - 1; j >= 0; j-- {
b = append(b, fa.decimal[j])
}
inWhole = true
continue
}
if inWhole {
if count == 3 {
for j := len(fa.group) - 1; j >= 0; j-- {
b = append(b, fa.group[j])
}
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
for j := len(symbol) - 1; j >= 0; j-- {
b = append(b, symbol[j])
}
for j := len(fa.currencyNegativePrefix) - 1; j >= 0; j-- {
b = append(b, fa.currencyNegativePrefix[j])
}
for j := len(fa.minus) - 1; j >= 0; j-- {
b = append(b, fa.minus[j])
}
} else {
for j := len(symbol) - 1; j >= 0; j-- {
b = append(b, symbol[j])
}
for j := len(fa.currencyPositivePrefix) - 1; j >= 0; j-- {
b = append(b, fa.currencyPositivePrefix[j])
}
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
if int(v) < 2 {
if v == 0 {
b = append(b, fa.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
return string(b)
}
// FmtDateShort returns the short date representation of 't' for 'fa_IR'
func (fa *fa_IR) FmtDateShort(t time.Time) string {
b := make([]byte, 0, 32)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
b = append(b, []byte{0x2f}...)
b = strconv.AppendInt(b, int64(t.Month()), 10)
b = append(b, []byte{0x2f}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
return string(b)
}
// FmtDateMedium returns the medium date representation of 't' for 'fa_IR'
func (fa *fa_IR) FmtDateMedium(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, fa.monthsAbbreviated[t.Month()]...)
b = append(b, []byte{0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtDateLong returns the long date representation of 't' for 'fa_IR'
func (fa *fa_IR) FmtDateLong(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, fa.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtDateFull returns the full date representation of 't' for 'fa_IR'
func (fa *fa_IR) FmtDateFull(t time.Time) string {
b := make([]byte, 0, 32)
b = append(b, fa.daysWide[t.Weekday()]...)
b = append(b, []byte{0x20}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, fa.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtTimeShort returns the short time representation of 't' for 'fa_IR'
func (fa *fa_IR) FmtTimeShort(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, fa.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
return string(b)
}
// FmtTimeMedium returns the medium time representation of 't' for 'fa_IR'
func (fa *fa_IR) FmtTimeMedium(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, fa.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, fa.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
return string(b)
}
// FmtTimeLong returns the long time representation of 't' for 'fa_IR'
func (fa *fa_IR) FmtTimeLong(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, fa.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, fa.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20, 0x28}...)
tz, _ := t.Zone()
b = append(b, tz...)
b = append(b, []byte{0x29}...)
return string(b)
}
// FmtTimeFull returns the full time representation of 't' for 'fa_IR'
func (fa *fa_IR) FmtTimeFull(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, fa.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, fa.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20, 0x28}...)
tz, _ := t.Zone()
if btz, ok := fa.timezones[tz]; ok {
b = append(b, btz...)
} else {
b = append(b, tz...)
}
b = append(b, []byte{0x29}...)
return string(b)
}
|
{
"pile_set_name": "Github"
}
|
import os
head = open('urdf-template/atlas_head.txt', 'r').read()
body = open('urdf-template/atlas_body.txt', 'r').read()
tail = open('urdf-template/atlas_tail.txt', 'r').read()
max_num_row = 5 # ADJUST
out_dir = 'output/atlas' # ADJUST
if not os.path.exists(out_dir):
os.makedirs(out_dir)
for numrow in range(1, max_num_row+1):
text = head + '\n'
print('generate URDF for numrow={}...'.format(numrow))
# body
i = 0
for row in range(0, numrow):
for col in range(0, numrow):
base_pos = (row * 2.0, col * 2.0, 1.0)
text += body.format(
base_pos_0 = base_pos[0],
base_pos_1 = base_pos[1],
base_pos_2 = base_pos[2],
id = i
)
i+=1
# tail
text += '\n'
text += tail
# save
print('save URDF for numrow={}...'.format(numrow))
with open(os.path.join(out_dir,
"robot{}.urdf".format(numrow)), "w") as text_file:
text_file.write(text)
print('Atlas URDF generate finished.')
|
{
"pile_set_name": "Github"
}
|
TARGET = rltotiff
OBJS = rltotiff.o tiff_rgba_io.o
include ../../splash_support/Makefile.config
LDFLAGS := $(LDFLAGS) -ltiff
clean:
rm -rf $(OBJS) $(TARGET)
|
{
"pile_set_name": "Github"
}
|
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
module Opaleye.Internal.TableMaker where
import qualified Opaleye.Column as C
import qualified Opaleye.Internal.Column as IC
import qualified Opaleye.Internal.PackMap as PM
import qualified Opaleye.Internal.Unpackspec as U
import Data.Profunctor (Profunctor, dimap)
import Data.Profunctor.Product (ProductProfunctor)
import qualified Data.Profunctor.Product as PP
import Data.Profunctor.Product.Default (Default, def)
import Control.Applicative (Applicative, pure, (<*>))
import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ
-- If we switch to a more lens-like approach to PackMap this should be
-- the equivalent of a Setter
newtype ViewColumnMaker strings columns =
ViewColumnMaker (PM.PackMap () () strings columns)
runViewColumnMaker :: ViewColumnMaker strings tablecolumns ->
strings -> tablecolumns
runViewColumnMaker (ViewColumnMaker f) = PM.overPM f id
{-# DEPRECATED ColumnMaker "Use Unpackspec instead" #-}
type ColumnMaker = U.Unpackspec
{-# DEPRECATED runColumnMaker "Use runUnpackspec instead" #-}
runColumnMaker :: Applicative f
=> ColumnMaker tablecolumns columns
-> (HPQ.PrimExpr -> f HPQ.PrimExpr)
-> tablecolumns -> f columns
runColumnMaker = U.runUnpackspec
-- There's surely a way of simplifying this implementation
tableColumn :: ViewColumnMaker String (C.Column a)
tableColumn = ViewColumnMaker
(PM.PackMap (\f s -> fmap (const (mkColumn s)) (f ())))
where mkColumn = IC.Column . HPQ.BaseTableAttrExpr
instance Default ViewColumnMaker String (C.Column a) where
def = tableColumn
{-# DEPRECATED column "Use unpackspecColumn instead" #-}
column :: ColumnMaker (C.Column a) (C.Column a)
column = U.unpackspecField
-- {
-- Boilerplate instance definitions. Theoretically, these are derivable.
instance Functor (ViewColumnMaker a) where
fmap f (ViewColumnMaker g) = ViewColumnMaker (fmap f g)
instance Applicative (ViewColumnMaker a) where
pure = ViewColumnMaker . pure
ViewColumnMaker f <*> ViewColumnMaker x = ViewColumnMaker (f <*> x)
instance Profunctor ViewColumnMaker where
dimap f g (ViewColumnMaker q) = ViewColumnMaker (dimap f g q)
instance ProductProfunctor ViewColumnMaker where
purePP = pure
(****) = (<*>)
--}
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env sh
TOOLS=./build/tools
$TOOLS/caffe train \
--solver=examples/cifar10/cifar10_full_sigmoid_solver.prototxt
|
{
"pile_set_name": "Github"
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LineLegendPosition.cs" company="OxyPlot">
// The MIT License (MIT)
//
// Copyright (c) 2012 Oystein Bjorke
//
// 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.
// </copyright>
// <summary>
// Specifies the position of legends rendered on a line series.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.Series
{
/// <summary>
/// Specifies the position of legends rendered on a <see cref="LineSeries"/>.
/// </summary>
public enum LineLegendPosition
{
/// <summary>
/// Do not render legend on the line.
/// </summary>
None,
/// <summary>
/// Render legend at the start of the line.
/// </summary>
Start,
/// <summary>
/// Render legend at the end of the line.
/// </summary>
End
}
}
|
{
"pile_set_name": "Github"
}
|
// jscs:disable requireArrowFunctions,disallowVar,requireEnhancedObjectLiterals
/* globals QUnit,Hammer,utils,Simulator */
var el;
var hammer;
var pressPeriod = 200;
var pressThreshold = 20;
var pressCount = 0;
var panStartCount = 0;
var swipeCount = 0;
QUnit.module('Require Failure ( Swipe & Press )', {
beforeEach: function() {
el = utils.createHitArea();
hammer = new Hammer(el, { recognizers: [] });
var swipe = new Hammer.Swipe({ threshold: 1 });
var press = new Hammer.Press({ time: pressPeriod, threshold: pressThreshold });
hammer.add(swipe);
hammer.add(press);
swipe.recognizeWith(press);
press.requireFailure(swipe);
pressCount = 0;
swipeCount = 0;
hammer.on('press', function() {
pressCount++;
});
hammer.on('swipe', function() {
swipeCount++;
});
},
afterEach: function() {
hammer.destroy();
}
});
QUnit.test('When swipe does not recognize the gesture, a press gesture can be fired', function(assert) {
var done = assert.async();
assert.expect(1);
utils.dispatchTouchEvent(el, 'start', 50, 50);
setTimeout(function() {
assert.equal(pressCount, 1, '1 press recognized');
done();
}, pressPeriod + 100);
});
QUnit.test('When swipe does recognize the gesture, a press gesture cannot be fired', function(assert) {
var done = assert.async();
assert.expect(2);
Simulator.gestures.swipe(el, null, function() {
assert.ok(swipeCount > 0, 'swipe gesture should be recognizing');
assert.equal(pressCount, 0, 'press gesture should not be recognized because swipe gesture is recognizing');
done();
});
});
QUnit.module('Require Failure ( Pan & Press )', {
beforeEach: function() {
el = document.createElement('div');
document.body.appendChild(el);
hammer = new Hammer(el, { recognizers: [] });
var pan = new Hammer.Pan({ threshold: 1 });
var press = new Hammer.Press({ time: pressPeriod, threshold: pressThreshold });
hammer.add([ pan, press ]);
pan.recognizeWith(press);
press.requireFailure(pan);
pressCount = 0;
panStartCount = 0;
hammer.on('press', function() {
pressCount++;
});
hammer.on('panstart', function() {
panStartCount++;
});
},
afterEach: function() {
document.body.removeChild(el);
hammer.destroy();
}
});
QUnit.test('When pan does not recognize the gesture, a press gesture can be fired', function(assert) {
var done = assert.async();
assert.expect(1);
utils.dispatchTouchEvent(el, 'start', 50, 50);
setTimeout(function() {
assert.equal(pressCount, 1, '1 press recognized');
done();
}, pressPeriod + 100);
});
QUnit.test('When pan recognizes the gesture, a press gesture cannot be fired', function(assert) {
var done = assert.async();
assert.expect(2);
utils.dispatchTouchEvent(el, 'start', 50, 50);
utils.dispatchTouchEvent(el, 'move', 50 + pressThreshold / 4, 50);
setTimeout(function() {
assert.ok(panStartCount > 0, 'pan gesture should be recognizing');
assert.equal(pressCount, 0, 'press gesture should not be recognized because pan gesture is recognizing');
done();
}, pressPeriod + 100);
});
|
{
"pile_set_name": "Github"
}
|
<info xmlns="http://docbook.org/ns/docbook" version="5.0">
<copyright>
<year>1999-2007</year>
<holder>Norman Walsh</holder>
</copyright>
<copyright>
<year>2003</year>
<holder>Jiří Kosek</holder>
</copyright>
<copyright>
<year>2004-2007</year>
<holder>Steve Ball</holder>
</copyright>
<copyright>
<year>2001-2007</year>
<holder>The DocBook Project</holder>
</copyright>
</info>
|
{
"pile_set_name": "Github"
}
|
# -*- coding: utf-8 -*-
"""
pygments.lexers.templates
~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for various template engines' markup.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexers.html import HtmlLexer, XmlLexer
from pygments.lexers.javascript import JavascriptLexer, LassoLexer
from pygments.lexers.css import CssLexer
from pygments.lexers.php import PhpLexer
from pygments.lexers.python import PythonLexer
from pygments.lexers.perl import PerlLexer
from pygments.lexers.jvm import JavaLexer, TeaLangLexer
from pygments.lexers.data import YamlLexer
from pygments.lexer import Lexer, DelegatingLexer, RegexLexer, bygroups, \
include, using, this, default, combined
from pygments.token import Error, Punctuation, Whitespace, \
Text, Comment, Operator, Keyword, Name, String, Number, Other, Token
from pygments.util import html_doctype_matches, looks_like_xml
__all__ = ['HtmlPhpLexer', 'XmlPhpLexer', 'CssPhpLexer',
'JavascriptPhpLexer', 'ErbLexer', 'RhtmlLexer',
'XmlErbLexer', 'CssErbLexer', 'JavascriptErbLexer',
'SmartyLexer', 'HtmlSmartyLexer', 'XmlSmartyLexer',
'CssSmartyLexer', 'JavascriptSmartyLexer', 'DjangoLexer',
'HtmlDjangoLexer', 'CssDjangoLexer', 'XmlDjangoLexer',
'JavascriptDjangoLexer', 'GenshiLexer', 'HtmlGenshiLexer',
'GenshiTextLexer', 'CssGenshiLexer', 'JavascriptGenshiLexer',
'MyghtyLexer', 'MyghtyHtmlLexer', 'MyghtyXmlLexer',
'MyghtyCssLexer', 'MyghtyJavascriptLexer', 'MasonLexer', 'MakoLexer',
'MakoHtmlLexer', 'MakoXmlLexer', 'MakoJavascriptLexer',
'MakoCssLexer', 'JspLexer', 'CheetahLexer', 'CheetahHtmlLexer',
'CheetahXmlLexer', 'CheetahJavascriptLexer', 'EvoqueLexer',
'EvoqueHtmlLexer', 'EvoqueXmlLexer', 'ColdfusionLexer',
'ColdfusionHtmlLexer', 'ColdfusionCFCLexer', 'VelocityLexer',
'VelocityHtmlLexer', 'VelocityXmlLexer', 'SspLexer',
'TeaTemplateLexer', 'LassoHtmlLexer', 'LassoXmlLexer',
'LassoCssLexer', 'LassoJavascriptLexer', 'HandlebarsLexer',
'HandlebarsHtmlLexer', 'YamlJinjaLexer', 'LiquidLexer',
'TwigLexer', 'TwigHtmlLexer']
class ErbLexer(Lexer):
"""
Generic `ERB <http://ruby-doc.org/core/classes/ERB.html>`_ (Ruby Templating)
lexer.
Just highlights ruby code between the preprocessor directives, other data
is left untouched by the lexer.
All options are also forwarded to the `RubyLexer`.
"""
name = 'ERB'
aliases = ['erb']
mimetypes = ['application/x-ruby-templating']
_block_re = re.compile(r'(<%%|%%>|<%=|<%#|<%-|<%|-%>|%>|^%[^%].*?$)', re.M)
def __init__(self, **options):
from pygments.lexers.ruby import RubyLexer
self.ruby_lexer = RubyLexer(**options)
Lexer.__init__(self, **options)
def get_tokens_unprocessed(self, text):
"""
Since ERB doesn't allow "<%" and other tags inside of ruby
blocks we have to use a split approach here that fails for
that too.
"""
tokens = self._block_re.split(text)
tokens.reverse()
state = idx = 0
try:
while True:
# text
if state == 0:
val = tokens.pop()
yield idx, Other, val
idx += len(val)
state = 1
# block starts
elif state == 1:
tag = tokens.pop()
# literals
if tag in ('<%%', '%%>'):
yield idx, Other, tag
idx += 3
state = 0
# comment
elif tag == '<%#':
yield idx, Comment.Preproc, tag
val = tokens.pop()
yield idx + 3, Comment, val
idx += 3 + len(val)
state = 2
# blocks or output
elif tag in ('<%', '<%=', '<%-'):
yield idx, Comment.Preproc, tag
idx += len(tag)
data = tokens.pop()
r_idx = 0
for r_idx, r_token, r_value in \
self.ruby_lexer.get_tokens_unprocessed(data):
yield r_idx + idx, r_token, r_value
idx += len(data)
state = 2
elif tag in ('%>', '-%>'):
yield idx, Error, tag
idx += len(tag)
state = 0
# % raw ruby statements
else:
yield idx, Comment.Preproc, tag[0]
r_idx = 0
for r_idx, r_token, r_value in \
self.ruby_lexer.get_tokens_unprocessed(tag[1:]):
yield idx + 1 + r_idx, r_token, r_value
idx += len(tag)
state = 0
# block ends
elif state == 2:
tag = tokens.pop()
if tag not in ('%>', '-%>'):
yield idx, Other, tag
else:
yield idx, Comment.Preproc, tag
idx += len(tag)
state = 0
except IndexError:
return
def analyse_text(text):
if '<%' in text and '%>' in text:
return 0.4
class SmartyLexer(RegexLexer):
"""
Generic `Smarty <http://smarty.php.net/>`_ template lexer.
Just highlights smarty code between the preprocessor directives, other
data is left untouched by the lexer.
"""
name = 'Smarty'
aliases = ['smarty']
filenames = ['*.tpl']
mimetypes = ['application/x-smarty']
flags = re.MULTILINE | re.DOTALL
tokens = {
'root': [
(r'[^{]+', Other),
(r'(\{)(\*.*?\*)(\})',
bygroups(Comment.Preproc, Comment, Comment.Preproc)),
(r'(\{php\})(.*?)(\{/php\})',
bygroups(Comment.Preproc, using(PhpLexer, startinline=True),
Comment.Preproc)),
(r'(\{)(/?[a-zA-Z_]\w*)(\s*)',
bygroups(Comment.Preproc, Name.Function, Text), 'smarty'),
(r'\{', Comment.Preproc, 'smarty')
],
'smarty': [
(r'\s+', Text),
(r'\{', Comment.Preproc, '#push'),
(r'\}', Comment.Preproc, '#pop'),
(r'#[a-zA-Z_]\w*#', Name.Variable),
(r'\$[a-zA-Z_]\w*(\.\w+)*', Name.Variable),
(r'[~!%^&*()+=|\[\]:;,.<>/?@-]', Operator),
(r'(true|false|null)\b', Keyword.Constant),
(r"[0-9](\.[0-9]*)?(eE[+-][0-9])?[flFLdD]?|"
r"0[xX][0-9a-fA-F]+[Ll]?", Number),
(r'"(\\\\|\\"|[^"])*"', String.Double),
(r"'(\\\\|\\'|[^'])*'", String.Single),
(r'[a-zA-Z_]\w*', Name.Attribute)
]
}
def analyse_text(text):
rv = 0.0
if re.search('\{if\s+.*?\}.*?\{/if\}', text):
rv += 0.15
if re.search('\{include\s+file=.*?\}', text):
rv += 0.15
if re.search('\{foreach\s+.*?\}.*?\{/foreach\}', text):
rv += 0.15
if re.search('\{\$.*?\}', text):
rv += 0.01
return rv
class VelocityLexer(RegexLexer):
"""
Generic `Velocity <http://velocity.apache.org/>`_ template lexer.
Just highlights velocity directives and variable references, other
data is left untouched by the lexer.
"""
name = 'Velocity'
aliases = ['velocity']
filenames = ['*.vm', '*.fhtml']
flags = re.MULTILINE | re.DOTALL
identifier = r'[a-zA-Z_]\w*'
tokens = {
'root': [
(r'[^{#$]+', Other),
(r'(#)(\*.*?\*)(#)',
bygroups(Comment.Preproc, Comment, Comment.Preproc)),
(r'(##)(.*?$)',
bygroups(Comment.Preproc, Comment)),
(r'(#\{?)(' + identifier + r')(\}?)(\s?\()',
bygroups(Comment.Preproc, Name.Function, Comment.Preproc, Punctuation),
'directiveparams'),
(r'(#\{?)(' + identifier + r')(\}|\b)',
bygroups(Comment.Preproc, Name.Function, Comment.Preproc)),
(r'\$\{?', Punctuation, 'variable')
],
'variable': [
(identifier, Name.Variable),
(r'\(', Punctuation, 'funcparams'),
(r'(\.)(' + identifier + r')',
bygroups(Punctuation, Name.Variable), '#push'),
(r'\}', Punctuation, '#pop'),
default('#pop')
],
'directiveparams': [
(r'(&&|\|\||==?|!=?|[-<>+*%&|^/])|\b(eq|ne|gt|lt|ge|le|not|in)\b',
Operator),
(r'\[', Operator, 'rangeoperator'),
(r'\b' + identifier + r'\b', Name.Function),
include('funcparams')
],
'rangeoperator': [
(r'\.\.', Operator),
include('funcparams'),
(r'\]', Operator, '#pop')
],
'funcparams': [
(r'\$\{?', Punctuation, 'variable'),
(r'\s+', Text),
(r',', Punctuation),
(r'"(\\\\|\\"|[^"])*"', String.Double),
(r"'(\\\\|\\'|[^'])*'", String.Single),
(r"0[xX][0-9a-fA-F]+[Ll]?", Number),
(r"\b[0-9]+\b", Number),
(r'(true|false|null)\b', Keyword.Constant),
(r'\(', Punctuation, '#push'),
(r'\)', Punctuation, '#pop'),
(r'\[', Punctuation, '#push'),
(r'\]', Punctuation, '#pop'),
]
}
def analyse_text(text):
rv = 0.0
if re.search(r'#\{?macro\}?\(.*?\).*?#\{?end\}?', text):
rv += 0.25
if re.search(r'#\{?if\}?\(.+?\).*?#\{?end\}?', text):
rv += 0.15
if re.search(r'#\{?foreach\}?\(.+?\).*?#\{?end\}?', text):
rv += 0.15
if re.search(r'\$\{?[a-zA-Z_]\w*(\([^)]*\))?'
r'(\.\w+(\([^)]*\))?)*\}?', text):
rv += 0.01
return rv
class VelocityHtmlLexer(DelegatingLexer):
"""
Subclass of the `VelocityLexer` that highlights unlexed data
with the `HtmlLexer`.
"""
name = 'HTML+Velocity'
aliases = ['html+velocity']
alias_filenames = ['*.html', '*.fhtml']
mimetypes = ['text/html+velocity']
def __init__(self, **options):
super(VelocityHtmlLexer, self).__init__(HtmlLexer, VelocityLexer,
**options)
class VelocityXmlLexer(DelegatingLexer):
"""
Subclass of the `VelocityLexer` that highlights unlexed data
with the `XmlLexer`.
"""
name = 'XML+Velocity'
aliases = ['xml+velocity']
alias_filenames = ['*.xml', '*.vm']
mimetypes = ['application/xml+velocity']
def __init__(self, **options):
super(VelocityXmlLexer, self).__init__(XmlLexer, VelocityLexer,
**options)
def analyse_text(text):
rv = VelocityLexer.analyse_text(text) - 0.01
if looks_like_xml(text):
rv += 0.4
return rv
class DjangoLexer(RegexLexer):
"""
Generic `django <http://www.djangoproject.com/documentation/templates/>`_
and `jinja <http://wsgiarea.pocoo.org/jinja/>`_ template lexer.
It just highlights django/jinja code between the preprocessor directives,
other data is left untouched by the lexer.
"""
name = 'Django/Jinja'
aliases = ['django', 'jinja']
mimetypes = ['application/x-django-templating', 'application/x-jinja']
flags = re.M | re.S
tokens = {
'root': [
(r'[^{]+', Other),
(r'\{\{', Comment.Preproc, 'var'),
# jinja/django comments
(r'\{[*#].*?[*#]\}', Comment),
# django comments
(r'(\{%)(-?\s*)(comment)(\s*-?)(%\})(.*?)'
r'(\{%)(-?\s*)(endcomment)(\s*-?)(%\})',
bygroups(Comment.Preproc, Text, Keyword, Text, Comment.Preproc,
Comment, Comment.Preproc, Text, Keyword, Text,
Comment.Preproc)),
# raw jinja blocks
(r'(\{%)(-?\s*)(raw)(\s*-?)(%\})(.*?)'
r'(\{%)(-?\s*)(endraw)(\s*-?)(%\})',
bygroups(Comment.Preproc, Text, Keyword, Text, Comment.Preproc,
Text, Comment.Preproc, Text, Keyword, Text,
Comment.Preproc)),
# filter blocks
(r'(\{%)(-?\s*)(filter)(\s+)([a-zA-Z_]\w*)',
bygroups(Comment.Preproc, Text, Keyword, Text, Name.Function),
'block'),
(r'(\{%)(-?\s*)([a-zA-Z_]\w*)',
bygroups(Comment.Preproc, Text, Keyword), 'block'),
(r'\{', Other)
],
'varnames': [
(r'(\|)(\s*)([a-zA-Z_]\w*)',
bygroups(Operator, Text, Name.Function)),
(r'(is)(\s+)(not)?(\s+)?([a-zA-Z_]\w*)',
bygroups(Keyword, Text, Keyword, Text, Name.Function)),
(r'(_|true|false|none|True|False|None)\b', Keyword.Pseudo),
(r'(in|as|reversed|recursive|not|and|or|is|if|else|import|'
r'with(?:(?:out)?\s*context)?|scoped|ignore\s+missing)\b',
Keyword),
(r'(loop|block|super|forloop)\b', Name.Builtin),
(r'[a-zA-Z][\w-]*', Name.Variable),
(r'\.\w+', Name.Variable),
(r':?"(\\\\|\\"|[^"])*"', String.Double),
(r":?'(\\\\|\\'|[^'])*'", String.Single),
(r'([{}()\[\]+\-*/,:~]|[><=]=?)', Operator),
(r"[0-9](\.[0-9]*)?(eE[+-][0-9])?[flFLdD]?|"
r"0[xX][0-9a-fA-F]+[Ll]?", Number),
],
'var': [
(r'\s+', Text),
(r'(-?)(\}\})', bygroups(Text, Comment.Preproc), '#pop'),
include('varnames')
],
'block': [
(r'\s+', Text),
(r'(-?)(%\})', bygroups(Text, Comment.Preproc), '#pop'),
include('varnames'),
(r'.', Punctuation)
]
}
def analyse_text(text):
rv = 0.0
if re.search(r'\{%\s*(block|extends)', text) is not None:
rv += 0.4
if re.search(r'\{%\s*if\s*.*?%\}', text) is not None:
rv += 0.1
if re.search(r'\{\{.*?\}\}', text) is not None:
rv += 0.1
return rv
class MyghtyLexer(RegexLexer):
"""
Generic `myghty templates`_ lexer. Code that isn't Myghty
markup is yielded as `Token.Other`.
.. versionadded:: 0.6
.. _myghty templates: http://www.myghty.org/
"""
name = 'Myghty'
aliases = ['myghty']
filenames = ['*.myt', 'autodelegate']
mimetypes = ['application/x-myghty']
tokens = {
'root': [
(r'\s+', Text),
(r'(<%(?:def|method))(\s*)(.*?)(>)(.*?)(</%\2\s*>)(?s)',
bygroups(Name.Tag, Text, Name.Function, Name.Tag,
using(this), Name.Tag)),
(r'(<%\w+)(.*?)(>)(.*?)(</%\2\s*>)(?s)',
bygroups(Name.Tag, Name.Function, Name.Tag,
using(PythonLexer), Name.Tag)),
(r'(<&[^|])(.*?)(,.*?)?(&>)',
bygroups(Name.Tag, Name.Function, using(PythonLexer), Name.Tag)),
(r'(<&\|)(.*?)(,.*?)?(&>)(?s)',
bygroups(Name.Tag, Name.Function, using(PythonLexer), Name.Tag)),
(r'</&>', Name.Tag),
(r'(<%!?)(.*?)(%>)(?s)',
bygroups(Name.Tag, using(PythonLexer), Name.Tag)),
(r'(?<=^)#[^\n]*(\n|\Z)', Comment),
(r'(?<=^)(%)([^\n]*)(\n|\Z)',
bygroups(Name.Tag, using(PythonLexer), Other)),
(r"""(?sx)
(.+?) # anything, followed by:
(?:
(?<=\n)(?=[%#]) | # an eval or comment line
(?=</?[%&]) | # a substitution or block or
# call start or end
# - don't consume
(\\\n) | # an escaped newline
\Z # end of string
)""", bygroups(Other, Operator)),
]
}
class MyghtyHtmlLexer(DelegatingLexer):
"""
Subclass of the `MyghtyLexer` that highlights unlexed data
with the `HtmlLexer`.
.. versionadded:: 0.6
"""
name = 'HTML+Myghty'
aliases = ['html+myghty']
mimetypes = ['text/html+myghty']
def __init__(self, **options):
super(MyghtyHtmlLexer, self).__init__(HtmlLexer, MyghtyLexer,
**options)
class MyghtyXmlLexer(DelegatingLexer):
"""
Subclass of the `MyghtyLexer` that highlights unlexed data
with the `XmlLexer`.
.. versionadded:: 0.6
"""
name = 'XML+Myghty'
aliases = ['xml+myghty']
mimetypes = ['application/xml+myghty']
def __init__(self, **options):
super(MyghtyXmlLexer, self).__init__(XmlLexer, MyghtyLexer,
**options)
class MyghtyJavascriptLexer(DelegatingLexer):
"""
Subclass of the `MyghtyLexer` that highlights unlexed data
with the `JavascriptLexer`.
.. versionadded:: 0.6
"""
name = 'JavaScript+Myghty'
aliases = ['js+myghty', 'javascript+myghty']
mimetypes = ['application/x-javascript+myghty',
'text/x-javascript+myghty',
'text/javascript+mygthy']
def __init__(self, **options):
super(MyghtyJavascriptLexer, self).__init__(JavascriptLexer,
MyghtyLexer, **options)
class MyghtyCssLexer(DelegatingLexer):
"""
Subclass of the `MyghtyLexer` that highlights unlexed data
with the `CssLexer`.
.. versionadded:: 0.6
"""
name = 'CSS+Myghty'
aliases = ['css+myghty']
mimetypes = ['text/css+myghty']
def __init__(self, **options):
super(MyghtyCssLexer, self).__init__(CssLexer, MyghtyLexer,
**options)
class MasonLexer(RegexLexer):
"""
Generic `mason templates`_ lexer. Stolen from Myghty lexer. Code that isn't
Mason markup is HTML.
.. _mason templates: http://www.masonhq.com/
.. versionadded:: 1.4
"""
name = 'Mason'
aliases = ['mason']
filenames = ['*.m', '*.mhtml', '*.mc', '*.mi', 'autohandler', 'dhandler']
mimetypes = ['application/x-mason']
tokens = {
'root': [
(r'\s+', Text),
(r'(<%doc>)(.*?)(</%doc>)(?s)',
bygroups(Name.Tag, Comment.Multiline, Name.Tag)),
(r'(<%(?:def|method))(\s*)(.*?)(>)(.*?)(</%\2\s*>)(?s)',
bygroups(Name.Tag, Text, Name.Function, Name.Tag,
using(this), Name.Tag)),
(r'(<%\w+)(.*?)(>)(.*?)(</%\2\s*>)(?s)',
bygroups(Name.Tag, Name.Function, Name.Tag,
using(PerlLexer), Name.Tag)),
(r'(<&[^|])(.*?)(,.*?)?(&>)(?s)',
bygroups(Name.Tag, Name.Function, using(PerlLexer), Name.Tag)),
(r'(<&\|)(.*?)(,.*?)?(&>)(?s)',
bygroups(Name.Tag, Name.Function, using(PerlLexer), Name.Tag)),
(r'</&>', Name.Tag),
(r'(<%!?)(.*?)(%>)(?s)',
bygroups(Name.Tag, using(PerlLexer), Name.Tag)),
(r'(?<=^)#[^\n]*(\n|\Z)', Comment),
(r'(?<=^)(%)([^\n]*)(\n|\Z)',
bygroups(Name.Tag, using(PerlLexer), Other)),
(r"""(?sx)
(.+?) # anything, followed by:
(?:
(?<=\n)(?=[%#]) | # an eval or comment line
(?=</?[%&]) | # a substitution or block or
# call start or end
# - don't consume
(\\\n) | # an escaped newline
\Z # end of string
)""", bygroups(using(HtmlLexer), Operator)),
]
}
def analyse_text(text):
rv = 0.0
if re.search('<&', text) is not None:
rv = 1.0
return rv
class MakoLexer(RegexLexer):
"""
Generic `mako templates`_ lexer. Code that isn't Mako
markup is yielded as `Token.Other`.
.. versionadded:: 0.7
.. _mako templates: http://www.makotemplates.org/
"""
name = 'Mako'
aliases = ['mako']
filenames = ['*.mao']
mimetypes = ['application/x-mako']
tokens = {
'root': [
(r'(\s*)(%)(\s*end(?:\w+))(\n|\Z)',
bygroups(Text, Comment.Preproc, Keyword, Other)),
(r'(\s*)(%)([^\n]*)(\n|\Z)',
bygroups(Text, Comment.Preproc, using(PythonLexer), Other)),
(r'(\s*)(##[^\n]*)(\n|\Z)',
bygroups(Text, Comment.Preproc, Other)),
(r'(?s)<%doc>.*?</%doc>', Comment.Preproc),
(r'(<%)([\w.:]+)',
bygroups(Comment.Preproc, Name.Builtin), 'tag'),
(r'(</%)([\w.:]+)(>)',
bygroups(Comment.Preproc, Name.Builtin, Comment.Preproc)),
(r'<%(?=([\w.:]+))', Comment.Preproc, 'ondeftags'),
(r'(<%(?:!?))(.*?)(%>)(?s)',
bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
(r'(\$\{)(.*?)(\})',
bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
(r'''(?sx)
(.+?) # anything, followed by:
(?:
(?<=\n)(?=%|\#\#) | # an eval or comment line
(?=\#\*) | # multiline comment
(?=</?%) | # a python block
# call start or end
(?=\$\{) | # a substitution
(?<=\n)(?=\s*%) |
# - don't consume
(\\\n) | # an escaped newline
\Z # end of string
)
''', bygroups(Other, Operator)),
(r'\s+', Text),
],
'ondeftags': [
(r'<%', Comment.Preproc),
(r'(?<=<%)(include|inherit|namespace|page)', Name.Builtin),
include('tag'),
],
'tag': [
(r'((?:\w+)\s*=)(\s*)(".*?")',
bygroups(Name.Attribute, Text, String)),
(r'/?\s*>', Comment.Preproc, '#pop'),
(r'\s+', Text),
],
'attr': [
('".*?"', String, '#pop'),
("'.*?'", String, '#pop'),
(r'[^\s>]+', String, '#pop'),
],
}
class MakoHtmlLexer(DelegatingLexer):
"""
Subclass of the `MakoLexer` that highlights unlexed data
with the `HtmlLexer`.
.. versionadded:: 0.7
"""
name = 'HTML+Mako'
aliases = ['html+mako']
mimetypes = ['text/html+mako']
def __init__(self, **options):
super(MakoHtmlLexer, self).__init__(HtmlLexer, MakoLexer,
**options)
class MakoXmlLexer(DelegatingLexer):
"""
Subclass of the `MakoLexer` that highlights unlexed data
with the `XmlLexer`.
.. versionadded:: 0.7
"""
name = 'XML+Mako'
aliases = ['xml+mako']
mimetypes = ['application/xml+mako']
def __init__(self, **options):
super(MakoXmlLexer, self).__init__(XmlLexer, MakoLexer,
**options)
class MakoJavascriptLexer(DelegatingLexer):
"""
Subclass of the `MakoLexer` that highlights unlexed data
with the `JavascriptLexer`.
.. versionadded:: 0.7
"""
name = 'JavaScript+Mako'
aliases = ['js+mako', 'javascript+mako']
mimetypes = ['application/x-javascript+mako',
'text/x-javascript+mako',
'text/javascript+mako']
def __init__(self, **options):
super(MakoJavascriptLexer, self).__init__(JavascriptLexer,
MakoLexer, **options)
class MakoCssLexer(DelegatingLexer):
"""
Subclass of the `MakoLexer` that highlights unlexed data
with the `CssLexer`.
.. versionadded:: 0.7
"""
name = 'CSS+Mako'
aliases = ['css+mako']
mimetypes = ['text/css+mako']
def __init__(self, **options):
super(MakoCssLexer, self).__init__(CssLexer, MakoLexer,
**options)
# Genshi and Cheetah lexers courtesy of Matt Good.
class CheetahPythonLexer(Lexer):
"""
Lexer for handling Cheetah's special $ tokens in Python syntax.
"""
def get_tokens_unprocessed(self, text):
pylexer = PythonLexer(**self.options)
for pos, type_, value in pylexer.get_tokens_unprocessed(text):
if type_ == Token.Error and value == '$':
type_ = Comment.Preproc
yield pos, type_, value
class CheetahLexer(RegexLexer):
"""
Generic `cheetah templates`_ lexer. Code that isn't Cheetah
markup is yielded as `Token.Other`. This also works for
`spitfire templates`_ which use the same syntax.
.. _cheetah templates: http://www.cheetahtemplate.org/
.. _spitfire templates: http://code.google.com/p/spitfire/
"""
name = 'Cheetah'
aliases = ['cheetah', 'spitfire']
filenames = ['*.tmpl', '*.spt']
mimetypes = ['application/x-cheetah', 'application/x-spitfire']
tokens = {
'root': [
(r'(##[^\n]*)$',
(bygroups(Comment))),
(r'#[*](.|\n)*?[*]#', Comment),
(r'#end[^#\n]*(?:#|$)', Comment.Preproc),
(r'#slurp$', Comment.Preproc),
(r'(#[a-zA-Z]+)([^#\n]*)(#|$)',
(bygroups(Comment.Preproc, using(CheetahPythonLexer),
Comment.Preproc))),
# TODO support other Python syntax like $foo['bar']
(r'(\$)([a-zA-Z_][\w.]*\w)',
bygroups(Comment.Preproc, using(CheetahPythonLexer))),
(r'(\$\{!?)(.*?)(\})(?s)',
bygroups(Comment.Preproc, using(CheetahPythonLexer),
Comment.Preproc)),
(r'''(?sx)
(.+?) # anything, followed by:
(?:
(?=\#[#a-zA-Z]*) | # an eval comment
(?=\$[a-zA-Z_{]) | # a substitution
\Z # end of string
)
''', Other),
(r'\s+', Text),
],
}
class CheetahHtmlLexer(DelegatingLexer):
"""
Subclass of the `CheetahLexer` that highlights unlexed data
with the `HtmlLexer`.
"""
name = 'HTML+Cheetah'
aliases = ['html+cheetah', 'html+spitfire', 'htmlcheetah']
mimetypes = ['text/html+cheetah', 'text/html+spitfire']
def __init__(self, **options):
super(CheetahHtmlLexer, self).__init__(HtmlLexer, CheetahLexer,
**options)
class CheetahXmlLexer(DelegatingLexer):
"""
Subclass of the `CheetahLexer` that highlights unlexed data
with the `XmlLexer`.
"""
name = 'XML+Cheetah'
aliases = ['xml+cheetah', 'xml+spitfire']
mimetypes = ['application/xml+cheetah', 'application/xml+spitfire']
def __init__(self, **options):
super(CheetahXmlLexer, self).__init__(XmlLexer, CheetahLexer,
**options)
class CheetahJavascriptLexer(DelegatingLexer):
"""
Subclass of the `CheetahLexer` that highlights unlexed data
with the `JavascriptLexer`.
"""
name = 'JavaScript+Cheetah'
aliases = ['js+cheetah', 'javascript+cheetah',
'js+spitfire', 'javascript+spitfire']
mimetypes = ['application/x-javascript+cheetah',
'text/x-javascript+cheetah',
'text/javascript+cheetah',
'application/x-javascript+spitfire',
'text/x-javascript+spitfire',
'text/javascript+spitfire']
def __init__(self, **options):
super(CheetahJavascriptLexer, self).__init__(JavascriptLexer,
CheetahLexer, **options)
class GenshiTextLexer(RegexLexer):
"""
A lexer that highlights `genshi <http://genshi.edgewall.org/>`_ text
templates.
"""
name = 'Genshi Text'
aliases = ['genshitext']
mimetypes = ['application/x-genshi-text', 'text/x-genshi']
tokens = {
'root': [
(r'[^#$\s]+', Other),
(r'^(\s*)(##.*)$', bygroups(Text, Comment)),
(r'^(\s*)(#)', bygroups(Text, Comment.Preproc), 'directive'),
include('variable'),
(r'[#$\s]', Other),
],
'directive': [
(r'\n', Text, '#pop'),
(r'(?:def|for|if)\s+.*', using(PythonLexer), '#pop'),
(r'(choose|when|with)([^\S\n]+)(.*)',
bygroups(Keyword, Text, using(PythonLexer)), '#pop'),
(r'(choose|otherwise)\b', Keyword, '#pop'),
(r'(end\w*)([^\S\n]*)(.*)', bygroups(Keyword, Text, Comment), '#pop'),
],
'variable': [
(r'(?<!\$)(\$\{)(.+?)(\})',
bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
(r'(?<!\$)(\$)([a-zA-Z_][\w.]*)',
Name.Variable),
]
}
class GenshiMarkupLexer(RegexLexer):
"""
Base lexer for Genshi markup, used by `HtmlGenshiLexer` and
`GenshiLexer`.
"""
flags = re.DOTALL
tokens = {
'root': [
(r'[^<$]+', Other),
(r'(<\?python)(.*?)(\?>)',
bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
# yield style and script blocks as Other
(r'<\s*(script|style)\s*.*?>.*?<\s*/\1\s*>', Other),
(r'<\s*py:[a-zA-Z0-9]+', Name.Tag, 'pytag'),
(r'<\s*[a-zA-Z0-9:]+', Name.Tag, 'tag'),
include('variable'),
(r'[<$]', Other),
],
'pytag': [
(r'\s+', Text),
(r'[\w:-]+\s*=', Name.Attribute, 'pyattr'),
(r'/?\s*>', Name.Tag, '#pop'),
],
'pyattr': [
('(")(.*?)(")', bygroups(String, using(PythonLexer), String), '#pop'),
("(')(.*?)(')", bygroups(String, using(PythonLexer), String), '#pop'),
(r'[^\s>]+', String, '#pop'),
],
'tag': [
(r'\s+', Text),
(r'py:[\w-]+\s*=', Name.Attribute, 'pyattr'),
(r'[\w:-]+\s*=', Name.Attribute, 'attr'),
(r'/?\s*>', Name.Tag, '#pop'),
],
'attr': [
('"', String, 'attr-dstring'),
("'", String, 'attr-sstring'),
(r'[^\s>]*', String, '#pop')
],
'attr-dstring': [
('"', String, '#pop'),
include('strings'),
("'", String)
],
'attr-sstring': [
("'", String, '#pop'),
include('strings'),
("'", String)
],
'strings': [
('[^"\'$]+', String),
include('variable')
],
'variable': [
(r'(?<!\$)(\$\{)(.+?)(\})',
bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
(r'(?<!\$)(\$)([a-zA-Z_][\w\.]*)',
Name.Variable),
]
}
class HtmlGenshiLexer(DelegatingLexer):
"""
A lexer that highlights `genshi <http://genshi.edgewall.org/>`_ and
`kid <http://kid-templating.org/>`_ kid HTML templates.
"""
name = 'HTML+Genshi'
aliases = ['html+genshi', 'html+kid']
alias_filenames = ['*.html', '*.htm', '*.xhtml']
mimetypes = ['text/html+genshi']
def __init__(self, **options):
super(HtmlGenshiLexer, self).__init__(HtmlLexer, GenshiMarkupLexer,
**options)
def analyse_text(text):
rv = 0.0
if re.search('\$\{.*?\}', text) is not None:
rv += 0.2
if re.search('py:(.*?)=["\']', text) is not None:
rv += 0.2
return rv + HtmlLexer.analyse_text(text) - 0.01
class GenshiLexer(DelegatingLexer):
"""
A lexer that highlights `genshi <http://genshi.edgewall.org/>`_ and
`kid <http://kid-templating.org/>`_ kid XML templates.
"""
name = 'Genshi'
aliases = ['genshi', 'kid', 'xml+genshi', 'xml+kid']
filenames = ['*.kid']
alias_filenames = ['*.xml']
mimetypes = ['application/x-genshi', 'application/x-kid']
def __init__(self, **options):
super(GenshiLexer, self).__init__(XmlLexer, GenshiMarkupLexer,
**options)
def analyse_text(text):
rv = 0.0
if re.search('\$\{.*?\}', text) is not None:
rv += 0.2
if re.search('py:(.*?)=["\']', text) is not None:
rv += 0.2
return rv + XmlLexer.analyse_text(text) - 0.01
class JavascriptGenshiLexer(DelegatingLexer):
"""
A lexer that highlights javascript code in genshi text templates.
"""
name = 'JavaScript+Genshi Text'
aliases = ['js+genshitext', 'js+genshi', 'javascript+genshitext',
'javascript+genshi']
alias_filenames = ['*.js']
mimetypes = ['application/x-javascript+genshi',
'text/x-javascript+genshi',
'text/javascript+genshi']
def __init__(self, **options):
super(JavascriptGenshiLexer, self).__init__(JavascriptLexer,
GenshiTextLexer,
**options)
def analyse_text(text):
return GenshiLexer.analyse_text(text) - 0.05
class CssGenshiLexer(DelegatingLexer):
"""
A lexer that highlights CSS definitions in genshi text templates.
"""
name = 'CSS+Genshi Text'
aliases = ['css+genshitext', 'css+genshi']
alias_filenames = ['*.css']
mimetypes = ['text/css+genshi']
def __init__(self, **options):
super(CssGenshiLexer, self).__init__(CssLexer, GenshiTextLexer,
**options)
def analyse_text(text):
return GenshiLexer.analyse_text(text) - 0.05
class RhtmlLexer(DelegatingLexer):
"""
Subclass of the ERB lexer that highlights the unlexed data with the
html lexer.
Nested Javascript and CSS is highlighted too.
"""
name = 'RHTML'
aliases = ['rhtml', 'html+erb', 'html+ruby']
filenames = ['*.rhtml']
alias_filenames = ['*.html', '*.htm', '*.xhtml']
mimetypes = ['text/html+ruby']
def __init__(self, **options):
super(RhtmlLexer, self).__init__(HtmlLexer, ErbLexer, **options)
def analyse_text(text):
rv = ErbLexer.analyse_text(text) - 0.01
if html_doctype_matches(text):
# one more than the XmlErbLexer returns
rv += 0.5
return rv
class XmlErbLexer(DelegatingLexer):
"""
Subclass of `ErbLexer` which highlights data outside preprocessor
directives with the `XmlLexer`.
"""
name = 'XML+Ruby'
aliases = ['xml+erb', 'xml+ruby']
alias_filenames = ['*.xml']
mimetypes = ['application/xml+ruby']
def __init__(self, **options):
super(XmlErbLexer, self).__init__(XmlLexer, ErbLexer, **options)
def analyse_text(text):
rv = ErbLexer.analyse_text(text) - 0.01
if looks_like_xml(text):
rv += 0.4
return rv
class CssErbLexer(DelegatingLexer):
"""
Subclass of `ErbLexer` which highlights unlexed data with the `CssLexer`.
"""
name = 'CSS+Ruby'
aliases = ['css+erb', 'css+ruby']
alias_filenames = ['*.css']
mimetypes = ['text/css+ruby']
def __init__(self, **options):
super(CssErbLexer, self).__init__(CssLexer, ErbLexer, **options)
def analyse_text(text):
return ErbLexer.analyse_text(text) - 0.05
class JavascriptErbLexer(DelegatingLexer):
"""
Subclass of `ErbLexer` which highlights unlexed data with the
`JavascriptLexer`.
"""
name = 'JavaScript+Ruby'
aliases = ['js+erb', 'javascript+erb', 'js+ruby', 'javascript+ruby']
alias_filenames = ['*.js']
mimetypes = ['application/x-javascript+ruby',
'text/x-javascript+ruby',
'text/javascript+ruby']
def __init__(self, **options):
super(JavascriptErbLexer, self).__init__(JavascriptLexer, ErbLexer,
**options)
def analyse_text(text):
return ErbLexer.analyse_text(text) - 0.05
class HtmlPhpLexer(DelegatingLexer):
"""
Subclass of `PhpLexer` that highlights unhandled data with the `HtmlLexer`.
Nested Javascript and CSS is highlighted too.
"""
name = 'HTML+PHP'
aliases = ['html+php']
filenames = ['*.phtml']
alias_filenames = ['*.php', '*.html', '*.htm', '*.xhtml',
'*.php[345]']
mimetypes = ['application/x-php',
'application/x-httpd-php', 'application/x-httpd-php3',
'application/x-httpd-php4', 'application/x-httpd-php5']
def __init__(self, **options):
super(HtmlPhpLexer, self).__init__(HtmlLexer, PhpLexer, **options)
def analyse_text(text):
rv = PhpLexer.analyse_text(text) - 0.01
if html_doctype_matches(text):
rv += 0.5
return rv
class XmlPhpLexer(DelegatingLexer):
"""
Subclass of `PhpLexer` that highlights unhandled data with the `XmlLexer`.
"""
name = 'XML+PHP'
aliases = ['xml+php']
alias_filenames = ['*.xml', '*.php', '*.php[345]']
mimetypes = ['application/xml+php']
def __init__(self, **options):
super(XmlPhpLexer, self).__init__(XmlLexer, PhpLexer, **options)
def analyse_text(text):
rv = PhpLexer.analyse_text(text) - 0.01
if looks_like_xml(text):
rv += 0.4
return rv
class CssPhpLexer(DelegatingLexer):
"""
Subclass of `PhpLexer` which highlights unmatched data with the `CssLexer`.
"""
name = 'CSS+PHP'
aliases = ['css+php']
alias_filenames = ['*.css']
mimetypes = ['text/css+php']
def __init__(self, **options):
super(CssPhpLexer, self).__init__(CssLexer, PhpLexer, **options)
def analyse_text(text):
return PhpLexer.analyse_text(text) - 0.05
class JavascriptPhpLexer(DelegatingLexer):
"""
Subclass of `PhpLexer` which highlights unmatched data with the
`JavascriptLexer`.
"""
name = 'JavaScript+PHP'
aliases = ['js+php', 'javascript+php']
alias_filenames = ['*.js']
mimetypes = ['application/x-javascript+php',
'text/x-javascript+php',
'text/javascript+php']
def __init__(self, **options):
super(JavascriptPhpLexer, self).__init__(JavascriptLexer, PhpLexer,
**options)
def analyse_text(text):
return PhpLexer.analyse_text(text)
class HtmlSmartyLexer(DelegatingLexer):
"""
Subclass of the `SmartyLexer` that highlights unlexed data with the
`HtmlLexer`.
Nested Javascript and CSS is highlighted too.
"""
name = 'HTML+Smarty'
aliases = ['html+smarty']
alias_filenames = ['*.html', '*.htm', '*.xhtml', '*.tpl']
mimetypes = ['text/html+smarty']
def __init__(self, **options):
super(HtmlSmartyLexer, self).__init__(HtmlLexer, SmartyLexer, **options)
def analyse_text(text):
rv = SmartyLexer.analyse_text(text) - 0.01
if html_doctype_matches(text):
rv += 0.5
return rv
class XmlSmartyLexer(DelegatingLexer):
"""
Subclass of the `SmartyLexer` that highlights unlexed data with the
`XmlLexer`.
"""
name = 'XML+Smarty'
aliases = ['xml+smarty']
alias_filenames = ['*.xml', '*.tpl']
mimetypes = ['application/xml+smarty']
def __init__(self, **options):
super(XmlSmartyLexer, self).__init__(XmlLexer, SmartyLexer, **options)
def analyse_text(text):
rv = SmartyLexer.analyse_text(text) - 0.01
if looks_like_xml(text):
rv += 0.4
return rv
class CssSmartyLexer(DelegatingLexer):
"""
Subclass of the `SmartyLexer` that highlights unlexed data with the
`CssLexer`.
"""
name = 'CSS+Smarty'
aliases = ['css+smarty']
alias_filenames = ['*.css', '*.tpl']
mimetypes = ['text/css+smarty']
def __init__(self, **options):
super(CssSmartyLexer, self).__init__(CssLexer, SmartyLexer, **options)
def analyse_text(text):
return SmartyLexer.analyse_text(text) - 0.05
class JavascriptSmartyLexer(DelegatingLexer):
"""
Subclass of the `SmartyLexer` that highlights unlexed data with the
`JavascriptLexer`.
"""
name = 'JavaScript+Smarty'
aliases = ['js+smarty', 'javascript+smarty']
alias_filenames = ['*.js', '*.tpl']
mimetypes = ['application/x-javascript+smarty',
'text/x-javascript+smarty',
'text/javascript+smarty']
def __init__(self, **options):
super(JavascriptSmartyLexer, self).__init__(JavascriptLexer, SmartyLexer,
**options)
def analyse_text(text):
return SmartyLexer.analyse_text(text) - 0.05
class HtmlDjangoLexer(DelegatingLexer):
"""
Subclass of the `DjangoLexer` that highlights unlexed data with the
`HtmlLexer`.
Nested Javascript and CSS is highlighted too.
"""
name = 'HTML+Django/Jinja'
aliases = ['html+django', 'html+jinja', 'htmldjango']
alias_filenames = ['*.html', '*.htm', '*.xhtml']
mimetypes = ['text/html+django', 'text/html+jinja']
def __init__(self, **options):
super(HtmlDjangoLexer, self).__init__(HtmlLexer, DjangoLexer, **options)
def analyse_text(text):
rv = DjangoLexer.analyse_text(text) - 0.01
if html_doctype_matches(text):
rv += 0.5
return rv
class XmlDjangoLexer(DelegatingLexer):
"""
Subclass of the `DjangoLexer` that highlights unlexed data with the
`XmlLexer`.
"""
name = 'XML+Django/Jinja'
aliases = ['xml+django', 'xml+jinja']
alias_filenames = ['*.xml']
mimetypes = ['application/xml+django', 'application/xml+jinja']
def __init__(self, **options):
super(XmlDjangoLexer, self).__init__(XmlLexer, DjangoLexer, **options)
def analyse_text(text):
rv = DjangoLexer.analyse_text(text) - 0.01
if looks_like_xml(text):
rv += 0.4
return rv
class CssDjangoLexer(DelegatingLexer):
"""
Subclass of the `DjangoLexer` that highlights unlexed data with the
`CssLexer`.
"""
name = 'CSS+Django/Jinja'
aliases = ['css+django', 'css+jinja']
alias_filenames = ['*.css']
mimetypes = ['text/css+django', 'text/css+jinja']
def __init__(self, **options):
super(CssDjangoLexer, self).__init__(CssLexer, DjangoLexer, **options)
def analyse_text(text):
return DjangoLexer.analyse_text(text) - 0.05
class JavascriptDjangoLexer(DelegatingLexer):
"""
Subclass of the `DjangoLexer` that highlights unlexed data with the
`JavascriptLexer`.
"""
name = 'JavaScript+Django/Jinja'
aliases = ['js+django', 'javascript+django',
'js+jinja', 'javascript+jinja']
alias_filenames = ['*.js']
mimetypes = ['application/x-javascript+django',
'application/x-javascript+jinja',
'text/x-javascript+django',
'text/x-javascript+jinja',
'text/javascript+django',
'text/javascript+jinja']
def __init__(self, **options):
super(JavascriptDjangoLexer, self).__init__(JavascriptLexer, DjangoLexer,
**options)
def analyse_text(text):
return DjangoLexer.analyse_text(text) - 0.05
class JspRootLexer(RegexLexer):
"""
Base for the `JspLexer`. Yields `Token.Other` for area outside of
JSP tags.
.. versionadded:: 0.7
"""
tokens = {
'root': [
(r'<%\S?', Keyword, 'sec'),
# FIXME: I want to make these keywords but still parse attributes.
(r'</?jsp:(forward|getProperty|include|plugin|setProperty|useBean).*?>',
Keyword),
(r'[^<]+', Other),
(r'<', Other),
],
'sec': [
(r'%>', Keyword, '#pop'),
# note: '\w\W' != '.' without DOTALL.
(r'[\w\W]+?(?=%>|\Z)', using(JavaLexer)),
],
}
class JspLexer(DelegatingLexer):
"""
Lexer for Java Server Pages.
.. versionadded:: 0.7
"""
name = 'Java Server Page'
aliases = ['jsp']
filenames = ['*.jsp']
mimetypes = ['application/x-jsp']
def __init__(self, **options):
super(JspLexer, self).__init__(XmlLexer, JspRootLexer, **options)
def analyse_text(text):
rv = JavaLexer.analyse_text(text) - 0.01
if looks_like_xml(text):
rv += 0.4
if '<%' in text and '%>' in text:
rv += 0.1
return rv
class EvoqueLexer(RegexLexer):
"""
For files using the Evoque templating system.
.. versionadded:: 1.1
"""
name = 'Evoque'
aliases = ['evoque']
filenames = ['*.evoque']
mimetypes = ['application/x-evoque']
flags = re.DOTALL
tokens = {
'root': [
(r'[^#$]+', Other),
(r'#\[', Comment.Multiline, 'comment'),
(r'\$\$', Other),
# svn keywords
(r'\$\w+:[^$\n]*\$', Comment.Multiline),
# directives: begin, end
(r'(\$)(begin|end)(\{(%)?)(.*?)((?(4)%)\})',
bygroups(Punctuation, Name.Builtin, Punctuation, None,
String, Punctuation)),
# directives: evoque, overlay
# see doc for handling first name arg: /directives/evoque/
# + minor inconsistency: the "name" in e.g. $overlay{name=site_base}
# should be using(PythonLexer), not passed out as String
(r'(\$)(evoque|overlay)(\{(%)?)(\s*[#\w\-"\'.]+[^=,%}]+?)?'
r'(.*?)((?(4)%)\})',
bygroups(Punctuation, Name.Builtin, Punctuation, None,
String, using(PythonLexer), Punctuation)),
# directives: if, for, prefer, test
(r'(\$)(\w+)(\{(%)?)(.*?)((?(4)%)\})',
bygroups(Punctuation, Name.Builtin, Punctuation, None,
using(PythonLexer), Punctuation)),
# directive clauses (no {} expression)
(r'(\$)(else|rof|fi)', bygroups(Punctuation, Name.Builtin)),
# expressions
(r'(\$\{(%)?)(.*?)((!)(.*?))?((?(2)%)\})',
bygroups(Punctuation, None, using(PythonLexer),
Name.Builtin, None, None, Punctuation)),
(r'#', Other),
],
'comment': [
(r'[^\]#]', Comment.Multiline),
(r'#\[', Comment.Multiline, '#push'),
(r'\]#', Comment.Multiline, '#pop'),
(r'[\]#]', Comment.Multiline)
],
}
class EvoqueHtmlLexer(DelegatingLexer):
"""
Subclass of the `EvoqueLexer` that highlights unlexed data with the
`HtmlLexer`.
.. versionadded:: 1.1
"""
name = 'HTML+Evoque'
aliases = ['html+evoque']
filenames = ['*.html']
mimetypes = ['text/html+evoque']
def __init__(self, **options):
super(EvoqueHtmlLexer, self).__init__(HtmlLexer, EvoqueLexer,
**options)
class EvoqueXmlLexer(DelegatingLexer):
"""
Subclass of the `EvoqueLexer` that highlights unlexed data with the
`XmlLexer`.
.. versionadded:: 1.1
"""
name = 'XML+Evoque'
aliases = ['xml+evoque']
filenames = ['*.xml']
mimetypes = ['application/xml+evoque']
def __init__(self, **options):
super(EvoqueXmlLexer, self).__init__(XmlLexer, EvoqueLexer,
**options)
class ColdfusionLexer(RegexLexer):
"""
Coldfusion statements
"""
name = 'cfstatement'
aliases = ['cfs']
filenames = []
mimetypes = []
flags = re.IGNORECASE
tokens = {
'root': [
(r'//.*?\n', Comment.Single),
(r'/\*(?:.|\n)*?\*/', Comment.Multiline),
(r'\+\+|--', Operator),
(r'[-+*/^&=!]', Operator),
(r'<=|>=|<|>|==', Operator),
(r'mod\b', Operator),
(r'(eq|lt|gt|lte|gte|not|is|and|or)\b', Operator),
(r'\|\||&&', Operator),
(r'\?', Operator),
(r'"', String.Double, 'string'),
# There is a special rule for allowing html in single quoted
# strings, evidently.
(r"'.*?'", String.Single),
(r'\d+', Number),
(r'(if|else|len|var|xml|default|break|switch|component|property|function|do|'
r'try|catch|in|continue|for|return|while|required|any|array|binary|boolean|'
r'component|date|guid|numeric|query|string|struct|uuid|case)\b', Keyword),
(r'(true|false|null)\b', Keyword.Constant),
(r'(application|session|client|cookie|super|this|variables|arguments)\b',
Name.Constant),
(r'([a-z_$][\w.]*)(\s*)(\()',
bygroups(Name.Function, Text, Punctuation)),
(r'[a-z_$][\w.]*', Name.Variable),
(r'[()\[\]{};:,.\\]', Punctuation),
(r'\s+', Text),
],
'string': [
(r'""', String.Double),
(r'#.+?#', String.Interp),
(r'[^"#]+', String.Double),
(r'#', String.Double),
(r'"', String.Double, '#pop'),
],
}
class ColdfusionMarkupLexer(RegexLexer):
"""
Coldfusion markup only
"""
name = 'Coldfusion'
aliases = ['cf']
filenames = []
mimetypes = []
tokens = {
'root': [
(r'[^<]+', Other),
include('tags'),
(r'<[^<>]*', Other),
],
'tags': [
(r'<!---', Comment.Multiline, 'cfcomment'),
(r'(?s)<!--.*?-->', Comment),
(r'<cfoutput.*?>', Name.Builtin, 'cfoutput'),
(r'(?s)(<cfscript.*?>)(.+?)(</cfscript.*?>)',
bygroups(Name.Builtin, using(ColdfusionLexer), Name.Builtin)),
# negative lookbehind is for strings with embedded >
(r'(?s)(</?cf(?:component|include|if|else|elseif|loop|return|'
r'dbinfo|dump|abort|location|invoke|throw|file|savecontent|'
r'mailpart|mail|header|content|zip|image|lock|argument|try|'
r'catch|break|directory|http|set|function|param)\b)(.*?)((?<!\\)>)',
bygroups(Name.Builtin, using(ColdfusionLexer), Name.Builtin)),
],
'cfoutput': [
(r'[^#<]+', Other),
(r'(#)(.*?)(#)', bygroups(Punctuation, using(ColdfusionLexer),
Punctuation)),
# (r'<cfoutput.*?>', Name.Builtin, '#push'),
(r'</cfoutput.*?>', Name.Builtin, '#pop'),
include('tags'),
(r'(?s)<[^<>]*', Other),
(r'#', Other),
],
'cfcomment': [
(r'<!---', Comment.Multiline, '#push'),
(r'--->', Comment.Multiline, '#pop'),
(r'([^<-]|<(?!!---)|-(?!-->))+', Comment.Multiline),
],
}
class ColdfusionHtmlLexer(DelegatingLexer):
"""
Coldfusion markup in html
"""
name = 'Coldfusion HTML'
aliases = ['cfm']
filenames = ['*.cfm', '*.cfml']
mimetypes = ['application/x-coldfusion']
def __init__(self, **options):
super(ColdfusionHtmlLexer, self).__init__(HtmlLexer, ColdfusionMarkupLexer,
**options)
class ColdfusionCFCLexer(DelegatingLexer):
"""
Coldfusion markup/script components
.. versionadded:: 2.0
"""
name = 'Coldfusion CFC'
aliases = ['cfc']
filenames = ['*.cfc']
mimetypes = []
def __init__(self, **options):
super(ColdfusionCFCLexer, self).__init__(ColdfusionHtmlLexer, ColdfusionLexer,
**options)
class SspLexer(DelegatingLexer):
"""
Lexer for Scalate Server Pages.
.. versionadded:: 1.4
"""
name = 'Scalate Server Page'
aliases = ['ssp']
filenames = ['*.ssp']
mimetypes = ['application/x-ssp']
def __init__(self, **options):
super(SspLexer, self).__init__(XmlLexer, JspRootLexer, **options)
def analyse_text(text):
rv = 0.0
if re.search('val \w+\s*:', text):
rv += 0.6
if looks_like_xml(text):
rv += 0.2
if '<%' in text and '%>' in text:
rv += 0.1
return rv
class TeaTemplateRootLexer(RegexLexer):
"""
Base for the `TeaTemplateLexer`. Yields `Token.Other` for area outside of
code blocks.
.. versionadded:: 1.5
"""
tokens = {
'root': [
(r'<%\S?', Keyword, 'sec'),
(r'[^<]+', Other),
(r'<', Other),
],
'sec': [
(r'%>', Keyword, '#pop'),
# note: '\w\W' != '.' without DOTALL.
(r'[\w\W]+?(?=%>|\Z)', using(TeaLangLexer)),
],
}
class TeaTemplateLexer(DelegatingLexer):
"""
Lexer for `Tea Templates <http://teatrove.org/>`_.
.. versionadded:: 1.5
"""
name = 'Tea'
aliases = ['tea']
filenames = ['*.tea']
mimetypes = ['text/x-tea']
def __init__(self, **options):
super(TeaTemplateLexer, self).__init__(XmlLexer,
TeaTemplateRootLexer, **options)
def analyse_text(text):
rv = TeaLangLexer.analyse_text(text) - 0.01
if looks_like_xml(text):
rv += 0.4
if '<%' in text and '%>' in text:
rv += 0.1
return rv
class LassoHtmlLexer(DelegatingLexer):
"""
Subclass of the `LassoLexer` which highlights unhandled data with the
`HtmlLexer`.
Nested JavaScript and CSS is also highlighted.
.. versionadded:: 1.6
"""
name = 'HTML+Lasso'
aliases = ['html+lasso']
alias_filenames = ['*.html', '*.htm', '*.xhtml', '*.lasso', '*.lasso[89]',
'*.incl', '*.inc', '*.las']
mimetypes = ['text/html+lasso',
'application/x-httpd-lasso',
'application/x-httpd-lasso[89]']
def __init__(self, **options):
super(LassoHtmlLexer, self).__init__(HtmlLexer, LassoLexer, **options)
def analyse_text(text):
rv = LassoLexer.analyse_text(text) - 0.01
if html_doctype_matches(text): # same as HTML lexer
rv += 0.5
return rv
class LassoXmlLexer(DelegatingLexer):
"""
Subclass of the `LassoLexer` which highlights unhandled data with the
`XmlLexer`.
.. versionadded:: 1.6
"""
name = 'XML+Lasso'
aliases = ['xml+lasso']
alias_filenames = ['*.xml', '*.lasso', '*.lasso[89]',
'*.incl', '*.inc', '*.las']
mimetypes = ['application/xml+lasso']
def __init__(self, **options):
super(LassoXmlLexer, self).__init__(XmlLexer, LassoLexer, **options)
def analyse_text(text):
rv = LassoLexer.analyse_text(text) - 0.01
if looks_like_xml(text):
rv += 0.4
return rv
class LassoCssLexer(DelegatingLexer):
"""
Subclass of the `LassoLexer` which highlights unhandled data with the
`CssLexer`.
.. versionadded:: 1.6
"""
name = 'CSS+Lasso'
aliases = ['css+lasso']
alias_filenames = ['*.css']
mimetypes = ['text/css+lasso']
def __init__(self, **options):
options['requiredelimiters'] = True
super(LassoCssLexer, self).__init__(CssLexer, LassoLexer, **options)
def analyse_text(text):
rv = LassoLexer.analyse_text(text) - 0.05
if re.search(r'\w+:.+?;', text):
rv += 0.1
if 'padding:' in text:
rv += 0.1
return rv
class LassoJavascriptLexer(DelegatingLexer):
"""
Subclass of the `LassoLexer` which highlights unhandled data with the
`JavascriptLexer`.
.. versionadded:: 1.6
"""
name = 'JavaScript+Lasso'
aliases = ['js+lasso', 'javascript+lasso']
alias_filenames = ['*.js']
mimetypes = ['application/x-javascript+lasso',
'text/x-javascript+lasso',
'text/javascript+lasso']
def __init__(self, **options):
options['requiredelimiters'] = True
super(LassoJavascriptLexer, self).__init__(JavascriptLexer, LassoLexer,
**options)
def analyse_text(text):
rv = LassoLexer.analyse_text(text) - 0.05
if 'function' in text:
rv += 0.2
return rv
class HandlebarsLexer(RegexLexer):
"""
Generic `handlebars <http://handlebarsjs.com/>` template lexer.
Highlights only the Handlebars template tags (stuff between `{{` and `}}`).
Everything else is left for a delegating lexer.
.. versionadded:: 2.0
"""
name = "Handlebars"
aliases = ['handlebars']
tokens = {
'root': [
(r'[^{]+', Other),
(r'\{\{!.*\}\}', Comment),
(r'(\{\{\{)(\s*)', bygroups(Comment.Special, Text), 'tag'),
(r'(\{\{)(\s*)', bygroups(Comment.Preproc, Text), 'tag'),
],
'tag': [
(r'\s+', Text),
(r'\}\}\}', Comment.Special, '#pop'),
(r'\}\}', Comment.Preproc, '#pop'),
# Handlebars
(r'([#/]*)(each|if|unless|else|with|log|in)', bygroups(Keyword,
Keyword)),
# General {{#block}}
(r'([#/])([\w-]+)', bygroups(Name.Function, Name.Function)),
# {{opt=something}}
(r'([\w-]+)(=)', bygroups(Name.Attribute, Operator)),
# borrowed from DjangoLexer
(r':?"(\\\\|\\"|[^"])*"', String.Double),
(r":?'(\\\\|\\'|[^'])*'", String.Single),
(r'[a-zA-Z][\w-]*', Name.Variable),
(r'\.[\w-]+', Name.Variable),
(r"[0-9](\.[0-9]*)?(eE[+-][0-9])?[flFLdD]?|"
r"0[xX][0-9a-fA-F]+[Ll]?", Number),
]
}
class HandlebarsHtmlLexer(DelegatingLexer):
"""
Subclass of the `HandlebarsLexer` that highlights unlexed data with the
`HtmlLexer`.
.. versionadded:: 2.0
"""
name = "HTML+Handlebars"
aliases = ["html+handlebars"]
filenames = ['*.handlebars', '*.hbs']
mimetypes = ['text/html+handlebars', 'text/x-handlebars-template']
def __init__(self, **options):
super(HandlebarsHtmlLexer, self).__init__(HtmlLexer, HandlebarsLexer, **options)
class YamlJinjaLexer(DelegatingLexer):
"""
Subclass of the `DjangoLexer` that highlights unlexed data with the
`YamlLexer`.
Commonly used in Saltstack salt states.
.. versionadded:: 2.0
"""
name = 'YAML+Jinja'
aliases = ['yaml+jinja', 'salt', 'sls']
filenames = ['*.sls']
mimetypes = ['text/x-yaml+jinja', 'text/x-sls']
def __init__(self, **options):
super(YamlJinjaLexer, self).__init__(YamlLexer, DjangoLexer, **options)
class LiquidLexer(RegexLexer):
"""
Lexer for `Liquid templates
<http://www.rubydoc.info/github/Shopify/liquid>`_.
.. versionadded:: 2.0
"""
name = 'liquid'
aliases = ['liquid']
filenames = ['*.liquid']
tokens = {
'root': [
(r'[^{]+', Text),
# tags and block tags
(r'(\{%)(\s*)', bygroups(Punctuation, Whitespace), 'tag-or-block'),
# output tags
(r'(\{\{)(\s*)([^\s}]+)',
bygroups(Punctuation, Whitespace, using(this, state = 'generic')),
'output'),
(r'\{', Text)
],
'tag-or-block': [
# builtin logic blocks
(r'(if|unless|elsif|case)(?=\s+)', Keyword.Reserved, 'condition'),
(r'(when)(\s+)', bygroups(Keyword.Reserved, Whitespace),
combined('end-of-block', 'whitespace', 'generic')),
(r'(else)(\s*)(%\})',
bygroups(Keyword.Reserved, Whitespace, Punctuation), '#pop'),
# other builtin blocks
(r'(capture)(\s+)([^\s%]+)(\s*)(%\})',
bygroups(Name.Tag, Whitespace, using(this, state = 'variable'),
Whitespace, Punctuation), '#pop'),
(r'(comment)(\s*)(%\})',
bygroups(Name.Tag, Whitespace, Punctuation), 'comment'),
(r'(raw)(\s*)(%\})',
bygroups(Name.Tag, Whitespace, Punctuation), 'raw'),
# end of block
(r'(end(case|unless|if))(\s*)(%\})',
bygroups(Keyword.Reserved, None, Whitespace, Punctuation), '#pop'),
(r'(end([^\s%]+))(\s*)(%\})',
bygroups(Name.Tag, None, Whitespace, Punctuation), '#pop'),
# builtin tags (assign and include are handled together with usual tags)
(r'(cycle)(\s+)(?:([^\s:]*)(:))?(\s*)',
bygroups(Name.Tag, Whitespace,
using(this, state='generic'), Punctuation, Whitespace),
'variable-tag-markup'),
# other tags or blocks
(r'([^\s%]+)(\s*)', bygroups(Name.Tag, Whitespace), 'tag-markup')
],
'output': [
include('whitespace'),
('\}\}', Punctuation, '#pop'), # end of output
(r'\|', Punctuation, 'filters')
],
'filters': [
include('whitespace'),
(r'\}\}', Punctuation, ('#pop', '#pop')), # end of filters and output
(r'([^\s|:]+)(:?)(\s*)',
bygroups(Name.Function, Punctuation, Whitespace), 'filter-markup')
],
'filter-markup': [
(r'\|', Punctuation, '#pop'),
include('end-of-tag'),
include('default-param-markup')
],
'condition': [
include('end-of-block'),
include('whitespace'),
(r'([^\s=!><]+)(\s*)([=!><]=?)(\s*)(\S+)(\s*)(%\})',
bygroups(using(this, state = 'generic'), Whitespace, Operator,
Whitespace, using(this, state = 'generic'), Whitespace,
Punctuation)),
(r'\b!', Operator),
(r'\bnot\b', Operator.Word),
(r'([\w.\'"]+)(\s+)(contains)(\s+)([\w.\'"]+)',
bygroups(using(this, state = 'generic'), Whitespace, Operator.Word,
Whitespace, using(this, state = 'generic'))),
include('generic'),
include('whitespace')
],
'generic-value': [
include('generic'),
include('end-at-whitespace')
],
'operator': [
(r'(\s*)((=|!|>|<)=?)(\s*)',
bygroups(Whitespace, Operator, None, Whitespace), '#pop'),
(r'(\s*)(\bcontains\b)(\s*)',
bygroups(Whitespace, Operator.Word, Whitespace), '#pop'),
],
'end-of-tag': [
(r'\}\}', Punctuation, '#pop')
],
'end-of-block': [
(r'%\}', Punctuation, ('#pop', '#pop'))
],
'end-at-whitespace': [
(r'\s+', Whitespace, '#pop')
],
# states for unknown markup
'param-markup': [
include('whitespace'),
# params with colons or equals
(r'([^\s=:]+)(\s*)(=|:)',
bygroups(Name.Attribute, Whitespace, Operator)),
# explicit variables
(r'(\{\{)(\s*)([^\s}])(\s*)(\}\})',
bygroups(Punctuation, Whitespace, using(this, state = 'variable'),
Whitespace, Punctuation)),
include('string'),
include('number'),
include('keyword'),
(r',', Punctuation)
],
'default-param-markup': [
include('param-markup'),
(r'.', Text) # fallback for switches / variables / un-quoted strings / ...
],
'variable-param-markup': [
include('param-markup'),
include('variable'),
(r'.', Text) # fallback
],
'tag-markup': [
(r'%\}', Punctuation, ('#pop', '#pop')), # end of tag
include('default-param-markup')
],
'variable-tag-markup': [
(r'%\}', Punctuation, ('#pop', '#pop')), # end of tag
include('variable-param-markup')
],
# states for different values types
'keyword': [
(r'\b(false|true)\b', Keyword.Constant)
],
'variable': [
(r'[a-zA-Z_]\w*', Name.Variable),
(r'(?<=\w)\.(?=\w)', Punctuation)
],
'string': [
(r"'[^']*'", String.Single),
(r'"[^"]*"', String.Double)
],
'number': [
(r'\d+\.\d+', Number.Float),
(r'\d+', Number.Integer)
],
'generic': [ # decides for variable, string, keyword or number
include('keyword'),
include('string'),
include('number'),
include('variable')
],
'whitespace': [
(r'[ \t]+', Whitespace)
],
# states for builtin blocks
'comment': [
(r'(\{%)(\s*)(endcomment)(\s*)(%\})',
bygroups(Punctuation, Whitespace, Name.Tag, Whitespace,
Punctuation), ('#pop', '#pop')),
(r'.', Comment)
],
'raw': [
(r'[^{]+', Text),
(r'(\{%)(\s*)(endraw)(\s*)(%\})',
bygroups(Punctuation, Whitespace, Name.Tag, Whitespace,
Punctuation), '#pop'),
(r'\{', Text)
],
}
class TwigLexer(RegexLexer):
"""
`Twig <http://twig.sensiolabs.org/>`_ template lexer.
It just highlights Twig code between the preprocessor directives,
other data is left untouched by the lexer.
.. versionadded:: 2.0
"""
name = 'Twig'
aliases = ['twig']
mimetypes = ['application/x-twig']
flags = re.M | re.S
# Note that a backslash is included in the following two patterns
# PHP uses a backslash as a namespace separator
_ident_char = r'[\\\w-]|[^\x00-\x7f]'
_ident_begin = r'(?:[\\_a-z]|[^\x00-\x7f])'
_ident_end = r'(?:' + _ident_char + ')*'
_ident_inner = _ident_begin + _ident_end
tokens = {
'root': [
(r'[^{]+', Other),
(r'\{\{', Comment.Preproc, 'var'),
# twig comments
(r'\{\#.*?\#\}', Comment),
# raw twig blocks
(r'(\{%)(-?\s*)(raw)(\s*-?)(%\})(.*?)'
r'(\{%)(-?\s*)(endraw)(\s*-?)(%\})',
bygroups(Comment.Preproc, Text, Keyword, Text, Comment.Preproc,
Other, Comment.Preproc, Text, Keyword, Text,
Comment.Preproc)),
(r'(\{%)(-?\s*)(verbatim)(\s*-?)(%\})(.*?)'
r'(\{%)(-?\s*)(endverbatim)(\s*-?)(%\})',
bygroups(Comment.Preproc, Text, Keyword, Text, Comment.Preproc,
Other, Comment.Preproc, Text, Keyword, Text,
Comment.Preproc)),
# filter blocks
(r'(\{%%)(-?\s*)(filter)(\s+)(%s)' % _ident_inner,
bygroups(Comment.Preproc, Text, Keyword, Text, Name.Function),
'tag'),
(r'(\{%)(-?\s*)([a-zA-Z_]\w*)',
bygroups(Comment.Preproc, Text, Keyword), 'tag'),
(r'\{', Other),
],
'varnames': [
(r'(\|)(\s*)(%s)' % _ident_inner,
bygroups(Operator, Text, Name.Function)),
(r'(is)(\s+)(not)?(\s*)(%s)' % _ident_inner,
bygroups(Keyword, Text, Keyword, Text, Name.Function)),
(r'(?i)(true|false|none|null)\b', Keyword.Pseudo),
(r'(in|not|and|b-and|or|b-or|b-xor|is'
r'if|elseif|else|import'
r'constant|defined|divisibleby|empty|even|iterable|odd|sameas'
r'matches|starts\s+with|ends\s+with)\b',
Keyword),
(r'(loop|block|parent)\b', Name.Builtin),
(_ident_inner, Name.Variable),
(r'\.' + _ident_inner, Name.Variable),
(r'\.[0-9]+', Number),
(r':?"(\\\\|\\"|[^"])*"', String.Double),
(r":?'(\\\\|\\'|[^'])*'", String.Single),
(r'([{}()\[\]+\-*/,:~%]|\.\.|\?|:|\*\*|\/\/|!=|[><=]=?)', Operator),
(r"[0-9](\.[0-9]*)?(eE[+-][0-9])?[flFLdD]?|"
r"0[xX][0-9a-fA-F]+[Ll]?", Number),
],
'var': [
(r'\s+', Text),
(r'(-?)(\}\})', bygroups(Text, Comment.Preproc), '#pop'),
include('varnames')
],
'tag': [
(r'\s+', Text),
(r'(-?)(%\})', bygroups(Text, Comment.Preproc), '#pop'),
include('varnames'),
(r'.', Punctuation),
],
}
class TwigHtmlLexer(DelegatingLexer):
"""
Subclass of the `TwigLexer` that highlights unlexed data with the
`HtmlLexer`.
.. versionadded:: 2.0
"""
name = "HTML+Twig"
aliases = ["html+twig"]
filenames = ['*.twig']
mimetypes = ['text/html+twig']
def __init__(self, **options):
super(TwigHtmlLexer, self).__init__(HtmlLexer, TwigLexer, **options)
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" PolicyId="urn:oasis:names:tc:xacml:2.0:conformance-test:IIC156:policy" RuleCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:deny-overrides" Version="1.0" xsi:schemaLocation="urn:oasis:names:tc:xacml:3.0:policy:schema:os access_control-xacml-2.0-policy-schema-os.xsd">
<Description>
Policy for Conformance Test IIC156.
</Description>
<Target/>
<Rule Effect="Permit" RuleId="urn:oasis:names:tc:xacml:2.0:conformance-test:IIC156:rule">
<Condition>
<Apply FunctionId="urn:oasis:names:tc:xacml:3.0:function:yearMonthDuration-is-in">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#yearMonthDuration">P5Y3M</AttributeValue>
<AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:2.0:conformance-test:test-attr" Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" DataType="http://www.w3.org/2001/XMLSchema#yearMonthDuration" MustBePresent="false"/>
</Apply>
</Condition>
</Rule>
</Policy>
|
{
"pile_set_name": "Github"
}
|
<?php
use Illuminate\Database\Seeder;
class AlterPasswordClientSecret extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Laravel\Passport\Client::query()
->where('id', 2)->update([
'secret' => 'bXKWFmfsJsQJn9iwDU2K4qEvMAb9uYvqlQqSFRiR',
]);
}
}
|
{
"pile_set_name": "Github"
}
|
#define SOC 0x01
|
{
"pile_set_name": "Github"
}
|
<?xml version='1.0' encoding='utf-8'?>
<!-- Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information. -->
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<ItemGroup>
<ProjectReference Include="ca\uica.vcxproj" />
<ProjectReference Include="wixlib\UIExtension.wixproj" />
<ProjectReference Include="wixext\WixUIExtension.csproj" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), wix.proj))\tools\Traversal.targets" />
</Project>
|
{
"pile_set_name": "Github"
}
|
<p>This datepicker uses a custom month layout.</p>
<div class="d-inline-block">
<div class="btn-group d-flex justify-content-end mb-2" role="group">
<button type="button" class="btn btn-sm btn-outline-primary" (click)="navigate(-1);">Prev</button>
<button type="button" class="btn btn-sm btn-outline-primary" (click)="today()">Today</button>
<button type="button" class="btn btn-sm btn-outline-primary" (click)="navigate(1)">Next</button>
</div>
<ngb-datepicker class="custom-datepicker px-3 pt-1 pb-3"
#dp
[displayMonths]="4"
outsideDays="hidden"
[showWeekdays]="false"
navigation="none">
<ng-template ngbDatepickerContent>
<div *ngFor="let month of dp.state.months">
<div class="text-primary p-1 font-weight-bold">{{ i18n.getMonthShortName(month.month) }} {{ month.year }}</div>
<ngb-datepicker-month class="border rounded" [month]="month"></ngb-datepicker-month>
</div>
</ng-template>
</ngb-datepicker>
</div>
|
{
"pile_set_name": "Github"
}
|
--TEST--
phpunit --colors=always BankAccountTest ../_files/BankAccountTest.php
--FILE--
<?php
$_SERVER['argv'][1] = '--no-configuration';
$_SERVER['argv'][2] = '--colors=always';
$_SERVER['argv'][3] = __DIR__ . '/../_files/BankAccountTest.php';
require __DIR__ . '/../bootstrap.php';
PHPUnit_TextUI_Command::main();
?>
--EXPECTF--
PHPUnit %s by Sebastian Bergmann and contributors.
...
Time: %s, Memory: %sMb
%s[30;42mOK (3 tests, 3 assertions)%s[0m
|
{
"pile_set_name": "Github"
}
|
// field paths that every tar file must have.
// header is padded to 512 bytes.
var f = 0
, fields = {}
, path = fields.path = f++
, mode = fields.mode = f++
, uid = fields.uid = f++
, gid = fields.gid = f++
, size = fields.size = f++
, mtime = fields.mtime = f++
, cksum = fields.cksum = f++
, type = fields.type = f++
, linkpath = fields.linkpath = f++
, headerSize = 512
, blockSize = 512
, fieldSize = []
fieldSize[path] = 100
fieldSize[mode] = 8
fieldSize[uid] = 8
fieldSize[gid] = 8
fieldSize[size] = 12
fieldSize[mtime] = 12
fieldSize[cksum] = 8
fieldSize[type] = 1
fieldSize[linkpath] = 100
// "ustar\0" may introduce another bunch of headers.
// these are optional, and will be nulled out if not present.
var ustar = fields.ustar = f++
, ustarver = fields.ustarver = f++
, uname = fields.uname = f++
, gname = fields.gname = f++
, devmaj = fields.devmaj = f++
, devmin = fields.devmin = f++
, prefix = fields.prefix = f++
, fill = fields.fill = f++
// terminate fields.
fields[f] = null
fieldSize[ustar] = 6
fieldSize[ustarver] = 2
fieldSize[uname] = 32
fieldSize[gname] = 32
fieldSize[devmaj] = 8
fieldSize[devmin] = 8
fieldSize[prefix] = 155
fieldSize[fill] = 12
// nb: prefix field may in fact be 130 bytes of prefix,
// a null char, 12 bytes for atime, 12 bytes for ctime.
//
// To recognize this format:
// 1. prefix[130] === ' ' or '\0'
// 2. atime and ctime are octal numeric values
// 3. atime and ctime have ' ' in their last byte
var fieldEnds = {}
, fieldOffs = {}
, fe = 0
for (var i = 0; i < f; i ++) {
fieldOffs[i] = fe
fieldEnds[i] = (fe += fieldSize[i])
}
// build a translation table of field paths.
Object.keys(fields).forEach(function (f) {
if (fields[f] !== null) fields[fields[f]] = f
})
// different values of the 'type' field
// paths match the values of Stats.isX() functions, where appropriate
var types =
{ 0: "File"
, "\0": "OldFile" // like 0
, "": "OldFile"
, 1: "Link"
, 2: "SymbolicLink"
, 3: "CharacterDevice"
, 4: "BlockDevice"
, 5: "Directory"
, 6: "FIFO"
, 7: "ContiguousFile" // like 0
// posix headers
, g: "GlobalExtendedHeader" // k=v for the rest of the archive
, x: "ExtendedHeader" // k=v for the next file
// vendor-specific stuff
, A: "SolarisACL" // skip
, D: "GNUDumpDir" // like 5, but with data, which should be skipped
, I: "Inode" // metadata only, skip
, K: "NextFileHasLongLinkpath" // data = link path of next file
, L: "NextFileHasLongPath" // data = path of next file
, M: "ContinuationFile" // skip
, N: "OldGnuLongPath" // like L
, S: "SparseFile" // skip
, V: "TapeVolumeHeader" // skip
, X: "OldExtendedHeader" // like x
}
Object.keys(types).forEach(function (t) {
types[types[t]] = types[types[t]] || t
})
// values for the mode field
var modes =
{ suid: 04000 // set uid on extraction
, sgid: 02000 // set gid on extraction
, svtx: 01000 // set restricted deletion flag on dirs on extraction
, uread: 0400
, uwrite: 0200
, uexec: 0100
, gread: 040
, gwrite: 020
, gexec: 010
, oread: 4
, owrite: 2
, oexec: 1
, all: 07777
}
var numeric =
{ mode: true
, uid: true
, gid: true
, size: true
, mtime: true
, devmaj: true
, devmin: true
, cksum: true
, atime: true
, ctime: true
, dev: true
, ino: true
, nlink: true
}
Object.keys(modes).forEach(function (t) {
modes[modes[t]] = modes[modes[t]] || t
})
var knownExtended =
{ atime: true
, charset: true
, comment: true
, ctime: true
, gid: true
, gname: true
, linkpath: true
, mtime: true
, path: true
, realtime: true
, security: true
, size: true
, uid: true
, uname: true }
exports.fields = fields
exports.fieldSize = fieldSize
exports.fieldOffs = fieldOffs
exports.fieldEnds = fieldEnds
exports.types = types
exports.modes = modes
exports.numeric = numeric
exports.headerSize = headerSize
exports.blockSize = blockSize
exports.knownExtended = knownExtended
exports.Pack = require("./lib/pack.js")
exports.Parse = require("./lib/parse.js")
exports.Extract = require("./lib/extract.js")
|
{
"pile_set_name": "Github"
}
|
class Greeter {
greet(@required name: string) {
return "Hello " + name + "!";
}
}
|
{
"pile_set_name": "Github"
}
|
package com.metasploit.meterpreter.stdapi;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
import java.awt.Robot;
import java.awt.event.InputEvent;
public class stdapi_ui_send_mouse_V1_4 extends stdapi_ui_send_mouse implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
int action = request.getIntValue(TLVType.TLV_TYPE_MOUSE_ACTION);
int x = request.getIntValue(TLVType.TLV_TYPE_MOUSE_X);
int y = request.getIntValue(TLVType.TLV_TYPE_MOUSE_Y);
Robot robot = new Robot();
if (x != -1 && y != -1) {
robot.mouseMove(x, y);
}
switch (action) {
case 1:
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
break;
case 2:
robot.mousePress(InputEvent.BUTTON1_MASK);
break;
case 3:
robot.mouseRelease(InputEvent.BUTTON1_MASK);
break;
case 4:
robot.mousePress(InputEvent.BUTTON3_MASK);
robot.mouseRelease(InputEvent.BUTTON3_MASK);
break;
case 5:
robot.mousePress(InputEvent.BUTTON3_MASK);
break;
case 6:
robot.mouseRelease(InputEvent.BUTTON3_MASK);
break;
case 7:
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
break;
}
return ERROR_SUCCESS;
}
}
|
{
"pile_set_name": "Github"
}
|
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"angular-guestbook": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular-guestbook",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "angular-guestbook:build"
},
"configurations": {
"production": {
"browserTarget": "angular-guestbook:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "angular-guestbook:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.css"
],
"scripts": [],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"angular-guestbook-e2e": {
"root": "e2e/",
"projectType": "application",
"prefix": "",
"architect": {
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "angular-guestbook:serve"
},
"configurations": {
"production": {
"devServerTarget": "angular-guestbook:serve:production"
}
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "angular-guestbook"
}
|
{
"pile_set_name": "Github"
}
|
Extensions
==========
Extensions are redistributable software packages specifically designed to be used in Yii applications and provide
ready-to-use features. For example, the [yiisoft/yii2-debug](tool-debugger.md) extension adds a handy debug toolbar
at the bottom of every page in your application to help you more easily grasp how the pages are generated. You can
use extensions to accelerate your development process. You can also package your code as extensions to share with
other people your great work.
> Info: We use the term "extension" to refer to Yii-specific software packages. For general purpose software packages
that can be used without Yii, we will refer to them using the term "package" or "library".
## Using Extensions <a name="using-extensions"></a>
To use an extension, you need to install it first. Most extensions are distributed as [Composer](https://getcomposer.org/)
packages which can be installed by taking the following two simple steps:
1. modify the `composer.json` file of your application and specify which extensions (Composer packages) you want to install.
2. run `composer install` to install the specified extensions.
Note that you may need to install [Composer](https://getcomposer.org/) if you do not have it.
By default, Composer installs packages registered on [Packagist](https://packagist.org/) - the biggest repository
for open source Composer packages. You can look for extensions on Packagist. You may also
[create your own repository](https://getcomposer.org/doc/05-repositories.md#repository) and configure Composer
to use it. This is useful if you are developing closed open extensions and want to share within your projects.
Extensions installed by Composer are stored in the `BasePath/vendor` directory, where `BasePath` refers to the
application's [base path](structure-applications.md#basePath). Because Composer is a dependency manager, when
it installs a package, it will also install all its dependent packages.
For example, to install the `yiisoft/yii2-imagine` extension, modify your `composer.json` like the following:
```json
{
// ...
"require": {
// ... other dependencies
"yiisoft/yii2-imagine": "*"
}
}
```
After the installation, you should see the directory `yiisoft/yii2-imagine` under `BasePath/vendor`. You should
also see another directory `imagine/imagine` which contains the installed dependent package.
> Info: The `yiisoft/yii2-imagine` is a core extension developed and maintained by the Yii developer team. All
core extensions are hosted on [Packagist](https://packagist.org/) and named like `yiisoft/yii2-xyz`, where `xyz`
varies for different extensions.
Now you can use the installed extensions like they are part of your application. The following example shows
how you can use the `yii\imagine\Image` class provided by the `yiisoft/yii2-imagine` extension:
```php
use Yii;
use yii\imagine\Image;
// generate a thumbnail image
Image::thumbnail('@webroot/img/test-image.jpg', 120, 120)
->save(Yii::getAlias('@runtime/thumb-test-image.jpg'), ['quality' => 50]);
```
> Info: Extension classes are autoloaded by the [Yii class autoloader](concept-autoloading.md).
### Installing Extensions Manually <a name="installing-extensions-manually"></a>
In some rare occasions, you may want to install some or all extensions manually, rather than relying on Composer.
To do so, you should
1. download the extension archive files and unpack them in the `vendor` directory.
2. install the class autoloaders provided by the extensions, if any.
3. download and install all dependent extensions as instructed.
If an extension does not have a class autoloader but follows the [PSR-4 standard](http://www.php-fig.org/psr/psr-4/),
you may use the class autoloader provided by Yii to autoload the extension classes. All you need to do is just to
declare a [root alias](concept-aliases.md#defining-aliases) for the extension root directory. For example,
assuming you have installed an extension in the directory `vendor/mycompany/myext`, and the extension classes
are under the `myext` namespace, then you can include the following code in your application configuration:
```php
[
'aliases' => [
'@myext' => '@vendor/mycompany/myext',
],
]
```
## Creating Extensions <a name="creating-extensions"></a>
You may consider creating an extension when you feel the need to share with other people your great code.
An extension can contain any code you like, such as a helper class, a widget, a module, etc.
It is recommended that you create an extension in terms of a [Composer package](https://getcomposer.org/) so that
it can be more easily installed and used by other users, liked described in the last subsection.
Below are the basic steps you may follow to create an extension as a Composer package.
1. Create a project for your extension and host it on a VCS repository, such as [github.com](https://github.com).
The development and maintenance work about the extension should be done on this repository.
2. Under the root directory of the project, create a file named `composer.json` as required by Composer. Please
refer to the next subsection for more details.
3. Register your extension with a Composer repository, such as [Packagist](https://packagist.org/), so that
other users can find and install your extension using Composer.
### `composer.json` <a name="composer-json"></a>
Each Composer package must have a `composer.json` file in its root directory. The file contains the metadata about
the package. You may find complete specification about this file in the [Composer Manual](https://getcomposer.org/doc/01-basic-usage.md#composer-json-project-setup).
The following example shows the `composer.json` file for the `yiisoft/yii2-imagine` extension:
```json
{
// package name
"name": "yiisoft/yii2-imagine",
// package type
"type": "yii2-extension",
"description": "The Imagine integration for the Yii framework",
"keywords": ["yii2", "imagine", "image", "helper"],
"license": "BSD-3-Clause",
"support": {
"issues": "https://github.com/yiisoft/yii2/issues?labels=ext%3Aimagine",
"forum": "http://www.yiiframework.com/forum/",
"wiki": "http://www.yiiframework.com/wiki/",
"irc": "irc://irc.freenode.net/yii",
"source": "https://github.com/yiisoft/yii2"
},
"authors": [
{
"name": "Antonio Ramirez",
"email": "amigo.cobos@gmail.com"
}
],
// package dependencies
"require": {
"yiisoft/yii2": "*",
"imagine/imagine": "v0.5.0"
},
// class autoloading specs
"autoload": {
"psr-4": {
"yii\\imagine\\": ""
}
}
}
```
#### Package Name <a name="package-name"></a>
Each Composer package should have a package name which uniquely identifies the package among all others.
The format of package names is `vendorName/projectName`. For example, in the package name `yiisoft/yii2-imagine`,
the vendor name and the project name are `yiisoft` and `yii2-imagine`, respectively.
Do NOT use `yiisoft` as vendor name as it is reserved for use by the Yii core code.
We recommend you prefix `yii2-` to the project name for packages representing Yii 2 extensions, for example,
`myname/yii2-mywidget`. This will allow users to more easily tell whether a package is a Yii 2 extension.
#### Package Type <a name="package-type"></a>
It is important that you specify the package type of your extension as `yii2-extension` so that the package can
be recognized as a Yii extension when being installed.
When a user runs `composer install` to install an extension, the file `vendor/yiisoft/extensions.php`
will be automatically updated to include the information about the new extension. From this file, Yii applications
can know which extensions are installed (the information can be accessed via [[yii\base\Application::extensions]].
#### Dependencies <a name="dependencies"></a>
Your extension depends on Yii (of course). So you should list it (`yiisoft/yii2`) in the `require` entry in `composer.json`.
If your extension also depends on other extensions or third-party libraries, you should list them as well.
Make sure you also list appropriate version constraints (e.g. `1.*`, `@stable`) for each dependent package. Use stable
dependencies when your extension is released in a stable version.
Most JavaScript/CSS packages are managed using [Bower](http://bower.io/) and/or [NPM](https://www.npmjs.org/),
instead of Composer. Yii uses the [Composer asset plugin](https://github.com/francoispluchino/composer-asset-plugin)
to enable managing these kinds of packages through Composer. If your extension depends on a Bower package, you can
simply list the dependency in `composer.json` like the following:
```json
{
// package dependencies
"require": {
"bower-asset/jquery": ">=1.11.*"
}
}
```
The above code states that the extension depends on the `jquery` Bower package. In general, you can use
`bower-asset/PackageName` to refer to a Bower package in `composer.json`, and use `npm-asset/PackageName`
to refer to a NPM package. When Composer installs a Bower or NPM package, by default the package content will be
installed under the `@vendor/bower/PackageName` and `@vendor/npm/Packages` directories, respectively.
These two directories can also be referred to using the shorter aliases `@bower/PackageName` and `@npm/PackageName`.
For more details about asset management, please refer to the [Assets](structure-assets.md#bower-npm-assets) section.
#### Class Autoloading <a name="class-autoloading"></a>
In order for your classes to be autoloaded by the Yii class autoloader or the Composer class autoloader,
you should specify the `autoload` entry in the `composer.json` file, like shown below:
```json
{
// ....
"autoload": {
"psr-4": {
"yii\\imagine\\": ""
}
}
}
```
You may list one or multiple root namespaces and their corresponding file paths.
When the extension is installed in an application, Yii will create for each listed root namespace
an [alias](concept-aliases.md#extension-aliases) that refers to the directory corresponding to the namespace.
For example, the above `autoload` declaration will correspond to an alias named `@yii/imagine`.
### Recommended Practices <a name="recommended-practices"></a>
Because extensions are meant to be used by other people, you often need to take extra development effort. Below
we introduce some common and recommended practices in creating high quality extensions.
#### Namespaces <a name="namespaces"></a>
To avoid name collisions and make the classes in your extension autoloadable, you should use namespaces and
name the classes in your extension by following the [PSR-4 standard](http://www.php-fig.org/psr/psr-4/) or
[PSR-0 standard](http://www.php-fig.org/psr/psr-0/).
You class namespaces should start with `vendorName\extensionName`, where `extensionName` is similar to the project name
in the package name except that it should not contain the `yii2-` prefix. For example, for the `yiisoft/yii2-imagine`
extension, we use `yii\imagine` as the namespace its classes.
Do not use `yii`, `yii2` or `yiisoft` as vendor name. These names are reserved for use by the Yii core code.
#### Bootstrapping Classes <a name="bootstrapping-classes"></a>
Sometimes, you may want your extension to execute some code during the [bootstrapping process](runtime-bootstrapping.md)
stage of an application. For example, your extension may want to respond to the application's `beginRequest` event
to adjust some environment settings. While you can instruct users of the extension to explicitly attach your event
handler in the extension to the `beginRequest` event, a better way is to do this automatically.
To achieve this goal, you can create a so-called *bootstrapping class* by implementing [[yii\base\BootstrapInterface]].
For example,
```php
namespace myname\mywidget;
use yii\base\BootstrapInterface;
use yii\base\Application;
class MyBootstrapClass implements BootstrapInterface
{
public function bootstrap($app)
{
$app->on(Application::EVENT_BEFORE_REQUEST, function () {
// do something here
});
}
}
```
You then list this class in the `composer.json` file of your extension like follows,
```json
{
// ...
"extra": {
"bootstrap": "myname\\mywidget\\MyBootstrapClass"
}
}
```
When the extension is installed in an application, Yii will automatically instantiate the bootstrapping class
and call its [[yii\base\BootstrapInterface::bootstrap()|bootstrap()]] method during the bootstrapping process for
every request.
#### Working with Databases <a name="working-with-databases"></a>
Your extension may need to access databases. Do not assume that the applications that use your extension will always
use `Yii::$db` as the DB connection. Instead, you should declare a `db` property for the classes that require DB access.
The property will allow users of your extension to customize which DB connection they would like your extension to use.
As an example, you may refer to the [[yii\caching\DbCache]] class and see how it declares and uses the `db` property.
If your extension needs to create specific DB tables or make changes to DB schema, you should
- provide [migrations](db-migrations.md) to manipulate DB schema, rather than using plain SQL files;
- try to make the migrations applicable to different DBMS;
- avoid using [Active Record](db-active-record.md) in the migrations.
#### Using Assets <a name="using-assets"></a>
If your extension is a widget or a module, chances are that it may require some [assets](structure-assets.md) to work.
For example, a module may display some pages which contain images, JavaScript, and CSS. Because the files of an
extension are all under the same directory which is not Web accessible when installed in an application, you have
two choices to make the asset files directly accessible via Web:
- ask users of the extension to manually copy the asset files to a specific Web-accessible folder;
- declare an [asset bundle](structure-assets.md) and rely on the asset publishing mechanism to automatically
copy the files listed in the asset bundle to a Web-accessible folder.
We recommend you use the second approach so that your extension can be more easily used by other people.
Please refer to the [Assets](structure-assets.md) section for more details about how to work with assets in general.
#### Internationalization and Localization <a name="i18n-l10n"></a>
Your extension may be used by applications supporting different languages! Therefore, if your extension displays
content to end users, you should try to [internationalize and localize](tutorial-i18n.md) it. In particular,
- If the extension displays messages intended for end users, the messages should be wrapped into `Yii::t()`
so that they can be translated. Messages meant for developers (such as internal exception messages) do not need
to be translated.
- If the extension displays numbers, dates, etc., they should be formatted using [[yii\i18n\Formatter]] with
appropriate formatting rules.
For more details, please refer to the [Internationalization](tutorial-i18n.md) section.
#### Testing <a name="testing"></a>
You want your extension to run flawlessly without bringing problems to other people. To reach this goal, you should
test your extension before releasing it to public.
It is recommended that you create various test cases to cover your extension code rather than relying on manual tests.
Each time before you release a new version of your extension, you may simply run these test cases to make sure
everything is in good shape. Yii provides testing support, which can help you to more easily write unit tests,
acceptance tests and functionality tests. For more details, please refer to the [Testing](test-overview.md) section.
#### Versioning <a name="versioning"></a>
You should give each release of your extension a version number (e.g. `1.0.1`). We recommend you follow the
[semantic versioning](http://semver.org) practice when determining what version numbers should be used.
#### Releasing <a name="releasing"></a>
To let other people know your extension, you need to release it to public.
If it is the first time you release an extension, you should register it on a Composer repository, such as
[Packagist](https://packagist.org/). After that, all you need to do is simply creating a release tag (e.g. `v1.0.1`)
on the VCS repository of your extension and notify the Composer repository about the new release. People will
then be able to find the new release, and install or update the extension through the Composer repository.
In the releases of your extension, besides code files you should also consider including the followings to
help other people learn about and use your extension:
* A readme file in the package root directory: it describes what your extension does and how to install and use it.
We recommend you write it in [Markdown](http://daringfireball.net/projects/markdown/) format and name the file
as `readme.md`.
* A changelog file in the package root directory: it lists what changes are made in each release. The file
may be written in Markdown format and named as `changelog.md`.
* An upgrade file in the package root directory: it gives the instructions on how to upgrade from older releases
of the extension. The file may be written in Markdown format and named as `upgrade.md`.
* Tutorials, demos, screenshots, etc.: these are needed if your extension provides many features that cannot be
fully covered in the readme file.
* API documentation: your code should be well documented to allow other people more easily read and understand it.
You may refer to the [Object class file](https://github.com/yiisoft/yii2/blob/master/framework/base/Object.php)
to learn how to document your code.
> Info: Your code comments can be written in Markdown format. The `yiisoft/yii2-apidoc` extension provides a tool
for you to generate pretty API documentation based on your code comments.
> Info: While not a requirement, we suggest your extension adhere to certain coding styles. You may refer to
the [core framework code style](https://github.com/yiisoft/yii2/wiki/Core-framework-code-style).
## Core Extensions <a name="core-extensions"></a>
Yii provides the following core extensions that are developed and maintained by the Yii developer team. They are all
registered on [Packagist](https://packagist.org/) and can be easily installed as described in the
[Using Extensions](#using-extensions) subsection.
- [yiisoft/yii2-apidoc](https://github.com/yiisoft/yii2-apidoc):
provides an extensible and high-performance API documentation generator. It is also used to generate the core
framework API documentation.
- [yiisoft/yii2-authclient](https://github.com/yiisoft/yii2-authclient):
provides a set of commonly used auth clients, such as Facebook OAuth2 client, GitHub OAuth2 client.
- [yiisoft/yii2-bootstrap](https://github.com/yiisoft/yii2-bootstrap):
provides a set of widgets that encapsulate the [Bootstrap](http://getbootstrap.com/) components and plugins.
- [yiisoft/yii2-codeception](https://github.com/yiisoft/yii2-codeception):
provides testing support based on [Codeception](http://codeception.com/).
- [yiisoft/yii2-debug](https://github.com/yiisoft/yii2-debug):
provides debugging support for Yii applications. When this extension is used, a debugger toolbar will appear
at the bottom of every page. The extension also provides a set of standalone pages to display more detailed
debug information.
- [yiisoft/yii2-elasticsearch](https://github.com/yiisoft/yii2-elasticsearch):
provides the support for using [Elasticsearch](http://www.elasticsearch.org/). It includes basic querying/search
support and also implements the [Active Record](db-active-record.md) pattern that allows you to store active records
in Elasticsearch.
- [yiisoft/yii2-faker](https://github.com/yiisoft/yii2-faker):
provides the support for using [Faker](https://github.com/fzaninotto/Faker) to generate fake data for you.
- [yiisoft/yii2-gii](https://github.com/yiisoft/yii2-gii):
provides a Web-based code generator that is highly extensible and can be used to quickly generate models,
forms, modules, CRUD, etc.
- [yiisoft/yii2-imagine](https://github.com/yiisoft/yii2-imagine):
provides commonly used image manipulation functions based on [Imagine](http://imagine.readthedocs.org/).
- [yiisoft/yii2-jui](https://github.com/yiisoft/yii2-jui):
provides a set of widgets that encapsulate the [JQuery UI](http://jqueryui.com/) interactions and widgets.
- [yiisoft/yii2-mongodb](https://github.com/yiisoft/yii2-mongodb):
provides the support for using [MongoDB](http://www.mongodb.org/). It includes features such as basic query,
Active Record, migrations, caching, code generation, etc.
- [yiisoft/yii2-redis](https://github.com/yiisoft/yii2-redis):
provides the support for using [redis](http://redis.io/). It includes features such as basic query,
Active Record, caching, etc.
- [yiisoft/yii2-smarty](https://github.com/yiisoft/yii2-smarty):
provides a template engine based on [Smarty](http://www.smarty.net/).
- [yiisoft/yii2-sphinx](https://github.com/yiisoft/yii2-sphinx):
provides the support for using [Sphinx](http://sphinxsearch.com). It includes features such as basic query,
Active Record, code generation, etc.
- [yiisoft/yii2-swiftmailer](https://github.com/yiisoft/yii2-swiftmailer):
provides email sending features based on [swiftmailer](http://swiftmailer.org/).
- [yiisoft/yii2-twig](https://github.com/yiisoft/yii2-twig):
provides a template engine based on [Twig](http://twig.sensiolabs.org/).
|
{
"pile_set_name": "Github"
}
|
#import <Foundation/Foundation.h>
@interface PodsDummy_Alamofire : NSObject
@end
@implementation PodsDummy_Alamofire
@end
|
{
"pile_set_name": "Github"
}
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/grappler/utils/scc.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/grappler/clusters/virtual_cluster.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/inputs/trivial_test_graph_input_yielder.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace grappler {
namespace {
class SCCTest : public ::testing::Test {
public:
void SetUp() override {
std::unordered_map<string, DeviceProperties> devices;
DeviceProperties unknown_device;
devices["MY_DEVICE"] = unknown_device;
cluster_.reset(new VirtualCluster(devices));
TF_CHECK_OK(cluster_->Provision());
}
void TearDown() override { cluster_.reset(); }
protected:
static NodeDef CreateNode(const string& name,
gtl::ArraySlice<string> inputs) {
NodeDef node;
node.set_name(name);
for (const string& input : inputs) {
node.add_input(input);
}
return node;
}
std::unique_ptr<VirtualCluster> cluster_;
};
TEST_F(SCCTest, NoLoops) {
// Create a simple graph without any loop.
TrivialTestGraphInputYielder fake_input(4, 1, 10, false,
cluster_->GetDeviceNames());
GrapplerItem item;
CHECK(fake_input.NextItem(&item));
std::unordered_map<const NodeDef*, int> components;
int num_components;
StronglyConnectedComponents(item.graph, &components, &num_components);
EXPECT_EQ(num_components, 1);
for (const auto& node : item.graph.node()) {
EXPECT_EQ(-1, components[&node]);
}
}
TEST_F(SCCTest, DisjointCycleAndPath) {
GraphDef graph;
// Create a cycle
*graph.add_node() = CreateNode("a", {"d"});
*graph.add_node() = CreateNode("b", {"a"});
*graph.add_node() = CreateNode("c", {"b"});
*graph.add_node() = CreateNode("d", {"c"});
// Add a path disjoint from cycle
*graph.add_node() = CreateNode("e", {});
*graph.add_node() = CreateNode("f", {"e"});
*graph.add_node() = CreateNode("g", {"f"});
*graph.add_node() = CreateNode("h", {"g"});
std::vector<const NodeDef*> nodes;
std::unordered_map<string, const NodeDef*> name_to_node;
for (const auto& n : graph.node()) {
nodes.push_back(&n);
name_to_node[n.name()] = &n;
}
int num_components;
std::unordered_map<const NodeDef*, int> components;
StronglyConnectedComponents(graph, &components, &num_components);
EXPECT_EQ(num_components, 2);
for (const auto& pair : {std::make_pair("a", "b"), std::make_pair("a", "c"),
std::make_pair("a", "d")}) {
EXPECT_EQ(components[name_to_node[pair.first]],
components[name_to_node[pair.second]]);
}
for (const auto& node : {"e", "f", "g", "h"})
EXPECT_EQ(-1, components[name_to_node[node]]);
}
} // namespace
TEST_F(SCCTest, WikipediaExample) {
// Graph with 4 SCCs:
// SCC1:
// a -> b
// b -> c
// c -> a
// d -> b
// d -> c
// SCC2:
// d -> e
// e -> d
// e -> f
// f -> c
// SCC3:
// f -> g
// g -> f
// h -> g
// h -> d
// SCC4:
// h -> h
// NodeDefs define inbound connections (inputs)
GraphDef graph;
*graph.add_node() = CreateNode("a", {"c"});
*graph.add_node() = CreateNode("b", {"a", "d"});
*graph.add_node() = CreateNode("c", {"b", "d", "f"});
*graph.add_node() = CreateNode("d", {"e"});
*graph.add_node() = CreateNode("e", {"d"});
*graph.add_node() = CreateNode("f", {"e", "g"});
*graph.add_node() = CreateNode("g", {"f", "h"});
*graph.add_node() = CreateNode("h", {"h"});
std::vector<const NodeDef*> nodes;
std::unordered_map<string, const NodeDef*> name_to_node;
for (const auto& n : graph.node()) {
nodes.push_back(&n);
name_to_node[n.name()] = &n;
}
int num_components;
std::unordered_map<const NodeDef*, int> components;
StronglyConnectedComponents(graph, &components, &num_components);
EXPECT_EQ(num_components, 4);
for (const auto& pair :
{std::make_pair("a", "b"), std::make_pair("a", "c"),
std::make_pair("d", "e"), std::make_pair("f", "g")}) {
EXPECT_EQ(components[name_to_node[pair.first]],
components[name_to_node[pair.second]]);
}
for (const auto& pair :
{std::make_pair("a", "d"), std::make_pair("a", "f"),
std::make_pair("a", "h"), std::make_pair("d", "f"),
std::make_pair("d", "h"), std::make_pair("f", "h")}) {
EXPECT_NE(components[name_to_node[pair.first]],
components[name_to_node[pair.second]]);
}
}
TEST_F(SCCTest, TensorFlowLoop) {
// Test graph produced in python using:
/*
with tf.Graph().as_default():
i = tf.constant(0)
c = lambda i: tf.less(i, 10)
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])
with open('/tmp/graph.txt', 'w') as f:
f.write(str(tf.get_default_graph().as_graph_def()))
*/
const string gdef_ascii = R"EOF(
node {
name: "Const"
op: "Const"
attr {
key: "dtype"
value {
type: DT_INT32
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_INT32
tensor_shape {
}
int_val: 0
}
}
}
}
node {
name: "while/Enter"
op: "Enter"
input: "Const"
attr {
key: "T"
value {
type: DT_INT32
}
}
attr {
key: "frame_name"
value {
s: "while/while/"
}
}
attr {
key: "is_constant"
value {
b: false
}
}
attr {
key: "parallel_iterations"
value {
i: 10
}
}
}
node {
name: "while/Merge"
op: "Merge"
input: "while/Enter"
input: "while/NextIteration"
attr {
key: "N"
value {
i: 2
}
}
attr {
key: "T"
value {
type: DT_INT32
}
}
}
node {
name: "while/Less/y"
op: "Const"
input: "^while/Merge"
attr {
key: "dtype"
value {
type: DT_INT32
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_INT32
tensor_shape {
}
int_val: 10
}
}
}
}
node {
name: "while/Less"
op: "Less"
input: "while/Merge"
input: "while/Less/y"
attr {
key: "T"
value {
type: DT_INT32
}
}
}
node {
name: "while/LoopCond"
op: "LoopCond"
input: "while/Less"
}
node {
name: "while/Switch"
op: "Switch"
input: "while/Merge"
input: "while/LoopCond"
attr {
key: "T"
value {
type: DT_INT32
}
}
attr {
key: "_class"
value {
list {
s: "loc:@while/Merge"
}
}
}
}
node {
name: "while/Identity"
op: "Identity"
input: "while/Switch:1"
attr {
key: "T"
value {
type: DT_INT32
}
}
}
node {
name: "while/Add/y"
op: "Const"
input: "^while/Identity"
attr {
key: "dtype"
value {
type: DT_INT32
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_INT32
tensor_shape {
}
int_val: 1
}
}
}
}
node {
name: "while/Add"
op: "Add"
input: "while/Identity"
input: "while/Add/y"
attr {
key: "T"
value {
type: DT_INT32
}
}
}
node {
name: "while/NextIteration"
op: "NextIteration"
input: "while/Add"
attr {
key: "T"
value {
type: DT_INT32
}
}
}
node {
name: "while/Exit"
op: "Exit"
input: "while/Switch"
attr {
key: "T"
value {
type: DT_INT32
}
}
}
versions {
producer: 11
}
)EOF";
GrapplerItem item;
CHECK(protobuf::TextFormat::ParseFromString(gdef_ascii, &item.graph));
std::unordered_map<const NodeDef*, int> components;
int num_components;
StronglyConnectedComponents(item.graph, &components, &num_components);
EXPECT_EQ(num_components, 2);
for (const auto& node : item.graph.node()) {
if (node.name() == "Const" || node.name() == "while/Enter" ||
node.name() == "while/Exit") {
// These nodes are not part of the loop, they should be assigned the id
// -1.
EXPECT_EQ(-1, components[&node]);
} else {
// These nodes are part of the loop, they should be assigned a positive
// id.
EXPECT_LE(0, components[&node]);
}
}
}
TEST_F(SCCTest, NestedLoops) {
GrapplerItem item;
string filename = io::JoinPath(
testing::TensorFlowSrcRoot(),
"core/grappler/costs/graph_properties_testdata/nested_loop.pbtxt");
TF_CHECK_OK(ReadGraphDefFromFile(filename, &item.graph));
for (const auto& node : item.graph.node()) {
std::cout << node.DebugString() << std::endl;
}
std::unordered_map<const NodeDef*, std::vector<int>> loops;
int num_loops = IdentifyLoops(item.graph, &loops);
EXPECT_EQ(4, num_loops);
for (const auto& node_info : loops) {
std::cout << node_info.first->name() << " [";
for (int i : node_info.second) {
std::cout << " " << i;
}
std::cout << "]" << std::endl;
}
}
} // namespace grappler
} // namespace tensorflow
|
{
"pile_set_name": "Github"
}
|
#pragma once
#include <gtkmm.h>
#include <set>
#include "util/uuid.hpp"
#include "common/common.hpp"
#include "util/pool_goto_provider.hpp"
namespace horizon {
class PreviewBase : public PoolGotoProvider {
protected:
Gtk::Button *create_goto_button(ObjectType type, std::function<UUID(void)> fn);
std::set<Gtk::Button *> goto_buttons;
};
} // namespace horizon
|
{
"pile_set_name": "Github"
}
|
--
-- Derived from a program believed to be originally written by John
-- Launchbury, and incorporating the RSA algorithm which is in the
-- public domain.
--
import System.Environment
import Control.Parallel.Strategies
import Data.List
import qualified Data.ByteString.Lazy.Char8 as B
import Data.ByteString.Lazy.Char8 (ByteString)
import ByteStringCompat
main = do
[cmd,f] <- getArgs
text <- case f of
"-" -> B.getContents
_ -> B.readFile f
case cmd of
"encrypt" -> B.putStr (encrypt n e text)
"decrypt" -> B.putStr (decrypt n d text)
-- example keys, created by makeKey below
n, d, e :: Integer
(n,d,e) = (3539517541822645630044332546732747854710141643130106075585179940882036712515975698104695392573887034788933523673604280427152984392565826058380509963039612419361429882234327760449752708861159361414595229,121492527803044541056704751360974487724009957507650761043424679483464778334890045929773805597614290949,216244483337223224019000724904989828660716358310562600433314577442746058361727768326718965949745599136958260211917551718034992348233259083876505235987999070191048638795502931877693189179113255689722281)
encrypt, decrypt :: Integer -> Integer -> ByteString -> ByteString
-- <<encrypt
encrypt n e = B.unlines
. withStrategy (parList rdeepseq) -- <1>
. map (B.pack . show . power e n . code)
. chunk (size n)
-- >>
decrypt n d = B.concat
. map (B.pack . decode . power d n)
. integers
. B.lines
integers :: [ByteString] -> [Integer]
integers bs = [ i | Just (i,_) <- map B.readInteger bs ]
-------- Converting between Strings and Integers -----------
code :: ByteString -> Integer
code = B.foldl' accum 0
where accum x y = (128 * x) + fromIntegral (fromEnum y)
decode :: Integer -> String
decode n = reverse (expand n)
where expand 0 = []
expand x = toEnum (fromIntegral (x `mod` 128)) : expand (x `div` 128)
chunk :: Int -> ByteString -> [ByteString]
chunk n xs | B.null xs = []
chunk n xs = as : chunk n bs
where (as,bs) = B.splitAt (fromIntegral n) xs
size :: Integer -> Int
size n = (length (show n) * 47) `div` 100 -- log_128 10 = 0.4745
------- Constructing keys -------------------------
makeKeys :: Integer -> Integer -> (Integer, Integer, Integer)
makeKeys r s = (p*q, d, invert ((p-1)*(q-1)) d)
where p = nextPrime r
q = nextPrime s
d = nextPrime (p+q+1)
nextPrime :: Integer -> Integer
nextPrime a = head (filter prime [odd,odd+2..])
where odd | even a = a+1
| True = a
prime p = and [power (p-1) p x == 1 | x <- [3,5,7]]
invert :: Integer -> Integer -> Integer
invert n a = if e<0 then e+n else e
where e=iter n 0 a 1
iter :: Integer -> Integer -> Integer -> Integer -> Integer
iter g v 0 w = v
iter g v h w = iter h w (g `mod` h) (v - (g `div` h)*w)
------- Fast exponentiation, mod m -----------------
power :: Integer -> Integer -> Integer -> Integer
power 0 m x = 1
power n m x | even n = sqr (power (n `div` 2) m x) `mod` m
| True = (x * power (n-1) m x) `mod` m
sqr :: Integer -> Integer
sqr x = x * x
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>GLFW: Globals</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="extra.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<div class="glfwheader">
<a href="http://www.glfw.org/" id="glfwhome">GLFW</a>
<ul class="glfwnavbar">
<li><a href="http://www.glfw.org/documentation.html">Documentation</a></li>
<li><a href="http://www.glfw.org/download.html">Download</a></li>
<li><a href="http://www.glfw.org/media.html">Media</a></li>
<li><a href="http://www.glfw.org/community.html">Community</a></li>
</ul>
</div>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.6 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li class="current"><a href="globals.html"><span>Globals</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li class="current"><a href="globals.html"><span>All</span></a></li>
<li><a href="globals_func.html"><span>Functions</span></a></li>
<li><a href="globals_type.html"><span>Typedefs</span></a></li>
<li><a href="globals_defs.html"><span>Macros</span></a></li>
</ul>
</div>
<div id="navrow4" class="tabs3">
<ul class="tablist">
<li><a href="globals.html#index_a"><span>a</span></a></li>
<li><a href="globals_b.html#index_b"><span>b</span></a></li>
<li class="current"><a href="globals_c.html#index_c"><span>c</span></a></li>
<li><a href="globals_d.html#index_d"><span>d</span></a></li>
<li><a href="globals_e.html#index_e"><span>e</span></a></li>
<li><a href="globals_f.html#index_f"><span>f</span></a></li>
<li><a href="globals_g.html#index_g"><span>g</span></a></li>
<li><a href="globals_h.html#index_h"><span>h</span></a></li>
<li><a href="globals_i.html#index_i"><span>i</span></a></li>
<li><a href="globals_j.html#index_j"><span>j</span></a></li>
<li><a href="globals_k.html#index_k"><span>k</span></a></li>
<li><a href="globals_l.html#index_l"><span>l</span></a></li>
<li><a href="globals_m.html#index_m"><span>m</span></a></li>
<li><a href="globals_n.html#index_n"><span>n</span></a></li>
<li><a href="globals_o.html#index_o"><span>o</span></a></li>
<li><a href="globals_p.html#index_p"><span>p</span></a></li>
<li><a href="globals_r.html#index_r"><span>r</span></a></li>
<li><a href="globals_s.html#index_s"><span>s</span></a></li>
<li><a href="globals_t.html#index_t"><span>t</span></a></li>
<li><a href="globals_v.html#index_v"><span>v</span></a></li>
<li><a href="globals_w.html#index_w"><span>w</span></a></li>
</ul>
</div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Macros</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>Groups</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark"> </span>Pages</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
<div class="textblock">Here is a list of all functions, variables, defines, enums, and typedefs with links to the files they belong to:</div>
<h3><a class="anchor" id="index_c"></a>- c -</h3><ul>
<li>GLFW_CLIENT_API
: <a class="el" href="glfw3_8h.html#a649309cf72a3d3de5b1348ca7936c95b">glfw3.h</a>
</li>
<li>GLFW_CONNECTED
: <a class="el" href="glfw3_8h.html#abe11513fd1ffbee5bb9b173f06028b9e">glfw3.h</a>
</li>
<li>GLFW_CONTEXT_RELEASE_BEHAVIOR
: <a class="el" href="glfw3_8h.html#a72b648a8378fe3310c7c7bbecc0f7be6">glfw3.h</a>
</li>
<li>GLFW_CONTEXT_REVISION
: <a class="el" href="glfw3_8h.html#afb9475071aa77c6fb05ca5a5c8678a08">glfw3.h</a>
</li>
<li>GLFW_CONTEXT_ROBUSTNESS
: <a class="el" href="glfw3_8h.html#ade3593916b4c507900aa2d6844810e00">glfw3.h</a>
</li>
<li>GLFW_CONTEXT_VERSION_MAJOR
: <a class="el" href="glfw3_8h.html#afe5e4922de1f9932d7e9849bb053b0c0">glfw3.h</a>
</li>
<li>GLFW_CONTEXT_VERSION_MINOR
: <a class="el" href="glfw3_8h.html#a31aca791e4b538c4e4a771eb95cc2d07">glfw3.h</a>
</li>
<li>GLFW_CROSSHAIR_CURSOR
: <a class="el" href="group__shapes.html#ga8af88c0ea05ab9e8f9ac1530e8873c22">glfw3.h</a>
</li>
<li>GLFW_CURSOR
: <a class="el" href="glfw3_8h.html#aade31da5b884a84a7625c6b059b9132c">glfw3.h</a>
</li>
<li>GLFW_CURSOR_DISABLED
: <a class="el" href="glfw3_8h.html#a2315b99a329ce53e6a13a9d46fd5ca88">glfw3.h</a>
</li>
<li>GLFW_CURSOR_HIDDEN
: <a class="el" href="glfw3_8h.html#ac4d5cb9d78de8573349c58763d53bf11">glfw3.h</a>
</li>
<li>GLFW_CURSOR_NORMAL
: <a class="el" href="glfw3_8h.html#ae04dd25c8577e19fa8c97368561f6c68">glfw3.h</a>
</li>
<li>glfwCreateCursor()
: <a class="el" href="group__input.html#gafca356935e10135016aa49ffa464c355">glfw3.h</a>
</li>
<li>glfwCreateStandardCursor()
: <a class="el" href="group__input.html#gaa65f416d03ebbbb5b8db71a489fcb894">glfw3.h</a>
</li>
<li>glfwCreateWindow()
: <a class="el" href="group__window.html#ga5c336fddf2cbb5b92f65f10fb6043344">glfw3.h</a>
</li>
</ul>
</div><!-- contents -->
<address class="footer">
<p>
Last update on Thu Mar 19 2015 for GLFW 3.1.1
</p>
</address>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
################################################################################
#
# perl-mojolicious
#
################################################################################
PERL_MOJOLICIOUS_VERSION = 8.40
PERL_MOJOLICIOUS_SOURCE = Mojolicious-$(PERL_MOJOLICIOUS_VERSION).tar.gz
PERL_MOJOLICIOUS_SITE = $(BR2_CPAN_MIRROR)/authors/id/S/SR/SRI
PERL_MOJOLICIOUS_LICENSE = Artistic-2.0
PERL_MOJOLICIOUS_LICENSE_FILES = LICENSE
PERL_MOJOLICIOUS_DISTNAME = Mojolicious
$(eval $(perl-package))
|
{
"pile_set_name": "Github"
}
|
ExUnit.start
|
{
"pile_set_name": "Github"
}
|
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["factory_interfaces.go"],
importmap = "k8s.io/kubernetes/vendor/k8s.io/client-go/informers/internalinterfaces",
importpath = "k8s.io/client-go/informers/internalinterfaces",
deps = [
"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//staging/src/k8s.io/client-go/kubernetes:go_default_library",
"//staging/src/k8s.io/client-go/tools/cache:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
|
{
"pile_set_name": "Github"
}
|
module PublishingApi
module PayloadBuilder
class AnalyticsIdentifier
attr_reader :item
def self.for(item)
new(item).call
end
def initialize(item)
@item = item
end
def call
{ analytics_identifier: item.analytics_identifier }
end
end
end
end
|
{
"pile_set_name": "Github"
}
|
/*
*
* Copyright 2018 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 service manages connections between the VM application and the ALTS
// handshaker service.
package service
import (
"sync"
grpc "google.golang.org/grpc"
)
var (
// hsConn represents a connection to hypervisor handshaker service.
hsConn *grpc.ClientConn
mu sync.Mutex
// hsDialer will be reassigned in tests.
hsDialer = grpc.Dial
)
// Dial dials the handshake service in the hypervisor. If a connection has
// already been established, this function returns it. Otherwise, a new
// connection is created.
func Dial(hsAddress string) (*grpc.ClientConn, error) {
mu.Lock()
defer mu.Unlock()
if hsConn == nil {
// Create a new connection to the handshaker service. Note that
// this connection stays open until the application is closed.
var err error
hsConn, err = hsDialer(hsAddress, grpc.WithInsecure())
if err != nil {
return nil, err
}
}
return hsConn, nil
}
|
{
"pile_set_name": "Github"
}
|
<testcase>
<info>
<keywords>
SCP
FAILURE
</keywords>
</info>
#
# Client-side
<client>
<server>
scp
</server>
<name>
SCP retrieval of missing file followed by good file
</name>
<command>
--key curl_client_key --pubkey curl_client_key.pub -u %USER: scp://%HOSTIP:%SSHPORT%PWD/log/not-a-valid-file-moooo scp://%HOSTIP:%SSHPORT%PWD/log/file621.txt --insecure
</command>
<file name="log/file621.txt">
Test data
for ssh test
</file>
</client>
#
# Verify data after the test has been "shot"
<verify>
<valgrind>
disable
</valgrind>
<stdout>
Test data
for ssh test
</stdout>
</verify>
</testcase>
|
{
"pile_set_name": "Github"
}
|
var setup = require('../submission/setup')
var drawLine
exports.init = function(gl) {
drawLine = setup(gl)
}
exports.draw = function(gl) {
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight)
gl.clearColor(0,0,0,1)
gl.clear(gl.COLOR_BUFFER_BIT)
gl.lineWidth(1)
drawLine(-0.5, [1,0,0])
gl.lineWidth(5)
drawLine(0, [0,1,0])
gl.lineWidth(10)
drawLine(0.5, [1,1,1])
}
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.