text
stringlengths 2
100k
| meta
dict |
---|---|
// -*- mode: c++; tab-width: 4; indent-tabs-mode: t; c-file-style: "stroustrup"; -*-
// vi:set ts=4 sts=4 sw=4 noet :
// Copyright 2008, 2012, The TPIE development team
//
// This file is part of TPIE.
//
// TPIE is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// TPIE is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TPIE. If not, see <http://www.gnu.org/licenses/>
#ifndef _TPIE_CPU_TIMER_H
#define _TPIE_CPU_TIMER_H
///////////////////////////////////////////////////////////////////////////
/// \file cpu_timer.h
/// Timer measuring user time, system time and wall clock time.
///////////////////////////////////////////////////////////////////////////
// Get definitions for working with Unix and Windows
#include <tpie/portability.h>
#include <iostream>
#include <time.h>
#include <boost/date_time.hpp>
#ifndef _WIN32
#include <sys/times.h>
#include <sys/resource.h>
#endif
namespace tpie {
///////////////////////////////////////////////////////////////////////////
/// A timer measuring user time, system time and wall clock time. The
/// timer can be start()'ed, stop()'ed, and queried. Querying can be
/// done without stopping the timer, to report intermediate values.
/// \internal
///////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
typedef boost::posix_time::ptime tms;
#else
using ::tms;
#endif
class cpu_timer {
private:
long clock_tick_;
tms last_sync_;
tms elapsed_;
clock_t last_sync_real_;
clock_t elapsed_real_;
bool running_;
inline void set_clock_tick();
inline void last_sync_real_declaration();
public:
cpu_timer();
///////////////////////////////////////////////////////////////////////////
/// Start the timer.
///////////////////////////////////////////////////////////////////////////
void start();
///////////////////////////////////////////////////////////////////////////
/// Stop the timer.
///////////////////////////////////////////////////////////////////////////
void stop();
///////////////////////////////////////////////////////////////////////////
/// Update fields such that running(), clock_tick(), elapsed(),
/// elapsed_real() will return recent measurements.
///////////////////////////////////////////////////////////////////////////
void sync();
///////////////////////////////////////////////////////////////////////////
/// Reset the timer to zero.
///////////////////////////////////////////////////////////////////////////
void reset();
///////////////////////////////////////////////////////////////////////////
/// Linux: Query the amount of time spent by this process in user mode
/// since the timer was reset.
///
/// Windows: Query the amount of wall clock time spent by this process
/// since the timer was reset.
///////////////////////////////////////////////////////////////////////////
double user_time();
///////////////////////////////////////////////////////////////////////////
/// Linux: Query the amount of time spent by this process in kernel mode
/// since the timer was reset.
///
/// Windows: Query the amount of wall clock time spent by this process
/// since the timer was reset.
///////////////////////////////////////////////////////////////////////////
double system_time();
///////////////////////////////////////////////////////////////////////////
/// Query the amount of wall clock time spent by this process since the
/// timer was reset.
///////////////////////////////////////////////////////////////////////////
double wall_time();
///////////////////////////////////////////////////////////////////////////
/// Tell whether the timer is currently running.
///////////////////////////////////////////////////////////////////////////
inline bool running() const {
return running_;
}
///////////////////////////////////////////////////////////////////////////
/// Return number of ticks per wall clock second as reported by the OS.
///////////////////////////////////////////////////////////////////////////
inline long clock_tick() const {
return clock_tick_;
}
///////////////////////////////////////////////////////////////////////////
/// Return the timestamp of last sync.
///////////////////////////////////////////////////////////////////////////
inline tms last_sync() const {
return last_sync_;
}
///////////////////////////////////////////////////////////////////////////
/// Return the timestamp indicating the elapsed time. Only useful on Linux.
///////////////////////////////////////////////////////////////////////////
inline tms elapsed() const {
return elapsed_;
}
///////////////////////////////////////////////////////////////////////////
/// Return the wall clock timestamp of the last sync.
///////////////////////////////////////////////////////////////////////////
inline clock_t last_sync_real() const {
return last_sync_real_;
}
///////////////////////////////////////////////////////////////////////////
/// Return the elapsed wall clock time at the last sync.
///////////////////////////////////////////////////////////////////////////
inline clock_t elapsed_real() const {
return elapsed_real_;
}
};
///////////////////////////////////////////////////////////////////////////////
/// Enable outputting the queriable values of this timer. On Windows, just
/// output the elapsed real time in seconds. On Linux, output user, system and
/// wall clock time in seconds.
///////////////////////////////////////////////////////////////////////////////
std::ostream &operator<<(std::ostream &s, cpu_timer &ct);
}
#endif // _TPIE_CPU_TIMER_H
| {
"pile_set_name": "Github"
} |
.. algorithm::
.. summary::
.. relatedalgorithms::
.. properties::
Description
-----------
Uses the :ref:`UB matrix <Lattice>` on the sample to calculate the Miller indices for all
peaks in the peaks workspace. Unlike :ref:`algm-IndexPeaks` this
algorithm does not perform any mandatory optimization. This algorithm
does not round the Miller indices to the nearest integer.
Alternatives
------------
:ref:`algm-IndexPeaks`
Usage
-----
**Example - Calculate peak HKL values based on UB matrix**
.. testcode:: CalculatePeaksHKLExample
mdew = Load("TOPAZ_3680_5_sec_MDEW.nxs")
# Find some peaks. These are all unindexed so will have HKL = [0,0,0]
peaks = FindPeaksMD(InputWorkspace=mdew, MaxPeaks=1)
# Set the UB to unity
SetUB(peaks, UB=[1,0,0,0,1,0,0,0,1])
# Run the algorithm
indexed = CalculatePeaksHKL(PeaksWorkspace=peaks, OverWrite=True)
print("Number of Indexed Peaks: {}".format(indexed))
Output:
.. testoutput:: CalculatePeaksHKLExample
Number of Indexed Peaks: 1
.. categories::
.. sourcelink::
| {
"pile_set_name": "Github"
} |
package org.rewedigital.katana.android.example.main
import org.rewedigital.katana.android.example.remote.ApiModule
import org.rewedigital.katana.android.example.remote.MoshiModule
import org.rewedigital.katana.android.example.remote.RepositoryModule
import org.rewedigital.katana.android.example.remote.RetrofitModule
object Modules {
// Additional modules for main feature are placed here.
// We can replace this list during UI tests with mock modules.
var modules = listOf(
MoshiModule,
RetrofitModule,
ApiModule,
RepositoryModule
)
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2018 Red Hat Inc.
*
* 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "changk104.h"
#include "cgrp.h"
#include <core/client.h>
#include <core/gpuobj.h>
#include <nvif/clc36f.h>
#include <nvif/unpack.h>
static u32
tu102_fifo_gpfifo_submit_token(struct nvkm_fifo_chan *base)
{
struct gk104_fifo_chan *chan = gk104_fifo_chan(base);
return (chan->runl << 16) | chan->base.chid;
}
static const struct nvkm_fifo_chan_func
tu102_fifo_gpfifo = {
.dtor = gk104_fifo_gpfifo_dtor,
.init = gk104_fifo_gpfifo_init,
.fini = gk104_fifo_gpfifo_fini,
.ntfy = gf100_fifo_chan_ntfy,
.engine_ctor = gk104_fifo_gpfifo_engine_ctor,
.engine_dtor = gk104_fifo_gpfifo_engine_dtor,
.engine_init = gv100_fifo_gpfifo_engine_init,
.engine_fini = gv100_fifo_gpfifo_engine_fini,
.submit_token = tu102_fifo_gpfifo_submit_token,
};
int
tu102_fifo_gpfifo_new(struct gk104_fifo *fifo, const struct nvkm_oclass *oclass,
void *data, u32 size, struct nvkm_object **pobject)
{
struct nvkm_object *parent = oclass->parent;
union {
struct volta_channel_gpfifo_a_v0 v0;
} *args = data;
int ret = -ENOSYS;
nvif_ioctl(parent, "create channel gpfifo size %d\n", size);
if (!(ret = nvif_unpack(ret, &data, &size, args->v0, 0, 0, false))) {
nvif_ioctl(parent, "create channel gpfifo vers %d vmm %llx "
"ioffset %016llx ilength %08x "
"runlist %016llx priv %d\n",
args->v0.version, args->v0.vmm, args->v0.ioffset,
args->v0.ilength, args->v0.runlist, args->v0.priv);
if (args->v0.priv && !oclass->client->super)
return -EINVAL;
return gv100_fifo_gpfifo_new_(&tu102_fifo_gpfifo, fifo,
&args->v0.runlist,
&args->v0.chid,
args->v0.vmm,
args->v0.ioffset,
args->v0.ilength,
&args->v0.inst,
args->v0.priv,
&args->v0.token,
oclass, pobject);
}
return ret;
}
| {
"pile_set_name": "Github"
} |
CONFIG_ZTEST=y
| {
"pile_set_name": "Github"
} |
/*============================================================================
This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.
Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions, and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=============================================================================*/
#include <stdbool.h>
#include <stdint.h>
#include "platform.h"
#include "internals.h"
#include "specialize.h"
#include "softfloat.h"
/*----------------------------------------------------------------------------
| Assuming at least one of the two 128-bit floating-point values pointed to by
| `aWPtr' and `bWPtr' is a NaN, stores the combined NaN result at the location
| pointed to by `zWPtr'. If either original floating-point value is a
| signaling NaN, the invalid exception is raised. Each of `aWPtr', `bWPtr',
| and `zWPtr' points to an array of four 32-bit elements that concatenate in
| the platform's normal endian order to form a 128-bit floating-point value.
*----------------------------------------------------------------------------*/
void
softfloat_propagateNaNF128M(
const uint32_t *aWPtr, const uint32_t *bWPtr, uint32_t *zWPtr )
{
bool isSigNaNA;
const uint32_t *ptr;
ptr = aWPtr;
isSigNaNA = f128M_isSignalingNaN( (const float128_t *) aWPtr );
if (
isSigNaNA
|| (bWPtr && f128M_isSignalingNaN( (const float128_t *) bWPtr ))
) {
softfloat_raiseFlags( softfloat_flag_invalid );
if ( isSigNaNA ) goto copy;
}
if ( ! softfloat_isNaNF128M( aWPtr ) ) ptr = bWPtr;
copy:
zWPtr[indexWordHi( 4 )] = ptr[indexWordHi( 4 )] | 0x00008000;
zWPtr[indexWord( 4, 2 )] = ptr[indexWord( 4, 2 )];
zWPtr[indexWord( 4, 1 )] = ptr[indexWord( 4, 1 )];
zWPtr[indexWord( 4, 0 )] = ptr[indexWord( 4, 0 )];
}
| {
"pile_set_name": "Github"
} |
---
id: navigation-plugin
title: Navigation Plugin Setup
sidebar_label: Navigation
---
## Android
First, add the plugin to your Flipper client instance:
```java
import com.facebook.flipper.android.AndroidFlipperClient;
import com.facebook.flipper.plugins.navigation.NavigationFlipperPlugin;
final FlipperClient client = AndroidFlipperClient.getInstance(this);
client.addPlugin(NavigationFlipperPlugin.getInstance());
```
Navigation events in the app can then be recorded by calling `sendNavigationEvent` method of the `NavigationFlipperPlugin` instance from anywhere in the app. This allows for the Navigation Plugin to be integrated into existing navigation frameworks.
### Using Android Deep Links
The Navigation Plugin can be used with built in [deep links for Android](https://developer.android.com/training/app-links/deep-linking).
To deep link to an activity, edit the AndroidManifest.xml and add the intent filter for the given activity.
```xml
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="flipper" android:host="deep_link_activity" />
</intent-filter>
```
This will allow the user to jump to `flipper://deep_link_activity` within Flipper.
To log that navigation event in flipper, we can send the navigation event in the Activity's `onCreate` method.
```java
public class DeepLinkActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NavigationFlipperPlugin.getInstance().sendNavigationEvent("flipper://deep_link_activity/");
...
```
### Third Party Solutions
The Navigation Plugin can easily be integrated into a third party navigation framework.
#### AirBnB Deep Link Dispatch
[Deep Link Dispatch](https://github.com/airbnb/DeepLinkDispatch) will work out of the box with Flipper for navigating to links, including support for url parameters. To add logging, simply add a BroadcastReceiver to your app that is called on any incoming deep links.
```java
public class DeepLinkReceiver extends BroadcastReceiver {
private static final String TAG = "DeepLinkReceiver";
@Override public void onReceive(Context context, Intent intent) {
String deepLinkUri = intent.getStringExtra(DeepLinkHandler.EXTRA_URI);
if (intent.getBooleanExtra(DeepLinkHandler.EXTRA_SUCCESSFUL, false)) {
NavigationFlipperPlugin.getInstance().sendNavigationEvent(deepLinkUri);
}
}
}
public class DeepLinkApplication extends Application {
@Override public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter(DeepLinkHandler.ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new DeepLinkReceiver(), intentFilter);
}
}
```
## iOS
iOS support is coming soon.
| {
"pile_set_name": "Github"
} |
CFLAGS = -c
LDFLAGS =
ODIR = baddir
EXEBASE = bspinfo3
EXE = $(ODIR)/bspinfo3
all: $(EXE)
_next:
make "CFLAGS = -c -g -I../../common -DDOUBLEVEC_T" "ODIR = next"
_irix:
make "CFLAGS = -c -Ofast=ip32_10k -I../../common -Xcpluscomm -DDOUBLEVEC_T" "LDFLAGS = -Ofast=ip32_10k" "ODIR = irix"
_irixdebug:
make "CFLAGS = -c -O2 -g -I../../common -Xcpluscomm -DDOUBLEVEC_T" "LDFLAGS = -g" "ODIR = irix"
_irixinst:
make "CFLAGS = -c -Ofast=ip32_10k -I../../common -Xcpluscomm -DDOUBLEVEC_T" "LDFLAGS = -Ofast=ip32_10k" "ODIR = irix"
cp irix/$(EXEBASE) /limbo/quake2/bin_irix
_irixclean:
rm -f irix/*.o irix/$(EXEBASE)
_osf:
make "CFLAGS = -c -O4 -I../../common -threads -DDOUBLEVEC_T" "LDFLAGS = -threads" "ODIR = osf"
clean:
rm -f irix/*.o irix/$(EXEBASE)
install:
cp irix/$(EXEBASE) /limbo/quake2/bin_irix
FILES = $(ODIR)/bspinfo3.o $(ODIR)/bspfile.o $(ODIR)/cmdlib.o $(ODIR)/scriplib.o
$(EXE) : $(FILES)
cc -o $(EXE) $(LDFLAGS) $(FILES)
$(ODIR)/bspinfo3.o : bspinfo3.c
cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
cc $(CFLAGS) -o $@ /tmp/temp.i
$(ODIR)/cmdlib.o : ../../common/cmdlib.c
cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
cc $(CFLAGS) -o $@ /tmp/temp.i
$(ODIR)/scriplib.o : ../../common/scriplib.c
cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
cc $(CFLAGS) -o $@ /tmp/temp.i
$(ODIR)/bspfile.o : ../../common/bspfile.c
cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i
cc $(CFLAGS) -o $@ /tmp/temp.i
| {
"pile_set_name": "Github"
} |
/*
* Creates a window station and starts a process under it. The new process
* also gets a new console.
*/
#include <windows.h>
#include <string.h>
#include <stdio.h>
int main()
{
BOOL success;
SECURITY_ATTRIBUTES sa;
memset(&sa, 0, sizeof(sa));
sa.bInheritHandle = TRUE;
HWINSTA originalStation = GetProcessWindowStation();
printf("originalStation == 0x%x\n", originalStation);
HWINSTA station = CreateWindowStation(NULL,
0,
WINSTA_ALL_ACCESS,
&sa);
printf("station == 0x%x\n", station);
if (!SetProcessWindowStation(station))
printf("SetWindowStation failed!\n");
HDESK desktop = CreateDesktop("Default", NULL, NULL,
/*dwFlags=*/0, GENERIC_ALL,
&sa);
printf("desktop = 0x%x\n", desktop);
char stationName[256];
stationName[0] = '\0';
success = GetUserObjectInformation(station, UOI_NAME,
stationName, sizeof(stationName),
NULL);
printf("stationName = [%s]\n", stationName);
char startupDesktop[256];
sprintf(startupDesktop, "%s\\Default", stationName);
STARTUPINFO sui;
PROCESS_INFORMATION pi;
memset(&sui, 0, sizeof(sui));
memset(&pi, 0, sizeof(pi));
sui.cb = sizeof(STARTUPINFO);
sui.lpDesktop = startupDesktop;
// Start a cmd subprocess, and have it start its own cmd subprocess.
// Both subprocesses will connect to the same non-interactive window
// station.
const char program[] = "c:\\windows\\system32\\cmd.exe";
char cmdline[256];
sprintf(cmdline, "%s /c cmd", program);
success = CreateProcess(program,
cmdline,
NULL,
NULL,
/*bInheritHandles=*/FALSE,
/*dwCreationFlags=*/CREATE_NEW_CONSOLE,
NULL, NULL,
&sui,
&pi);
printf("pid == %d\n", pi.dwProcessId);
// This sleep is necessary. We must give the child enough time to
// connect to the specified window station.
Sleep(5000);
SetProcessWindowStation(originalStation);
CloseWindowStation(station);
CloseDesktop(desktop);
Sleep(5000);
return 0;
}
| {
"pile_set_name": "Github"
} |
export * from './layers.component';
| {
"pile_set_name": "Github"
} |
'use strict';
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const yaml = require('yaml');
const swagger2openapi = require('../packages/swagger2openapi/index.js');
const doPrivate = (!process.env.SKIP_PRIVATE);
const tests = fs.readdirSync(path.join(__dirname,'s2o-test')).filter(file => {
return fs.statSync(path.join(__dirname, 's2o-test', file)).isDirectory() && file !== 'include' && (!file.startsWith('_') || doPrivate);
});
describe('Converter tests', () => {
tests.forEach((test) => {
describe(test, () => {
it('should match expected output', (done) => {
const swagger = yaml.parse(fs.readFileSync(path.join(__dirname, 's2o-test', test, 'swagger.yaml'),'utf8'),{schema:'core'});
const openapi = yaml.parse(fs.readFileSync(path.join(__dirname, 's2o-test', test, 'openapi.yaml'),'utf8'),{schema:'core'});
let options = {};
try {
options = yaml.parse(fs.readFileSync(path.join(__dirname, 's2o-test', test, 'options.yaml'),'utf8'),{schema:'core'});
options.source = path.join(__dirname, 's2o-test', test, 'swagger.yaml');
}
catch (ex) {}
swagger2openapi.convertObj(swagger, options, (err, result) => {
if (err && !options.throws) return done(err);
if (!err && options.throws) return done(new Error('Test should have thrown an exception'));
if (!options.throws) assert.deepStrictEqual(result.openapi, openapi);
return done();
});
});
});
});
});
| {
"pile_set_name": "Github"
} |
/**
* A simple theme for reveal.js presentations, similar
* to the default theme. The accent color is darkblue.
*
* This theme is Copyright (C) 2012 Owen Versteeg, https://github.com/StereotypicalApps. It is MIT licensed.
* reveal.js is Copyright (C) 2011-2012 Hakim El Hattab, http://hakim.se
*/
@import url(https://fonts.googleapis.com/css?family=News+Cycle:400,700);
@import url(https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic);
section.has-dark-background, section.has-dark-background h1, section.has-dark-background h2, section.has-dark-background h3, section.has-dark-background h4, section.has-dark-background h5, section.has-dark-background h6 {
color: #fff; }
/*********************************************
* GLOBAL STYLES
*********************************************/
body {
background: #fff;
background-color: #fff; }
.reveal {
font-family: "Lato", sans-serif;
font-size: 40px;
font-weight: normal;
color: #000; }
::selection {
color: #fff;
background: rgba(0, 0, 0, 0.99);
text-shadow: none; }
::-moz-selection {
color: #fff;
background: rgba(0, 0, 0, 0.99);
text-shadow: none; }
.reveal .slides section,
.reveal .slides section > section {
line-height: 1.3;
font-weight: inherit; }
/*********************************************
* HEADERS
*********************************************/
.reveal h1,
.reveal h2,
.reveal h3,
.reveal h4,
.reveal h5,
.reveal h6 {
margin: 0 0 20px 0;
color: #000;
font-family: "News Cycle", Impact, sans-serif;
font-weight: normal;
line-height: 1.2;
letter-spacing: normal;
text-transform: none;
text-shadow: none;
word-wrap: break-word; }
.reveal h1 {
font-size: 3.77em; }
.reveal h2 {
font-size: 2.11em; }
.reveal h3 {
font-size: 1.55em; }
.reveal h4 {
font-size: 1em; }
.reveal h1 {
text-shadow: none; }
/*********************************************
* OTHER
*********************************************/
.reveal p {
margin: 20px 0;
line-height: 1.3; }
/* Ensure certain elements are never larger than the slide itself */
.reveal img,
.reveal video,
.reveal iframe {
max-width: 95%;
max-height: 95%; }
.reveal strong,
.reveal b {
font-weight: bold; }
.reveal em {
font-style: italic; }
.reveal ol,
.reveal dl,
.reveal ul {
display: inline-block;
text-align: left;
margin: 0 0 0 1em; }
.reveal ol {
list-style-type: decimal; }
.reveal ul {
list-style-type: disc; }
.reveal ul ul {
list-style-type: square; }
.reveal ul ul ul {
list-style-type: circle; }
.reveal ul ul,
.reveal ul ol,
.reveal ol ol,
.reveal ol ul {
display: block;
margin-left: 40px; }
.reveal dt {
font-weight: bold; }
.reveal dd {
margin-left: 40px; }
.reveal blockquote {
display: block;
position: relative;
width: 70%;
margin: 20px auto;
padding: 5px;
font-style: italic;
background: rgba(255, 255, 255, 0.05);
box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.2); }
.reveal blockquote p:first-child,
.reveal blockquote p:last-child {
display: inline-block; }
.reveal q {
font-style: italic; }
.reveal pre {
display: block;
position: relative;
width: 90%;
margin: 20px auto;
text-align: left;
font-size: 0.55em;
font-family: SFMono-Regular, 'Roboto Mono', monospace;
line-height: 1.2em;
word-wrap: break-word;
box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.3); }
.reveal code {
font-family: SFMono-Regular, 'Roboto Mono', monospace;
text-transform: none;
border: 1px solid #9acd32;
background-color: #9acd3240;
border-radius: 10px;
padding: 0 10px; }
.reveal pre code {
display: block;
padding: 5px;
overflow: auto;
max-height: 400px;
word-wrap: normal;
border: none;
background-color: #282c34; }
.reveal table {
margin: auto;
border-collapse: collapse;
border-spacing: 0; }
.reveal table th {
font-weight: bold; }
.reveal table th,
.reveal table td {
text-align: left;
padding: 0.2em 0.5em 0.2em 0.5em;
border-bottom: 1px solid; }
.reveal table th[align="center"],
.reveal table td[align="center"] {
text-align: center; }
.reveal table th[align="right"],
.reveal table td[align="right"] {
text-align: right; }
.reveal table tbody tr:last-child th,
.reveal table tbody tr:last-child td {
border-bottom: none; }
.reveal sup {
vertical-align: super;
font-size: smaller; }
.reveal sub {
vertical-align: sub;
font-size: smaller; }
.reveal small {
display: inline-block;
font-size: 0.6em;
line-height: 1.2em;
vertical-align: top; }
.reveal small * {
vertical-align: top; }
/*********************************************
* LINKS
*********************************************/
.reveal a {
color: #00008B;
text-decoration: none;
-webkit-transition: color .15s ease;
-moz-transition: color .15s ease;
transition: color .15s ease; }
.reveal a:hover {
color: #0000f1;
text-shadow: none;
border: none; }
.reveal .roll span:after {
color: #fff;
background: #00003f; }
/*********************************************
* IMAGES
*********************************************/
.reveal section img {
margin: 15px 0px;
background: rgba(255, 255, 255, 0.12);
border: 4px solid #000;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.15); }
.reveal section img.plain {
border: 0;
box-shadow: none;
background: none; }
.reveal a img {
-webkit-transition: all .15s linear;
-moz-transition: all .15s linear;
transition: all .15s linear; }
.reveal a:hover img {
background: rgba(255, 255, 255, 0.2);
border-color: #00008B;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.55); }
/*********************************************
* NAVIGATION CONTROLS
*********************************************/
.reveal .controls {
color: #00008B; }
/*********************************************
* PROGRESS BAR
*********************************************/
.reveal .progress {
background: rgba(0, 0, 0, 0.2);
color: #00008B; }
.reveal .progress span {
-webkit-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
-moz-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); }
/*********************************************
* PRINT BACKGROUND
*********************************************/
@media print {
.backgrounds {
background-color: #fff; } }
| {
"pile_set_name": "Github"
} |
# mall功能结构说明
## 后台管理系统
### 商品管理

### 订单管理

### 促销管理

### 内容管理

### 用户管理

## 前台商城系统
 | {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.sonatype.spice</groupId>
<artifactId>spice-parent</artifactId>
<version>12</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.sonatype.plexus</groupId>
<artifactId>plexus-cipher</artifactId>
<url>http://spice.sonatype.org/${project.artifactId}</url>
<name>Plexus Cipher: encryption/decryption Component</name>
<version>1.4</version>
<distributionManagement>
<site>
<id>sonatype.org-sites</id>
<url>${spiceSiteBaseUrl}/${project.artifactId}</url>
</site>
</distributionManagement>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-maven-plugin</artifactId>
<version>1.3.5</version>
<executions>
<execution>
<goals>
<goal>descriptor</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.4</source>
<target>1.4</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-container-default</artifactId>
<version>1.0-alpha-9-stable-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.2</version>
</dependency>
</dependencies>
<scm>
<connection>scm:svn:http://svn.sonatype.org/spice/tags/plexus-cipher-1.4</connection>
<developerConnection>scm:svn:https://svn.sonatype.org/spice/tags/plexus-cipher-1.4</developerConnection>
<url>http://svn.sonatype.org/spice/tags/plexus-cipher-1.4</url>
</scm>
</project>
| {
"pile_set_name": "Github"
} |
varying highp vec2 textureCoordinate;
precision highp float;
uniform sampler2D inputImageTexture;
uniform sampler2D curve;
void main()
{
lowp vec4 textureColor;
lowp vec4 textureColorRes;
lowp vec4 textureColorOri;
vec4 grey1Color;
vec4 layerColor;
mediump float satVal = 115.0 / 100.0;
float xCoordinate = textureCoordinate.x;
float yCoordinate = textureCoordinate.y;
highp float redCurveValue;
highp float greenCurveValue;
highp float blueCurveValue;
textureColor = texture2D( inputImageTexture, vec2(xCoordinate, yCoordinate));
textureColorRes = textureColor;
textureColorOri = textureColor;
// step1. screen blending
textureColor = 1.0 - ((1.0 - textureColorOri) * (1.0 - textureColorOri));
textureColor = (textureColor - textureColorOri) + textureColorOri;
// step2. curve
redCurveValue = texture2D(curve, vec2(textureColor.r, 0.0)).r;
greenCurveValue = texture2D(curve, vec2(textureColor.g, 0.0)).g;
blueCurveValue = texture2D(curve, vec2(textureColor.b, 0.0)).b;
// step3. saturation
highp float G = (redCurveValue + greenCurveValue + blueCurveValue);
G = G / 3.0;
redCurveValue = ((1.0 - satVal) * G + satVal * redCurveValue);
greenCurveValue = ((1.0 - satVal) * G + satVal * greenCurveValue);
blueCurveValue = ((1.0 - satVal) * G + satVal * blueCurveValue);
textureColor = vec4(redCurveValue, greenCurveValue, blueCurveValue, 1.0);
gl_FragColor = vec4(textureColor.r, textureColor.g, textureColor.b, 1.0);
}
| {
"pile_set_name": "Github"
} |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import collections
import page_sets
import re
from core import perf_benchmark
from telemetry.core import util
from telemetry.page import legacy_page_test
from telemetry.timeline import async_slice as async_slice_module
from telemetry.timeline import slice as slice_module
from telemetry.value import scalar
from measurements import timeline_controller
from metrics import speedindex
class _ServiceWorkerTimelineMetric(object):
def AddResultsOfCounters(self, process, counter_regex_string, results):
counter_filter = re.compile(counter_regex_string)
for counter_name, counter in process.counters.iteritems():
if not counter_filter.search(counter_name):
continue
total = sum(counter.totals)
# Results objects cannot contain the '.' character, so remove that here.
sanitized_counter_name = counter_name.replace('.', '_')
results.AddValue(scalar.ScalarValue(
results.current_page, sanitized_counter_name, 'count', total))
results.AddValue(scalar.ScalarValue(
results.current_page, sanitized_counter_name + '_avg', 'count',
total / float(len(counter.totals))))
def AddResultsOfEvents(
self, process, thread_regex_string, event_regex_string, results):
thread_filter = re.compile(thread_regex_string)
event_filter = re.compile(event_regex_string)
for thread in process.threads.itervalues():
thread_name = thread.name.replace('/', '_')
if not thread_filter.search(thread_name):
continue
filtered_events = []
for event in thread.IterAllEvents():
event_name = event.name.replace('.', '_')
if event_filter.search(event_name):
filtered_events.append(event)
async_events_by_name = collections.defaultdict(list)
sync_events_by_name = collections.defaultdict(list)
for event in filtered_events:
if isinstance(event, async_slice_module.AsyncSlice):
async_events_by_name[event.name].append(event)
elif isinstance(event, slice_module.Slice):
sync_events_by_name[event.name].append(event)
for event_name, event_group in async_events_by_name.iteritems():
times = [e.duration for e in event_group]
self._AddResultOfEvent(thread_name, event_name, times, results)
for event_name, event_group in sync_events_by_name.iteritems():
times = [e.self_time for e in event_group]
self._AddResultOfEvent(thread_name, event_name, times, results)
def _AddResultOfEvent(self, thread_name, event_name, times, results):
total = sum(times)
biggest_jank = max(times)
# Results objects cannot contain the '.' character, so remove that here.
sanitized_event_name = event_name.replace('.', '_')
full_name = thread_name + '|' + sanitized_event_name
results.AddValue(scalar.ScalarValue(
results.current_page, full_name, 'ms', total))
results.AddValue(scalar.ScalarValue(
results.current_page, full_name + '_max', 'ms', biggest_jank))
results.AddValue(scalar.ScalarValue(
results.current_page, full_name + '_avg', 'ms', total / len(times)))
class _ServiceWorkerMeasurement(legacy_page_test.LegacyPageTest):
"""Measure Speed Index and TRACE_EVENTs"""
def __init__(self):
super(_ServiceWorkerMeasurement, self).__init__()
self._timeline_controller = timeline_controller.TimelineController()
self._speed_index = speedindex.SpeedIndexMetric()
self._page_open_times = collections.defaultdict(int)
def DidRunPage(self, platform):
if platform.tracing_controller.is_tracing_running:
platform.tracing_controller.StopTracing()
def WillNavigateToPage(self, page, tab):
self._timeline_controller.SetUp(page, tab)
self._timeline_controller.Start(tab)
self._speed_index.Start(page, tab)
def ValidateAndMeasurePage(self, page, tab, results):
# timeline_controller requires creation of at least a single interaction
# record. service_worker should be refactored to follow the
# timeline_based_measurement or it should not re-use timeline_controller
# logic for start & stop tracing.
with tab.action_runner.CreateInteraction('_DummyInteraction'):
pass
tab.WaitForDocumentReadyStateToBeComplete(40)
self._timeline_controller.Stop(tab, results)
# Retrieve TRACE_EVENTs
timeline_metric = _ServiceWorkerTimelineMetric()
browser_process = self._timeline_controller.model.browser_process
filter_text = '(RegisterServiceWorker|'\
'UnregisterServiceWorker|'\
'ProcessAllocate|'\
'FindRegistrationForDocument|'\
'DispatchFetchEvent)'
timeline_metric.AddResultsOfEvents(
browser_process, 'IOThread', filter_text, results)
# Record Speed Index
def SpeedIndexIsFinished():
return self._speed_index.IsFinished(tab)
util.WaitFor(SpeedIndexIsFinished, 60)
self._speed_index.Stop(page, tab)
# Distinguish the first and second load from the subsequent loads
url = str(page)
chart_prefix = 'page_load'
self._page_open_times[url] += 1
if self._page_open_times[url] == 1:
chart_prefix += '_1st'
elif self._page_open_times[url] == 2:
chart_prefix += '_2nd'
else:
chart_prefix += '_later'
self._speed_index.AddResults(tab, results, chart_prefix)
class _ServiceWorkerMicroBenchmarkMeasurement(legacy_page_test.LegacyPageTest):
"""Record results reported by the JS microbenchmark."""
def __init__(self):
super(_ServiceWorkerMicroBenchmarkMeasurement, self).__init__()
def ValidateAndMeasurePage(self, page, tab, results):
del page # unused
tab.WaitForJavaScriptExpression('window.done', 40)
json = tab.EvaluateJavaScript('window.results || {}')
for key, value in json.iteritems():
results.AddValue(scalar.ScalarValue(
results.current_page, key, value['units'], value['value']))
class ServiceWorkerPerfTest(perf_benchmark.PerfBenchmark):
"""Performance test of pages using ServiceWorker.
The page set contains pages like Trained to Thrill and svgomg.
Execution time of these pages will be shown as Speed Index, and TRACE_EVENTs
are subsidiary information to understand performance regressions in more
detail.
"""
test = _ServiceWorkerMeasurement
page_set = page_sets.ServiceWorkerPageSet
@classmethod
def Name(cls):
return 'service_worker.service_worker'
class ServiceWorkerMicroBenchmarkPerfTest(perf_benchmark.PerfBenchmark):
"""This test is a microbenchmark of service worker.
The page set is a benchmark page that generates many concurrent requests
handled by a service worker that does respondWith(new Response()). The test
result is the response times.
"""
test = _ServiceWorkerMicroBenchmarkMeasurement
page_set = page_sets.ServiceWorkerMicroBenchmarkPageSet
@classmethod
def Name(cls):
return 'service_worker.service_worker_micro_benchmark'
@classmethod
def ShouldDisable(cls, possible_browser): # http://crbug.com/597656
return (possible_browser.browser_type == 'reference' and
possible_browser.platform.GetDeviceTypeName() == 'Nexus 5X')
| {
"pile_set_name": "Github"
} |
{include file="overall_header.tpl"}
<form action="" method="post">
<input type="hidden" name="opt_save" value="1">
<table width="70%" cellpadding="2" cellspacing="2">
<tr>
<th colspan="2">{$se_server_parameters}</th>
<th>(?)</th>
</tr><tr>
<td>{$ch_channelname}</td>
<td><input name="chat_channelname" value="{$chat_channelname}" type="text"></td>
<td> </td>
</tr><tr>
<td>{$ch_botname}</td>
<td><input name="chat_botname" value="{$chat_botname}" type="text"></td>
<td> </td>
</tr><tr>
<td>{$ch_nickchange}</td>
<td><input name="chat_nickchange"{if $chat_nickchange == '1'} checked="checked"{/if} type="checkbox"></td>
<td> </td>
</tr><tr>
<td>{$ch_logmessage}</td>
<td><input name="chat_logmessage"{if $chat_logmessage == '1'} checked="checked"{/if} type="checkbox"></td>
<td> </td>
</tr><tr>
<td>{$ch_allowmes}</td>
<td><input name="chat_allowmes"{if $chat_allowmes == '1'} checked="checked"{/if} type="checkbox"></td>
<td> </td>
</tr><tr>
<td>{$ch_allowchan}</td>
<td><input name="chat_allowchan"{if $chat_allowchan == '1'} checked="checked"{/if} type="checkbox"></td>
<td> </td>
</tr><tr>
<td>{$ch_closed}</td>
<td><input name="chat_closed"{if $chat_closed == '1'} checked="checked"{/if} type="checkbox"></td>
<td> </td>
</tr>
<tr>
<td colspan="3"><input value="{$se_save_parameters}" type="submit"></td>
</tr>
</table>
</form>
{include file="overall_footer.tpl"} | {
"pile_set_name": "Github"
} |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
#ifndef __PROCESS_PID_HPP__
#define __PROCESS_PID_HPP__
#include <stdint.h>
#include <iosfwd>
#include <string>
#include <boost/functional/hash.hpp>
#include <process/address.hpp>
#include <stout/ip.hpp>
namespace process {
// Forward declaration to break cyclic dependencies.
class ProcessBase;
/**
* An "untyped" `PID`, used to encapsulate the process ID for
* lower-layer abstractions (eg, when receiving incoming requests)
* in the dispatching mechanism.
*
* @see process::PID
*/
struct UPID
{
UPID() = default;
UPID(const UPID& that) = default;
UPID(UPID&& that) = default;
UPID(const char* id_, const net::IP& ip_, uint16_t port_)
: id(id_), address(ip_, port_) { resolve(); }
UPID(const char* id_, const network::inet::Address& address_)
: id(id_), address(address_) { resolve(); }
UPID(const std::string& id_, const net::IP& ip_, uint16_t port_)
: id(id_), address(ip_, port_) { resolve(); }
UPID(const std::string& id_, const network::inet::Address& address_)
: id(id_), address(address_) { resolve(); }
/*implicit*/ UPID(const char* s);
/*implicit*/ UPID(const std::string& s);
/*implicit*/ UPID(const ProcessBase& process);
UPID& operator=(const UPID& that) = default;
UPID& operator=(UPID&& that) = default;
operator std::string() const;
operator bool() const
{
return id != "" && !address.ip.isAny() && address.port != 0;
}
bool operator!() const // NOLINT(whitespace/operators)
{
return id == "" && address.ip.isAny() && address.port == 0;
}
bool operator<(const UPID& that) const
{
if (address == that.address) {
return id < that.id;
} else {
return address < that.address;
}
}
bool operator==(const UPID& that) const
{
return (id == that.id && address == that.address);
}
bool operator!=(const UPID& that) const
{
return !(*this == that);
}
// Attempts to resolve and cache a weak pointer to the ProcessBase
// to which this UPID refers.
void resolve();
// TODO(benh): store all of the members of UPID behind a
// copy-on-write implementation because UPID is often copied but
// rarely written which means we could optimize performance by not
// making so many copies.
// A copy-on-write string for performance.
//
// TODO(benh): Factor this out into a generic copy-on-write string.
struct ID
{
static const std::string EMPTY;
ID() = default;
ID(const std::string& s)
: id(std::make_shared<std::string>(s)) {}
ID(std::string&& s)
: id(std::make_shared<std::string>(std::move(s))) {}
ID& operator=(std::string&& that)
{
id = std::make_shared<std::string>(std::move(that));
return *this;
}
bool operator==(const std::string& that) const
{
if (!id) {
return EMPTY == that;
}
return *id == that;
}
bool operator==(const char* that) const
{
if (!id) {
return EMPTY == that;
}
return *id == that;
}
bool operator!=(const std::string& that) const
{
return !(*this == that);
}
bool operator<(const std::string& that) const
{
if (!id) {
return EMPTY < that;
}
return *id < that;
}
operator const std::string&() const
{
if (!id) {
return EMPTY;
}
return *id;
}
private:
std::shared_ptr<std::string> id;
} id;
// TODO(asridharan): Ideally, the following `address` field should be of
// type `network::Address` so that the default address of the PID
// could be a unix domain socket or an IPv4/v6 address. This change
// however is disruptive at this point and should be done after we have
// introduced support for unix domain and IPv6 sockets into
// `libprocess`.
network::inet::Address address = network::inet4::Address::ANY_ANY();
// TODO(asridharan): Currently we are introducing only an `Optional`
// IPv6 address in the following `addresses` structure. This will
// help us initiate some basic IPv6 support for the
// `DockerContainerizer`. However, going forward, once we start
// supporting unix domain sockets and IPv4/IPv6 socket in
// `libprocess` we will add the following fields to this structure.
//
// Option<network::unix::Address> unix;
// Option<network::inet4::Address> v4;
//
// With the introduction of the above fields `libprocess` PID will
// be able to support unix, IPv4 and IPv6 sockets simultaneously.
struct
{
Option<network::inet6::Address> v6;
} addresses = {None()};
// The hostname that was used to create this UPID, if any. This is useful
// both for display purposes and when making outgoing connections on a TLS
// socket, where the name recorded here can be used for hostname validation
// checks against the X509 certificate presented by the server.
//
// NOTE: In the context of TLS hostname validation, this can also be set
// manually to override the result of DNS resolution before trying to
// `connect()` to this UPID, similar to `curl --resolve`.
Option<std::string> host;
protected:
friend class ProcessBase;
friend class ProcessManager;
// A weak pointer to the actual process used to optimize enqueuing
// events without having to go through a shared lock in the
// `ProcessManager`. This is `None` if someone creates a UPID and
// doesn't call `resolve()` or if `resolve()` doesn't find a valid
// process (i.e., the process hasn't started or has terminated).
Option<std::weak_ptr<ProcessBase*>> reference = None();
};
inline std::ostream& operator<<(std::ostream& stream, const UPID::ID& id)
{
const std::string& s = id;
return stream << s;
}
inline bool operator==(const std::string& s, const UPID::ID& id)
{
return id == s;
}
inline bool operator!=(const std::string& s, const UPID::ID& id)
{
return !(s == id);
}
inline std::string operator+(const UPID::ID& id, const std::string& s)
{
return (const std::string&) id + s;
}
inline std::string operator+(const UPID::ID& id, std::string&& s)
{
return (const std::string&) id + std::move(s);
}
inline std::string operator+(const std::string& s, const UPID::ID& id)
{
return s + (const std::string&) id;
}
inline std::string operator+(std::string&& s, const UPID::ID& id)
{
return std::move(s) + (const std::string&) id;
}
/**
* A "process identifier" used to uniquely identify a process when
* dispatching messages.
*
* Typed with the actual process class's type, which must be
* derived from `process::ProcessBase`.
*
* Use it like this:
*
* using namespace process;
*
* class SimpleProcess : public Process<SimpleProcess>
* {
* // ...
* };
*
*
* SimpleProcess process;
* PID<SimpleProcess> pid = spawn(process);
*
* // ...
*
* dispatchpid, &SimpleProcess::method, "argument");
*
* @see process::ProcessBase
*/
template <typename T = ProcessBase>
struct PID : UPID
{
// Need to declare PID<U> as a friend in order to write `reference`.
template <typename U>
friend struct PID;
PID() : UPID() {}
/*implicit*/ PID(const T* t) : UPID(static_cast<const ProcessBase&>(*t)) {}
/*implicit*/ PID(const T& t) : UPID(static_cast<const ProcessBase&>(t)) {}
template <typename Base>
operator PID<Base>() const
{
// Only allow upcasts!
T* t = nullptr;
Base* base = t;
(void)base; // Eliminate unused base warning.
PID<Base> pid;
pid.id = id;
pid.address = address;
pid.addresses = addresses;
pid.reference = reference;
return pid;
}
};
// Outputing UPIDs and generating UPIDs using streams.
std::ostream& operator<<(std::ostream&, const UPID&);
std::istream& operator>>(std::istream&, UPID&);
} // namespace process {
namespace std {
template <>
struct hash<process::UPID>
{
typedef size_t result_type;
typedef process::UPID argument_type;
result_type operator()(const argument_type& upid) const
{
size_t seed = 0;
boost::hash_combine(seed, (const std::string&) upid.id);
boost::hash_combine(seed, std::hash<net::IP>()(upid.address.ip));
boost::hash_combine(seed, upid.address.port);
return seed;
}
};
} // namespace std {
#endif // __PROCESS_PID_HPP__
| {
"pile_set_name": "Github"
} |
// +build !darwin
package dbus
import (
"bytes"
"errors"
"os/exec"
)
func sessionBusPlatform() (*Conn, error) {
cmd := exec.Command("dbus-launch")
b, err := cmd.CombinedOutput()
if err != nil {
return nil, err
}
i := bytes.IndexByte(b, '=')
j := bytes.IndexByte(b, '\n')
if i == -1 || j == -1 {
return nil, errors.New("dbus: couldn't determine address of session bus")
}
return Dial(string(b[i+1 : j]))
}
| {
"pile_set_name": "Github"
} |
// ------------------------------------------------------------------------------
// Copyright (c) 2015 Microsoft Corporation
//
// 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.
// ------------------------------------------------------------------------------
package com.onedrive.sdk.extensions;
import com.onedrive.sdk.concurrency.*;
import com.onedrive.sdk.core.*;
import com.onedrive.sdk.extensions.*;
import com.onedrive.sdk.http.*;
import com.onedrive.sdk.generated.*;
import com.onedrive.sdk.options.*;
import com.onedrive.sdk.serializer.*;
import java.util.*;
import com.onedrive.sdk.authentication.*;
import com.onedrive.sdk.logger.*;
import android.app.Activity;
// This file is available for extending, afterwards please submit a pull request.
/**
* The class for the One Drive Client.
*/
public class OneDriveClient extends BaseOneDriveClient implements IOneDriveClient {
/**
* Restricted constructor
*/
protected OneDriveClient() {
}
/**
* Gets a request builder for the default drive
* @return The request builder
*/
@Override
public IDriveRequestBuilder getDrive() {
return new DriveRequestBuilder(getServiceRoot() + "/drive", this, null);
}
/**
* The builder for this OneDriveClient
*/
public static class Builder {
/**
* The client under construction
*/
private final OneDriveClient mClient = new OneDriveClient();
/**
* Sets the serializer
* @param serializer The serializer
* @return the instance of this builder
*/
public Builder serializer(final ISerializer serializer) {
mClient.setSerializer(serializer);
return this;
}
/**
* Sets the httpProvider
* @param httpProvider The httpProvider
* @return the instance of this builder
*/
public Builder httpProvider(final IHttpProvider httpProvider) {
mClient.setHttpProvider(httpProvider);
return this;
}
/**
* Sets the authenticator
* @param authenticator The authenticator
* @return the instance of this builder
*/
public Builder authenticator(final IAuthenticator authenticator) {
mClient.setAuthenticator(authenticator);
return this;
}
/**
* Sets the executors
* @param executors The executors
* @return the instance of this builder
*/
public Builder executors(final IExecutors executors) {
mClient.setExecutors(executors);
return this;
}
/**
* Sets the logger
* @param logger The logger
* @return the instance of this builder
*/
private Builder logger(final ILogger logger) {
mClient.setLogger(logger);
return this;
}
/**
* Set this builder based on the client configuration
* @param clientConfig The client configuration
* @return the instance of this builder
*/
public Builder fromConfig(final IClientConfig clientConfig) {
return this.authenticator(clientConfig.getAuthenticator())
.executors(clientConfig.getExecutors())
.httpProvider(clientConfig.getHttpProvider())
.logger(clientConfig.getLogger())
.serializer(clientConfig.getSerializer());
}
/**
* Login a user and then returns the OneDriveClient asynchronously
* @param activity The activity the UI should be from
* @param callback The callback when the client has been built
*/
public void loginAndBuildClient(final Activity activity, final ICallback<IOneDriveClient> callback) {
mClient.validate();
mClient.getExecutors().performOnBackground(new Runnable() {
@Override
public void run() {
final IExecutors executors = mClient.getExecutors();
try {
executors.performOnForeground(loginAndBuildClient(activity), callback);
} catch (final ClientException e) {
executors.performOnForeground(e, callback);
}
}
});
}
/**
* Login a user and then returns the OneDriveClient
* @param activity The activity the UI should be from
* @throws ClientException if there was an exception creating the client
*/
private IOneDriveClient loginAndBuildClient(final Activity activity) throws ClientException {
mClient.validate();
mClient.getAuthenticator()
.init(mClient.getExecutors(), mClient.getHttpProvider(), activity, mClient.getLogger());
IAccountInfo silentAccountInfo = null;
try {
silentAccountInfo = mClient.getAuthenticator().loginSilent();
} catch (final Exception ignored) {
}
if (silentAccountInfo == null
&& mClient.getAuthenticator().login(null) == null) {
throw new ClientAuthenticatorException("Unable to authenticate silently or interactively",
OneDriveErrorCodes.AuthenticationFailure);
}
return mClient;
}
}
}
| {
"pile_set_name": "Github"
} |
html {
font-size: 64px;
}
li:nth-child(even) {
color: red;
} | {
"pile_set_name": "Github"
} |
<snippet>
<content><![CDATA[getMinimumValue()]]></content>
<tabTrigger>getMinimumValue()</tabTrigger>
<scope>source.lua</scope>
<description>ControlPotentiometer</description>
</snippet>
| {
"pile_set_name": "Github"
} |
/*
* /MathJax/jax/output/HTML-CSS/fonts/TeX/Main/Bold/MiscMathSymbolsA.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* 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.
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["MathJax_Main-bold"],{10216:[750,249,447,127,382],10217:[750,249,447,64,319]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/Main/Bold/MiscMathSymbolsA.js");
| {
"pile_set_name": "Github"
} |
<?php
namespace React\Promise;
class FunctionReduceTest extends TestCase
{
protected function plus()
{
return function ($sum, $val) {
return $sum + $val;
};
}
protected function append()
{
return function ($sum, $val) {
return $sum . $val;
};
}
/** @test */
public function shouldReduceValuesWithoutInitialValue()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(6));
reduce(
[1, 2, 3],
$this->plus()
)->then($mock);
}
/** @test */
public function shouldReduceValuesWithInitialValue()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(7));
reduce(
[1, 2, 3],
$this->plus(),
1
)->then($mock);
}
/** @test */
public function shouldReduceValuesWithInitialPromise()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(7));
reduce(
[1, 2, 3],
$this->plus(),
resolve(1)
)->then($mock);
}
/** @test */
public function shouldReducePromisedValuesWithoutInitialValue()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(6));
reduce(
[resolve(1), resolve(2), resolve(3)],
$this->plus()
)->then($mock);
}
/** @test */
public function shouldReducePromisedValuesWithInitialValue()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(7));
reduce(
[resolve(1), resolve(2), resolve(3)],
$this->plus(),
1
)->then($mock);
}
/** @test */
public function shouldReducePromisedValuesWithInitialPromise()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(7));
reduce(
[resolve(1), resolve(2), resolve(3)],
$this->plus(),
resolve(1)
)->then($mock);
}
/** @test */
public function shouldReduceEmptyInputWithInitialValue()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(1));
reduce(
[],
$this->plus(),
1
)->then($mock);
}
/** @test */
public function shouldReduceEmptyInputWithInitialPromise()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(1));
reduce(
[],
$this->plus(),
resolve(1)
)->then($mock);
}
/** @test */
public function shouldRejectWhenInputContainsRejection()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(2));
reduce(
[resolve(1), reject(2), resolve(3)],
$this->plus(),
resolve(1)
)->then($this->expectCallableNever(), $mock);
}
/** @test */
public function shouldResolveWithNullWhenInputIsEmptyAndNoInitialValueOrPromiseProvided()
{
// Note: this is different from when.js's behavior!
// In when.reduce(), this rejects with a TypeError exception (following
// JavaScript's [].reduce behavior.
// We're following PHP's array_reduce behavior and resolve with NULL.
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(null));
reduce(
[],
$this->plus()
)->then($mock);
}
/** @test */
public function shouldAllowSparseArrayInputWithoutInitialValue()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(3));
reduce(
[null, null, 1, null, 1, 1],
$this->plus()
)->then($mock);
}
/** @test */
public function shouldAllowSparseArrayInputWithInitialValue()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(4));
reduce(
[null, null, 1, null, 1, 1],
$this->plus(),
1
)->then($mock);
}
/** @test */
public function shouldReduceInInputOrder()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo('123'));
reduce(
[1, 2, 3],
$this->append(),
''
)->then($mock);
}
/** @test */
public function shouldAcceptAPromiseForAnArray()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo('123'));
reduce(
resolve([1, 2, 3]),
$this->append(),
''
)->then($mock);
}
/** @test */
public function shouldResolveToInitialValueWhenInputPromiseDoesNotResolveToAnArray()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(1));
reduce(
resolve(1),
$this->plus(),
1
)->then($mock);
}
/** @test */
public function shouldProvideCorrectBasisValue()
{
$insertIntoArray = function ($arr, $val, $i) {
$arr[$i] = $val;
return $arr;
};
$d1 = new Deferred();
$d2 = new Deferred();
$d3 = new Deferred();
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo([1, 2, 3]));
reduce(
[$d1->promise(), $d2->promise(), $d3->promise()],
$insertIntoArray,
[]
)->then($mock);
$d3->resolve(3);
$d1->resolve(1);
$d2->resolve(2);
}
/** @test */
public function shouldRejectWhenInputPromiseRejects()
{
$mock = $this->createCallableMock();
$mock
->expects($this->once())
->method('__invoke')
->with($this->identicalTo(null));
reduce(
reject(),
$this->plus(),
1
)->then($this->expectCallableNever(), $mock);
}
/** @test */
public function shouldCancelInputPromise()
{
$mock = $this
->getMockBuilder('React\Promise\CancellablePromiseInterface')
->getMock();
$mock
->expects($this->once())
->method('cancel');
reduce(
$mock,
$this->plus(),
1
)->cancel();
}
/** @test */
public function shouldCancelInputArrayPromises()
{
$mock1 = $this
->getMockBuilder('React\Promise\CancellablePromiseInterface')
->getMock();
$mock1
->expects($this->once())
->method('cancel');
$mock2 = $this
->getMockBuilder('React\Promise\CancellablePromiseInterface')
->getMock();
$mock2
->expects($this->once())
->method('cancel');
reduce(
[$mock1, $mock2],
$this->plus(),
1
)->cancel();
}
}
| {
"pile_set_name": "Github"
} |
target datalayout = "e-m:e-p:32:32-i64:64-n32:64-S128"
target triple = "wasm32-unknown-unknown"
declare void @llvm.wasm.throw(i32, i8*)
define void @bar(i8* %p) {
call void @llvm.wasm.throw(i32 0, i8* %p)
ret void
}
| {
"pile_set_name": "Github"
} |
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build go1.7
package unix_test
import (
"fmt"
"testing"
"golang.org/x/sys/unix"
)
func TestDevices(t *testing.T) {
testCases := []struct {
path string
major uint32
minor uint32
}{
// Most of the device major/minor numbers on Darwin are
// dynamically generated by devfs. These are some well-known
// static numbers.
{"/dev/ttyp0", 4, 0},
{"/dev/ttys0", 4, 48},
{"/dev/ptyp0", 5, 0},
{"/dev/ptyr0", 5, 32},
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) {
var stat unix.Stat_t
err := unix.Stat(tc.path, &stat)
if err != nil {
t.Errorf("failed to stat device: %v", err)
return
}
dev := uint64(stat.Rdev)
if unix.Major(dev) != tc.major {
t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major)
}
if unix.Minor(dev) != tc.minor {
t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor)
}
if unix.Mkdev(tc.major, tc.minor) != dev {
t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev)
}
})
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2013-2020 Cinchapi Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cinchapi.concourse.server.storage.cache;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.concurrent.NotThreadSafe;
import com.cinchapi.common.base.CheckedExceptions;
import com.cinchapi.concourse.server.io.ByteBufferInputStream;
import com.cinchapi.concourse.server.io.ByteSink;
import com.cinchapi.concourse.server.io.Byteable;
import com.cinchapi.concourse.server.io.Composite;
import com.cinchapi.concourse.util.Serializables;
/**
* A wrapper around a {@link com.google.common.hash.BloomFilter} with methods
* that make it easier to add one or more {@link Byteable} objects at a time
* while also abstracting away the notion of funnels, etc.
* </p>
*
* @author Jeff Nelson
*/
@NotThreadSafe
public class BloomFilter implements Byteable {
/**
* Create a new BloomFilter with enough capacity for
* {@code expectedInsertions} but cannot be synced to disk.
* <p>
* Note that overflowing a BloomFilter with significantly more elements than
* specified, will result in its saturation, and a sharp deterioration of
* its false positive probability (source:
* {@link BloomFilter#reserve(com.google.common.hash.Funnel, int)})
* <p>
*
* @param expectedInsertions
* @return the BloomFilter
*/
public static BloomFilter create(int expectedInsertions) {
return new BloomFilter(expectedInsertions);
}
/**
* Load an existing {@link BloomFilter} from the {@code bytes}.
*
* @param bytes
* @return the loaded {@link BloomFilter}
*/
public static BloomFilter load(ByteBuffer bytes) {
return new BloomFilter(bytes);
}
/**
* The wrapped bloom filter. This is where the data is actually stored.
*/
private final com.google.common.hash.BloomFilter<Composite> source;
/**
* Track if this {@link BloomFilter} was upgraded when being
* {@link BloomFilter(ByteBuffer) loaded}.
*/
private final boolean upgraded;
/**
* Construct a new instance.
*
* @param bytes
*/
@SuppressWarnings({ "unchecked" })
private BloomFilter(ByteBuffer bytes) {
try {
final AtomicBoolean upgraded = new AtomicBoolean(false);
ObjectInput input = new ObjectInputStream(
new BufferedInputStream(new ByteBufferInputStream(bytes))) {
// In v0.3.0 the ByteableFunnel class was moved to a different
// package, so we must translate any old data that exists.
@Override
protected ObjectStreamClass readClassDescriptor()
throws IOException, ClassNotFoundException {
ObjectStreamClass read = super.readClassDescriptor();
if(read.getName().equals(
"com.cinchapi.concourse.server.storage.ByteableFunnel")) {
upgraded.set(true);
return ObjectStreamClass.lookup(ByteableFunnel.class);
}
return read;
}
};
this.source = (com.google.common.hash.BloomFilter<Composite>) input
.readObject();
this.upgraded = upgraded.get();
input.close();
}
catch (IOException e) {
throw CheckedExceptions.wrapAsRuntimeException(e);
}
catch (ClassNotFoundException e) {
throw CheckedExceptions.wrapAsRuntimeException(e);
}
}
/**
* Construct a new instance.
*
* @param expectedInsertions
*/
private BloomFilter(int expectedInsertions) {
this.source = com.google.common.hash.BloomFilter
.create(ByteableFunnel.INSTANCE, expectedInsertions); // uses 3%
// false
// positive
// probability
this.upgraded = false;
}
@Override
public void copyTo(ByteSink sink) {
ByteBuffer bytes = getBytes();
sink.put(bytes);
}
@Override
public boolean equals(Object obj) {
if(obj instanceof BloomFilter) {
BloomFilter other = (BloomFilter) obj;
return source.equals(other.source);
}
else {
return false;
}
}
@Override
public ByteBuffer getBytes() {
return Serializables.getBytes(source);
}
@Override
public int hashCode() {
return source.hashCode();
}
/**
* Return {@code true} if this {@link BloomFilter} was upgraded and should
* have its {@link #getBytes() bytes} rewritten to any underlying data
* store.
*
* @return {@code true} if this {@link BloomFilter} was upgraded
*/
public boolean isUpgraded() {
return upgraded;
}
/**
* Return true if an element made up of {@code byteables} might have been
* put in this filter or false if this is definitely not the case.
*
* @param byteables
* @return {@code true} if {@code byteables} might exist
*/
public boolean mightContain(Byteable... byteables) {
Composite composite = Composite.create(byteables);
return mightContain(composite);
}
/**
* Return true if the {@code composite} <strong>might</strong> have been put
* in this filter or false if this is definitely not the case.
*
* @param composite
* @return {@code true} if {@code composite} might exist
*/
public boolean mightContain(Composite composite) {
return source.mightContain(composite);
}
/**
* Return true if an element made up of a cached copy of the
* {@code byteables} might have been put in this filter or false if this is
* definitely not the case.
* <p>
* Since caching is involved, this method is more prone to false positives
* than the {@link #mightContain(Byteable...)} alternative, but it will
* never return false negatives as long as the bits were added with the
* {@code #putCached(Byteable...)} method.
* </p>
*
* @param byteables
* @return {@code true} if {@code byteables} might exist
*/
public boolean mightContainCached(Byteable... byteables) {
Composite composite = Composite.createCached(byteables);
return mightContain(composite);
}
/**
* <p>
* <strong>Copied from {@link BloomFilter#put(Object)}.</strong>
* </p>
* Puts {@link byteables} into this BloomFilter as a single element.
* Ensures that subsequent invocations of {@link #mightContain(Byteable...)}
* with the same elements will always return true.
*
* @param byteables
* @return {@code true} if the filter's bits changed as a result of this
* operation. If the bits changed, this is definitely the first time
* {@code byteables} have been added to the filter. If the bits
* haven't changed, this might be the first time they have been
* added. Note that put(t) always returns the opposite result to
* what mightContain(t) would have returned at the time it is
* called.
*/
public boolean put(Byteable... byteables) {
return put(Composite.create(byteables));
}
/**
* <p>
* <strong>Copied from {@link BloomFilter#put(Object)}.</strong>
* </p>
* Puts the {@link composite} item into this BloomFilter such that
* subsequent invocations of {@link #mightContain(Composite)}
* with the same {@link Composite} will always return true.
*
* @param composite
* @return {@code true} if the filter's bits changed as a result of this
* operation. If the bits changed, this is definitely the first time
* {@code byteables} have been added to the filter. If the bits
* haven't changed, this might be the first time they have been
* added. Note that put(t) always returns the opposite result to
* what mightContain(t) would have returned at the time it is
* called.
*/
public boolean put(Composite composite) {
return source.put(composite);
}
/**
* <p>
* <strong>Copied from {@link BloomFilter#put(Object)}.</strong>
* </p>
* Puts {@link byteables} into this BloomFilter as a single element with
* support for caching to ensure that subsequent invocations of
* {@link #mightContainCached(Byteable...)} with the same elements will
* always return true.
*
* @param byteables
* @return {@code true} if the filter's bits changed as a result of this
* operation. If the bits changed, this is definitely the first time
* {@code byteables} have been added to the filter. If the bits
* haven't changed, this might be the first time they have been
* added. Note that put(t) always returns the opposite result to
* what mightContain(t) would have returned at the time it is
* called.
*/
public boolean putCached(Byteable... byteables) {
return put(Composite.createCached(byteables));
}
@Override
public int size() {
return getBytes().capacity();
}
/**
* Return the underlying source for this {@link BloomFilter}.
*
* @return the source
*/
com.google.common.hash.BloomFilter<Composite> source() {
return source;
}
}
| {
"pile_set_name": "Github"
} |
/*
de-DE.h - localization for German - Germany for Tasmota
Copyright (C) 2020 VinceMasuka
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _LANGUAGE_DE_DE_H_
#define _LANGUAGE_DE_DE_H_
/*************************** ATTENTION *******************************\
*
* Due to memory constraints only UTF-8 is supported.
* To save code space keep text as short as possible.
* Time and Date provided by SDK can not be localized (yet).
* Use online command StateText to translate ON, OFF, HOLD and TOGGLE.
* Use online command Prefix to translate cmnd, stat and tele.
*
* Updated until v8.4.0.3
\*********************************************************************/
//#define LANGUAGE_MODULE_NAME // Enable to display "Module Generic" (ie Spanish), Disable to display "Generic Module" (ie English)
#define LANGUAGE_LCID 1031
// HTML (ISO 639-1) Language Code
#define D_HTML_LANGUAGE "de"
// "2017-03-07T11:08:02" - ISO8601:2004
#define D_YEAR_MONTH_SEPARATOR "."
#define D_MONTH_DAY_SEPARATOR "."
#define D_DATE_TIME_SEPARATOR " "
#define D_HOUR_MINUTE_SEPARATOR ":"
#define D_MINUTE_SECOND_SEPARATOR ":"
#define D_DAY3LIST "So Mo Di Mi Do Fr Sa "
#define D_MONTH3LIST "JanFebMärAprMaiJunJulAugSepOktNovDez"
// Non JSON decimal separator
#define D_DECIMAL_SEPARATOR "."
// Common
#define D_ADMIN "Admin"
#define D_AIR_QUALITY "Luftqualität"
#define D_AP "AP" // Access Point
#define D_AS "als"
#define D_AUTO "AUTO"
#define D_BATT "Batt" // Short for Battery
#define D_BLINK "Blinken"
#define D_BLINKOFF "BlinkenAus"
#define D_BOOT_COUNT "Anzahl Startvorgänge"
#define D_BRIGHTLIGHT "hell"
#define D_BSSID "BSSId"
#define D_BUTTON "Knopf"
#define D_BY "von" // Written by me
#define D_BYTES "Bytes"
#define D_CELSIUS "Celsius"
#define D_CHANNEL "Kanal"
#define D_CO2 "CO₂"
#define D_CODE "code" // Button code
#define D_COLDLIGHT "kalt"
#define D_COMMAND "Befehl"
#define D_CONNECTED "verbunden"
#define D_CORS_DOMAIN "CORS Domain"
#define D_COUNT "zählen"
#define D_COUNTER "Zähler"
#define D_CT_POWER "CT Power"
#define D_CURRENT "Strom" // As in Voltage and Current
#define D_DATA "Daten"
#define D_DARKLIGHT "dunkel"
#define D_DEBUG "debug"
#define D_DEWPOINT "Taupunkt"
#define D_DISABLED "deaktiviert"
#define D_DISTANCE "Abstand"
#define D_DNS_SERVER "DNS-Server"
#define D_DONE "erledigt"
#define D_DST_TIME "DST"
#define D_ECO2 "eCO₂"
#define D_EMULATION "Emulation"
#define D_ENABLED "aktiviert"
#define D_ERASE "löschen"
#define D_ERROR "Fehler"
#define D_FAHRENHEIT "Fahrenheit"
#define D_FAILED "fehlgeschlagen"
#define D_FALLBACK "Fallback"
#define D_FALLBACK_TOPIC "Fallback-Topic"
#define D_FALSE "falsch"
#define D_FILE "Datei"
#define D_FLOW_RATE "Durchflussmenge"
#define D_FREE_MEMORY "Freier Arbeitsspeicher"
#define D_PSR_MAX_MEMORY "PS-RAM Speicher"
#define D_PSR_FREE_MEMORY "PS-RAM freier Speicher"
#define D_FREQUENCY "Frequenz"
#define D_GAS "Gas"
#define D_GATEWAY "Gateway"
#define D_GROUP "Gruppe"
#define D_HOST "Host"
#define D_HOSTNAME "Hostname"
#define D_HUMIDITY "Feuchtigkeit"
#define D_ILLUMINANCE "Beleuchtungsstärke"
#define D_IMMEDIATE "direkt" // Button immediate
#define D_INDEX "Index"
#define D_INFO "Info"
#define D_INFRARED "Infrarot"
#define D_INITIALIZED "initialisiert"
#define D_IP_ADDRESS "IP-Adresse"
#define D_LIGHT "Licht"
#define D_LWT "LWT"
#define D_LQI "LQI" // Zigbee Link Quality Index
#define D_MODULE "Modul"
#define D_MOISTURE "Feuchtigkeit"
#define D_MQTT "MQTT"
#define D_MULTI_PRESS "Mehrfachdruck"
#define D_NOISE "Lautstärke"
#define D_NONE "keine"
#define D_OFF "aus"
#define D_OFFLINE "Offline"
#define D_OK "OK"
#define D_ON "an"
#define D_ONLINE "Online"
#define D_PASSWORD "Passwort"
#define D_PORT "Port"
#define D_POWER_FACTOR "Leistungsfaktor"
#define D_POWERUSAGE "Leistung"
#define D_POWERUSAGE_ACTIVE "Wirkleistung"
#define D_POWERUSAGE_APPARENT "Scheinleistung"
#define D_POWERUSAGE_REACTIVE "Blindleistung"
#define D_PRESSURE "Luftdruck"
#define D_PRESSUREATSEALEVEL "Luftdruck auf Meereshöhe"
#define D_PROGRAM_FLASH_SIZE "Ges. Flash Speicher"
#define D_PROGRAM_SIZE "Ben. Flash Speicher"
#define D_PROJECT "Projekt"
#define D_RAIN "Regen"
#define D_RANGE "Bereich"
#define D_RECEIVED "erhalten"
#define D_RESTART "Neustart"
#define D_RESTARTING "starte neu"
#define D_RESTART_REASON "Grund für Neustart"
#define D_RESTORE "Wiederherstellung"
#define D_RETAINED "beibehalten"
#define D_RULE "Regel"
#define D_SAVE "Speichern"
#define D_SENSOR "Sensor"
#define D_SSID "SSID"
#define D_START "Start"
#define D_STD_TIME "STD"
#define D_STOP "Stop"
#define D_SUBNET_MASK "Subnetzmaske"
#define D_SUBSCRIBE_TO "abonniere"
#define D_UNSUBSCRIBE_FROM "löse abo. von"
#define D_SUCCESSFUL "erfolgreich"
#define D_SUNRISE "Sonnenaufgang"
#define D_SUNSET "Sonnenuntergang"
#define D_TEMPERATURE "Temperatur"
#define D_TO "zu"
#define D_TOGGLE "An/Aus"
#define D_TOPIC "topic"
#define D_TOTAL_USAGE "Gesamtverbrauch"
#define D_TRANSMIT "Übertragen"
#define D_TRUE "wahr"
#define D_TVOC "TVOC"
#define D_UPGRADE "update"
#define D_UPLOAD "Upload"
#define D_UPTIME "Laufzeit"
#define D_USER "Benutzer"
#define D_UTC_TIME "UTC"
#define D_UV_INDEX "UV-Index"
#define D_UV_INDEX_1 "Niedrig"
#define D_UV_INDEX_2 "Mittel"
#define D_UV_INDEX_3 "Hoch"
#define D_UV_INDEX_4 "Intensiv"
#define D_UV_INDEX_5 "Gefährlich"
#define D_UV_INDEX_6 "Schädlich"
#define D_UV_INDEX_7 "Messwert!"
#define D_UV_LEVEL "UV-Level"
#define D_UV_POWER "UV Intensität"
#define D_VERSION "Version"
#define D_VOLTAGE "Spannung"
#define D_WEIGHT "Gewicht"
#define D_WARMLIGHT "warm"
#define D_WEB_SERVER "Web-Server"
// tasmota.ino
#define D_WARNING_MINIMAL_VERSION "ACHTUNG: Diese Version unterstützt keine persistenten Einstellungen"
#define D_LEVEL_10 "level 1-0"
#define D_LEVEL_01 "level 0-1"
#define D_SERIAL_LOGGING_DISABLED "Serielles Logging deaktiviert"
#define D_SYSLOG_LOGGING_REENABLED "Syslog-Logging aktiviert"
#define D_SET_BAUDRATE_TO "Setze Baudrate auf"
#define D_RECEIVED_TOPIC "empfangenes topic"
#define D_DATA_SIZE "Datengröße"
#define D_ANALOG_INPUT "Analog"
// support.ino
#define D_OSWATCH "osWatch"
#define D_BLOCKED_LOOP "Schleife blockiert."
#define D_WPS_FAILED_WITH_STATUS "WPS fehlgeschlagen mit Status"
#define D_ACTIVE_FOR_3_MINUTES "aktiv für 3 Minuten"
#define D_FAILED_TO_START "Starten fehlgeschlagen"
#define D_PATCH_ISSUE_2186 "Repariere Problem #2186"
#define D_CONNECTING_TO_AP "verbinden mit AP"
#define D_IN_MODE "in Modus"
#define D_CONNECT_FAILED_NO_IP_ADDRESS "Verbindung fehlgeschlagen, da keine IP-Adresse zugeteilt wurde"
#define D_CONNECT_FAILED_AP_NOT_REACHED "Verbindung fehlgeschlagen, da AP nicht erreicht werden konnte"
#define D_CONNECT_FAILED_WRONG_PASSWORD "Verbindung fehlgeschlagen"
#define D_CONNECT_FAILED_AP_TIMEOUT "Verbindung fehlgeschlagen, da der AP nicht antwortet (timeout)"
#define D_ATTEMPTING_CONNECTION "Verbindungsversuch..."
#define D_CHECKING_CONNECTION "Prüfe Verbindung..."
#define D_QUERY_DONE "Suchanfrage abgeschlossen. MQTT-Services gefunden"
#define D_MQTT_SERVICE_FOUND "MQTT-Service gefunden bei"
#define D_FOUND_AT "gefunden bei"
#define D_SYSLOG_HOST_NOT_FOUND "Syslog-Host nicht gefunden"
// settings.ino
#define D_SAVED_TO_FLASH_AT "in Flash gespeichert am"
#define D_LOADED_FROM_FLASH_AT "aus Flash geladen am"
#define D_USE_DEFAULTS "Standard verwenden"
#define D_ERASED_SECTOR "gelöschter Sektor"
// xdrv_02_webserver.ino
#define D_NOSCRIPT "JavaScript aktivieren um Tasmota benutzen zu können"
#define D_MINIMAL_FIRMWARE_PLEASE_UPGRADE "MINIMUM-Firmware<br>bitte upgraden"
#define D_WEBSERVER_ACTIVE_ON "Web-Server aktiv bei"
#define D_WITH_IP_ADDRESS "mit IP-Adresse"
#define D_WEBSERVER_STOPPED "Web-Server angehalten"
#define D_FILE_NOT_FOUND "Datei nicht gefunden"
#define D_REDIRECTED "umgeleitet zu captive portal"
#define D_WIFIMANAGER_SET_ACCESSPOINT_AND_STATION "WLAN-Manager AccessPoint gesetzt und behält Station"
#define D_WIFIMANAGER_SET_ACCESSPOINT "WLAN-Manager AccessPoint gesetzt"
#define D_TRYING_TO_CONNECT "Versuche Gerät mit Netzwerk zu verbinden"
#define D_RESTART_IN "Neustart in"
#define D_SECONDS "Sekunden"
#define D_DEVICE_WILL_RESTART "Gerät wird jetzt neu gestartet"
#define D_BUTTON_TOGGLE "An/Aus"
#define D_CONFIGURATION "Einstellungen"
#define D_INFORMATION "Informationen"
#define D_FIRMWARE_UPGRADE "Firmware Update"
#define D_CONSOLE "Konsole"
#define D_CONFIRM_RESTART "Wirklich neustarten?"
#define D_CONFIGURE_MODULE "Gerät konfigurieren"
#define D_CONFIGURE_WIFI "WLAN konfigurieren"
#define D_CONFIGURE_MQTT "MQTT konfigurieren"
#define D_CONFIGURE_DOMOTICZ "Domoticz konfigurieren"
#define D_CONFIGURE_LOGGING "Logging konfigurieren"
#define D_CONFIGURE_OTHER "Sonstige Konfiguration"
#define D_CONFIRM_RESET_CONFIGURATION "Zurücksetzen der Konfiguration bestätigen"
#define D_RESET_CONFIGURATION "Konfiguration zurücksetzen"
#define D_BACKUP_CONFIGURATION "Konfiguration sichern"
#define D_RESTORE_CONFIGURATION "Konfiguration wiederherstellen"
#define D_MAIN_MENU "Hauptmenü"
#define D_MODULE_PARAMETERS "Geräte-Einstellungen"
#define D_MODULE_TYPE "Gerätetyp"
#define D_PULLUP_ENABLE "Kein Taster/Schalter Pull-up"
#define D_ADC "ADC"
#define D_GPIO "GPIO"
#define D_SERIAL_IN "serieller Eingang [serial in]"
#define D_SERIAL_OUT "serieller Ausgang [serial out]"
#define D_WIFI_PARAMETERS "WLAN-Einstellungen"
#define D_SCAN_FOR_WIFI_NETWORKS "WLAN-Netzwerk suchen und auswählen"
#define D_SCAN_DONE "Suche abgeschlossen"
#define D_NO_NETWORKS_FOUND "Keine Netzwerke gefunden"
#define D_REFRESH_TO_SCAN_AGAIN "Aktualisieren, um erneut zu suchen"
#define D_DUPLICATE_ACCESSPOINT "AccessPoint duplizieren"
#define D_SKIPPING_LOW_QUALITY "überspringe wegen niedriger Qualität"
#define D_RSSI "RSSI"
#define D_WEP "WEP"
#define D_WPA_PSK "WPA-PSK"
#define D_WPA2_PSK "WPA2-PSK"
#define D_AP1_SSID "WLAN 1 - SSID"
#define D_AP1_PASSWORD "WLAN 1 - Passwort"
#define D_AP2_SSID "WLAN 2 - SSID"
#define D_AP2_PASSWORD "WLAN 2 - Passwort"
#define D_MQTT_PARAMETERS "MQTT-Einstellungen"
#define D_CLIENT "client"
#define D_FULL_TOPIC "full topic"
#define D_LOGGING_PARAMETERS "Logging-Einstellungen"
#define D_SERIAL_LOG_LEVEL "Seriell-Log Level"
#define D_MQTT_LOG_LEVEL "Mqtt-Log Level"
#define D_WEB_LOG_LEVEL "Web-Log Level"
#define D_SYS_LOG_LEVEL "Sys-Log Level"
#define D_MORE_DEBUG "Mehr Details"
#define D_SYSLOG_HOST "Sys-Log Host"
#define D_SYSLOG_PORT "Sys-Log Port"
#define D_TELEMETRY_PERIOD "Telemetrieperiode"
#define D_OTHER_PARAMETERS "Sonstige Einstellungen"
#define D_TEMPLATE "Vorlage"
#define D_ACTIVATE "Aktivieren"
#define D_DEVICE_NAME "Device Name"
#define D_WEB_ADMIN_PASSWORD "Passwort für Web Oberfläche"
#define D_MQTT_ENABLE "MQTT aktivieren"
#define D_MQTT_TLS_ENABLE "MQTT TLS"
#define D_FRIENDLY_NAME "Name [friendly name]"
#define D_BELKIN_WEMO "Belkin WeMo"
#define D_HUE_BRIDGE "Hue Bridge"
#define D_SINGLE_DEVICE "Einzelnes Gerät"
#define D_MULTI_DEVICE "Mehrfachgerät"
#define D_CONFIGURE_TEMPLATE "Vorlage konfigurieren"
#define D_TEMPLATE_PARAMETERS "Vorlage Parameter"
#define D_TEMPLATE_NAME "Name"
#define D_BASE_TYPE "basiert auf"
#define D_TEMPLATE_FLAGS "Options"
#define D_SAVE_CONFIGURATION "Konfiguration speichern"
#define D_CONFIGURATION_SAVED "Konfiguration gespeichert"
#define D_CONFIGURATION_RESET "Konfiguration zurücksetzen"
#define D_PROGRAM_VERSION "Tasmota Version"
#define D_BUILD_DATE_AND_TIME "Build-Datum & -Uhrzeit"
#define D_CORE_AND_SDK_VERSION "Core-/SDK-Version"
#define D_FLASH_WRITE_COUNT "Anz. Flash Schreibzugriffe"
#define D_MAC_ADDRESS "MAC-Adresse"
#define D_MQTT_HOST "MQTT Host"
#define D_MQTT_PORT "MQTT Port"
#define D_MQTT_CLIENT "MQTT Client"
#define D_MQTT_USER "MQTT Benutzer"
#define D_MQTT_TOPIC "MQTT Topic"
#define D_MQTT_GROUP_TOPIC "MQTT Group Topic"
#define D_MQTT_FULL_TOPIC "MQTT Full Topic"
#define D_MQTT_NO_RETAIN "MQTT No Retain"
#define D_MDNS_DISCOVERY "mDNS-Ermittlung"
#define D_MDNS_ADVERTISE "mDNS-Bekanntmachung"
#define D_ESP_CHIP_ID "ESP Chip ID"
#define D_FLASH_CHIP_ID "Flash Chip ID"
#define D_FLASH_CHIP_SIZE "Realer Flash Speicher"
#define D_FREE_PROGRAM_SPACE "Verf. Flash Speicher"
#define D_UPGRADE_BY_WEBSERVER "Update über Web-Server"
#define D_OTA_URL "OTA-URL"
#define D_START_UPGRADE "Update starten"
#define D_UPGRADE_BY_FILE_UPLOAD "Update Datei hochladen"
#define D_UPLOAD_STARTED "Upload gestartet"
#define D_UPGRADE_STARTED "Update gestartet"
#define D_UPLOAD_DONE "Upload abgeschlossen"
#define D_UPLOAD_TRANSFER "Upload Übertragung"
#define D_TRANSFER_STARTED "Transfer gestartet"
#define D_UPLOAD_ERR_1 "Keine Datei ausgewählt"
#define D_UPLOAD_ERR_2 "Ungenügend Speicherplatz"
#define D_UPLOAD_ERR_3 "Magic Byte ist nicht 0xE9"
#define D_UPLOAD_ERR_4 "Datei überschreitet vorhdn. Flashspeicher"
#define D_UPLOAD_ERR_5 "Upload Buffer Vergleich weicht ab"
#define D_UPLOAD_ERR_6 "Upload fehlgeschlagen. Aktiviere logging 3"
#define D_UPLOAD_ERR_7 "Upload abgebrochen"
#define D_UPLOAD_ERR_8 "Datei ungültig"
#define D_UPLOAD_ERR_9 "Datei zu groß"
#define D_UPLOAD_ERR_10 "RF Chip init fehlgeschlagen"
#define D_UPLOAD_ERR_11 "RF Chip löschen fehlgeschlagen"
#define D_UPLOAD_ERR_12 "RF Chip beschreiben fehlgeschlagen"
#define D_UPLOAD_ERR_13 "RF Firmware ungültig"
#define D_UPLOAD_ERR_14 "Nicht kompatibel"
#define D_UPLOAD_ERROR_CODE "Upload Fehler Nummer"
#define D_ENTER_COMMAND "Befehl eingeben"
#define D_ENABLE_WEBLOG_FOR_RESPONSE "Aktivere Web Log Level 2 falls Reaktion erwartet"
#define D_NEED_USER_AND_PASSWORD "Benötige user=<Benutzername>&password=<Passwort>"
// xdrv_01_mqtt.ino
#define D_FINGERPRINT "TLS-Fingerabdruck wird verifiziert..."
#define D_TLS_CONNECT_FAILED_TO "TLS-Verbindung fehlgeschlagen an"
#define D_RETRY_IN "Wiederversuch in"
#define D_VERIFIED "verifiziert mit Fingerabdruck"
#define D_INSECURE "unsichere Verbindung aufgrund ungültigen Fingerabdrucks"
#define D_CONNECT_FAILED_TO "Verbindung fehlgeschlagen aufgrund von"
// xplg_wemohue.ino
#define D_MULTICAST_DISABLED "Multicast deaktiviert"
#define D_MULTICAST_REJOINED "Multicast (wieder-)verbunden"
#define D_MULTICAST_JOIN_FAILED "Multicast Verbindung fehlgeschlagen"
#define D_FAILED_TO_SEND_RESPONSE "Antwort senden fehlgeschlagen"
#define D_WEMO "WeMo"
#define D_WEMO_BASIC_EVENT "WeMo basic event"
#define D_WEMO_EVENT_SERVICE "WeMo event service"
#define D_WEMO_META_SERVICE "WeMo meta service"
#define D_WEMO_SETUP "WeMo-Setup"
#define D_RESPONSE_SENT "Antwort gesendet"
#define D_HUE "Hue"
#define D_HUE_BRIDGE_SETUP "Hue-Setup"
#define D_HUE_API_NOT_IMPLEMENTED "Hue-API nicht implementiert"
#define D_HUE_API "Hue-API"
#define D_HUE_POST_ARGS "Hue POST-Argumente"
#define D_3_RESPONSE_PACKETS_SENT "3 Antwortpakete gesendet"
// xdrv_07_domoticz.ino
#define D_DOMOTICZ_PARAMETERS "Domoticz-Parameter"
#define D_DOMOTICZ_IDX "Idx"
#define D_DOMOTICZ_KEY_IDX "Key idx"
#define D_DOMOTICZ_SWITCH_IDX "Switch idx"
#define D_DOMOTICZ_SENSOR_IDX "Sensor idx"
#define D_DOMOTICZ_TEMP "Temp"
#define D_DOMOTICZ_TEMP_HUM "Temp,Hum"
#define D_DOMOTICZ_TEMP_HUM_BARO "Temp,Hum,Baro"
#define D_DOMOTICZ_POWER_ENERGY "Power,Energy"
#define D_DOMOTICZ_ILLUMINANCE "Illuminance"
#define D_DOMOTICZ_COUNT "Count/PM1"
#define D_DOMOTICZ_VOLTAGE "Voltage/PM2.5"
#define D_DOMOTICZ_CURRENT "Current/PM10"
#define D_DOMOTICZ_AIRQUALITY "AirQuality"
#define D_DOMOTICZ_P1_SMART_METER "P1SmartMeter"
#define D_DOMOTICZ_UPDATE_TIMER "Update Zeitplan"
// xdrv_09_timers.ino
#define D_CONFIGURE_TIMER "Zeitplan konfigurieren"
#define D_TIMER_PARAMETERS "Zeitplan-Einstellungen"
#define D_TIMER_ENABLE "Zeitpläne aktivieren"
#define D_TIMER_ARM "Aktiv"
#define D_TIMER_TIME "Uhrzeit"
#define D_TIMER_DAYS "Wochentage"
#define D_TIMER_REPEAT "Wiederholen"
#define D_TIMER_OUTPUT "Ausgang"
#define D_TIMER_ACTION "Aktion"
// xdrv_10_knx.ino
#define D_CONFIGURE_KNX "KNX konfigurieren"
#define D_KNX_PARAMETERS "KNX-Parameter"
#define D_KNX_GENERAL_CONFIG "Allgemein"
#define D_KNX_PHYSICAL_ADDRESS "Physikalische Adresse"
#define D_KNX_PHYSICAL_ADDRESS_NOTE "( Muss einmalig im KNX-Netzwerk sein )"
#define D_KNX_ENABLE "KNX aktivieren"
#define D_KNX_GROUP_ADDRESS_TO_WRITE "Daten zum Senden an Gruppenadresse"
#define D_ADD "Hinzufügen"
#define D_DELETE "Löschen"
#define D_REPLY "Antworten"
#define D_KNX_GROUP_ADDRESS_TO_READ "Gruppenadresse zum Emfang von Daten"
#define D_RECEIVED_FROM "Empfangen von"
#define D_KNX_COMMAND_WRITE "Schreiben"
#define D_KNX_COMMAND_READ "Lesen"
#define D_KNX_COMMAND_OTHER "Andere"
#define D_SENT_TO "gesendet an"
#define D_KNX_WARNING "Die Gruppenadresse (0/0/0) ist reserviert und kann nicht verwendet werden."
#define D_KNX_ENHANCEMENT "Erweiterte Kommunikation"
#define D_KNX_TX_SLOT "KNX TX"
#define D_KNX_RX_SLOT "KNX RX"
#define D_KNX_TX_SCENE "KNX SCENE TX"
#define D_KNX_RX_SCENE "KNX SCENE RX"
// xdrv_03_energy.ino
#define D_ENERGY_TODAY "Energie heute"
#define D_ENERGY_YESTERDAY "Energie gestern"
#define D_ENERGY_TOTAL "Energie insgesamt"
// xdrv_27_shutter.ino
#define D_OPEN "Öffnen"
#define D_CLOSE "Schliessen"
#define D_DOMOTICZ_SHUTTER "Rollo"
// xdrv_28_pcf8574.ino
#define D_CONFIGURE_PCF8574 "Konfiguriere PCF8574"
#define D_PCF8574_PARAMETERS "PCF8574 Parameter"
#define D_INVERT_PORTS "Invertiere Ports"
#define D_DEVICE "Gerät"
#define D_DEVICE_INPUT "Eingang"
#define D_DEVICE_OUTPUT "Ausgang"
// xsns_05_ds18b20.ino
#define D_SENSOR_BUSY "Sensor beschäftigt"
#define D_SENSOR_CRC_ERROR "Sensor CRC-Fehler"
#define D_SENSORS_FOUND "Sensor gefunden"
// xsns_06_dht.ino
#define D_TIMEOUT_WAITING_FOR "Timeout während Warten auf"
#define D_START_SIGNAL_LOW "Startausschlag niedrig"
#define D_START_SIGNAL_HIGH "Startausschlag hoch"
#define D_PULSE "Puls"
#define D_CHECKSUM_FAILURE "Checksum-Fehler"
// xsns_07_sht1x.ino
#define D_SENSOR_DID_NOT_ACK_COMMAND "Sensor hat ACK-Befehl nicht ausgeführt"
#define D_SHT1X_FOUND "SHT1X gefunden"
// xsns_18_pms5003.ino
#define D_STANDARD_CONCENTRATION "CF-1 PM" // Standard Particle CF-1 Particle Matter
#define D_ENVIRONMENTAL_CONCENTRATION "PM" // Environmetal Particle Matter
#define D_PARTICALS_BEYOND "Partikel"
// xsns_27_apds9960.ino
#define D_GESTURE "Geste"
#define D_COLOR_RED "Rot"
#define D_COLOR_GREEN "Grün"
#define D_COLOR_BLUE "Blau"
#define D_CCT "CCT"
#define D_PROXIMITY "Nähe"
// xsns_32_mpu6050.ino
#define D_AX_AXIS "Beschl. X-Achse"
#define D_AY_AXIS "Beschl. Y-Achse"
#define D_AZ_AXIS "Beschl. Z-Achse"
#define D_GX_AXIS "Gyroskop X-Achse"
#define D_GY_AXIS "Gyroskop Y-Achse"
#define D_GZ_AXIS "Gyroskop Z-Achse"
// xsns_34_hx711.ino
#define D_HX_CAL_REMOVE "Wägegut entfernen"
#define D_HX_CAL_REFERENCE "Referenzgewicht auflegen"
#define D_HX_CAL_DONE "kalibriert"
#define D_HX_CAL_FAIL "Kalibrierung fehlgeschlagen"
#define D_RESET_HX711 "Tara"
#define D_CONFIGURE_HX711 "Tara Wert?"
#define D_HX711_PARAMETERS "Skala Parameter"
#define D_ITEM_WEIGHT "Wägegut Gewicht"
#define D_REFERENCE_WEIGHT "Referenz Gewicht"
#define D_CALIBRATE "kalibriert"
#define D_CALIBRATION "Kalibrierung"
//xsns_35_tx20.ino
#define D_TX20_WIND_DIRECTION "Windrichtung"
#define D_TX20_WIND_SPEED "Windgeschwindigkeit"
#define D_TX20_WIND_SPEED_MIN "Windgeschwindigkeit Min"
#define D_TX20_WIND_SPEED_MAX "Windgeschwindigkeit Max"
#define D_TX20_NORTH "N"
#define D_TX20_EAST "O"
#define D_TX20_SOUTH "S"
#define D_TX20_WEST "W"
// xsns_53_sml.ino
#define D_TPWRIN "Verbrauch"
#define D_TPWROUT "Einspeisung"
#define D_TPWRCURR "Aktueller Verbrauch"
#define D_TPWRCURR1 "Verbrauch P1"
#define D_TPWRCURR2 "Verbrauch P2"
#define D_TPWRCURR3 "Verbrauch P3"
#define D_Strom_L1 "Strom L1"
#define D_Strom_L2 "Strom L2"
#define D_Strom_L3 "Strom L3"
#define D_Spannung_L1 "Spannung L1"
#define D_Spannung_L2 "Spannung L2"
#define D_Spannung_L3 "Spannung L3"
#define D_METERNR "Zähler Nr"
#define D_METERSID "Service ID"
#define D_GasIN "Zählerstand" // Gas-Verbrauch
#define D_H2oIN "Zählerstand" // H2o-Verbrauch
#define D_StL1L2L3 "Ströme L1+L2+L3"
#define D_SpL1L2L3 "Spannung L1+L2+L3/3"
// tasmota_template.h - keep them as short as possible to be able to fit them in GUI drop down box
#define D_SENSOR_NONE "None"
#define D_SENSOR_USER "User"
#define D_SENSOR_DHT11 "DHT11"
#define D_SENSOR_AM2301 "AM2301"
#define D_SENSOR_SI7021 "SI7021"
#define D_SENSOR_DS18X20 "DS18x20"
#define D_SENSOR_I2C_SCL "I2C SCL"
#define D_SENSOR_I2C_SDA "I2C SDA"
#define D_SENSOR_WS2812 "WS2812"
#define D_SENSOR_DFR562 "MP3 Player"
#define D_SENSOR_IRSEND "IRsend"
#define D_SENSOR_SWITCH "Switch" // Suffix "1"
#define D_SENSOR_BUTTON "Button" // Suffix "1"
#define D_SENSOR_RELAY "Relay" // Suffix "1i"
#define D_SENSOR_LED "Led" // Suffix "1i"
#define D_SENSOR_LED_LINK "LedLink" // Suffix "i"
#define D_SENSOR_PWM "PWM" // Suffix "1"
#define D_SENSOR_COUNTER "Counter" // Suffix "1"
#define D_SENSOR_IRRECV "IRrecv"
#define D_SENSOR_MHZ_RX "MHZ Rx"
#define D_SENSOR_MHZ_TX "MHZ Tx"
#define D_SENSOR_PZEM004_RX "PZEM004 Rx"
#define D_SENSOR_PZEM016_RX "PZEM016 Rx"
#define D_SENSOR_PZEM017_RX "PZEM017 Rx"
#define D_SENSOR_PZEM0XX_TX "PZEM0XX Tx"
#define D_SENSOR_SAIR_RX "SAir Rx"
#define D_SENSOR_SAIR_TX "SAir Tx"
#define D_SENSOR_SPI_CS "SPI CS"
#define D_SENSOR_SPI_DC "SPI DC"
#define D_SENSOR_SPI_MISO "SPI MISO"
#define D_SENSOR_SPI_MOSI "SPI MOSI"
#define D_SENSOR_SPI_CLK "SPI CLK"
#define D_SENSOR_BACKLIGHT "Backlight"
#define D_SENSOR_PMS5003_TX "PMS5003 Tx"
#define D_SENSOR_PMS5003_RX "PMS5003 Rx"
#define D_SENSOR_SDS0X1_RX "SDS0X1 Rx"
#define D_SENSOR_SDS0X1_TX "SDS0X1 Tx"
#define D_SENSOR_HPMA_RX "HPMA Rx"
#define D_SENSOR_HPMA_TX "HPMA Tx"
#define D_SENSOR_SBR_RX "SerBr Rx"
#define D_SENSOR_SBR_TX "SerBr Tx"
#define D_SENSOR_SR04_TRIG "SR04 Tri/TX"
#define D_SENSOR_SR04_ECHO "SR04 Ech/RX"
#define D_SENSOR_SDM120_TX "SDMx20 Tx"
#define D_SENSOR_SDM120_RX "SDMx20 Rx"
#define D_SENSOR_SDM630_TX "SDM630 Tx"
#define D_SENSOR_SDM630_RX "SDM630 Rx"
#define D_SENSOR_TM1638_CLK "TM16 CLK"
#define D_SENSOR_TM1638_DIO "TM16 DIO"
#define D_SENSOR_TM1638_STB "TM16 STB"
#define D_SENSOR_HX711_SCK "HX711 SCK"
#define D_SENSOR_HX711_DAT "HX711 DAT"
#define D_SENSOR_TX2X_TX "TX2x"
#define D_SENSOR_RFSEND "RFSend"
#define D_SENSOR_RFRECV "RFrecv"
#define D_SENSOR_TUYA_TX "Tuya Tx"
#define D_SENSOR_TUYA_RX "Tuya Rx"
#define D_SENSOR_MGC3130_XFER "MGC3130 Xfr"
#define D_SENSOR_MGC3130_RESET "MGC3130 Rst"
#define D_SENSOR_SSPI_MISO "SSPI MISO"
#define D_SENSOR_SSPI_MOSI "SSPI MOSI"
#define D_SENSOR_SSPI_SCLK "SSPI SCLK"
#define D_SENSOR_SSPI_CS "SSPI CS"
#define D_SENSOR_SSPI_DC "SSPI DC"
#define D_SENSOR_RF_SENSOR "RF Sensor"
#define D_SENSOR_AZ_RX "AZ Rx"
#define D_SENSOR_AZ_TX "AZ Tx"
#define D_SENSOR_MAX31855_CS "MX31855 CS"
#define D_SENSOR_MAX31855_CLK "MX31855 CLK"
#define D_SENSOR_MAX31855_DO "MX31855 DO"
#define D_SENSOR_MAX31865_CS "MX31865 CS"
#define D_SENSOR_NRG_SEL "HLWBL SEL" // Suffix "i"
#define D_SENSOR_NRG_CF1 "HLWBL CF1"
#define D_SENSOR_HLW_CF "HLW8012 CF"
#define D_SENSOR_HJL_CF "BL0937 CF"
#define D_SENSOR_MCP39F5_TX "MCP39F5 Tx"
#define D_SENSOR_MCP39F5_RX "MCP39F5 Rx"
#define D_SENSOR_MCP39F5_RST "MCP39F5 Rst"
#define D_SENSOR_CSE7766_TX "CSE7766 Tx"
#define D_SENSOR_CSE7766_RX "CSE7766 Rx"
#define D_SENSOR_PN532_TX "PN532 Tx"
#define D_SENSOR_PN532_RX "PN532 Rx"
#define D_SENSOR_SM16716_CLK "SM16716 CLK"
#define D_SENSOR_SM16716_DAT "SM16716 DAT"
#define D_SENSOR_SM16716_POWER "SM16716 PWR"
#define D_SENSOR_MY92X1_DI "MY92x1 DI"
#define D_SENSOR_MY92X1_DCKI "MY92x1 DCKI"
#define D_SENSOR_ARIRFRCV "ALux IrRcv"
#define D_SENSOR_ARIRFSEL "ALux IrSel"
#define D_SENSOR_TXD "Serial Tx"
#define D_SENSOR_RXD "Serial Rx"
#define D_SENSOR_ROTARY "Rotary" // Suffix "1A"
#define D_SENSOR_HRE_CLOCK "HRE Clock"
#define D_SENSOR_HRE_DATA "HRE Data"
#define D_SENSOR_ADE7953_IRQ "ADE7953 IRQ"
#define D_SENSOR_BUZZER "Buzzer"
#define D_SENSOR_OLED_RESET "OLED Reset"
#define D_SENSOR_ZIGBEE_TXD "Zigbee Tx"
#define D_SENSOR_ZIGBEE_RXD "Zigbee Rx"
#define D_SENSOR_ZIGBEE_RST "Zigbee Rst"
#define D_SENSOR_SOLAXX1_TX "SolaxX1 Tx"
#define D_SENSOR_SOLAXX1_RX "SolaxX1 Rx"
#define D_SENSOR_IBEACON_TX "iBeacon TX"
#define D_SENSOR_IBEACON_RX "iBeacon RX"
#define D_SENSOR_RDM6300_RX "RDM6300 RX"
#define D_SENSOR_CC1101_CS "CC1101 CS"
#define D_SENSOR_A4988_DIR "A4988 DIR"
#define D_SENSOR_A4988_STP "A4988 STP"
#define D_SENSOR_A4988_ENA "A4988 ENA"
#define D_SENSOR_A4988_MS1 "A4988 MS1"
#define D_SENSOR_A4988_MS2 "A4988 MS2"
#define D_SENSOR_A4988_MS3 "A4988 MS3"
#define D_SENSOR_DDS2382_TX "DDS238-2 Tx"
#define D_SENSOR_DDS2382_RX "DDS238-2 Rx"
#define D_SENSOR_DDSU666_TX "DDSU666 Tx"
#define D_SENSOR_DDSU666_RX "DDSU666 Rx"
#define D_SENSOR_SM2135_CLK "SM2135 Clk"
#define D_SENSOR_SM2135_DAT "SM2135 Dat"
#define D_SENSOR_DEEPSLEEP "DeepSleep"
#define D_SENSOR_EXS_ENABLE "EXS Enable"
#define D_SENSOR_CLIENT_TX "Client TX"
#define D_SENSOR_CLIENT_RX "Client RX"
#define D_SENSOR_CLIENT_RESET "Client RST"
#define D_SENSOR_GPS_RX "GPS RX"
#define D_SENSOR_GPS_TX "GPS TX"
#define D_SENSOR_HM10_RX "HM10 RX"
#define D_SENSOR_HM10_TX "HM10 TX"
#define D_SENSOR_LE01MR_RX "LE-01MR Rx"
#define D_SENSOR_LE01MR_TX "LE-01MR Tx"
#define D_SENSOR_BL0940_RX "BL0940 Rx"
#define D_SENSOR_CC1101_GDO0 "CC1101 GDO0"
#define D_SENSOR_CC1101_GDO2 "CC1101 GDO2"
#define D_SENSOR_HRXL_RX "HRXL Rx"
#define D_SENSOR_DYP_RX "DYP Rx"
#define D_SENSOR_ELECTRIQ_MOODL "MOODL Tx"
#define D_SENSOR_AS3935 "AS3935"
#define D_SENSOR_WINDMETER_SPEED "WindMeter Spd"
#define D_SENSOR_TELEINFO_RX "TInfo Rx"
#define D_SENSOR_TELEINFO_ENABLE "TInfo EN"
#define D_SENSOR_LMT01_PULSE "LMT01 Pulse"
#define D_SENSOR_ADC_INPUT "ADC Input"
#define D_SENSOR_ADC_TEMP "ADC Temp"
#define D_SENSOR_ADC_LIGHT "ADC Light"
#define D_SENSOR_ADC_BUTTON "ADC Button"
#define D_SENSOR_ADC_RANGE "ADC Range"
#define D_SENSOR_ADC_CT_POWER "ADC CT Power"
#define D_SENSOR_ADC_JOYSTICK "ADC Joystick"
#define D_GPIO_WEBCAM_PWDN "CAM_PWDN"
#define D_GPIO_WEBCAM_RESET "CAM_RESET"
#define D_GPIO_WEBCAM_XCLK "CAM_XCLK"
#define D_GPIO_WEBCAM_SIOD "CAM_SIOD"
#define D_GPIO_WEBCAM_SIOC "CAM_SIOC"
#define D_GPIO_WEBCAM_DATA "CAM_DATA"
#define D_GPIO_WEBCAM_VSYNC "CAM_VSYNC"
#define D_GPIO_WEBCAM_HREF "CAM_HREF"
#define D_GPIO_WEBCAM_PCLK "CAM_PCLK"
#define D_GPIO_WEBCAM_PSCLK "CAM_PSCLK"
#define D_GPIO_WEBCAM_HSD "CAM_HSD"
#define D_GPIO_WEBCAM_PSRCS "CAM_PSRCS"
#define D_SENSOR_ETH_PHY_POWER "ETH POWER"
#define D_SENSOR_ETH_PHY_MDC "ETH MDC"
#define D_SENSOR_ETH_PHY_MDIO "ETH MDIO"
#define D_SENSOR_TCP_TXD "TCP Tx"
#define D_SENSOR_TCP_RXD "TCP Rx"
#define D_SENSOR_IEM3000_TX "iEM3000 TX"
#define D_SENSOR_IEM3000_RX "iEM3000 RX"
// Units
#define D_UNIT_AMPERE "A"
#define D_UNIT_CELSIUS "C"
#define D_UNIT_CENTIMETER "cm"
#define D_UNIT_DEGREE "°"
#define D_UNIT_FAHRENHEIT "F"
#define D_UNIT_HERTZ "Hz"
#define D_UNIT_HOUR "h"
#define D_UNIT_GALLONS "gal"
#define D_UNIT_GALLONS_PER_MIN "g/m"
#define D_UNIT_INCREMENTS "inc"
#define D_UNIT_KELVIN "K"
#define D_UNIT_KILOMETER "km"
#define D_UNIT_KILOGRAM "kg"
#define D_UNIT_KILOMETER_PER_HOUR "km/h"
#define D_UNIT_KILOOHM "kΩ"
#define D_UNIT_KILOWATTHOUR "kWh"
#define D_UNIT_LUX "lx"
#define D_UNIT_MICROGRAM_PER_CUBIC_METER "µg/m³"
#define D_UNIT_MICROMETER "µm"
#define D_UNIT_MICROSECOND "µs"
#define D_UNIT_MILLIAMPERE "mA"
#define D_UNIT_MILLIMETER "mm"
#define D_UNIT_MILLIMETER_MERCURY "mmHg"
#define D_UNIT_MILLISECOND "ms"
#define D_UNIT_MINUTE "min"
#define D_UNIT_PARTS_PER_BILLION "ppb"
#define D_UNIT_PARTS_PER_DECILITER "ppd"
#define D_UNIT_PARTS_PER_MILLION "ppm"
#define D_UNIT_PERCENT "%%"
#define D_UNIT_PRESSURE "hPa"
#define D_UNIT_SECOND "s"
#define D_UNIT_SECTORS "Sektoren"
#define D_UNIT_VA "VA"
#define D_UNIT_VAR "VAr"
#define D_UNIT_VOLT "V"
#define D_UNIT_WATT "W"
#define D_UNIT_WATTHOUR "Wh"
#define D_UNIT_WATT_METER_QUADRAT "W/m²"
//SDM220, SDM120, LE01MR
#define D_PHASE_ANGLE "Phasenwinkel"
#define D_IMPORT_ACTIVE "Importiere Wirk"
#define D_EXPORT_ACTIVE "Exportiere Wirk"
#define D_IMPORT_REACTIVE "Importiere Blind"
#define D_EXPORT_REACTIVE "Exportiere Blind"
#define D_TOTAL_REACTIVE "Total Blind"
#define D_UNIT_KWARH "kVArh"
#define D_UNIT_ANGLE "Grad"
#define D_TOTAL_ACTIVE "Total Wirk"
//SOLAXX1
#define D_PV1_VOLTAGE "PV1 Spannung"
#define D_PV1_CURRENT "PV1 Strom"
#define D_PV1_POWER "PV1 Leistung"
#define D_PV2_VOLTAGE "PV2 Spannung"
#define D_PV2_CURRENT "PV2 Strom"
#define D_PV2_POWER "PV2 Leistung"
#define D_SOLAR_POWER "solare Leistung"
#define D_INVERTER_POWER "Inverter Leistung"
#define D_STATUS "Status"
#define D_WAITING "warten"
#define D_CHECKING "prüfen"
#define D_WORKING "arbeitet"
#define D_FAILURE "Fehler"
#define D_SOLAX_ERROR_0 "Kein Fehler Code"
#define D_SOLAX_ERROR_1 "Fehler im Solarstromnetz"
#define D_SOLAX_ERROR_2 "Spannungsfehler im Solarstromnetz"
#define D_SOLAX_ERROR_3 "Frequenzfehler im Solarstromnetz"
#define D_SOLAX_ERROR_4 "Pv Spannungsfehler"
#define D_SOLAX_ERROR_5 "Isolationsfehler"
#define D_SOLAX_ERROR_6 "Übertemperatur"
#define D_SOLAX_ERROR_7 "Lüfterfehler"
#define D_SOLAX_ERROR_8 "sonstiger Fehler"
//xdrv_10_scripter.ino
#define D_CONFIGURE_SCRIPT "Skript konfigurieren"
#define D_SCRIPT "Skript bearbeiten"
#define D_SDCARD_UPLOAD "Datei speichern"
#define D_SDCARD_DIR "SD Card Verzeichnis"
#define D_UPL_DONE "Fertig"
#define D_SCRIPT_CHARS_LEFT "Zeichen übrig"
#define D_SCRIPT_CHARS_NO_MORE "kein Speicher mehr"
#define D_SCRIPT_DOWNLOAD "Download"
#define D_SCRIPT_ENABLE "Skript aktivieren"
#define D_SCRIPT_UPLOAD "Upload"
#define D_SCRIPT_UPLOAD_FILES "Upload Dateien"
//xsns_67_as3935.ino
#define D_AS3935_GAIN "Umgebung:"
#define D_AS3935_ENERGY "Energie:"
#define D_AS3935_DISTANCE "Entfernung:"
#define D_AS3935_DISTURBER "Entstörer:"
#define D_AS3935_VRMS "µVrms:"
#define D_AS3935_APRX "ca.:"
#define D_AS3935_AWAY "entfernt"
#define D_AS3935_LIGHT "Blitz"
#define D_AS3935_OUT "ausserhalb der Reichweite"
#define D_AS3935_NOT "Entfernung nicht ermittelbar"
#define D_AS3935_ABOVE "Blitz überhalb"
#define D_AS3935_NOISE "Rauschen entdeckt"
#define D_AS3935_DISTDET "Störer entdeckt"
#define D_AS3935_INTNOEV "Interrupt ohne Grund!"
#define D_AS3935_FLICKER "IRQ Pin flackert!"
#define D_AS3935_POWEROFF "Ausgeschaltet"
#define D_AS3935_NOMESS "lausche..."
#define D_AS3935_ON "On"
#define D_AS3935_OFF "Off"
#define D_AS3935_INDOORS "Indoors"
#define D_AS3935_OUTDOORS "Outdoors"
#define D_AS3935_CAL_FAIL "Kalibrierung fehlerhaft"
#define D_AS3935_CAL_OK "Cap gesetzt auf:"
//xsns_68_opentherm.ino
#define D_SENSOR_BOILER_OT_RX "OpenTherm RX"
#define D_SENSOR_BOILER_OT_TX "OpenTherm TX"
// xnrg_15_teleinfo Denky (Teleinfo)
#define D_CONTRACT "Vertrag"
#define D_POWER_LOAD "Leistung"
#define D_CURRENT_TARIFF "Aktueller Tarif"
#define D_TARIFF "Tarif"
#define D_OVERLOAD "ADPS"
#define D_MAX_POWER "max. Leistung"
#define D_MAX_CURRENT "max. Stromstärke"
#endif // _LANGUAGE_DE_DE_H_
| {
"pile_set_name": "Github"
} |
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
logoText: "EasyDarwin",
logoMiniText: "ED",
serverInfo: {},
userInfo: null,
menus: [
{
path: '/',
title: "首页",
icon: 'dashboard'
}, {
path: '/pushers/1',
title: "推流列表",
icon: "video-camera"
}, {
path: '/players/1',
title: "拉流列表",
icon: "play"
}, {
path: "/about",
icon: "support",
title: "版本信息"
}, {
path: "/apidoc",
target: "blank",
icon: "book",
title: "接口文档"
}
]
},
mutations: {
updateServerInfo(state, serverInfo) {
state.serverInfo = serverInfo;
},
updateUserInfo(state, userInfo) {
state.userInfo = userInfo;
}
},
actions : {
getServerInfo({commit}){
return new Promise((resolve, reject) => {
$.get('/api/v1/serverinfo').then(serverInfo => {
commit('updateServerInfo', serverInfo);
resolve(serverInfo);
}).fail(() => {
resolve(null);
});
})
},
getUserInfo({ commit, state }) {
return new Promise((resolve, reject) => {
$.get("/api/v1/userinfo").then(userInfo => {
commit('updateUserInfo', userInfo);
resolve(userInfo);
}).fail(() => {
resolve(null);
})
})
},
logout({ commit, state }) {
return new Promise((resolve, reject) => {
$.get('/api/v1/logout').then(data => {
commit('updateUserInfo', null);
resolve(null);
}).fail(() => {
resolve(null);
})
})
}
}
})
export default store; | {
"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.3"/>
<title>dp14txss: APIs</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="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="HTML_custom.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="xlogo_bg.gif"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">dp14txss
</div>
<div id="projectbrief">Xilinx Vitis Drivers API Documentation</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.3 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Overview</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="globals.html"><span>APIs</span></a></li>
<li><a href="files.html"><span>File List</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_vars.html"><span>Variables</span></a></li>
<li><a href="globals_enum.html"><span>Enumerations</span></a></li>
<li><a href="globals_eval.html"><span>Enumerator</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_c"><span>c</span></a></li>
<li><a href="globals_0x64.html#index_d"><span>d</span></a></li>
<li><a href="globals_0x67.html#index_g"><span>g</span></a></li>
<li><a href="globals_0x68.html#index_h"><span>h</span></a></li>
<li><a href="globals_0x69.html#index_i"><span>i</span></a></li>
<li><a href="globals_0x6c.html#index_l"><span>l</span></a></li>
<li><a href="globals_0x6d.html#index_m"><span>m</span></a></li>
<li><a href="globals_0x70.html#index_p"><span>p</span></a></li>
<li><a href="globals_0x72.html#index_r"><span>r</span></a></li>
<li><a href="globals_0x73.html#index_s"><span>s</span></a></li>
<li class="current"><a href="globals_0x74.html#index_t"><span>t</span></a></li>
<li><a href="globals_0x75.html#index_u"><span>u</span></a></li>
<li><a href="globals_0x76.html#index_v"><span>v</span></a></li>
<li><a href="globals_0x77.html#index_w"><span>w</span></a></li>
<li><a href="globals_0x78.html#index_x"><span>x</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('globals_0x74.html','');});
</script>
<div id="doc-content">
<div class="contents">
<div class="textblock">Here is a list of all documented functions, variables, defines, enums, and typedefs with links to the documentation:</div>
<h3><a class="anchor" id="index_t"></a>- t -</h3><ul>
<li>TI_LMK03318_PowerDown()
: <a class="el" href="group___t_i___l_m_k03318.html#gad23a875ad2640e133b3c60b9b2614854">xdptxss_vcu118_tx.h</a>
</li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Copyright © 2015 Xilinx Inc. All rights reserved.</li>
</ul>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
package org.mamute.auth.rules;
public enum PermissionRules {
/**
* to vote up anything
*/
VOTE_UP("vote_up"),
/**
* to vote down anything
*/
VOTE_DOWN("vote_down"),
/**
* to answer own question
*/
ANSWER_OWN_QUESTION("answer_own_question"),
/**
* to flag anything
*/
CREATE_FLAG("create_flag"),
EDIT_QUESTION("edit_question"),
EDIT_ANSWER("edit_answer"),
/**
* to comment anything
*/
CREATE_COMMENT("create_comment"),
MODERATE_EDITS("moderate_edits"),
/**
* to interact with an inactive question
*/
INACTIVATE_QUESTION("inactivate_question");
private final String permissionName;
PermissionRules(String permissionName) {
this.permissionName = permissionName;
}
public String getPermissionName() {
return permissionName;
}
}
| {
"pile_set_name": "Github"
} |
// RUN: mlir-cuda-runner %s --shared-libs=%cuda_wrapper_library_dir/libcuda-runtime-wrappers%shlibext,%linalg_test_lib_dir/libmlir_runner_utils%shlibext --entry-point-result=void | FileCheck %s
// CHECK-COUNT-8: [{{(5356, ){12}5356}}]
func @main() {
%arg = alloc() : memref<2x4x13xf32>
%dst = memref_cast %arg : memref<2x4x13xf32> to memref<?x?x?xf32>
%c0 = constant 0 : index
%c1 = constant 1 : index
%c2 = constant 2 : index
%sx = dim %dst, %c2 : memref<?x?x?xf32>
%sy = dim %dst, %c1 : memref<?x?x?xf32>
%sz = dim %dst, %c0 : memref<?x?x?xf32>
%cast_dst = memref_cast %dst : memref<?x?x?xf32> to memref<*xf32>
gpu.host_register %cast_dst : memref<*xf32>
gpu.launch blocks(%bx, %by, %bz) in (%grid_x = %c1, %grid_y = %c1, %grid_z = %c1)
threads(%tx, %ty, %tz) in (%block_x = %sx, %block_y = %sy, %block_z = %sz) {
%t0 = muli %tz, %block_y : index
%t1 = addi %ty, %t0 : index
%t2 = muli %t1, %block_x : index
%idx = addi %tx, %t2 : index
%t3 = index_cast %idx : index to i32
%val = sitofp %t3 : i32 to f32
%sum = "gpu.all_reduce"(%val) ({}) { op = "add" } : (f32) -> (f32)
store %sum, %dst[%tz, %ty, %tx] : memref<?x?x?xf32>
gpu.terminator
}
call @print_memref_f32(%cast_dst) : (memref<*xf32>) -> ()
return
}
func @print_memref_f32(%ptr : memref<*xf32>)
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Runtime.Serialization.Json;
using Microsoft.DotNet.XHarness.iOS.Shared.Execution;
using Microsoft.DotNet.XHarness.iOS.Shared.Logging;
using Microsoft.DotNet.XHarness.iOS.Shared.Utilities;
using Microsoft.DotNet.XHarness.iOS.Shared.Listeners;
using ExceptionLogger = System.Action<int, string>;
namespace Microsoft.DotNet.XHarness.iOS.Shared {
// main class that gets the result of an executed test application, parses the results and provides information
// about the success or failure of the execution.
public class TestReporter : ITestReporter {
const string timeoutMessage = "Test run timed out after {0} minute(s).";
const string completionMessage = "Test run completed";
const string failureMessage = "Test run failed";
readonly ISimpleListener listener;
readonly ILog mainLog;
readonly ILogs crashLogs;
readonly ILog runLog;
readonly ILogs logs;
readonly ICrashSnapshotReporter crashReporter;
readonly IResultParser resultParser;
readonly AppBundleInformation appInfo;
readonly RunMode runMode;
readonly XmlResultJargon xmlJargon;
readonly IProcessManager processManager;
readonly string deviceName;
readonly TimeSpan timeout;
readonly Stopwatch timeoutWatch;
/// <summary>
/// Additional logs that will be sent with the report in case of a failure.
/// Used by the Xamarin.Xharness project to add BuildTask logs.
/// </summary>
readonly string additionalLogsDirectory;
/// <summary>
/// Callback needed for the Xamarin.Xharness project that does extra logging in case of a crash.
/// </summary>
readonly ExceptionLogger exceptionLogger;
bool waitedForExit = true;
bool launchFailure;
bool isSimulatorTest;
bool timedout;
public ILog CallbackLog { get; private set; }
public bool? Success { get; private set; }
public CancellationToken CancellationToken => cancellationTokenSource.Token;
public bool ResultsUseXml => xmlJargon != XmlResultJargon.Missing;
readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource ();
public TestReporter (IProcessManager processManager,
ILog mainLog,
ILog runLog,
ILogs logs,
ICrashSnapshotReporter crashReporter,
ISimpleListener simpleListener,
IResultParser parser,
AppBundleInformation appInformation,
RunMode runMode,
XmlResultJargon xmlJargon,
string device,
TimeSpan timeout,
string additionalLogsDirectory = null,
ExceptionLogger exceptionLogger = null)
{
this.processManager = processManager ?? throw new ArgumentNullException (nameof (processManager));
this.deviceName = device; // can be null on simulators
this.listener = simpleListener ?? throw new ArgumentNullException (nameof (simpleListener));
this.mainLog = mainLog ?? throw new ArgumentNullException (nameof (mainLog));
this.runLog = runLog ?? throw new ArgumentNullException (nameof (runLog));
this.logs = logs ?? throw new ArgumentNullException (nameof (logs));
this.crashReporter = crashReporter ?? throw new ArgumentNullException (nameof (crashReporter));
this.crashLogs = new Logs (logs.Directory);
this.resultParser = parser ?? throw new ArgumentNullException (nameof (parser));
this.appInfo = appInformation ?? throw new ArgumentNullException (nameof (appInformation));
this.runMode = runMode;
this.xmlJargon = xmlJargon;
this.timeout = timeout;
this.additionalLogsDirectory = additionalLogsDirectory;
this.exceptionLogger = exceptionLogger;
this.timeoutWatch = Stopwatch.StartNew ();
CallbackLog = new CallbackLog ((line) => {
// MT1111: Application launched successfully, but it's not possible to wait for the app to exit as requested because it's not possible to detect app termination when launching using gdbserver
waitedForExit &= line?.Contains ("MT1111: ") != true;
if (line?.Contains ("error MT1007") == true)
launchFailure = true;
});
}
// parse the run log and decide if we managed to start the process or not
async Task<(int pid, bool launchFailure)> GetPidFromRunLog () {
(int pid, bool launchFailure) pidData = (-1, true);
using var reader = runLog.GetReader (); // diposed at the end of the method, which is what we want
if (reader.Peek () == -1) {
// empty file! we definetly had a launch error in this case
pidData.launchFailure = true;
} else {
while (!reader.EndOfStream) {
var line = await reader.ReadLineAsync ();
if (line.StartsWith ("Application launched. PID = ", StringComparison.Ordinal)) {
var pidstr = line.Substring ("Application launched. PID = ".Length);
if (!int.TryParse (pidstr, out pidData.pid))
mainLog.WriteLine ("Could not parse pid: {0}", pidstr);
} else if (line.Contains ("Xamarin.Hosting: Launched ") && line.Contains (" with pid ")) {
var pidstr = line.Substring (line.LastIndexOf (' '));
if (!int.TryParse (pidstr, out pidData.pid))
mainLog.WriteLine ("Could not parse pid: {0}", pidstr);
} else if (line.Contains ("error MT1008")) {
pidData.launchFailure = true;
}
}
}
return pidData;
}
// parse the main log to get the pid
async Task<int> GetPidFromMainLog ()
{
int pid = -1;
using var log_reader = mainLog.GetReader (); // dispose when we leave the method, which is what we want
string line;
while ((line = await log_reader.ReadLineAsync ()) != null) {
const string str = "was launched with pid '";
var idx = line.IndexOf (str, StringComparison.Ordinal);
if (idx > 0) {
idx += str.Length;
var next_idx = line.IndexOf ('\'', idx);
if (next_idx > idx)
int.TryParse (line.Substring (idx, next_idx - idx), out pid);
}
if (pid != -1)
return pid;
}
return pid;
}
// return the reason for a crash found in a log
void GetCrashReason (int pid, ILog crashLog, out string crashReason)
{
crashReason = null;
using var crashReader = crashLog.GetReader (); // dispose when we leave the method
var text = crashReader.ReadToEnd ();
var reader = JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (text), new XmlDictionaryReaderQuotas ());
var doc = new XmlDocument ();
doc.Load (reader);
foreach (XmlNode node in doc.SelectNodes ($"/root/processes/item[pid = '" + pid + "']")) {
Console.WriteLine (node?.InnerXml);
Console.WriteLine (node?.SelectSingleNode ("reason")?.InnerText);
crashReason = node?.SelectSingleNode ("reason")?.InnerText;
}
}
// return if the tcp connection with the device failed
async Task<bool> TcpConnectionFailed ()
{
using var reader = mainLog.GetReader ();
string line;
while ((line = await reader.ReadLineAsync ()) != null) {
if (line.Contains ("Couldn't establish a TCP connection with any of the hostnames")) {
return true;
}
}
return false;
}
// kill any process
Task KillAppProcess (int pid, CancellationTokenSource cancellationSource) {
var launchTimedout = cancellationSource.IsCancellationRequested;
var timeoutType = launchTimedout ? "Launch" : "Completion";
mainLog.WriteLine ($"{timeoutType} timed out after {timeoutWatch.Elapsed.TotalSeconds} seconds");
return processManager.KillTreeAsync (pid, mainLog, true);
}
async Task CollectResult (Task<ProcessExecutionResult> processExecution)
{
// wait for the execution of the process, once that is done, perform all the parsing operations and
// leave a clean API to be used by AppRunner, hidding all the diff details
var result = await processExecution;
if (!waitedForExit && !result.TimedOut) {
// mlaunch couldn't wait for exit for some reason. Let's assume the app exits when the test listener completes.
mainLog.WriteLine ("Waiting for listener to complete, since mlaunch won't tell.");
if (!await listener.CompletionTask.TimeoutAfter (timeout - timeoutWatch.Elapsed)) {
result.TimedOut = true;
}
}
if (result.TimedOut) {
timedout = true;
Success = false;
mainLog.WriteLine (timeoutMessage, timeout.TotalMinutes);
} else if (result.Succeeded) {
mainLog.WriteLine (completionMessage);
Success = true;
} else {
mainLog.WriteLine (failureMessage);
Success = false;
}
}
public void LaunchCallback (Task<bool> launchResult)
{
if (launchResult.IsFaulted) {
mainLog.WriteLine ("Test launch failed: {0}", launchResult.Exception);
} else if (launchResult.IsCanceled) {
mainLog.WriteLine ("Test launch was cancelled.");
} else if (launchResult.Result) {
mainLog.WriteLine ("Test run started");
} else {
cancellationTokenSource.Cancel ();
mainLog.WriteLine ("Test launch timed out after {0} minute(s).", timeoutWatch.Elapsed.TotalMinutes);
timedout = true;
}
}
public async Task CollectSimulatorResult (Task<ProcessExecutionResult> processExecution)
{
isSimulatorTest = true;
await CollectResult (processExecution);
if (!Success.Value) {
var (pid, launchFailure) = await GetPidFromRunLog ();
this.launchFailure = launchFailure;
if (pid > 0) {
await KillAppProcess (pid, cancellationTokenSource);
} else {
mainLog.WriteLine ("Could not find pid in mtouch output.");
}
}
}
public async Task CollectDeviceResult (Task<ProcessExecutionResult> processExecution)
{
isSimulatorTest = false;
await CollectResult (processExecution);
}
async Task<(string ResultLine, bool Failed)> GetResultLine (string logPath)
{
string resultLine = null;
bool failed = false;
using var reader = new StreamReader (logPath);
string line = null;
while ((line = await reader.ReadLineAsync ()) != null) {
if (line.Contains ("Tests run:")) {
Console.WriteLine (line);
resultLine = line;
break;
} else if (line.Contains ("[FAIL]")) {
Console.WriteLine (line);
failed = true;
}
}
return (ResultLine: resultLine, Failed: failed);
}
async Task<(string resultLine, bool failed, bool crashed)> ParseResultFile (AppBundleInformation appInfo, string test_log_path, bool timed_out)
{
(string resultLine, bool failed, bool crashed) parseResult = (null, false, false);
if (!File.Exists (test_log_path)) {
parseResult.crashed = true; // if we do not have a log file, the test crashes
return parseResult;
}
// parsing the result is different if we are in jenkins or not.
// When in Jenkins, Touch.Unit produces an xml file instead of a console log (so that we can get better test reporting).
// However, for our own reporting, we still want the console-based log. This log is embedded inside the xml produced
// by Touch.Unit, so we need to extract it and write it to disk. We also need to re-save the xml output, since Touch.Unit
// wraps the NUnit xml output with additional information, which we need to unwrap so that Jenkins understands it.
//
// On the other hand, the nunit and xunit do not have that data and have to be parsed.
//
// This if statement has a small trick, we found out that internet sharing in some of the bots (VSTS) does not work, in
// that case, we cannot do a TCP connection to xharness to get the log, this is a problem since if we did not get the xml
// from the TCP connection, we are going to fail when trying to read it and not parse it. Therefore, we are not only
// going to check if we are in CI, but also if the listener_log is valid.
var path = Path.ChangeExtension (test_log_path, "xml");
if (path == test_log_path)
path = Path.Combine (Path.GetDirectoryName (path), Path.GetFileNameWithoutExtension (path) + "-clean.xml");
resultParser.CleanXml (test_log_path, path);
if (ResultsUseXml && resultParser.IsValidXml (path, out var xmlType)) {
try {
var newFilename = resultParser.GetXmlFilePath (path, xmlType);
// at this point, we have the test results, but we want to be able to have attachments in vsts, so if the format is
// the right one (NUnitV3) add the nodes. ATM only TouchUnit uses V3.
var testRunName = $"{appInfo.AppName} {appInfo.Variation}";
if (xmlType == XmlResultJargon.NUnitV3) {
var logFiles = new List<string> ();
// add our logs AND the logs of the previous task, which is the build task
logFiles.AddRange (Directory.GetFiles (crashLogs.Directory));
if (additionalLogsDirectory != null) // when using the run command, we do not have a build task, ergo, there are no logs to add.
logFiles.AddRange (Directory.GetFiles (additionalLogsDirectory));
// add the attachments and write in the new filename
// add a final prefix to the file name to make sure that the VSTS test uploaded just pick
// the final version, else we will upload tests more than once
newFilename = XmlResultParser.GetVSTSFilename (newFilename);
resultParser.UpdateMissingData (path, newFilename, testRunName, logFiles);
} else {
// rename the path to the correct value
File.Move (path, newFilename);
}
path = newFilename;
var humanReadableLog = logs.CreateFile (Path.GetFileNameWithoutExtension (test_log_path) + ".log", LogType.NUnitResult.ToString ());
(parseResult.resultLine, parseResult.failed) = resultParser.GenerateHumanReadableResults (path, humanReadableLog, xmlType);
// we do not longer need the tmp file
logs.AddFile (path, LogType.XmlLog.ToString ());
return parseResult;
} catch (Exception e) {
mainLog.WriteLine ("Could not parse xml result file: {0}", e);
// print file for better debugging
mainLog.WriteLine ("File data is:");
mainLog.WriteLine (new string ('#', 10));
using (var stream = new StreamReader (path)) {
string line;
while ((line = await stream.ReadLineAsync ()) != null) {
mainLog.WriteLine (line);
}
}
mainLog.WriteLine (new string ('#', 10));
mainLog.WriteLine ("End of xml results.");
if (timed_out) {
WrenchLog.WriteLine ($"AddSummary: <b><i>{runMode} timed out</i></b><br/>");
return parseResult;
} else {
WrenchLog.WriteLine ($"AddSummary: <b><i>{runMode} crashed</i></b><br/>");
mainLog.WriteLine ("Test run crashed");
parseResult.crashed = true;
return parseResult;
}
}
}
// delete not needed copy
File.Delete (path);
// not the most efficient way but this just happens when we run
// the tests locally and we usually do not run all tests, we are
// more interested to be efficent on the bots
(parseResult.resultLine, parseResult.failed) = await GetResultLine (test_log_path);
return parseResult;
}
async Task<(bool Succeeded, bool Crashed)> TestsSucceeded (AppBundleInformation appInfo, string test_log_path, bool timed_out)
{
var (resultLine, failed, crashed) = await ParseResultFile (appInfo, test_log_path, timed_out);
// read the parsed logs in a human readable way
if (resultLine != null) {
var tests_run = resultLine.Replace ("Tests run: ", "");
if (failed) {
WrenchLog.WriteLine ("AddSummary: <b>{0} failed: {1}</b><br/>", runMode, tests_run);
mainLog.WriteLine ("Test run failed");
return (false, crashed);
} else {
WrenchLog.WriteLine ("AddSummary: {0} succeeded: {1}<br/>", runMode, tests_run);
mainLog.WriteLine ("Test run succeeded");
return (true, crashed);
}
} else if (timed_out) {
WrenchLog.WriteLine ("AddSummary: <b><i>{0} timed out</i></b><br/>", runMode);
return (false, false);
} else {
WrenchLog.WriteLine ("AddSummary: <b><i>{0} crashed</i></b><br/>", runMode);
mainLog.WriteLine ("Test run crashed");
return (false, true);
}
}
// generate all the xml failures that will help the integration with the CI and return the failure reason
async Task GenerateXmlFailures (string failureMessage, bool crashed, string crashReason)
{
using var mainLogReader = mainLog.GetReader ();
if (!ResultsUseXml) // nothing to do
return;
if (!string.IsNullOrEmpty (crashReason)) {
resultParser.GenerateFailure (
logs,
"crash",
appInfo.AppName,
appInfo.Variation,
$"App Crash {appInfo.AppName} {appInfo.Variation}",
$"App crashed: {failureMessage}",
mainLogReader,
xmlJargon);
} else if (launchFailure) {
resultParser.GenerateFailure (
logs,
"launch",
appInfo.AppName,
appInfo.Variation,
$"App Launch {appInfo.AppName} {appInfo.Variation} on {deviceName}",
$"{failureMessage} on {deviceName}",
mainLogReader,
xmlJargon);
} else if (!isSimulatorTest && crashed && string.IsNullOrEmpty (crashReason)) {
// this happens more that what we would like on devices, the main reason most of the time is that we have had netwoking problems and the
// tcp connection could not be stablished. We are going to report it as an error since we have not parsed the logs, evne when the app might have
// not crashed. We need to check the main_log to see if we do have an tcp issue or not
if (await TcpConnectionFailed ()) {
resultParser.GenerateFailure (
logs,
"tcp-connection",
appInfo.AppName,
appInfo.Variation,
$"TcpConnection on {deviceName}",
$"Device {deviceName} could not reach the host over tcp.",
mainLogReader,
xmlJargon);
}
} else if (timedout) {
resultParser.GenerateFailure (
logs,
"timeout",
appInfo.AppName,
appInfo.Variation,
$"App Timeout {appInfo.AppName} {appInfo.Variation} on bot {deviceName}",
$"{appInfo.AppName} {appInfo.Variation} Test run timed out after {timeout.TotalMinutes} minute(s) on bot {deviceName}.",
mainLogReader,
xmlJargon);
}
}
public async Task<(TestExecutingResult ExecutingResult, string FailureMessage)> ParseResult ()
{
var result = (ExecutingResult: TestExecutingResult.Finished, FailureMessage: (string) null);
var crashed = false;
if (File.Exists (listener.TestLog.FullPath)) {
WrenchLog.WriteLine ("AddFile: {0}", listener.TestLog.FullPath);
(Success, crashed) = await TestsSucceeded (appInfo, listener.TestLog.FullPath, timedout);
} else if (timedout) {
WrenchLog.WriteLine ("AddSummary: <b><i>{0} never launched</i></b><br/>", runMode);
mainLog.WriteLine ("Test run never launched");
Success = false;
} else if (launchFailure) {
WrenchLog.WriteLine ("AddSummary: <b><i>{0} failed to launch</i></b><br/>", runMode);
mainLog.WriteLine ("Test run failed to launch");
Success = false;
} else {
WrenchLog.WriteLine ("AddSummary: <b><i>{0} crashed at startup (no log)</i></b><br/>", runMode);
mainLog.WriteLine ("Test run crashed before it started (no log file produced)");
crashed = true;
Success = false;
}
if (!Success.HasValue)
Success = false;
var crashLogWaitTime = 0;
if (!Success.Value)
crashLogWaitTime = 5;
if (crashed)
crashLogWaitTime = 30;
await crashReporter.EndCaptureAsync (TimeSpan.FromSeconds (crashLogWaitTime));
if (timedout) {
result.ExecutingResult = TestExecutingResult.TimedOut;
} else if (crashed) {
result.ExecutingResult = TestExecutingResult.Crashed;
} else if (Success.Value) {
result.ExecutingResult = TestExecutingResult.Succeeded;
} else {
result.ExecutingResult = TestExecutingResult.Failed;
}
// Check crash reports to see if any of them explains why the test run crashed.
if (!Success.Value) {
int pid = -1;
string crashReason = null;
foreach (var crashLog in crashLogs) {
try {
logs.Add (crashLog);
if (pid == -1) {
// Find the pid
pid = await GetPidFromMainLog ();
}
GetCrashReason (pid, crashLog, out crashReason);
if (crashReason != null)
break;
} catch (Exception e) {
var message = string.Format ("Failed to process crash report '{1}': {0}", e.Message, crashLog.Description);
mainLog.WriteLine (message);
exceptionLogger?.Invoke (2, message);
}
}
if (!string.IsNullOrEmpty (crashReason)) {
if (crashReason == "per-process-limit") {
result.FailureMessage = "Killed due to using too much memory (per-process-limit).";
} else {
result.FailureMessage = $"Killed by the OS ({crashReason})";
}
} else if (launchFailure) {
// same as with a crash
result.FailureMessage = $"Launch failure";
}
await GenerateXmlFailures (result.FailureMessage, crashed, crashReason);
}
return result;
}
}
}
| {
"pile_set_name": "Github"
} |
// Released under MIT license
// Copyright (c) 2009-2010 Dominic Baggott
// Copyright (c) 2009-2010 Ash Berlin
// Copyright (c) 2011 Christoph Dorn <[email protected]> (http://www.christophdorn.com)
/*jshint browser:true, devel:true */
(function( expose ) {
/**
* class Markdown
*
* Markdown processing in Javascript done right. We have very particular views
* on what constitutes 'right' which include:
*
* - produces well-formed HTML (this means that em and strong nesting is
* important)
*
* - has an intermediate representation to allow processing of parsed data (We
* in fact have two, both as [JsonML]: a markdown tree and an HTML tree).
*
* - is easily extensible to add new dialects without having to rewrite the
* entire parsing mechanics
*
* - has a good test suite
*
* This implementation fulfills all of these (except that the test suite could
* do with expanding to automatically run all the fixtures from other Markdown
* implementations.)
*
* ##### Intermediate Representation
*
* *TODO* Talk about this :) Its JsonML, but document the node names we use.
*
* [JsonML]: http://jsonml.org/ "JSON Markup Language"
**/
var Markdown = expose.Markdown = function(dialect) {
switch (typeof dialect) {
case "undefined":
this.dialect = Markdown.dialects.Gruber;
break;
case "object":
this.dialect = dialect;
break;
default:
if ( dialect in Markdown.dialects ) {
this.dialect = Markdown.dialects[dialect];
}
else {
throw new Error("Unknown Markdown dialect '" + String(dialect) + "'");
}
break;
}
this.em_state = [];
this.strong_state = [];
this.debug_indent = "";
};
/**
* parse( markdown, [dialect] ) -> JsonML
* - markdown (String): markdown string to parse
* - dialect (String | Dialect): the dialect to use, defaults to gruber
*
* Parse `markdown` and return a markdown document as a Markdown.JsonML tree.
**/
expose.parse = function( source, dialect ) {
// dialect will default if undefined
var md = new Markdown( dialect );
return md.toTree( source );
};
/**
* toHTML( markdown, [dialect] ) -> String
* toHTML( md_tree ) -> String
* - markdown (String): markdown string to parse
* - md_tree (Markdown.JsonML): parsed markdown tree
*
* Take markdown (either as a string or as a JsonML tree) and run it through
* [[toHTMLTree]] then turn it into a well-formated HTML fragment.
**/
expose.toHTML = function toHTML( source , dialect , options ) {
var input = expose.toHTMLTree( source , dialect , options );
return expose.renderJsonML( input );
};
/**
* toHTMLTree( markdown, [dialect] ) -> JsonML
* toHTMLTree( md_tree ) -> JsonML
* - markdown (String): markdown string to parse
* - dialect (String | Dialect): the dialect to use, defaults to gruber
* - md_tree (Markdown.JsonML): parsed markdown tree
*
* Turn markdown into HTML, represented as a JsonML tree. If a string is given
* to this function, it is first parsed into a markdown tree by calling
* [[parse]].
**/
expose.toHTMLTree = function toHTMLTree( input, dialect , options ) {
// convert string input to an MD tree
if ( typeof input ==="string" ) input = this.parse( input, dialect );
// Now convert the MD tree to an HTML tree
// remove references from the tree
var attrs = extract_attr( input ),
refs = {};
if ( attrs && attrs.references ) {
refs = attrs.references;
}
var html = convert_tree_to_html( input, refs , options );
merge_text_nodes( html );
return html;
};
// For Spidermonkey based engines
function mk_block_toSource() {
return "Markdown.mk_block( " +
uneval(this.toString()) +
", " +
uneval(this.trailing) +
", " +
uneval(this.lineNumber) +
" )";
}
// node
function mk_block_inspect() {
var util = require("util");
return "Markdown.mk_block( " +
util.inspect(this.toString()) +
", " +
util.inspect(this.trailing) +
", " +
util.inspect(this.lineNumber) +
" )";
}
var mk_block = Markdown.mk_block = function(block, trail, line) {
// Be helpful for default case in tests.
if ( arguments.length == 1 ) trail = "\n\n";
var s = new String(block);
s.trailing = trail;
// To make it clear its not just a string
s.inspect = mk_block_inspect;
s.toSource = mk_block_toSource;
if ( line != undefined )
s.lineNumber = line;
return s;
};
function count_lines( str ) {
var n = 0, i = -1;
while ( ( i = str.indexOf("\n", i + 1) ) !== -1 ) n++;
return n;
}
// Internal - split source into rough blocks
Markdown.prototype.split_blocks = function splitBlocks( input, startLine ) {
input = input.replace(/(\r\n|\n|\r)/g, "\n");
// [\s\S] matches _anything_ (newline or space)
// [^] is equivalent but doesn't work in IEs.
var re = /([\s\S]+?)($|\n#|\n(?:\s*\n|$)+)/g,
blocks = [],
m;
var line_no = 1;
if ( ( m = /^(\s*\n)/.exec(input) ) != null ) {
// skip (but count) leading blank lines
line_no += count_lines( m[0] );
re.lastIndex = m[0].length;
}
while ( ( m = re.exec(input) ) !== null ) {
if (m[2] == "\n#") {
m[2] = "\n";
re.lastIndex--;
}
blocks.push( mk_block( m[1], m[2], line_no ) );
line_no += count_lines( m[0] );
}
return blocks;
};
/**
* Markdown#processBlock( block, next ) -> undefined | [ JsonML, ... ]
* - block (String): the block to process
* - next (Array): the following blocks
*
* Process `block` and return an array of JsonML nodes representing `block`.
*
* It does this by asking each block level function in the dialect to process
* the block until one can. Succesful handling is indicated by returning an
* array (with zero or more JsonML nodes), failure by a false value.
*
* Blocks handlers are responsible for calling [[Markdown#processInline]]
* themselves as appropriate.
*
* If the blocks were split incorrectly or adjacent blocks need collapsing you
* can adjust `next` in place using shift/splice etc.
*
* If any of this default behaviour is not right for the dialect, you can
* define a `__call__` method on the dialect that will get invoked to handle
* the block processing.
*/
Markdown.prototype.processBlock = function processBlock( block, next ) {
var cbs = this.dialect.block,
ord = cbs.__order__;
if ( "__call__" in cbs ) {
return cbs.__call__.call(this, block, next);
}
for ( var i = 0; i < ord.length; i++ ) {
//D:this.debug( "Testing", ord[i] );
var res = cbs[ ord[i] ].call( this, block, next );
if ( res ) {
//D:this.debug(" matched");
if ( !isArray(res) || ( res.length > 0 && !( isArray(res[0]) ) ) )
this.debug(ord[i], "didn't return a proper array");
//D:this.debug( "" );
return res;
}
}
// Uhoh! no match! Should we throw an error?
return [];
};
Markdown.prototype.processInline = function processInline( block ) {
return this.dialect.inline.__call__.call( this, String( block ) );
};
/**
* Markdown#toTree( source ) -> JsonML
* - source (String): markdown source to parse
*
* Parse `source` into a JsonML tree representing the markdown document.
**/
// custom_tree means set this.tree to `custom_tree` and restore old value on return
Markdown.prototype.toTree = function toTree( source, custom_root ) {
var blocks = source instanceof Array ? source : this.split_blocks( source );
// Make tree a member variable so its easier to mess with in extensions
var old_tree = this.tree;
try {
this.tree = custom_root || this.tree || [ "markdown" ];
blocks:
while ( blocks.length ) {
var b = this.processBlock( blocks.shift(), blocks );
// Reference blocks and the like won't return any content
if ( !b.length ) continue blocks;
this.tree.push.apply( this.tree, b );
}
return this.tree;
}
finally {
if ( custom_root ) {
this.tree = old_tree;
}
}
};
// Noop by default
Markdown.prototype.debug = function () {
var args = Array.prototype.slice.call( arguments);
args.unshift(this.debug_indent);
if ( typeof print !== "undefined" )
print.apply( print, args );
if ( typeof console !== "undefined" && typeof console.log !== "undefined" )
console.log.apply( null, args );
}
Markdown.prototype.loop_re_over_block = function( re, block, cb ) {
// Dont use /g regexps with this
var m,
b = block.valueOf();
while ( b.length && (m = re.exec(b) ) != null ) {
b = b.substr( m[0].length );
cb.call(this, m);
}
return b;
};
/**
* Markdown.dialects
*
* Namespace of built-in dialects.
**/
Markdown.dialects = {};
/**
* Markdown.dialects.Gruber
*
* The default dialect that follows the rules set out by John Gruber's
* markdown.pl as closely as possible. Well actually we follow the behaviour of
* that script which in some places is not exactly what the syntax web page
* says.
**/
Markdown.dialects.Gruber = {
block: {
atxHeader: function atxHeader( block, next ) {
var m = block.match( /^(#{1,6})\s*(.*?)\s*#*\s*(?:\n|$)/ );
if ( !m ) return undefined;
var header = [ "header", { level: m[ 1 ].length } ];
Array.prototype.push.apply(header, this.processInline(m[ 2 ]));
if ( m[0].length < block.length )
next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) );
return [ header ];
},
setextHeader: function setextHeader( block, next ) {
var m = block.match( /^(.*)\n([-=])\2\2+(?:\n|$)/ );
if ( !m ) return undefined;
var level = ( m[ 2 ] === "=" ) ? 1 : 2;
var header = [ "header", { level : level }, m[ 1 ] ];
if ( m[0].length < block.length )
next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) );
return [ header ];
},
code: function code( block, next ) {
// | Foo
// |bar
// should be a code block followed by a paragraph. Fun
//
// There might also be adjacent code block to merge.
var ret = [],
re = /^(?: {0,3}\t| {4})(.*)\n?/,
lines;
// 4 spaces + content
if ( !block.match( re ) ) return undefined;
block_search:
do {
// Now pull out the rest of the lines
var b = this.loop_re_over_block(
re, block.valueOf(), function( m ) { ret.push( m[1] ); } );
if ( b.length ) {
// Case alluded to in first comment. push it back on as a new block
next.unshift( mk_block(b, block.trailing) );
break block_search;
}
else if ( next.length ) {
// Check the next block - it might be code too
if ( !next[0].match( re ) ) break block_search;
// Pull how how many blanks lines follow - minus two to account for .join
ret.push ( block.trailing.replace(/[^\n]/g, "").substring(2) );
block = next.shift();
}
else {
break block_search;
}
} while ( true );
return [ [ "code_block", ret.join("\n") ] ];
},
horizRule: function horizRule( block, next ) {
// this needs to find any hr in the block to handle abutting blocks
var m = block.match( /^(?:([\s\S]*?)\n)?[ \t]*([-_*])(?:[ \t]*\2){2,}[ \t]*(?:\n([\s\S]*))?$/ );
if ( !m ) {
return undefined;
}
var jsonml = [ [ "hr" ] ];
// if there's a leading abutting block, process it
if ( m[ 1 ] ) {
jsonml.unshift.apply( jsonml, this.processBlock( m[ 1 ], [] ) );
}
// if there's a trailing abutting block, stick it into next
if ( m[ 3 ] ) {
next.unshift( mk_block( m[ 3 ] ) );
}
return jsonml;
},
// There are two types of lists. Tight and loose. Tight lists have no whitespace
// between the items (and result in text just in the <li>) and loose lists,
// which have an empty line between list items, resulting in (one or more)
// paragraphs inside the <li>.
//
// There are all sorts weird edge cases about the original markdown.pl's
// handling of lists:
//
// * Nested lists are supposed to be indented by four chars per level. But
// if they aren't, you can get a nested list by indenting by less than
// four so long as the indent doesn't match an indent of an existing list
// item in the 'nest stack'.
//
// * The type of the list (bullet or number) is controlled just by the
// first item at the indent. Subsequent changes are ignored unless they
// are for nested lists
//
lists: (function( ) {
// Use a closure to hide a few variables.
var any_list = "[*+-]|\\d+\\.",
bullet_list = /[*+-]/,
number_list = /\d+\./,
// Capture leading indent as it matters for determining nested lists.
is_list_re = new RegExp( "^( {0,3})(" + any_list + ")[ \t]+" ),
indent_re = "(?: {0,3}\\t| {4})";
// TODO: Cache this regexp for certain depths.
// Create a regexp suitable for matching an li for a given stack depth
function regex_for_depth( depth ) {
return new RegExp(
// m[1] = indent, m[2] = list_type
"(?:^(" + indent_re + "{0," + depth + "} {0,3})(" + any_list + ")\\s+)|" +
// m[3] = cont
"(^" + indent_re + "{0," + (depth-1) + "}[ ]{0,4})"
);
}
function expand_tab( input ) {
return input.replace( / {0,3}\t/g, " " );
}
// Add inline content `inline` to `li`. inline comes from processInline
// so is an array of content
function add(li, loose, inline, nl) {
if ( loose ) {
li.push( [ "para" ].concat(inline) );
return;
}
// Hmmm, should this be any block level element or just paras?
var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] == "para"
? li[li.length -1]
: li;
// If there is already some content in this list, add the new line in
if ( nl && li.length > 1 ) inline.unshift(nl);
for ( var i = 0; i < inline.length; i++ ) {
var what = inline[i],
is_str = typeof what == "string";
if ( is_str && add_to.length > 1 && typeof add_to[add_to.length-1] == "string" ) {
add_to[ add_to.length-1 ] += what;
}
else {
add_to.push( what );
}
}
}
// contained means have an indent greater than the current one. On
// *every* line in the block
function get_contained_blocks( depth, blocks ) {
var re = new RegExp( "^(" + indent_re + "{" + depth + "}.*?\\n?)*$" ),
replace = new RegExp("^" + indent_re + "{" + depth + "}", "gm"),
ret = [];
while ( blocks.length > 0 ) {
if ( re.exec( blocks[0] ) ) {
var b = blocks.shift(),
// Now remove that indent
x = b.replace( replace, "");
ret.push( mk_block( x, b.trailing, b.lineNumber ) );
}
else {
break;
}
}
return ret;
}
// passed to stack.forEach to turn list items up the stack into paras
function paragraphify(s, i, stack) {
var list = s.list;
var last_li = list[list.length-1];
if ( last_li[1] instanceof Array && last_li[1][0] == "para" ) {
return;
}
if ( i + 1 == stack.length ) {
// Last stack frame
// Keep the same array, but replace the contents
last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ) );
}
else {
var sublist = last_li.pop();
last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ), sublist );
}
}
// The matcher function
return function( block, next ) {
var m = block.match( is_list_re );
if ( !m ) return undefined;
function make_list( m ) {
var list = bullet_list.exec( m[2] )
? ["bulletlist"]
: ["numberlist"];
stack.push( { list: list, indent: m[1] } );
return list;
}
var stack = [], // Stack of lists for nesting.
list = make_list( m ),
last_li,
loose = false,
ret = [ stack[0].list ],
i;
// Loop to search over block looking for inner block elements and loose lists
loose_search:
while ( true ) {
// Split into lines preserving new lines at end of line
var lines = block.split( /(?=\n)/ );
// We have to grab all lines for a li and call processInline on them
// once as there are some inline things that can span lines.
var li_accumulate = "";
// Loop over the lines in this block looking for tight lists.
tight_search:
for ( var line_no = 0; line_no < lines.length; line_no++ ) {
var nl = "",
l = lines[line_no].replace(/^\n/, function(n) { nl = n; return ""; });
// TODO: really should cache this
var line_re = regex_for_depth( stack.length );
m = l.match( line_re );
//print( "line:", uneval(l), "\nline match:", uneval(m) );
// We have a list item
if ( m[1] !== undefined ) {
// Process the previous list item, if any
if ( li_accumulate.length ) {
add( last_li, loose, this.processInline( li_accumulate ), nl );
// Loose mode will have been dealt with. Reset it
loose = false;
li_accumulate = "";
}
m[1] = expand_tab( m[1] );
var wanted_depth = Math.floor(m[1].length/4)+1;
//print( "want:", wanted_depth, "stack:", stack.length);
if ( wanted_depth > stack.length ) {
// Deep enough for a nested list outright
//print ( "new nested list" );
list = make_list( m );
last_li.push( list );
last_li = list[1] = [ "listitem" ];
}
else {
// We aren't deep enough to be strictly a new level. This is
// where Md.pl goes nuts. If the indent matches a level in the
// stack, put it there, else put it one deeper then the
// wanted_depth deserves.
var found = false;
for ( i = 0; i < stack.length; i++ ) {
if ( stack[ i ].indent != m[1] ) continue;
list = stack[ i ].list;
stack.splice( i+1, stack.length - (i+1) );
found = true;
break;
}
if (!found) {
//print("not found. l:", uneval(l));
wanted_depth++;
if ( wanted_depth <= stack.length ) {
stack.splice(wanted_depth, stack.length - wanted_depth);
//print("Desired depth now", wanted_depth, "stack:", stack.length);
list = stack[wanted_depth-1].list;
//print("list:", uneval(list) );
}
else {
//print ("made new stack for messy indent");
list = make_list(m);
last_li.push(list);
}
}
//print( uneval(list), "last", list === stack[stack.length-1].list );
last_li = [ "listitem" ];
list.push(last_li);
} // end depth of shenegains
nl = "";
}
// Add content
if ( l.length > m[0].length ) {
li_accumulate += nl + l.substr( m[0].length );
}
} // tight_search
if ( li_accumulate.length ) {
add( last_li, loose, this.processInline( li_accumulate ), nl );
// Loose mode will have been dealt with. Reset it
loose = false;
li_accumulate = "";
}
// Look at the next block - we might have a loose list. Or an extra
// paragraph for the current li
var contained = get_contained_blocks( stack.length, next );
// Deal with code blocks or properly nested lists
if ( contained.length > 0 ) {
// Make sure all listitems up the stack are paragraphs
forEach( stack, paragraphify, this);
last_li.push.apply( last_li, this.toTree( contained, [] ) );
}
var next_block = next[0] && next[0].valueOf() || "";
if ( next_block.match(is_list_re) || next_block.match( /^ / ) ) {
block = next.shift();
// Check for an HR following a list: features/lists/hr_abutting
var hr = this.dialect.block.horizRule( block, next );
if ( hr ) {
ret.push.apply(ret, hr);
break;
}
// Make sure all listitems up the stack are paragraphs
forEach( stack, paragraphify, this);
loose = true;
continue loose_search;
}
break;
} // loose_search
return ret;
};
})(),
blockquote: function blockquote( block, next ) {
if ( !block.match( /^>/m ) )
return undefined;
var jsonml = [];
// separate out the leading abutting block, if any. I.e. in this case:
//
// a
// > b
//
if ( block[ 0 ] != ">" ) {
var lines = block.split( /\n/ ),
prev = [],
line_no = block.lineNumber;
// keep shifting lines until you find a crotchet
while ( lines.length && lines[ 0 ][ 0 ] != ">" ) {
prev.push( lines.shift() );
line_no++;
}
var abutting = mk_block( prev.join( "\n" ), "\n", block.lineNumber );
jsonml.push.apply( jsonml, this.processBlock( abutting, [] ) );
// reassemble new block of just block quotes!
block = mk_block( lines.join( "\n" ), block.trailing, line_no );
}
// if the next block is also a blockquote merge it in
while ( next.length && next[ 0 ][ 0 ] == ">" ) {
var b = next.shift();
block = mk_block( block + block.trailing + b, b.trailing, block.lineNumber );
}
// Strip off the leading "> " and re-process as a block.
var input = block.replace( /^> ?/gm, "" ),
old_tree = this.tree,
processedBlock = this.toTree( input, [ "blockquote" ] ),
attr = extract_attr( processedBlock );
// If any link references were found get rid of them
if ( attr && attr.references ) {
delete attr.references;
// And then remove the attribute object if it's empty
if ( isEmpty( attr ) ) {
processedBlock.splice( 1, 1 );
}
}
jsonml.push( processedBlock );
return jsonml;
},
referenceDefn: function referenceDefn( block, next) {
var re = /^\s*\[(.*?)\]:\s*(\S+)(?:\s+(?:(['"])(.*?)\3|\((.*?)\)))?\n?/;
// interesting matches are [ , ref_id, url, , title, title ]
if ( !block.match(re) )
return undefined;
// make an attribute node if it doesn't exist
if ( !extract_attr( this.tree ) ) {
this.tree.splice( 1, 0, {} );
}
var attrs = extract_attr( this.tree );
// make a references hash if it doesn't exist
if ( attrs.references === undefined ) {
attrs.references = {};
}
var b = this.loop_re_over_block(re, block, function( m ) {
if ( m[2] && m[2][0] == "<" && m[2][m[2].length-1] == ">" )
m[2] = m[2].substring( 1, m[2].length - 1 );
var ref = attrs.references[ m[1].toLowerCase() ] = {
href: m[2]
};
if ( m[4] !== undefined )
ref.title = m[4];
else if ( m[5] !== undefined )
ref.title = m[5];
} );
if ( b.length )
next.unshift( mk_block( b, block.trailing ) );
return [];
},
para: function para( block, next ) {
// everything's a para!
return [ ["para"].concat( this.processInline( block ) ) ];
}
}
};
Markdown.dialects.Gruber.inline = {
__oneElement__: function oneElement( text, patterns_or_re, previous_nodes ) {
var m,
res,
lastIndex = 0;
patterns_or_re = patterns_or_re || this.dialect.inline.__patterns__;
var re = new RegExp( "([\\s\\S]*?)(" + (patterns_or_re.source || patterns_or_re) + ")" );
m = re.exec( text );
if (!m) {
// Just boring text
return [ text.length, text ];
}
else if ( m[1] ) {
// Some un-interesting text matched. Return that first
return [ m[1].length, m[1] ];
}
var res;
if ( m[2] in this.dialect.inline ) {
res = this.dialect.inline[ m[2] ].call(
this,
text.substr( m.index ), m, previous_nodes || [] );
}
// Default for now to make dev easier. just slurp special and output it.
res = res || [ m[2].length, m[2] ];
return res;
},
__call__: function inline( text, patterns ) {
var out = [],
res;
function add(x) {
//D:self.debug(" adding output", uneval(x));
if ( typeof x == "string" && typeof out[out.length-1] == "string" )
out[ out.length-1 ] += x;
else
out.push(x);
}
while ( text.length > 0 ) {
res = this.dialect.inline.__oneElement__.call(this, text, patterns, out );
text = text.substr( res.shift() );
forEach(res, add )
}
return out;
},
// These characters are intersting elsewhere, so have rules for them so that
// chunks of plain text blocks don't include them
"]": function () {},
"}": function () {},
__escape__ : /^\\[\\`\*_{}\[\]()#\+.!\-]/,
"\\": function escaped( text ) {
// [ length of input processed, node/children to add... ]
// Only esacape: \ ` * _ { } [ ] ( ) # * + - . !
if ( this.dialect.inline.__escape__.exec( text ) )
return [ 2, text.charAt( 1 ) ];
else
// Not an esacpe
return [ 1, "\\" ];
},
"
// 1 2 3 4 <--- captures
var m = text.match( /^!\[(.*?)\][ \t]*\([ \t]*([^")]*?)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/ );
if ( m ) {
if ( m[2] && m[2][0] == "<" && m[2][m[2].length-1] == ">" )
m[2] = m[2].substring( 1, m[2].length - 1 );
m[2] = this.dialect.inline.__call__.call( this, m[2], /\\/ )[0];
var attrs = { alt: m[1], href: m[2] || "" };
if ( m[4] !== undefined)
attrs.title = m[4];
return [ m[0].length, [ "img", attrs ] ];
}
// ![Alt text][id]
m = text.match( /^!\[(.*?)\][ \t]*\[(.*?)\]/ );
if ( m ) {
// We can't check if the reference is known here as it likely wont be
// found till after. Check it in md tree->hmtl tree conversion
return [ m[0].length, [ "img_ref", { alt: m[1], ref: m[2].toLowerCase(), original: m[0] } ] ];
}
// Just consume the '!['
return [ 2, "![" ];
},
"[": function link( text ) {
var orig = String(text);
// Inline content is possible inside `link text`
var res = Markdown.DialectHelpers.inline_until_char.call( this, text.substr(1), "]" );
// No closing ']' found. Just consume the [
if ( !res ) return [ 1, "[" ];
var consumed = 1 + res[ 0 ],
children = res[ 1 ],
link,
attrs;
// At this point the first [...] has been parsed. See what follows to find
// out which kind of link we are (reference or direct url)
text = text.substr( consumed );
// [link text](/path/to/img.jpg "Optional title")
// 1 2 3 <--- captures
// This will capture up to the last paren in the block. We then pull
// back based on if there a matching ones in the url
// ([here](/url/(test))
// The parens have to be balanced
var m = text.match( /^\s*\([ \t]*([^"']*)(?:[ \t]+(["'])(.*?)\2)?[ \t]*\)/ );
if ( m ) {
var url = m[1];
consumed += m[0].length;
if ( url && url[0] == "<" && url[url.length-1] == ">" )
url = url.substring( 1, url.length - 1 );
// If there is a title we don't have to worry about parens in the url
if ( !m[3] ) {
var open_parens = 1; // One open that isn't in the capture
for ( var len = 0; len < url.length; len++ ) {
switch ( url[len] ) {
case "(":
open_parens++;
break;
case ")":
if ( --open_parens == 0) {
consumed -= url.length - len;
url = url.substring(0, len);
}
break;
}
}
}
// Process escapes only
url = this.dialect.inline.__call__.call( this, url, /\\/ )[0];
attrs = { href: url || "" };
if ( m[3] !== undefined)
attrs.title = m[3];
link = [ "link", attrs ].concat( children );
return [ consumed, link ];
}
// [Alt text][id]
// [Alt text] [id]
m = text.match( /^\s*\[(.*?)\]/ );
if ( m ) {
consumed += m[ 0 ].length;
// [links][] uses links as its reference
attrs = { ref: ( m[ 1 ] || String(children) ).toLowerCase(), original: orig.substr( 0, consumed ) };
link = [ "link_ref", attrs ].concat( children );
// We can't check if the reference is known here as it likely wont be
// found till after. Check it in md tree->hmtl tree conversion.
// Store the original so that conversion can revert if the ref isn't found.
return [ consumed, link ];
}
// [id]
// Only if id is plain (no formatting.)
if ( children.length == 1 && typeof children[0] == "string" ) {
attrs = { ref: children[0].toLowerCase(), original: orig.substr( 0, consumed ) };
link = [ "link_ref", attrs, children[0] ];
return [ consumed, link ];
}
// Just consume the "["
return [ 1, "[" ];
},
"<": function autoLink( text ) {
var m;
if ( ( m = text.match( /^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\.[a-zA-Z]+))>/ ) ) != null ) {
if ( m[3] ) {
return [ m[0].length, [ "link", { href: "mailto:" + m[3] }, m[3] ] ];
}
else if ( m[2] == "mailto" ) {
return [ m[0].length, [ "link", { href: m[1] }, m[1].substr("mailto:".length ) ] ];
}
else
return [ m[0].length, [ "link", { href: m[1] }, m[1] ] ];
}
return [ 1, "<" ];
},
"`": function inlineCode( text ) {
// Inline code block. as many backticks as you like to start it
// Always skip over the opening ticks.
var m = text.match( /(`+)(([\s\S]*?)\1)/ );
if ( m && m[2] )
return [ m[1].length + m[2].length, [ "inlinecode", m[3] ] ];
else {
// TODO: No matching end code found - warn!
return [ 1, "`" ];
}
},
" \n": function lineBreak( text ) {
return [ 3, [ "linebreak" ] ];
}
};
// Meta Helper/generator method for em and strong handling
function strong_em( tag, md ) {
var state_slot = tag + "_state",
other_slot = tag == "strong" ? "em_state" : "strong_state";
function CloseTag(len) {
this.len_after = len;
this.name = "close_" + md;
}
return function ( text, orig_match ) {
if ( this[state_slot][0] == md ) {
// Most recent em is of this type
//D:this.debug("closing", md);
this[state_slot].shift();
// "Consume" everything to go back to the recrusion in the else-block below
return[ text.length, new CloseTag(text.length-md.length) ];
}
else {
// Store a clone of the em/strong states
var other = this[other_slot].slice(),
state = this[state_slot].slice();
this[state_slot].unshift(md);
//D:this.debug_indent += " ";
// Recurse
var res = this.processInline( text.substr( md.length ) );
//D:this.debug_indent = this.debug_indent.substr(2);
var last = res[res.length - 1];
//D:this.debug("processInline from", tag + ": ", uneval( res ) );
var check = this[state_slot].shift();
if ( last instanceof CloseTag ) {
res.pop();
// We matched! Huzzah.
var consumed = text.length - last.len_after;
return [ consumed, [ tag ].concat(res) ];
}
else {
// Restore the state of the other kind. We might have mistakenly closed it.
this[other_slot] = other;
this[state_slot] = state;
// We can't reuse the processed result as it could have wrong parsing contexts in it.
return [ md.length, md ];
}
}
}; // End returned function
}
Markdown.dialects.Gruber.inline["**"] = strong_em("strong", "**");
Markdown.dialects.Gruber.inline["__"] = strong_em("strong", "__");
Markdown.dialects.Gruber.inline["*"] = strong_em("em", "*");
Markdown.dialects.Gruber.inline["_"] = strong_em("em", "_");
// Build default order from insertion order.
Markdown.buildBlockOrder = function(d) {
var ord = [];
for ( var i in d ) {
if ( i == "__order__" || i == "__call__" ) continue;
ord.push( i );
}
d.__order__ = ord;
};
// Build patterns for inline matcher
Markdown.buildInlinePatterns = function(d) {
var patterns = [];
for ( var i in d ) {
// __foo__ is reserved and not a pattern
if ( i.match( /^__.*__$/) ) continue;
var l = i.replace( /([\\.*+?|()\[\]{}])/g, "\\$1" )
.replace( /\n/, "\\n" );
patterns.push( i.length == 1 ? l : "(?:" + l + ")" );
}
patterns = patterns.join("|");
d.__patterns__ = patterns;
//print("patterns:", uneval( patterns ) );
var fn = d.__call__;
d.__call__ = function(text, pattern) {
if ( pattern != undefined ) {
return fn.call(this, text, pattern);
}
else
{
return fn.call(this, text, patterns);
}
};
};
Markdown.DialectHelpers = {};
Markdown.DialectHelpers.inline_until_char = function( text, want ) {
var consumed = 0,
nodes = [];
while ( true ) {
if ( text.charAt( consumed ) == want ) {
// Found the character we were looking for
consumed++;
return [ consumed, nodes ];
}
if ( consumed >= text.length ) {
// No closing char found. Abort.
return null;
}
var res = this.dialect.inline.__oneElement__.call(this, text.substr( consumed ) );
consumed += res[ 0 ];
// Add any returned nodes.
nodes.push.apply( nodes, res.slice( 1 ) );
}
}
// Helper function to make sub-classing a dialect easier
Markdown.subclassDialect = function( d ) {
function Block() {}
Block.prototype = d.block;
function Inline() {}
Inline.prototype = d.inline;
return { block: new Block(), inline: new Inline() };
};
Markdown.buildBlockOrder ( Markdown.dialects.Gruber.block );
Markdown.buildInlinePatterns( Markdown.dialects.Gruber.inline );
Markdown.dialects.Maruku = Markdown.subclassDialect( Markdown.dialects.Gruber );
Markdown.dialects.Maruku.processMetaHash = function processMetaHash( meta_string ) {
var meta = split_meta_hash( meta_string ),
attr = {};
for ( var i = 0; i < meta.length; ++i ) {
// id: #foo
if ( /^#/.test( meta[ i ] ) ) {
attr.id = meta[ i ].substring( 1 );
}
// class: .foo
else if ( /^\./.test( meta[ i ] ) ) {
// if class already exists, append the new one
if ( attr["class"] ) {
attr["class"] = attr["class"] + meta[ i ].replace( /./, " " );
}
else {
attr["class"] = meta[ i ].substring( 1 );
}
}
// attribute: foo=bar
else if ( /\=/.test( meta[ i ] ) ) {
var s = meta[ i ].split( /\=/ );
attr[ s[ 0 ] ] = s[ 1 ];
}
}
return attr;
}
function split_meta_hash( meta_string ) {
var meta = meta_string.split( "" ),
parts = [ "" ],
in_quotes = false;
while ( meta.length ) {
var letter = meta.shift();
switch ( letter ) {
case " " :
// if we're in a quoted section, keep it
if ( in_quotes ) {
parts[ parts.length - 1 ] += letter;
}
// otherwise make a new part
else {
parts.push( "" );
}
break;
case "'" :
case '"' :
// reverse the quotes and move straight on
in_quotes = !in_quotes;
break;
case "\\" :
// shift off the next letter to be used straight away.
// it was escaped so we'll keep it whatever it is
letter = meta.shift();
default :
parts[ parts.length - 1 ] += letter;
break;
}
}
return parts;
}
Markdown.dialects.Maruku.block.document_meta = function document_meta( block, next ) {
// we're only interested in the first block
if ( block.lineNumber > 1 ) return undefined;
// document_meta blocks consist of one or more lines of `Key: Value\n`
if ( ! block.match( /^(?:\w+:.*\n)*\w+:.*$/ ) ) return undefined;
// make an attribute node if it doesn't exist
if ( !extract_attr( this.tree ) ) {
this.tree.splice( 1, 0, {} );
}
var pairs = block.split( /\n/ );
for ( p in pairs ) {
var m = pairs[ p ].match( /(\w+):\s*(.*)$/ ),
key = m[ 1 ].toLowerCase(),
value = m[ 2 ];
this.tree[ 1 ][ key ] = value;
}
// document_meta produces no content!
return [];
};
Markdown.dialects.Maruku.block.block_meta = function block_meta( block, next ) {
// check if the last line of the block is an meta hash
var m = block.match( /(^|\n) {0,3}\{:\s*((?:\\\}|[^\}])*)\s*\}$/ );
if ( !m ) return undefined;
// process the meta hash
var attr = this.dialect.processMetaHash( m[ 2 ] );
var hash;
// if we matched ^ then we need to apply meta to the previous block
if ( m[ 1 ] === "" ) {
var node = this.tree[ this.tree.length - 1 ];
hash = extract_attr( node );
// if the node is a string (rather than JsonML), bail
if ( typeof node === "string" ) return undefined;
// create the attribute hash if it doesn't exist
if ( !hash ) {
hash = {};
node.splice( 1, 0, hash );
}
// add the attributes in
for ( a in attr ) {
hash[ a ] = attr[ a ];
}
// return nothing so the meta hash is removed
return [];
}
// pull the meta hash off the block and process what's left
var b = block.replace( /\n.*$/, "" ),
result = this.processBlock( b, [] );
// get or make the attributes hash
hash = extract_attr( result[ 0 ] );
if ( !hash ) {
hash = {};
result[ 0 ].splice( 1, 0, hash );
}
// attach the attributes to the block
for ( a in attr ) {
hash[ a ] = attr[ a ];
}
return result;
};
Markdown.dialects.Maruku.block.definition_list = function definition_list( block, next ) {
// one or more terms followed by one or more definitions, in a single block
var tight = /^((?:[^\s:].*\n)+):\s+([\s\S]+)$/,
list = [ "dl" ],
i, m;
// see if we're dealing with a tight or loose block
if ( ( m = block.match( tight ) ) ) {
// pull subsequent tight DL blocks out of `next`
var blocks = [ block ];
while ( next.length && tight.exec( next[ 0 ] ) ) {
blocks.push( next.shift() );
}
for ( var b = 0; b < blocks.length; ++b ) {
var m = blocks[ b ].match( tight ),
terms = m[ 1 ].replace( /\n$/, "" ).split( /\n/ ),
defns = m[ 2 ].split( /\n:\s+/ );
// print( uneval( m ) );
for ( i = 0; i < terms.length; ++i ) {
list.push( [ "dt", terms[ i ] ] );
}
for ( i = 0; i < defns.length; ++i ) {
// run inline processing over the definition
list.push( [ "dd" ].concat( this.processInline( defns[ i ].replace( /(\n)\s+/, "$1" ) ) ) );
}
}
}
else {
return undefined;
}
return [ list ];
};
// splits on unescaped instances of @ch. If @ch is not a character the result
// can be unpredictable
Markdown.dialects.Maruku.block.table = function table (block, next) {
var _split_on_unescaped = function(s, ch) {
ch = ch || '\\s';
if (ch.match(/^[\\|\[\]{}?*.+^$]$/)) { ch = '\\' + ch; }
var res = [ ],
r = new RegExp('^((?:\\\\.|[^\\\\' + ch + '])*)' + ch + '(.*)'),
m;
while(m = s.match(r)) {
res.push(m[1]);
s = m[2];
}
res.push(s);
return res;
}
var leading_pipe = /^ {0,3}\|(.+)\n {0,3}\|\s*([\-:]+[\-| :]*)\n((?:\s*\|.*(?:\n|$))*)(?=\n|$)/,
// find at least an unescaped pipe in each line
no_leading_pipe = /^ {0,3}(\S(?:\\.|[^\\|])*\|.*)\n {0,3}([\-:]+\s*\|[\-| :]*)\n((?:(?:\\.|[^\\|])*\|.*(?:\n|$))*)(?=\n|$)/,
i, m;
if (m = block.match(leading_pipe)) {
// remove leading pipes in contents
// (header and horizontal rule already have the leading pipe left out)
m[3] = m[3].replace(/^\s*\|/gm, '');
} else if (! ( m = block.match(no_leading_pipe))) {
return undefined;
}
var table = [ "table", [ "thead", [ "tr" ] ], [ "tbody" ] ];
// remove trailing pipes, then split on pipes
// (no escaped pipes are allowed in horizontal rule)
m[2] = m[2].replace(/\|\s*$/, '').split('|');
// process alignment
var html_attrs = [ ];
forEach (m[2], function (s) {
if (s.match(/^\s*-+:\s*$/)) html_attrs.push({align: "right"});
else if (s.match(/^\s*:-+\s*$/)) html_attrs.push({align: "left"});
else if (s.match(/^\s*:-+:\s*$/)) html_attrs.push({align: "center"});
else html_attrs.push({});
});
// now for the header, avoid escaped pipes
m[1] = _split_on_unescaped(m[1].replace(/\|\s*$/, ''), '|');
for (i = 0; i < m[1].length; i++) {
table[1][1].push(['th', html_attrs[i] || {}].concat(
this.processInline(m[1][i].trim())));
}
// now for body contents
forEach (m[3].replace(/\|\s*$/mg, '').split('\n'), function (row) {
var html_row = ['tr'];
row = _split_on_unescaped(row, '|');
for (i = 0; i < row.length; i++) {
html_row.push(['td', html_attrs[i] || {}].concat(this.processInline(row[i].trim())));
}
table[2].push(html_row);
}, this);
return [table];
}
Markdown.dialects.Maruku.inline[ "{:" ] = function inline_meta( text, matches, out ) {
if ( !out.length ) {
return [ 2, "{:" ];
}
// get the preceeding element
var before = out[ out.length - 1 ];
if ( typeof before === "string" ) {
return [ 2, "{:" ];
}
// match a meta hash
var m = text.match( /^\{:\s*((?:\\\}|[^\}])*)\s*\}/ );
// no match, false alarm
if ( !m ) {
return [ 2, "{:" ];
}
// attach the attributes to the preceeding element
var meta = this.dialect.processMetaHash( m[ 1 ] ),
attr = extract_attr( before );
if ( !attr ) {
attr = {};
before.splice( 1, 0, attr );
}
for ( var k in meta ) {
attr[ k ] = meta[ k ];
}
// cut out the string and replace it with nothing
return [ m[ 0 ].length, "" ];
};
Markdown.dialects.Maruku.inline.__escape__ = /^\\[\\`\*_{}\[\]()#\+.!\-|:]/;
Markdown.buildBlockOrder ( Markdown.dialects.Maruku.block );
Markdown.buildInlinePatterns( Markdown.dialects.Maruku.inline );
var isArray = Array.isArray || function(obj) {
return Object.prototype.toString.call(obj) == "[object Array]";
};
var forEach;
// Don't mess with Array.prototype. Its not friendly
if ( Array.prototype.forEach ) {
forEach = function( arr, cb, thisp ) {
return arr.forEach( cb, thisp );
};
}
else {
forEach = function(arr, cb, thisp) {
for (var i = 0; i < arr.length; i++) {
cb.call(thisp || arr, arr[i], i, arr);
}
}
}
var isEmpty = function( obj ) {
for ( var key in obj ) {
if ( hasOwnProperty.call( obj, key ) ) {
return false;
}
}
return true;
}
function extract_attr( jsonml ) {
return isArray(jsonml)
&& jsonml.length > 1
&& typeof jsonml[ 1 ] === "object"
&& !( isArray(jsonml[ 1 ]) )
? jsonml[ 1 ]
: undefined;
}
/**
* renderJsonML( jsonml[, options] ) -> String
* - jsonml (Array): JsonML array to render to XML
* - options (Object): options
*
* Converts the given JsonML into well-formed XML.
*
* The options currently understood are:
*
* - root (Boolean): wether or not the root node should be included in the
* output, or just its children. The default `false` is to not include the
* root itself.
*/
expose.renderJsonML = function( jsonml, options ) {
options = options || {};
// include the root element in the rendered output?
options.root = options.root || false;
var content = [];
if ( options.root ) {
content.push( render_tree( jsonml ) );
}
else {
jsonml.shift(); // get rid of the tag
if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) {
jsonml.shift(); // get rid of the attributes
}
while ( jsonml.length ) {
content.push( render_tree( jsonml.shift() ) );
}
}
return content.join( "\n\n" );
};
function escapeHTML( text ) {
return text.replace( /&/g, "&" )
.replace( /</g, "<" )
.replace( />/g, ">" )
.replace( /"/g, """ )
.replace( /'/g, "'" );
}
function render_tree( jsonml ) {
// basic case
if ( typeof jsonml === "string" ) {
return escapeHTML( jsonml );
}
var tag = jsonml.shift(),
attributes = {},
content = [];
if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) {
attributes = jsonml.shift();
}
while ( jsonml.length ) {
content.push( render_tree( jsonml.shift() ) );
}
var tag_attrs = "";
for ( var a in attributes ) {
tag_attrs += " " + a + '="' + escapeHTML( attributes[ a ] ) + '"';
}
// be careful about adding whitespace here for inline elements
if ( tag == "img" || tag == "br" || tag == "hr" ) {
return "<"+ tag + tag_attrs + "/>";
}
else {
return "<"+ tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">";
}
}
function convert_tree_to_html( tree, references, options ) {
var i;
options = options || {};
// shallow clone
var jsonml = tree.slice( 0 );
if ( typeof options.preprocessTreeNode === "function" ) {
jsonml = options.preprocessTreeNode(jsonml, references);
}
// Clone attributes if they exist
var attrs = extract_attr( jsonml );
if ( attrs ) {
jsonml[ 1 ] = {};
for ( i in attrs ) {
jsonml[ 1 ][ i ] = attrs[ i ];
}
attrs = jsonml[ 1 ];
}
// basic case
if ( typeof jsonml === "string" ) {
return jsonml;
}
// convert this node
switch ( jsonml[ 0 ] ) {
case "header":
jsonml[ 0 ] = "h" + jsonml[ 1 ].level;
delete jsonml[ 1 ].level;
break;
case "bulletlist":
jsonml[ 0 ] = "ul";
break;
case "numberlist":
jsonml[ 0 ] = "ol";
break;
case "listitem":
jsonml[ 0 ] = "li";
break;
case "para":
jsonml[ 0 ] = "p";
break;
case "markdown":
jsonml[ 0 ] = "html";
if ( attrs ) delete attrs.references;
break;
case "code_block":
jsonml[ 0 ] = "pre";
i = attrs ? 2 : 1;
var code = [ "code" ];
code.push.apply( code, jsonml.splice( i, jsonml.length - i ) );
jsonml[ i ] = code;
break;
case "inlinecode":
jsonml[ 0 ] = "code";
break;
case "img":
jsonml[ 1 ].src = jsonml[ 1 ].href;
delete jsonml[ 1 ].href;
break;
case "linebreak":
jsonml[ 0 ] = "br";
break;
case "link":
jsonml[ 0 ] = "a";
break;
case "link_ref":
jsonml[ 0 ] = "a";
// grab this ref and clean up the attribute node
var ref = references[ attrs.ref ];
// if the reference exists, make the link
if ( ref ) {
delete attrs.ref;
// add in the href and title, if present
attrs.href = ref.href;
if ( ref.title ) {
attrs.title = ref.title;
}
// get rid of the unneeded original text
delete attrs.original;
}
// the reference doesn't exist, so revert to plain text
else {
return attrs.original;
}
break;
case "img_ref":
jsonml[ 0 ] = "img";
// grab this ref and clean up the attribute node
var ref = references[ attrs.ref ];
// if the reference exists, make the link
if ( ref ) {
delete attrs.ref;
// add in the href and title, if present
attrs.src = ref.href;
if ( ref.title ) {
attrs.title = ref.title;
}
// get rid of the unneeded original text
delete attrs.original;
}
// the reference doesn't exist, so revert to plain text
else {
return attrs.original;
}
break;
}
// convert all the children
i = 1;
// deal with the attribute node, if it exists
if ( attrs ) {
// if there are keys, skip over it
for ( var key in jsonml[ 1 ] ) {
i = 2;
break;
}
// if there aren't, remove it
if ( i === 1 ) {
jsonml.splice( i, 1 );
}
}
for ( ; i < jsonml.length; ++i ) {
jsonml[ i ] = convert_tree_to_html( jsonml[ i ], references, options );
}
return jsonml;
}
// merges adjacent text nodes into a single node
function merge_text_nodes( jsonml ) {
// skip the tag name and attribute hash
var i = extract_attr( jsonml ) ? 2 : 1;
while ( i < jsonml.length ) {
// if it's a string check the next item too
if ( typeof jsonml[ i ] === "string" ) {
if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) {
// merge the second string into the first and remove it
jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ];
}
else {
++i;
}
}
// if it's not a string recurse
else {
merge_text_nodes( jsonml[ i ] );
++i;
}
}
}
} )( (function() {
if ( typeof exports === "undefined" ) {
window.markdown = {};
return window.markdown;
}
else {
return exports;
}
} )() );
| {
"pile_set_name": "Github"
} |
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/NewsCore.framework/NewsCore
*/
@interface FCBundleLookupClass : NSObject
@end
| {
"pile_set_name": "Github"
} |
use v6;
use Test;
use Alma::Test;
my $files = find(".", /[".pm6" | ".t"] $/)\
.grep({ $_ !~~ / "do-not-create-val-none.t" / })\
.join(" ");
my @lines-with-val-none-new =
qqx[grep -Fwrin 'Val::None.new' $files].lines\
# exception: we store Val::None.new once as a constant
.grep({ $_ !~~ / ":constant NONE is export = " / });
is @lines-with-val-none-new.join("\n"), "",
"no unnecessary calls to Val::None.new";
done-testing;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2014-2015 Broadcom Corporation
*
* 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 version 2.
*
* This program is distributed "as is" WITHOUT ANY WARRANTY of any
* kind, whether express or implied; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of_device.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/soc-dai.h>
#include "cygnus-ssp.h"
#define DEFAULT_VCO 1354750204
#define CAPTURE_FCI_ID_BASE 0x180
#define CYGNUS_SSP_TRISTATE_MASK 0x001fff
#define CYGNUS_PLLCLKSEL_MASK 0xf
/* Used with stream_on field to indicate which streams are active */
#define PLAYBACK_STREAM_MASK BIT(0)
#define CAPTURE_STREAM_MASK BIT(1)
#define I2S_STREAM_CFG_MASK 0xff003ff
#define I2S_CAP_STREAM_CFG_MASK 0xf0
#define SPDIF_STREAM_CFG_MASK 0x3ff
#define CH_GRP_STEREO 0x1
/* Begin register offset defines */
#define AUD_MISC_SEROUT_OE_REG_BASE 0x01c
#define AUD_MISC_SEROUT_SPDIF_OE 12
#define AUD_MISC_SEROUT_MCLK_OE 3
#define AUD_MISC_SEROUT_LRCK_OE 2
#define AUD_MISC_SEROUT_SCLK_OE 1
#define AUD_MISC_SEROUT_SDAT_OE 0
/* AUD_FMM_BF_CTRL_xxx regs */
#define BF_DST_CFG0_OFFSET 0x100
#define BF_DST_CFG1_OFFSET 0x104
#define BF_DST_CFG2_OFFSET 0x108
#define BF_DST_CTRL0_OFFSET 0x130
#define BF_DST_CTRL1_OFFSET 0x134
#define BF_DST_CTRL2_OFFSET 0x138
#define BF_SRC_CFG0_OFFSET 0x148
#define BF_SRC_CFG1_OFFSET 0x14c
#define BF_SRC_CFG2_OFFSET 0x150
#define BF_SRC_CFG3_OFFSET 0x154
#define BF_SRC_CTRL0_OFFSET 0x1c0
#define BF_SRC_CTRL1_OFFSET 0x1c4
#define BF_SRC_CTRL2_OFFSET 0x1c8
#define BF_SRC_CTRL3_OFFSET 0x1cc
#define BF_SRC_GRP0_OFFSET 0x1fc
#define BF_SRC_GRP1_OFFSET 0x200
#define BF_SRC_GRP2_OFFSET 0x204
#define BF_SRC_GRP3_OFFSET 0x208
#define BF_SRC_GRP_EN_OFFSET 0x320
#define BF_SRC_GRP_FLOWON_OFFSET 0x324
#define BF_SRC_GRP_SYNC_DIS_OFFSET 0x328
/* AUD_FMM_IOP_OUT_I2S_xxx regs */
#define OUT_I2S_0_STREAM_CFG_OFFSET 0xa00
#define OUT_I2S_0_CFG_OFFSET 0xa04
#define OUT_I2S_0_MCLK_CFG_OFFSET 0xa0c
#define OUT_I2S_1_STREAM_CFG_OFFSET 0xa40
#define OUT_I2S_1_CFG_OFFSET 0xa44
#define OUT_I2S_1_MCLK_CFG_OFFSET 0xa4c
#define OUT_I2S_2_STREAM_CFG_OFFSET 0xa80
#define OUT_I2S_2_CFG_OFFSET 0xa84
#define OUT_I2S_2_MCLK_CFG_OFFSET 0xa8c
/* AUD_FMM_IOP_OUT_SPDIF_xxx regs */
#define SPDIF_STREAM_CFG_OFFSET 0xac0
#define SPDIF_CTRL_OFFSET 0xac4
#define SPDIF_FORMAT_CFG_OFFSET 0xad8
#define SPDIF_MCLK_CFG_OFFSET 0xadc
/* AUD_FMM_IOP_PLL_0_xxx regs */
#define IOP_PLL_0_MACRO_OFFSET 0xb00
#define IOP_PLL_0_MDIV_Ch0_OFFSET 0xb14
#define IOP_PLL_0_MDIV_Ch1_OFFSET 0xb18
#define IOP_PLL_0_MDIV_Ch2_OFFSET 0xb1c
#define IOP_PLL_0_ACTIVE_MDIV_Ch0_OFFSET 0xb30
#define IOP_PLL_0_ACTIVE_MDIV_Ch1_OFFSET 0xb34
#define IOP_PLL_0_ACTIVE_MDIV_Ch2_OFFSET 0xb38
/* AUD_FMM_IOP_xxx regs */
#define IOP_PLL_0_CONTROL_OFFSET 0xb04
#define IOP_PLL_0_USER_NDIV_OFFSET 0xb08
#define IOP_PLL_0_ACTIVE_NDIV_OFFSET 0xb20
#define IOP_PLL_0_RESET_OFFSET 0xb5c
/* AUD_FMM_IOP_IN_I2S_xxx regs */
#define IN_I2S_0_STREAM_CFG_OFFSET 0x00
#define IN_I2S_0_CFG_OFFSET 0x04
#define IN_I2S_1_STREAM_CFG_OFFSET 0x40
#define IN_I2S_1_CFG_OFFSET 0x44
#define IN_I2S_2_STREAM_CFG_OFFSET 0x80
#define IN_I2S_2_CFG_OFFSET 0x84
/* AUD_FMM_IOP_MISC_xxx regs */
#define IOP_SW_INIT_LOGIC 0x1c0
/* End register offset defines */
/* AUD_FMM_IOP_OUT_I2S_x_MCLK_CFG_0_REG */
#define I2S_OUT_MCLKRATE_SHIFT 16
/* AUD_FMM_IOP_OUT_I2S_x_MCLK_CFG_REG */
#define I2S_OUT_PLLCLKSEL_SHIFT 0
/* AUD_FMM_IOP_OUT_I2S_x_STREAM_CFG */
#define I2S_OUT_STREAM_ENA 31
#define I2S_OUT_STREAM_CFG_GROUP_ID 20
#define I2S_OUT_STREAM_CFG_CHANNEL_GROUPING 24
/* AUD_FMM_IOP_IN_I2S_x_CAP */
#define I2S_IN_STREAM_CFG_CAP_ENA 31
#define I2S_IN_STREAM_CFG_0_GROUP_ID 4
/* AUD_FMM_IOP_OUT_I2S_x_I2S_CFG_REG */
#define I2S_OUT_CFGX_CLK_ENA 0
#define I2S_OUT_CFGX_DATA_ENABLE 1
#define I2S_OUT_CFGX_DATA_ALIGNMENT 6
#define I2S_OUT_CFGX_BITS_PER_SLOT 13
#define I2S_OUT_CFGX_VALID_SLOT 14
#define I2S_OUT_CFGX_FSYNC_WIDTH 18
#define I2S_OUT_CFGX_SCLKS_PER_1FS_DIV32 26
#define I2S_OUT_CFGX_SLAVE_MODE 30
#define I2S_OUT_CFGX_TDM_MODE 31
/* AUD_FMM_BF_CTRL_SOURCECH_CFGx_REG */
#define BF_SRC_CFGX_SFIFO_ENA 0
#define BF_SRC_CFGX_BUFFER_PAIR_ENABLE 1
#define BF_SRC_CFGX_SAMPLE_CH_MODE 2
#define BF_SRC_CFGX_SFIFO_SZ_DOUBLE 5
#define BF_SRC_CFGX_NOT_PAUSE_WHEN_EMPTY 10
#define BF_SRC_CFGX_BIT_RES 20
#define BF_SRC_CFGX_PROCESS_SEQ_ID_VALID 31
/* AUD_FMM_BF_CTRL_DESTCH_CFGx_REG */
#define BF_DST_CFGX_CAP_ENA 0
#define BF_DST_CFGX_BUFFER_PAIR_ENABLE 1
#define BF_DST_CFGX_DFIFO_SZ_DOUBLE 2
#define BF_DST_CFGX_NOT_PAUSE_WHEN_FULL 11
#define BF_DST_CFGX_FCI_ID 12
#define BF_DST_CFGX_CAP_MODE 24
#define BF_DST_CFGX_PROC_SEQ_ID_VALID 31
/* AUD_FMM_IOP_OUT_SPDIF_xxx */
#define SPDIF_0_OUT_DITHER_ENA 3
#define SPDIF_0_OUT_STREAM_ENA 31
/* AUD_FMM_IOP_PLL_0_USER */
#define IOP_PLL_0_USER_NDIV_FRAC 10
/* AUD_FMM_IOP_PLL_0_ACTIVE */
#define IOP_PLL_0_ACTIVE_NDIV_FRAC 10
#define INIT_SSP_REGS(num) (struct cygnus_ssp_regs){ \
.i2s_stream_cfg = OUT_I2S_ ##num## _STREAM_CFG_OFFSET, \
.i2s_cap_stream_cfg = IN_I2S_ ##num## _STREAM_CFG_OFFSET, \
.i2s_cfg = OUT_I2S_ ##num## _CFG_OFFSET, \
.i2s_cap_cfg = IN_I2S_ ##num## _CFG_OFFSET, \
.i2s_mclk_cfg = OUT_I2S_ ##num## _MCLK_CFG_OFFSET, \
.bf_destch_ctrl = BF_DST_CTRL ##num## _OFFSET, \
.bf_destch_cfg = BF_DST_CFG ##num## _OFFSET, \
.bf_sourcech_ctrl = BF_SRC_CTRL ##num## _OFFSET, \
.bf_sourcech_cfg = BF_SRC_CFG ##num## _OFFSET, \
.bf_sourcech_grp = BF_SRC_GRP ##num## _OFFSET \
}
struct pll_macro_entry {
u32 mclk;
u32 pll_ch_num;
};
/*
* PLL has 3 output channels (1x, 2x, and 4x). Below are
* the common MCLK frequencies used by audio driver
*/
static const struct pll_macro_entry pll_predef_mclk[] = {
{ 4096000, 0},
{ 8192000, 1},
{16384000, 2},
{ 5644800, 0},
{11289600, 1},
{22579200, 2},
{ 6144000, 0},
{12288000, 1},
{24576000, 2},
{12288000, 0},
{24576000, 1},
{49152000, 2},
{22579200, 0},
{45158400, 1},
{90316800, 2},
{24576000, 0},
{49152000, 1},
{98304000, 2},
};
#define CYGNUS_RATE_MIN 8000
#define CYGNUS_RATE_MAX 384000
/* List of valid frame sizes for tdm mode */
static const int ssp_valid_tdm_framesize[] = {32, 64, 128, 256, 512};
static const unsigned int cygnus_rates[] = {
8000, 11025, 16000, 22050, 32000, 44100, 48000,
88200, 96000, 176400, 192000, 352800, 384000
};
static const struct snd_pcm_hw_constraint_list cygnus_rate_constraint = {
.count = ARRAY_SIZE(cygnus_rates),
.list = cygnus_rates,
};
static struct cygnus_aio_port *cygnus_dai_get_portinfo(struct snd_soc_dai *dai)
{
struct cygnus_audio *cygaud = snd_soc_dai_get_drvdata(dai);
return &cygaud->portinfo[dai->id];
}
static int audio_ssp_init_portregs(struct cygnus_aio_port *aio)
{
u32 value, fci_id;
int status = 0;
switch (aio->port_type) {
case PORT_TDM:
value = readl(aio->cygaud->audio + aio->regs.i2s_stream_cfg);
value &= ~I2S_STREAM_CFG_MASK;
/* Set Group ID */
writel(aio->portnum,
aio->cygaud->audio + aio->regs.bf_sourcech_grp);
/* Configure the AUD_FMM_IOP_OUT_I2S_x_STREAM_CFG reg */
value |= aio->portnum << I2S_OUT_STREAM_CFG_GROUP_ID;
value |= aio->portnum; /* FCI ID is the port num */
value |= CH_GRP_STEREO << I2S_OUT_STREAM_CFG_CHANNEL_GROUPING;
writel(value, aio->cygaud->audio + aio->regs.i2s_stream_cfg);
/* Configure the AUD_FMM_BF_CTRL_SOURCECH_CFGX reg */
value = readl(aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
value &= ~BIT(BF_SRC_CFGX_NOT_PAUSE_WHEN_EMPTY);
value |= BIT(BF_SRC_CFGX_SFIFO_SZ_DOUBLE);
value |= BIT(BF_SRC_CFGX_PROCESS_SEQ_ID_VALID);
writel(value, aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
/* Configure the AUD_FMM_IOP_IN_I2S_x_CAP_STREAM_CFG_0 reg */
value = readl(aio->cygaud->i2s_in +
aio->regs.i2s_cap_stream_cfg);
value &= ~I2S_CAP_STREAM_CFG_MASK;
value |= aio->portnum << I2S_IN_STREAM_CFG_0_GROUP_ID;
writel(value, aio->cygaud->i2s_in +
aio->regs.i2s_cap_stream_cfg);
/* Configure the AUD_FMM_BF_CTRL_DESTCH_CFGX_REG_BASE reg */
fci_id = CAPTURE_FCI_ID_BASE + aio->portnum;
value = readl(aio->cygaud->audio + aio->regs.bf_destch_cfg);
value |= BIT(BF_DST_CFGX_DFIFO_SZ_DOUBLE);
value &= ~BIT(BF_DST_CFGX_NOT_PAUSE_WHEN_FULL);
value |= (fci_id << BF_DST_CFGX_FCI_ID);
value |= BIT(BF_DST_CFGX_PROC_SEQ_ID_VALID);
writel(value, aio->cygaud->audio + aio->regs.bf_destch_cfg);
/* Enable the transmit pin for this port */
value = readl(aio->cygaud->audio + AUD_MISC_SEROUT_OE_REG_BASE);
value &= ~BIT((aio->portnum * 4) + AUD_MISC_SEROUT_SDAT_OE);
writel(value, aio->cygaud->audio + AUD_MISC_SEROUT_OE_REG_BASE);
break;
case PORT_SPDIF:
writel(aio->portnum, aio->cygaud->audio + BF_SRC_GRP3_OFFSET);
value = readl(aio->cygaud->audio + SPDIF_CTRL_OFFSET);
value |= BIT(SPDIF_0_OUT_DITHER_ENA);
writel(value, aio->cygaud->audio + SPDIF_CTRL_OFFSET);
/* Enable and set the FCI ID for the SPDIF channel */
value = readl(aio->cygaud->audio + SPDIF_STREAM_CFG_OFFSET);
value &= ~SPDIF_STREAM_CFG_MASK;
value |= aio->portnum; /* FCI ID is the port num */
value |= BIT(SPDIF_0_OUT_STREAM_ENA);
writel(value, aio->cygaud->audio + SPDIF_STREAM_CFG_OFFSET);
value = readl(aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
value &= ~BIT(BF_SRC_CFGX_NOT_PAUSE_WHEN_EMPTY);
value |= BIT(BF_SRC_CFGX_SFIFO_SZ_DOUBLE);
value |= BIT(BF_SRC_CFGX_PROCESS_SEQ_ID_VALID);
writel(value, aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
/* Enable the spdif output pin */
value = readl(aio->cygaud->audio + AUD_MISC_SEROUT_OE_REG_BASE);
value &= ~BIT(AUD_MISC_SEROUT_SPDIF_OE);
writel(value, aio->cygaud->audio + AUD_MISC_SEROUT_OE_REG_BASE);
break;
default:
dev_err(aio->cygaud->dev, "Port not supported\n");
status = -EINVAL;
}
return status;
}
static void audio_ssp_in_enable(struct cygnus_aio_port *aio)
{
u32 value;
value = readl(aio->cygaud->audio + aio->regs.bf_destch_cfg);
value |= BIT(BF_DST_CFGX_CAP_ENA);
writel(value, aio->cygaud->audio + aio->regs.bf_destch_cfg);
writel(0x1, aio->cygaud->audio + aio->regs.bf_destch_ctrl);
value = readl(aio->cygaud->audio + aio->regs.i2s_cfg);
value |= BIT(I2S_OUT_CFGX_CLK_ENA);
value |= BIT(I2S_OUT_CFGX_DATA_ENABLE);
writel(value, aio->cygaud->audio + aio->regs.i2s_cfg);
value = readl(aio->cygaud->i2s_in + aio->regs.i2s_cap_stream_cfg);
value |= BIT(I2S_IN_STREAM_CFG_CAP_ENA);
writel(value, aio->cygaud->i2s_in + aio->regs.i2s_cap_stream_cfg);
aio->streams_on |= CAPTURE_STREAM_MASK;
}
static void audio_ssp_in_disable(struct cygnus_aio_port *aio)
{
u32 value;
value = readl(aio->cygaud->i2s_in + aio->regs.i2s_cap_stream_cfg);
value &= ~BIT(I2S_IN_STREAM_CFG_CAP_ENA);
writel(value, aio->cygaud->i2s_in + aio->regs.i2s_cap_stream_cfg);
aio->streams_on &= ~CAPTURE_STREAM_MASK;
/* If both playback and capture are off */
if (!aio->streams_on) {
value = readl(aio->cygaud->audio + aio->regs.i2s_cfg);
value &= ~BIT(I2S_OUT_CFGX_CLK_ENA);
value &= ~BIT(I2S_OUT_CFGX_DATA_ENABLE);
writel(value, aio->cygaud->audio + aio->regs.i2s_cfg);
}
writel(0x0, aio->cygaud->audio + aio->regs.bf_destch_ctrl);
value = readl(aio->cygaud->audio + aio->regs.bf_destch_cfg);
value &= ~BIT(BF_DST_CFGX_CAP_ENA);
writel(value, aio->cygaud->audio + aio->regs.bf_destch_cfg);
}
static int audio_ssp_out_enable(struct cygnus_aio_port *aio)
{
u32 value;
int status = 0;
switch (aio->port_type) {
case PORT_TDM:
value = readl(aio->cygaud->audio + aio->regs.i2s_stream_cfg);
value |= BIT(I2S_OUT_STREAM_ENA);
writel(value, aio->cygaud->audio + aio->regs.i2s_stream_cfg);
writel(1, aio->cygaud->audio + aio->regs.bf_sourcech_ctrl);
value = readl(aio->cygaud->audio + aio->regs.i2s_cfg);
value |= BIT(I2S_OUT_CFGX_CLK_ENA);
value |= BIT(I2S_OUT_CFGX_DATA_ENABLE);
writel(value, aio->cygaud->audio + aio->regs.i2s_cfg);
value = readl(aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
value |= BIT(BF_SRC_CFGX_SFIFO_ENA);
writel(value, aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
aio->streams_on |= PLAYBACK_STREAM_MASK;
break;
case PORT_SPDIF:
value = readl(aio->cygaud->audio + SPDIF_FORMAT_CFG_OFFSET);
value |= 0x3;
writel(value, aio->cygaud->audio + SPDIF_FORMAT_CFG_OFFSET);
writel(1, aio->cygaud->audio + aio->regs.bf_sourcech_ctrl);
value = readl(aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
value |= BIT(BF_SRC_CFGX_SFIFO_ENA);
writel(value, aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
break;
default:
dev_err(aio->cygaud->dev,
"Port not supported %d\n", aio->portnum);
status = -EINVAL;
}
return status;
}
static int audio_ssp_out_disable(struct cygnus_aio_port *aio)
{
u32 value;
int status = 0;
switch (aio->port_type) {
case PORT_TDM:
aio->streams_on &= ~PLAYBACK_STREAM_MASK;
/* If both playback and capture are off */
if (!aio->streams_on) {
value = readl(aio->cygaud->audio + aio->regs.i2s_cfg);
value &= ~BIT(I2S_OUT_CFGX_CLK_ENA);
value &= ~BIT(I2S_OUT_CFGX_DATA_ENABLE);
writel(value, aio->cygaud->audio + aio->regs.i2s_cfg);
}
/* set group_sync_dis = 1 */
value = readl(aio->cygaud->audio + BF_SRC_GRP_SYNC_DIS_OFFSET);
value |= BIT(aio->portnum);
writel(value, aio->cygaud->audio + BF_SRC_GRP_SYNC_DIS_OFFSET);
writel(0, aio->cygaud->audio + aio->regs.bf_sourcech_ctrl);
value = readl(aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
value &= ~BIT(BF_SRC_CFGX_SFIFO_ENA);
writel(value, aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
/* set group_sync_dis = 0 */
value = readl(aio->cygaud->audio + BF_SRC_GRP_SYNC_DIS_OFFSET);
value &= ~BIT(aio->portnum);
writel(value, aio->cygaud->audio + BF_SRC_GRP_SYNC_DIS_OFFSET);
value = readl(aio->cygaud->audio + aio->regs.i2s_stream_cfg);
value &= ~BIT(I2S_OUT_STREAM_ENA);
writel(value, aio->cygaud->audio + aio->regs.i2s_stream_cfg);
/* IOP SW INIT on OUT_I2S_x */
value = readl(aio->cygaud->i2s_in + IOP_SW_INIT_LOGIC);
value |= BIT(aio->portnum);
writel(value, aio->cygaud->i2s_in + IOP_SW_INIT_LOGIC);
value &= ~BIT(aio->portnum);
writel(value, aio->cygaud->i2s_in + IOP_SW_INIT_LOGIC);
break;
case PORT_SPDIF:
value = readl(aio->cygaud->audio + SPDIF_FORMAT_CFG_OFFSET);
value &= ~0x3;
writel(value, aio->cygaud->audio + SPDIF_FORMAT_CFG_OFFSET);
writel(0, aio->cygaud->audio + aio->regs.bf_sourcech_ctrl);
value = readl(aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
value &= ~BIT(BF_SRC_CFGX_SFIFO_ENA);
writel(value, aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
break;
default:
dev_err(aio->cygaud->dev,
"Port not supported %d\n", aio->portnum);
status = -EINVAL;
}
return status;
}
static int pll_configure_mclk(struct cygnus_audio *cygaud, u32 mclk,
struct cygnus_aio_port *aio)
{
int i = 0, error;
bool found = false;
const struct pll_macro_entry *p_entry;
struct clk *ch_clk;
for (i = 0; i < ARRAY_SIZE(pll_predef_mclk); i++) {
p_entry = &pll_predef_mclk[i];
if (p_entry->mclk == mclk) {
found = true;
break;
}
}
if (!found) {
dev_err(cygaud->dev,
"%s No valid mclk freq (%u) found!\n", __func__, mclk);
return -EINVAL;
}
ch_clk = cygaud->audio_clk[p_entry->pll_ch_num];
if ((aio->clk_trace.cap_en) && (!aio->clk_trace.cap_clk_en)) {
error = clk_prepare_enable(ch_clk);
if (error) {
dev_err(cygaud->dev, "%s clk_prepare_enable failed %d\n",
__func__, error);
return error;
}
aio->clk_trace.cap_clk_en = true;
}
if ((aio->clk_trace.play_en) && (!aio->clk_trace.play_clk_en)) {
error = clk_prepare_enable(ch_clk);
if (error) {
dev_err(cygaud->dev, "%s clk_prepare_enable failed %d\n",
__func__, error);
return error;
}
aio->clk_trace.play_clk_en = true;
}
error = clk_set_rate(ch_clk, mclk);
if (error) {
dev_err(cygaud->dev, "%s Set MCLK rate failed: %d\n",
__func__, error);
return error;
}
return p_entry->pll_ch_num;
}
static int cygnus_ssp_set_clocks(struct cygnus_aio_port *aio)
{
u32 value;
u32 mask = 0xf;
u32 sclk;
u32 mclk_rate;
unsigned int bit_rate;
unsigned int ratio;
bit_rate = aio->bit_per_frame * aio->lrclk;
/*
* Check if the bit clock can be generated from the given MCLK.
* MCLK must be a perfect multiple of bit clock and must be one of the
* following values... (2,4,6,8,10,12,14)
*/
if ((aio->mclk % bit_rate) != 0)
return -EINVAL;
ratio = aio->mclk / bit_rate;
switch (ratio) {
case 2:
case 4:
case 6:
case 8:
case 10:
case 12:
case 14:
mclk_rate = ratio / 2;
break;
default:
dev_err(aio->cygaud->dev,
"Invalid combination of MCLK and BCLK\n");
dev_err(aio->cygaud->dev, "lrclk = %u, bits/frame = %u, mclk = %u\n",
aio->lrclk, aio->bit_per_frame, aio->mclk);
return -EINVAL;
}
/* Set sclk rate */
switch (aio->port_type) {
case PORT_TDM:
sclk = aio->bit_per_frame;
if (sclk == 512)
sclk = 0;
/* sclks_per_1fs_div = sclk cycles/32 */
sclk /= 32;
/* Set number of bitclks per frame */
value = readl(aio->cygaud->audio + aio->regs.i2s_cfg);
value &= ~(mask << I2S_OUT_CFGX_SCLKS_PER_1FS_DIV32);
value |= sclk << I2S_OUT_CFGX_SCLKS_PER_1FS_DIV32;
writel(value, aio->cygaud->audio + aio->regs.i2s_cfg);
dev_dbg(aio->cygaud->dev,
"SCLKS_PER_1FS_DIV32 = 0x%x\n", value);
break;
case PORT_SPDIF:
break;
default:
dev_err(aio->cygaud->dev, "Unknown port type\n");
return -EINVAL;
}
/* Set MCLK_RATE ssp port (spdif and ssp are the same) */
value = readl(aio->cygaud->audio + aio->regs.i2s_mclk_cfg);
value &= ~(0xf << I2S_OUT_MCLKRATE_SHIFT);
value |= (mclk_rate << I2S_OUT_MCLKRATE_SHIFT);
writel(value, aio->cygaud->audio + aio->regs.i2s_mclk_cfg);
dev_dbg(aio->cygaud->dev, "mclk cfg reg = 0x%x\n", value);
dev_dbg(aio->cygaud->dev, "bits per frame = %u, mclk = %u Hz, lrclk = %u Hz\n",
aio->bit_per_frame, aio->mclk, aio->lrclk);
return 0;
}
static int cygnus_ssp_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct cygnus_aio_port *aio = cygnus_dai_get_portinfo(dai);
int rate, bitres;
u32 value;
u32 mask = 0x1f;
int ret = 0;
dev_dbg(aio->cygaud->dev, "%s port = %d\n", __func__, aio->portnum);
dev_dbg(aio->cygaud->dev, "params_channels %d\n",
params_channels(params));
dev_dbg(aio->cygaud->dev, "rate %d\n", params_rate(params));
dev_dbg(aio->cygaud->dev, "format %d\n", params_format(params));
rate = params_rate(params);
switch (aio->mode) {
case CYGNUS_SSPMODE_TDM:
if ((rate == 192000) && (params_channels(params) > 4)) {
dev_err(aio->cygaud->dev, "Cannot run %d channels at %dHz\n",
params_channels(params), rate);
return -EINVAL;
}
break;
case CYGNUS_SSPMODE_I2S:
aio->bit_per_frame = 64; /* I2S must be 64 bit per frame */
break;
default:
dev_err(aio->cygaud->dev,
"%s port running in unknown mode\n", __func__);
return -EINVAL;
}
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
value = readl(aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
value &= ~BIT(BF_SRC_CFGX_BUFFER_PAIR_ENABLE);
value &= ~BIT(BF_SRC_CFGX_SAMPLE_CH_MODE);
writel(value, aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
bitres = 16;
break;
case SNDRV_PCM_FORMAT_S32_LE:
/* 32 bit mode is coded as 0 */
bitres = 0;
break;
default:
return -EINVAL;
}
value = readl(aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
value &= ~(mask << BF_SRC_CFGX_BIT_RES);
value |= (bitres << BF_SRC_CFGX_BIT_RES);
writel(value, aio->cygaud->audio + aio->regs.bf_sourcech_cfg);
} else {
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
value = readl(aio->cygaud->audio +
aio->regs.bf_destch_cfg);
value |= BIT(BF_DST_CFGX_CAP_MODE);
writel(value, aio->cygaud->audio +
aio->regs.bf_destch_cfg);
break;
case SNDRV_PCM_FORMAT_S32_LE:
value = readl(aio->cygaud->audio +
aio->regs.bf_destch_cfg);
value &= ~BIT(BF_DST_CFGX_CAP_MODE);
writel(value, aio->cygaud->audio +
aio->regs.bf_destch_cfg);
break;
default:
return -EINVAL;
}
}
aio->lrclk = rate;
if (!aio->is_slave)
ret = cygnus_ssp_set_clocks(aio);
return ret;
}
/*
* This function sets the mclk frequency for pll clock
*/
static int cygnus_ssp_set_sysclk(struct snd_soc_dai *dai,
int clk_id, unsigned int freq, int dir)
{
int sel;
u32 value;
struct cygnus_aio_port *aio = cygnus_dai_get_portinfo(dai);
struct cygnus_audio *cygaud = snd_soc_dai_get_drvdata(dai);
dev_dbg(aio->cygaud->dev,
"%s Enter port = %d\n", __func__, aio->portnum);
sel = pll_configure_mclk(cygaud, freq, aio);
if (sel < 0) {
dev_err(aio->cygaud->dev,
"%s Setting mclk failed.\n", __func__);
return -EINVAL;
}
aio->mclk = freq;
dev_dbg(aio->cygaud->dev, "%s Setting MCLKSEL to %d\n", __func__, sel);
value = readl(aio->cygaud->audio + aio->regs.i2s_mclk_cfg);
value &= ~(0xf << I2S_OUT_PLLCLKSEL_SHIFT);
value |= (sel << I2S_OUT_PLLCLKSEL_SHIFT);
writel(value, aio->cygaud->audio + aio->regs.i2s_mclk_cfg);
return 0;
}
static int cygnus_ssp_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct cygnus_aio_port *aio = cygnus_dai_get_portinfo(dai);
snd_soc_dai_set_dma_data(dai, substream, aio);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
aio->clk_trace.play_en = true;
else
aio->clk_trace.cap_en = true;
substream->runtime->hw.rate_min = CYGNUS_RATE_MIN;
substream->runtime->hw.rate_max = CYGNUS_RATE_MAX;
snd_pcm_hw_constraint_list(substream->runtime, 0,
SNDRV_PCM_HW_PARAM_RATE, &cygnus_rate_constraint);
return 0;
}
static void cygnus_ssp_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct cygnus_aio_port *aio = cygnus_dai_get_portinfo(dai);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
aio->clk_trace.play_en = false;
else
aio->clk_trace.cap_en = false;
if (!aio->is_slave) {
u32 val;
val = readl(aio->cygaud->audio + aio->regs.i2s_mclk_cfg);
val &= CYGNUS_PLLCLKSEL_MASK;
if (val >= ARRAY_SIZE(aio->cygaud->audio_clk)) {
dev_err(aio->cygaud->dev, "Clk index %u is out of bounds\n",
val);
return;
}
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
if (aio->clk_trace.play_clk_en) {
clk_disable_unprepare(aio->cygaud->
audio_clk[val]);
aio->clk_trace.play_clk_en = false;
}
} else {
if (aio->clk_trace.cap_clk_en) {
clk_disable_unprepare(aio->cygaud->
audio_clk[val]);
aio->clk_trace.cap_clk_en = false;
}
}
}
}
/*
* Bit Update Notes
* 31 Yes TDM Mode (1 = TDM, 0 = i2s)
* 30 Yes Slave Mode (1 = Slave, 0 = Master)
* 29:26 No Sclks per frame
* 25:18 Yes FS Width
* 17:14 No Valid Slots
* 13 No Bits (1 = 16 bits, 0 = 32 bits)
* 12:08 No Bits per samp
* 07 Yes Justifcation (1 = LSB, 0 = MSB)
* 06 Yes Alignment (1 = Delay 1 clk, 0 = no delay
* 05 Yes SCLK polarity (1 = Rising, 0 = Falling)
* 04 Yes LRCLK Polarity (1 = High for left, 0 = Low for left)
* 03:02 Yes Reserved - write as zero
* 01 No Data Enable
* 00 No CLK Enable
*/
#define I2S_OUT_CFG_REG_UPDATE_MASK 0x3C03FF03
/* Input cfg is same as output, but the FS width is not a valid field */
#define I2S_IN_CFG_REG_UPDATE_MASK (I2S_OUT_CFG_REG_UPDATE_MASK | 0x03FC0000)
int cygnus_ssp_set_custom_fsync_width(struct snd_soc_dai *cpu_dai, int len)
{
struct cygnus_aio_port *aio = cygnus_dai_get_portinfo(cpu_dai);
if ((len > 0) && (len < 256)) {
aio->fsync_width = len;
return 0;
} else {
return -EINVAL;
}
}
EXPORT_SYMBOL_GPL(cygnus_ssp_set_custom_fsync_width);
static int cygnus_ssp_set_fmt(struct snd_soc_dai *cpu_dai, unsigned int fmt)
{
struct cygnus_aio_port *aio = cygnus_dai_get_portinfo(cpu_dai);
u32 ssp_curcfg;
u32 ssp_newcfg;
u32 ssp_outcfg;
u32 ssp_incfg;
u32 val;
u32 mask;
dev_dbg(aio->cygaud->dev, "%s Enter fmt: %x\n", __func__, fmt);
if (aio->port_type == PORT_SPDIF)
return -EINVAL;
ssp_newcfg = 0;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
ssp_newcfg |= BIT(I2S_OUT_CFGX_SLAVE_MODE);
aio->is_slave = 1;
break;
case SND_SOC_DAIFMT_CBS_CFS:
ssp_newcfg &= ~BIT(I2S_OUT_CFGX_SLAVE_MODE);
aio->is_slave = 0;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
ssp_newcfg |= BIT(I2S_OUT_CFGX_DATA_ALIGNMENT);
ssp_newcfg |= BIT(I2S_OUT_CFGX_FSYNC_WIDTH);
aio->mode = CYGNUS_SSPMODE_I2S;
break;
case SND_SOC_DAIFMT_DSP_A:
case SND_SOC_DAIFMT_DSP_B:
ssp_newcfg |= BIT(I2S_OUT_CFGX_TDM_MODE);
/* DSP_A = data after FS, DSP_B = data during FS */
if ((fmt & SND_SOC_DAIFMT_FORMAT_MASK) == SND_SOC_DAIFMT_DSP_A)
ssp_newcfg |= BIT(I2S_OUT_CFGX_DATA_ALIGNMENT);
if ((aio->fsync_width > 0) && (aio->fsync_width < 256))
ssp_newcfg |=
(aio->fsync_width << I2S_OUT_CFGX_FSYNC_WIDTH);
else
ssp_newcfg |= BIT(I2S_OUT_CFGX_FSYNC_WIDTH);
aio->mode = CYGNUS_SSPMODE_TDM;
break;
default:
return -EINVAL;
}
/*
* SSP out cfg.
* Retain bits we do not want to update, then OR in new bits
*/
ssp_curcfg = readl(aio->cygaud->audio + aio->regs.i2s_cfg);
ssp_outcfg = (ssp_curcfg & I2S_OUT_CFG_REG_UPDATE_MASK) | ssp_newcfg;
writel(ssp_outcfg, aio->cygaud->audio + aio->regs.i2s_cfg);
/*
* SSP in cfg.
* Retain bits we do not want to update, then OR in new bits
*/
ssp_curcfg = readl(aio->cygaud->i2s_in + aio->regs.i2s_cap_cfg);
ssp_incfg = (ssp_curcfg & I2S_IN_CFG_REG_UPDATE_MASK) | ssp_newcfg;
writel(ssp_incfg, aio->cygaud->i2s_in + aio->regs.i2s_cap_cfg);
val = readl(aio->cygaud->audio + AUD_MISC_SEROUT_OE_REG_BASE);
/*
* Configure the word clk and bit clk as output or tristate
* Each port has 4 bits for controlling its pins.
* Shift the mask based upon port number.
*/
mask = BIT(AUD_MISC_SEROUT_LRCK_OE)
| BIT(AUD_MISC_SEROUT_SCLK_OE)
| BIT(AUD_MISC_SEROUT_MCLK_OE);
mask = mask << (aio->portnum * 4);
if (aio->is_slave)
/* Set bit for tri-state */
val |= mask;
else
/* Clear bit for drive */
val &= ~mask;
dev_dbg(aio->cygaud->dev, "%s Set OE bits 0x%x\n", __func__, val);
writel(val, aio->cygaud->audio + AUD_MISC_SEROUT_OE_REG_BASE);
return 0;
}
static int cygnus_ssp_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
struct cygnus_aio_port *aio = cygnus_dai_get_portinfo(dai);
struct cygnus_audio *cygaud = snd_soc_dai_get_drvdata(dai);
dev_dbg(aio->cygaud->dev,
"%s cmd %d at port = %d\n", __func__, cmd, aio->portnum);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
audio_ssp_out_enable(aio);
else
audio_ssp_in_enable(aio);
cygaud->active_ports++;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
audio_ssp_out_disable(aio);
else
audio_ssp_in_disable(aio);
cygaud->active_ports--;
break;
default:
return -EINVAL;
}
return 0;
}
static int cygnus_set_dai_tdm_slot(struct snd_soc_dai *cpu_dai,
unsigned int tx_mask, unsigned int rx_mask, int slots, int slot_width)
{
struct cygnus_aio_port *aio = cygnus_dai_get_portinfo(cpu_dai);
u32 value;
int bits_per_slot = 0; /* default to 32-bits per slot */
int frame_bits;
unsigned int active_slots;
bool found = false;
int i;
if (tx_mask != rx_mask) {
dev_err(aio->cygaud->dev,
"%s tx_mask must equal rx_mask\n", __func__);
return -EINVAL;
}
active_slots = hweight32(tx_mask);
if (active_slots > 16)
return -EINVAL;
/* Slot value must be even */
if (active_slots % 2)
return -EINVAL;
/* We encode 16 slots as 0 in the reg */
if (active_slots == 16)
active_slots = 0;
/* Slot Width is either 16 or 32 */
switch (slot_width) {
case 16:
bits_per_slot = 1;
break;
case 32:
bits_per_slot = 0;
break;
default:
bits_per_slot = 0;
dev_warn(aio->cygaud->dev,
"%s Defaulting Slot Width to 32\n", __func__);
}
frame_bits = slots * slot_width;
for (i = 0; i < ARRAY_SIZE(ssp_valid_tdm_framesize); i++) {
if (ssp_valid_tdm_framesize[i] == frame_bits) {
found = true;
break;
}
}
if (!found) {
dev_err(aio->cygaud->dev,
"%s In TDM mode, frame bits INVALID (%d)\n",
__func__, frame_bits);
return -EINVAL;
}
aio->bit_per_frame = frame_bits;
dev_dbg(aio->cygaud->dev, "%s active_slots %u, bits per frame %d\n",
__func__, active_slots, frame_bits);
/* Set capture side of ssp port */
value = readl(aio->cygaud->i2s_in + aio->regs.i2s_cap_cfg);
value &= ~(0xf << I2S_OUT_CFGX_VALID_SLOT);
value |= (active_slots << I2S_OUT_CFGX_VALID_SLOT);
value &= ~BIT(I2S_OUT_CFGX_BITS_PER_SLOT);
value |= (bits_per_slot << I2S_OUT_CFGX_BITS_PER_SLOT);
writel(value, aio->cygaud->i2s_in + aio->regs.i2s_cap_cfg);
/* Set playback side of ssp port */
value = readl(aio->cygaud->audio + aio->regs.i2s_cfg);
value &= ~(0xf << I2S_OUT_CFGX_VALID_SLOT);
value |= (active_slots << I2S_OUT_CFGX_VALID_SLOT);
value &= ~BIT(I2S_OUT_CFGX_BITS_PER_SLOT);
value |= (bits_per_slot << I2S_OUT_CFGX_BITS_PER_SLOT);
writel(value, aio->cygaud->audio + aio->regs.i2s_cfg);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int cygnus_ssp_suspend(struct snd_soc_dai *cpu_dai)
{
struct cygnus_aio_port *aio = cygnus_dai_get_portinfo(cpu_dai);
if (!aio->is_slave) {
u32 val;
val = readl(aio->cygaud->audio + aio->regs.i2s_mclk_cfg);
val &= CYGNUS_PLLCLKSEL_MASK;
if (val >= ARRAY_SIZE(aio->cygaud->audio_clk)) {
dev_err(aio->cygaud->dev, "Clk index %u is out of bounds\n",
val);
return -EINVAL;
}
if (aio->clk_trace.cap_clk_en)
clk_disable_unprepare(aio->cygaud->audio_clk[val]);
if (aio->clk_trace.play_clk_en)
clk_disable_unprepare(aio->cygaud->audio_clk[val]);
aio->pll_clk_num = val;
}
return 0;
}
static int cygnus_ssp_resume(struct snd_soc_dai *cpu_dai)
{
struct cygnus_aio_port *aio = cygnus_dai_get_portinfo(cpu_dai);
int error;
if (!aio->is_slave) {
if (aio->clk_trace.cap_clk_en) {
error = clk_prepare_enable(aio->cygaud->
audio_clk[aio->pll_clk_num]);
if (error) {
dev_err(aio->cygaud->dev, "%s clk_prepare_enable failed\n",
__func__);
return -EINVAL;
}
}
if (aio->clk_trace.play_clk_en) {
error = clk_prepare_enable(aio->cygaud->
audio_clk[aio->pll_clk_num]);
if (error) {
if (aio->clk_trace.cap_clk_en)
clk_disable_unprepare(aio->cygaud->
audio_clk[aio->pll_clk_num]);
dev_err(aio->cygaud->dev, "%s clk_prepare_enable failed\n",
__func__);
return -EINVAL;
}
}
}
return 0;
}
#else
#define cygnus_ssp_suspend NULL
#define cygnus_ssp_resume NULL
#endif
static const struct snd_soc_dai_ops cygnus_ssp_dai_ops = {
.startup = cygnus_ssp_startup,
.shutdown = cygnus_ssp_shutdown,
.trigger = cygnus_ssp_trigger,
.hw_params = cygnus_ssp_hw_params,
.set_fmt = cygnus_ssp_set_fmt,
.set_sysclk = cygnus_ssp_set_sysclk,
.set_tdm_slot = cygnus_set_dai_tdm_slot,
};
static const struct snd_soc_dai_ops cygnus_spdif_dai_ops = {
.startup = cygnus_ssp_startup,
.shutdown = cygnus_ssp_shutdown,
.trigger = cygnus_ssp_trigger,
.hw_params = cygnus_ssp_hw_params,
.set_sysclk = cygnus_ssp_set_sysclk,
};
#define INIT_CPU_DAI(num) { \
.name = "cygnus-ssp" #num, \
.playback = { \
.channels_min = 2, \
.channels_max = 16, \
.rates = SNDRV_PCM_RATE_KNOT, \
.formats = SNDRV_PCM_FMTBIT_S16_LE | \
SNDRV_PCM_FMTBIT_S32_LE, \
}, \
.capture = { \
.channels_min = 2, \
.channels_max = 16, \
.rates = SNDRV_PCM_RATE_KNOT, \
.formats = SNDRV_PCM_FMTBIT_S16_LE | \
SNDRV_PCM_FMTBIT_S32_LE, \
}, \
.ops = &cygnus_ssp_dai_ops, \
.suspend = cygnus_ssp_suspend, \
.resume = cygnus_ssp_resume, \
}
static const struct snd_soc_dai_driver cygnus_ssp_dai_info[] = {
INIT_CPU_DAI(0),
INIT_CPU_DAI(1),
INIT_CPU_DAI(2),
};
static const struct snd_soc_dai_driver cygnus_spdif_dai_info = {
.name = "cygnus-spdif",
.playback = {
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_KNOT,
.formats = SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_S32_LE,
},
.ops = &cygnus_spdif_dai_ops,
.suspend = cygnus_ssp_suspend,
.resume = cygnus_ssp_resume,
};
static struct snd_soc_dai_driver cygnus_ssp_dai[CYGNUS_MAX_PORTS];
static const struct snd_soc_component_driver cygnus_ssp_component = {
.name = "cygnus-audio",
};
/*
* Return < 0 if error
* Return 0 if disabled
* Return 1 if enabled and node is parsed successfully
*/
static int parse_ssp_child_node(struct platform_device *pdev,
struct device_node *dn,
struct cygnus_audio *cygaud,
struct snd_soc_dai_driver *p_dai)
{
struct cygnus_aio_port *aio;
struct cygnus_ssp_regs ssp_regs[3];
u32 rawval;
int portnum = -1;
enum cygnus_audio_port_type port_type;
if (of_property_read_u32(dn, "reg", &rawval)) {
dev_err(&pdev->dev, "Missing reg property\n");
return -EINVAL;
}
portnum = rawval;
switch (rawval) {
case 0:
ssp_regs[0] = INIT_SSP_REGS(0);
port_type = PORT_TDM;
break;
case 1:
ssp_regs[1] = INIT_SSP_REGS(1);
port_type = PORT_TDM;
break;
case 2:
ssp_regs[2] = INIT_SSP_REGS(2);
port_type = PORT_TDM;
break;
case 3:
port_type = PORT_SPDIF;
break;
default:
dev_err(&pdev->dev, "Bad value for reg %u\n", rawval);
return -EINVAL;
}
aio = &cygaud->portinfo[portnum];
aio->cygaud = cygaud;
aio->portnum = portnum;
aio->port_type = port_type;
aio->fsync_width = -1;
switch (port_type) {
case PORT_TDM:
aio->regs = ssp_regs[portnum];
*p_dai = cygnus_ssp_dai_info[portnum];
aio->mode = CYGNUS_SSPMODE_UNKNOWN;
break;
case PORT_SPDIF:
aio->regs.bf_sourcech_cfg = BF_SRC_CFG3_OFFSET;
aio->regs.bf_sourcech_ctrl = BF_SRC_CTRL3_OFFSET;
aio->regs.i2s_mclk_cfg = SPDIF_MCLK_CFG_OFFSET;
aio->regs.i2s_stream_cfg = SPDIF_STREAM_CFG_OFFSET;
*p_dai = cygnus_spdif_dai_info;
/* For the purposes of this code SPDIF can be I2S mode */
aio->mode = CYGNUS_SSPMODE_I2S;
break;
default:
dev_err(&pdev->dev, "Bad value for port_type %d\n", port_type);
return -EINVAL;
}
dev_dbg(&pdev->dev, "%s portnum = %d\n", __func__, aio->portnum);
aio->streams_on = 0;
aio->cygaud->dev = &pdev->dev;
aio->clk_trace.play_en = false;
aio->clk_trace.cap_en = false;
audio_ssp_init_portregs(aio);
return 0;
}
static int audio_clk_init(struct platform_device *pdev,
struct cygnus_audio *cygaud)
{
int i;
char clk_name[PROP_LEN_MAX];
for (i = 0; i < ARRAY_SIZE(cygaud->audio_clk); i++) {
snprintf(clk_name, PROP_LEN_MAX, "ch%d_audio", i);
cygaud->audio_clk[i] = devm_clk_get(&pdev->dev, clk_name);
if (IS_ERR(cygaud->audio_clk[i]))
return PTR_ERR(cygaud->audio_clk[i]);
}
return 0;
}
static int cygnus_ssp_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct device_node *child_node;
struct resource *res;
struct cygnus_audio *cygaud;
int err = -EINVAL;
int node_count;
int active_port_count;
cygaud = devm_kzalloc(dev, sizeof(struct cygnus_audio), GFP_KERNEL);
if (!cygaud)
return -ENOMEM;
dev_set_drvdata(dev, cygaud);
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "aud");
cygaud->audio = devm_ioremap_resource(dev, res);
if (IS_ERR(cygaud->audio))
return PTR_ERR(cygaud->audio);
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "i2s_in");
cygaud->i2s_in = devm_ioremap_resource(dev, res);
if (IS_ERR(cygaud->i2s_in))
return PTR_ERR(cygaud->i2s_in);
/* Tri-state all controlable pins until we know that we need them */
writel(CYGNUS_SSP_TRISTATE_MASK,
cygaud->audio + AUD_MISC_SEROUT_OE_REG_BASE);
node_count = of_get_child_count(pdev->dev.of_node);
if ((node_count < 1) || (node_count > CYGNUS_MAX_PORTS)) {
dev_err(dev, "child nodes is %d. Must be between 1 and %d\n",
node_count, CYGNUS_MAX_PORTS);
return -EINVAL;
}
active_port_count = 0;
for_each_available_child_of_node(pdev->dev.of_node, child_node) {
err = parse_ssp_child_node(pdev, child_node, cygaud,
&cygnus_ssp_dai[active_port_count]);
/* negative is err, 0 is active and good, 1 is disabled */
if (err < 0)
return err;
else if (!err) {
dev_dbg(dev, "Activating DAI: %s\n",
cygnus_ssp_dai[active_port_count].name);
active_port_count++;
}
}
cygaud->dev = dev;
cygaud->active_ports = 0;
dev_dbg(dev, "Registering %d DAIs\n", active_port_count);
err = snd_soc_register_component(dev, &cygnus_ssp_component,
cygnus_ssp_dai, active_port_count);
if (err) {
dev_err(dev, "snd_soc_register_dai failed\n");
return err;
}
cygaud->irq_num = platform_get_irq(pdev, 0);
if (cygaud->irq_num <= 0) {
dev_err(dev, "platform_get_irq failed\n");
err = cygaud->irq_num;
goto err_irq;
}
err = audio_clk_init(pdev, cygaud);
if (err) {
dev_err(dev, "audio clock initialization failed\n");
goto err_irq;
}
err = cygnus_soc_platform_register(dev, cygaud);
if (err) {
dev_err(dev, "platform reg error %d\n", err);
goto err_irq;
}
return 0;
err_irq:
snd_soc_unregister_component(dev);
return err;
}
static int cygnus_ssp_remove(struct platform_device *pdev)
{
cygnus_soc_platform_unregister(&pdev->dev);
snd_soc_unregister_component(&pdev->dev);
return 0;
}
static const struct of_device_id cygnus_ssp_of_match[] = {
{ .compatible = "brcm,cygnus-audio" },
{},
};
MODULE_DEVICE_TABLE(of, cygnus_ssp_of_match);
static struct platform_driver cygnus_ssp_driver = {
.probe = cygnus_ssp_probe,
.remove = cygnus_ssp_remove,
.driver = {
.name = "cygnus-ssp",
.of_match_table = cygnus_ssp_of_match,
},
};
module_platform_driver(cygnus_ssp_driver);
MODULE_ALIAS("platform:cygnus-ssp");
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Broadcom");
MODULE_DESCRIPTION("Cygnus ASoC SSP Interface");
| {
"pile_set_name": "Github"
} |
// Copyright (c) 1997-2001 ETH Zurich (Switzerland).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s) : Kaspar Fischer <[email protected]>
// Note: whenever a comment refers to "Khachiyan's paper" then the
// paper "Rounding of polytopes in the real number model of
// computation" is ment (Mathematics of Operations Research, Vol. 21,
// No. 2, May 1996). Nontheless, most comments refer to the
// accompanying documentation sheet (and not to the above paper), see
// the file(s) in documentation/.
#include <numeric>
#include <CGAL/tags.h>
#include <CGAL/use.h>
#include <CGAL/Approximate_min_ellipsoid_d/Khachiyan_approximation.h>
namespace CGAL {
namespace Appel_impl {
// Computes the inverse of the positive definite (dxd)-matrix A
// into Ai, by using the Cholesky decomposition of A. All three
// iterator template parameters must be random access iterators of
// value type FT. The iterator tmp must have d entries. The
// routine returns true in case no errors occurred; false is
// returned in case of stability problems or when A is not
// positive definite.
//
// Note: A is destroyed in this process.
//
// Precondition: A and Ai may point to the same matrix (i.e., might alias).
template<typename FT,
typename Tmp_iterator,
typename A_iterator,
typename A_inverse_iterator>
bool pd_matrix_inverse(const int d,
A_iterator A,
A_inverse_iterator Ai,
Tmp_iterator tmp)
{
// I use the following version (in matlab notation) from Walter
// Gander's lecture "Ausgleichsrechnung" (ETH Zurich, around 2000, see
// http://www.inf.ethz.ch/personal/chinella/education/ausgleich/
// Demo2.txt):
//
// # compute lower-triangular L s.t. A = LL^T:
// for j=1:d
// v = A(j:d,j) - L(j:d,1:j-1) * L(j,1:j-1)';
// L(j:d,j) = v/sqrt(v(1));
// end;
//
// Observe that the vector v in this pseudo-code is a
// (d-j+1)-vector; we use (the last d-j+1 entries of) the vector
// tmp to store v. (Also, the above program uses one-based
// counting, the code below is of course zero-based.) Note also
// that instead of computing the result into L we can as well
// overwrite the lower part of A.
for (int j=0; j<d; ++j) {
// compute new column (v in above pseudo-code):
for (int i=j; i<d; ++i) {
FT ll(0);
for (int k=0; k<j; ++k)
ll += A[i+k*d] * A[j+k*d];
tmp[i] = A[i+j*d] - ll;
}
// check regularity:
if (tmp[j] <= 0) // todo: epsilon?
return false;
// overwrite column:
const FT scale = FT(1)/std::sqrt(tmp[j]);
for (int i=j; i<d; ++i)
A[i+j*d] = tmp[i] * scale;
}
// Now that we have in the lower triangular part of A the
// Cholesky decomposition A = LL^T of the original A, we compute
// the inverse of A see "Numerical Recipes in C", end of Chapter
// 2.9.
for (int i=0; i<d; ++i) {
A[i+i*d] = FT(1)/A[i+i*d];
for (int j=i+1; j<d; ++j) {
FT sum(0);
for (int k=i; k<j; ++k)
sum -= A[j+k*d] * A[k+i*d];
A[j+i*d] = sum/A[j+j*d];
}
}
// Finally, we calculate A^{-1} = (L^{-1})^T L^{-1} into Ai:
for (int i=0; i<d; ++i)
for (int j=0; j<=i; ++j) {
// compute entry (i,j) of A^{-1}:
FT sum(0);
for (int k=i; k<d; ++k)
sum += A[k+i*d] * A[k+j*d];
Ai[i+j*d] = sum;
// Since A^{-1} is symmetric, we set:
Ai[j+i*d] = sum;
}
return true;
}
} // end of namespace Appel_impl
template<bool Embed,class Traits>
Khachiyan_approximation<Embed,Traits>::
~Khachiyan_approximation()
{
CGAL_APPEL_ASSERT_EXPENSIVE(is_valid(false));
}
#ifdef CGAL_APPEL_ASSERTION_MODE
template<bool Embed,class Traits>
void Khachiyan_approximation<Embed,Traits>::compute_M_of_x()
// Computes into t the matrix
//
// M(x) = sum(x_i p_i p_i^T,i=0..(n-1)).
//
// Complexity: O(n d^2)
//
// Note: we only use this routine to check assertions.
{
// erase m:
for (int i=0; i<d; ++i)
for (int j=0; j<d; ++j)
t[i+j*d] = FT(0);
// evaluate products:
for (int k=0; k<n; ++k) {
C_it pi = tco.cartesian_begin(*P[k]);
for (int i=0; i<d_P; ++i, ++pi) {
C_it pj = tco.cartesian_begin(*P[k]);
for (int j=0; j<d_P; ++j, ++pj)
t[i+j*d] += x[k] * (*pi) * (*pj);
if (Embed)
t[i+d_P*d] += x[k] * (*pi);
}
if (Embed) {
C_it pj = tco.cartesian_begin(*P[k]);
for (int j=0; j<d_P; ++j, ++pj)
t[d_P+j*d] += x[k] * (*pj);
t[d_P+d_P*d] += x[k];
}
}
}
#endif // CGAL_APPEL_ASSERTION_MODE
template<bool Embed,class Traits>
bool Khachiyan_approximation<Embed,Traits>::
compute_inverse_of_t_into_mi(const Tag_true /* exact*/)
// Note: this routine is not used in CGAL; it turned out that using
// exact arithmetic, the algorithm is very slow.
{
// We need to compute into mi the inverse of the matrix t. We use
// Gauss-Jordan elimination to do this. So we write t and the
// identity matrix I as [I|t] and transform this (by means of row
// operations) into a system of the form [N|I]. Then N is the
// inverse of t. Why? This is like solving a linear system with
// several right-hand sides simultaneously by Gauss elimination:
// Since the transformations we apply do not change the solution
// space of the intermediate systems, we can say: The system t x =
// e_j has, for any i in {1,...,d}, the same solution space as I x
// = n_i (with n_i being the i-th column of N); it follows that
// x=n_i.
// store the identity matrix in mi:
for (int i=0; i<d; ++i)
for (int j=0; j<d; ++j)
mi[i+j*d] = FT(i==j? 1 : 0);
// Since it is not always possible to achieve a final form [*|I]
// without row exchanges, we try to get the form [*|P(I)] where
// P(I) stands for a permutation of the rows of the matrix I ---
// in other words: we want a "1" in every row. Therefore, we
// maintain a integer for every row with the number of the column
// into which we placed a "1", or a -1 in case we haven't yet
// place a "1" in this row. Also, we maintain for every column
// the number of the row into which we placed the one.
std::vector<int> col_with_one(d,-1);
std::vector<int> row_with_one(d);
for (int j=d-1; j>=0; --j) {
// In this iteration of the loop we try to make the column j of
// m a zero vector with exactly one 1 in an unused place (i.e.,
// in a place k for which one_in_row(k) isn't yet true).
// search for a suitable place k:
bool found = false;
int k = d-1;
for (; k>=0; --k)
if (!is_zero(t[k+j*d]) && col_with_one[k]<0) {
found = true;
break;
}
if (!found)
return false;
col_with_one[k] = j;
row_with_one[j] = k;
// zero out the entries above and below entry k:
for (int i=0; i<d; ++i)
if (i != k) {
// we add l times row k to row i:
const FT l = -t[i+j*d]/t[k+j*d];
for (int jj=0; jj<d; ++jj)
mi[i+jj*d] += l*mi[k+jj*d];
for (int jj=0; jj<=j; ++jj)
t[i+jj*d] += l*t[k+jj*d];
}
// finally, we scale row k to get a one at (k,j):
for (int jj=0; jj<d; ++jj)
mi[k+jj*d] /= t[k+j*d];
for (int jj=0; jj<=j; ++jj)
t[k+jj*d] /= t[k+j*d];
}
// At this point we know that for any i in {1,...,d} the system m
// x = e_i has the some solution as P(I) x = n_i. So x =
// P(I)^{-1} n_i and it thus suffices to undo the permutation:
for (int i=0; i<d; ++i)
if (row_with_one[i] != i) {
const int repl_row = row_with_one[i];
const int col = col_with_one[i];
for (int j=0; j<d; ++j)
std::swap(mi[i+j*d],mi[repl_row+j*d]);
row_with_one[col] = repl_row;
col_with_one[repl_row] = col;
row_with_one[i] = col_with_one[i] = i;
}
return true;
}
template<bool Embed,class Traits>
bool Khachiyan_approximation<Embed,Traits>::
compute_inverse_of_t_into_mi(const Tag_false /* exact */)
{
// handle the obvious case when the points cannot span \R^d:
if (P.size() <= static_cast<unsigned int>(d))
return false;
return Appel_impl::pd_matrix_inverse<FT>(d,
t.begin(),
mi.begin(),
tmp.begin());
}
template<bool Embed,class Traits>
bool Khachiyan_approximation<Embed,Traits>::
compute_initial_inverse_from_sum()
{
// assertions:
CGAL_APPEL_ASSERT(is_deg);
// check number of points:
if (n == 0)
return false;
// When this routine is called, the variable sum contains the
// matrix sum(p_i p_i^T,i=0...(n-1)), which coincides with n M(x)
// for x = (1/n,...,1/n). Our aim is to compute M(x)^{-1} into
// the variable mi and, if the latter matrix exits, to set x to
// (1/n,...,1/n). For this, we first compute M(x) into variable t:
const FT invOfn = 1/FT(n);
for (int i=0; i<d; ++i)
for (int j=0; j<d; ++j)
t[i+j*d] = sum[i+j*d] * invOfn;
if (!compute_inverse_of_t_into_mi(Exact_flag()))
return false;
#ifdef CGAL_APPEL_ASSERTION_MODE
// We start with the solution (1/n,...,1/n):
for (int k=0; k<n; ++k)
x[k] = invOfn;
#endif // CGAL_APPEL_ASSERTION_MODE
// Finally, we compute the excess of P[k] (w.r.t. x) into ex[k]
// for all k:
ex_max = 0;
for (int k=0; k<n; ++k)
if ((ex[k] = excess<FT>(tco.cartesian_begin(*P[k]))) > ex[ex_max])
ex_max = k;
CGAL_APPEL_LOG("appel"," Largest excess after initialization is " <<
to_double(ex[ex_max]) << "." << "\n");
// Accoding to Khachiyam (Lemma 3, eq. (2.20) in "Rounding of
// polytopes in the real number model of computation"), the
// following eps makes (*) hold:
eps = n-1;
is_exact_eps_uptodate = false;
return true;
}
#ifdef CGAL_APPEL_ASSERTION_MODE
template<bool Embed,class Traits>
typename Traits::FT Khachiyan_approximation<Embed,Traits>::
representation_error_of_mi()
{
using std::abs;
// If the points are degenerate then the inverse of M(x) doesn't
// exist, and so we exit immediately:
if (is_deg)
return FT(0);
// compute M(x) into the matrix represented by t:
compute_M_of_x();
// compute mi times the matrix M(x) (which should give the
// identity matrix):
FT max_error(0);
for (int i=0; i<d; ++i)
for (int j=0; j<d; ++j) {
// compute element (i,j) of the product of m and M(x):
FT v(0);
for (int k=0; k<d; ++k)
v += t[i+k*d] * mi[k+j*d];
// check it:
const FT exact(i == j? 1 : 0);
max_error = (std::max)(max_error,std::abs(v-exact));
}
// update statistics:
#ifdef CGAL_APPEL_STATS_MODE
max_error_m_all = (std::max)(max_error,max_error_m_all);
max_error_m = max_error;
#endif
CGAL_APPEL_LOG("appel"," The represenation error in m is: " <<
to_double(max_error) << (max_error == FT(0)?
" (zero)" : "") << "." << "\n");
return max_error;
}
#endif // CGAL_APPEL_ASSERTION_MODE
template<bool Embed,class Traits>
void Khachiyan_approximation<Embed,Traits>::rank_1_update(int k,
const FT& tau)
{
// check preconditions:
CGAL_APPEL_ASSERT(!check_tag(Exact_flag()) || tau == eps/((1+eps)*d-1));
CGAL_APPEL_ASSERT(!check_tag(Exact_flag()) ||
excess<ET>(tco.cartesian_begin(*P[k])) == (1+eps)*d);
CGAL_USE(tau);
const FT mu = eps / ((d-1)*(1+eps));
const FT alpha = 1 + mu;
const FT beta = mu / (1+eps);
// compute into tmp the vector M(x)^{-1} p_k:
for (int i=0; i<d; ++i) { // loop to determine tmp[i]
tmp[i] = FT(0);
C_it pk = tco.cartesian_begin(*P[k]);
for (int j=0; j<d_P; ++j, ++pk)
tmp[i] += (*pk) * mi[i+j*d];
if (Embed)
tmp[i] += mi[i+d_P*d];
}
// We need to scale the current matrix m by alpha and add to it
// the matrix (tmp tmp^T) times -beta:
for (int i=0; i<d; ++i)
for (int j=0; j<d; ++j) {
mi[i+j*d] *= alpha;
mi[i+j*d] -= beta * tmp[i]*tmp[j];
}
// Update ex[k]: We need to scale ex[k] by alpha and subtract from
// it beta (p_k^T tmp)^2:
ex_max = 0;
for (int k=0; k<n; ++k) {
// compute gamma = (p_k^T tmp)^2:
FT gamma(0);
C_it pk = tco.cartesian_begin(*P[k]);
for (int i=0; i<d_P; ++i, ++pk)
gamma += tmp[i] * (*pk);
if (Embed)
gamma += tmp[d_P];
gamma *= gamma;
// update ex[k]:
ex[k] *= alpha;
ex[k] -= beta*gamma;
// remember the largest so far:
if (ex[k] > ex[ex_max])
ex_max = k;
}
// check postcondition:
#ifdef CGAL_APPEL_EXP_ASSERTION_MODE
representation_error_of_mi();
#endif // CGAL_APPEL_EXP_ASSERTION_MODE
}
template<bool Embed,class Traits>
bool Khachiyan_approximation<Embed,Traits>::improve(const double desired_eps)
{
// Take the smallest eps s.t. (excess(p_m) =) p_m^T M(x)^{-1} p_m <=
// (1+eps) d holds for all m in {1,...,n}:
eps = ex[ex_max]/d - 1;
is_exact_eps_uptodate = false;
CGAL_APPEL_LOG("appel"," The current eps is: " << to_double(eps) << "\n");
// check if we have already reached an acceptable eps:
if (eps <= desired_eps) // numerics say we're ready to stop...
if (exact_epsilon() <= desired_eps) // ... and if it's o.k, we stop
// Note: if FT is inexact, exact_epsilon() may return a
// negative number here, which we will interpret as the input
// points being degenerate.
return true;
// We optimize along the line
//
// x' = (1 - tau) x + tau e_{ex_max},
//
// i.e., we replace our current solution x with x' for the value
// tau which minimizes the objective function on this line. It
// turns out that the minimum is attained at tau = eps/((1+eps)d-1)
// which then equals tau = eps/(largest_excess-1).
const FT tau = eps / (ex[ex_max] - 1);
#ifdef CGAL_APPEL_ASSERTION_MODE
// replace x by x':
for (int i=0; i<n; ++i)
x[i] = (1-tau)*x[i];
x[ex_max] += tau;
CGAL_APPEL_ASSERT(!check_tag(Exact_flag()) ||
std::accumulate(x.begin(),x.end(),FT(0)) == FT(1));
#endif // CGAL_APPEL_ASSERTION_MODE
// recompute the inverse m of M(x) (where x is our new x') and
// update the excesses in the array ex:
rank_1_update(ex_max,tau);
return false;
}
template<bool Embed,class Traits>
double Khachiyan_approximation<Embed,Traits>::exact_epsilon(bool recompute)
{
CGAL_APPEL_ASSERT(!is_deg);
// return cached result, if possible:
if (!recompute && is_exact_eps_uptodate)
return eps_exact;
// find max p_i^T M(x)^{-1} p_i:
ET max = 0;
for (int i=0; i<n; ++i)
max = (std::max)(max, excess<ET>(tco.cartesian_begin(*P[i])));
// compute (using exact arithmetic) epsilon via (*):
typedef CGAL::Quotient<ET> QET;
QET eps_e = QET(max,d)-1;
eps_exact = CGAL::to_interval(eps_e).second;
// debugging output:
CGAL_APPEL_LOG("appel",
"Exact epsilon is " << eps_e << " (rounded: " <<
eps_exact << ")." << "\n");
// check whether eps is negative (which under exact arithmetic is
// not possible, and which we will take as a sign that the input
// points are degenerate):
if (CGAL::is_negative(eps_e)) {
CGAL_APPEL_LOG("appel", "Negative Exact epsilon -> degenerate!" << "\n");
is_deg = true;
}
is_exact_eps_uptodate = true;
return eps_exact;
}
template<bool Embed,class Traits>
bool Khachiyan_approximation<Embed,Traits>::is_valid(bool verbose)
{
// debugging output:
if (verbose) {
CGAL_APPEL_IF_STATS(
std::cout << "The overall error in the matrix inverse is: "
<< max_error_m_all << "." << "\n");
}
// handle degenerate case:
if (is_deg)
return true;
// check Eq. (*) for the exact epsilon:
const double epsilon = exact_epsilon(true);
const ET ratio = (ET(epsilon)+1)*d;
for (int i=0; i<n; ++i)
if (excess<ET>(tco.cartesian_begin(*P[i])) > ratio) {
CGAL_APPEL_LOG("appel","ERROR: Eq. (*) violated." << "\n");
return false;
}
return true;
}
template<bool Embed,class Traits>
template<typename Iterator>
bool Khachiyan_approximation<Embed,Traits>::
compute_inverse_of_submatrix(Iterator inverse)
{
CGAL_APPEL_ASSERT(!is_deg);
// copy matrix to destination:
for (int i=0; i<d-1; ++i)
for (int j=0; j<d-1; ++j)
inverse[i+j*(d-1)] = mi[i+j*d];
// solve in place:
return Appel_impl::pd_matrix_inverse<FT>(d-1, inverse,
inverse, tmp.begin());
}
template<bool Embed,class Traits>
void Khachiyan_approximation<Embed,Traits>::print(std::ostream& o)
{
#ifdef CGAL_APPEL_ASSERTION_MODE
o << "xsol := [ ";
for (int k=0; k<n; ++k) {
o << x[k];
if (k<n-1)
o << ",";
}
o << "];" << "\n\n";
#endif // CGAL_APPEL_ASSERTION_MODE
o << "Mi:= matrix([" << "\n";
for (int i=0; i<d; ++i) {
o << " [ ";
for (int j=0; j<d; ++j) {
o << mi[i+j*d];
if (j<d-1)
o << ",";
}
o << "]";
if (i<d-1)
o << ",";
o << "\n";
}
o << "]);" << "\n";
o << "S:= matrix([" << "\n";
for (int i=0; i<d; ++i) {
o << " [ ";
for (int j=0; j<d; ++j) {
o << sum[i+j*d];
if (j<d-1)
o << ",";
}
o << "]";
if (i<d-1)
o << ",";
o << "\n";
}
o << "]);" << "\n";
o << "M:= matrix([" << "\n";
for (int i=0; i<d; ++i) {
o << " [ ";
for (int j=0; j<d; ++j) {
o << t[i+j*d];
if (j<d-1)
o << ",";
}
o << "]";
if (i<d-1)
o << ",";
o << "\n";
}
o << "]);" << "\n";
}
template<bool Embed,class Traits>
int Khachiyan_approximation<Embed,Traits>::write_eps() const
{
CGAL_APPEL_ASSERT(d == 2 && !Embed);
static int id = 0;
namespace Impl = Approximate_min_ellipsoid_d_impl;
// (Using "Impl::tostr(id)" in the following doesn't work on GCC 2.95.2.)
Impl::Eps_export_2 epsf(Approximate_min_ellipsoid_d_impl::tostr(id)+".eps",
100.0);
epsf.set_label_mode(Impl::Eps_export_2::None);
// output the input points:
for (int k=0; k<n; ++k) {
C_it pk = tco.cartesian_begin(*P[k]);
const double u = to_double(*pk++);
const double v = to_double(*pk);
epsf.write_circle(u,v,0.0);
}
// output the inscribed ellipse:
epsf.set_stroke_mode(Impl::Eps_export_2::Dashed);
epsf.write_cs_ellipse(to_double(mi[0+0*d]),
to_double(mi[1+1*d]),
to_double(mi[1+0*d]));
// Output the approximation of the minellipse: Since the relaxed
// optimality conditions (*) hold,
//
// p_i^T M(x)^{-1} p_i <= (1+eps) d,
//
// we can divide by a:=(1+eps)d to get
//
// p_i^T M(x)^{-1}/a p_i <= 1,
//
// which means that all points lie in the ellipsoid defined by the
// matrix M(x)^{-1}/alpha.
const FT a = (1+eps)*d;
for (int k=0; k<n; ++k) {
// compute M(x)^{-1}/alpha p_k into vector tmp:
for (int i=0; i<d; ++i) { // loop to determine tmp[i]
tmp[i] = FT(0);
C_it pk = tco.cartesian_begin(*P[k]);
for (int j=0; j<d; ++j, ++pk)
tmp[i] += (*pk) * mi[i+j*d];
}
// calculate p^T tmp:
FT result(0);
C_it pk = tco.cartesian_begin(*P[k]);
for (int i=0; i<d; ++i, ++pk)
result += (*pk) * tmp[i];
}
epsf.set_stroke_mode(Impl::Eps_export_2::Dashed);
epsf.set_label("E2");
epsf.write_cs_ellipse(to_double(mi[0+0*d]/a),
to_double(mi[1+1*d]/a),
to_double(mi[1+0*d]/a));
return id++;
}
}
| {
"pile_set_name": "Github"
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="./../../helpwin.css">
<title>MATLAB File Help: prtClassBagging/plot</title>
</head>
<body>
<!--Single-page help-->
<table border="0" cellspacing="0" width="100%">
<tr class="subheader">
<td class="headertitle">MATLAB File Help: prtClassBagging/plot</td>
</tr>
</table>
<div class="title">prtClassBagging/plot</div>
<div class="helptext"><pre><!--helptext --> <span class="helptopic">plot</span> Plot the output confidence of a prtClass object
OBJ.plot() plots the output confidence of a prtClass
object. This function only operates when the dimensionality
of dataset is 3 or less. When verboseStorage is set to
'true', the training data points are also displayed on the
plot.
Help for <span class="helptopic">prtClassBagging/plot</span> is inherited from superclass <a href="./../prtClass.html">prtClass</a></pre></div><!--after help --><!--seeAlso--><div class="footerlinktitle">See also</div><div class="footerlink"> prtClassBagging\explore()</div>
<!--Method-->
<div class="sectiontitle">Method Details</div>
<table class="class-details">
<tr>
<td class="class-detail-label">Defining Class</td>
<td>prtClass</td>
</tr>
<tr>
<td class="class-detail-label">Access</td>
<td>public</td>
</tr>
<tr>
<td class="class-detail-label">Sealed</td>
<td>false</td>
</tr>
<tr>
<td class="class-detail-label">Static</td>
<td>false</td>
</tr>
</table>
</body>
</html> | {
"pile_set_name": "Github"
} |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Denoising Autoencoder 代码实现"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Denoising Autoencoder(降噪自动编码器)就是在Autoencoder的基础之上,为了防止过拟合问题而对输入的数据(网络的输入层)加入噪音,使学习得到的编码器W\n",
"具有较强的鲁棒性,从而增强模型的泛化能力。Denoising Autoencoder是Bengio在08年提出的,具体内容可参考其论文:\n",
"\n",
"- Extracting and composing robust features with denoising autoencoders."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 代码实现细节\n",
"#### 构建一个DAE类"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"class DenoisingAutoencoder():\n",
" def __init__(self, n_input, transfer_fn... ):\n",
" ...\n",
"\n",
" # model\n",
" self.x = tf.placeholder(dtype=tf.float32, shape=[None, self.n_input])\n",
" self.x_corrupted = xxx\n",
" self.hidden = self.transfer(tf.add(tf.matmul(self.x_corrupted , self.weights['w1']), self.weights['b1']))\n",
" self.reconstruction = tf.add(tf.matmul(self.hidden, self.weights['w2']), self.weights['b2'])\n",
"\n",
" # cost\n",
" self.cost = .5*tf.reduce_mean(tf.pow(tf.subtract(self.reconstruction, self.x), 2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 三种加噪的方式\n",
"\n",
"去噪自编码器模型的输入是原始输入经某种形式的加噪过程后的退化形式,加噪过程一般分为:\n",
"\n",
"- 加性高斯噪声(additive gaussian noise)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"self.scale = tf.placeholder(dtype=tf.float32)\n",
"self.x_corrupted = tf.add(self.x, self.scale * tf.random_normal(shape=(self.n_input, )))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- 掩模噪声(mask)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"self.keep_prob = tf.placeholder(dtype=tf.float32)\n",
"self.x_corrupted = tf.nn.dropout(self.x, self.keep_prob)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- 椒盐噪声"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def salt_and_pepper_noise(X, v):\n",
" X_noise = X.copy()\n",
" n_features = X.shape[1]\n",
" mn = X.min()\n",
" mx = X.max()\n",
"\n",
" for i, sample in enumerate(X):\n",
" mask = np.random.randint(0, n_features, v)\n",
" for m in mask:\n",
" if np.random.rand() < .5:\n",
" X_noise[i][m] = mn\n",
" else:\n",
" X_noise[i][m] = mx\n",
" return X_noise"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 实践代码"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('Succesfully downloaded', 'train-images-idx3-ubyte.gz', 9912422, 'bytes.')\n",
"('Extracting', 'MNIST_data/train-images-idx3-ubyte.gz')\n"
]
},
{
"ename": "TypeError",
"evalue": "only integer scalar arrays can be converted to a scalar index",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-2-5946a4cc444d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 42\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 43\u001b[0m \u001b[0;31m# load MNIST data\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 44\u001b[0;31m \u001b[0mmnist\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0minput_data\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread_data_sets\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"MNIST_data/\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mone_hot\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 45\u001b[0m \u001b[0mtrX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtrY\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mteX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mteY\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmnist\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtrain\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mimages\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmnist\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtrain\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlabels\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmnist\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtest\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mimages\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmnist\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtest\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlabels\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 46\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/Users/shelter/Documents/huxiaoman7/learningdl/Chapter5/input_data.py\u001b[0m in \u001b[0;36mread_data_sets\u001b[0;34m(train_dir, fake_data, one_hot)\u001b[0m\n\u001b[1;32m 151\u001b[0m \u001b[0mVALIDATION_SIZE\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m5000\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 152\u001b[0m \u001b[0mlocal_file\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmaybe_download\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mTRAIN_IMAGES\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtrain_dir\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m#下载训练集的图像,返回图像文件所在目录\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 153\u001b[0;31m \u001b[0mtrain_images\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mextract_images\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlocal_file\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 154\u001b[0m \u001b[0mlocal_file\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmaybe_download\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mTRAIN_LABELS\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtrain_dir\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m#下载训练集的label\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 155\u001b[0m \u001b[0mtrain_labels\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mextract_labels\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlocal_file\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mone_hot\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mone_hot\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/Users/shelter/Documents/huxiaoman7/learningdl/Chapter5/input_data.py\u001b[0m in \u001b[0;36mextract_images\u001b[0;34m(filename)\u001b[0m\n\u001b[1;32m 41\u001b[0m \u001b[0mrows\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_read32\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mbytestream\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 42\u001b[0m \u001b[0mcols\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_read32\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mbytestream\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 43\u001b[0;31m \u001b[0mbuf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mbytestream\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mrows\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0mcols\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0mnum_images\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 44\u001b[0m \u001b[0mdata\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnumpy\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfrombuffer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mbuf\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdtype\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mnumpy\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0muint8\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m#将buf转化为1维数组\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 45\u001b[0m \u001b[0mdata\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mreshape\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnum_images\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrows\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcols\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m#改变数组形状:(60000, 28, 28, 1)for train, (10000, 28, 28, 1)for test\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/Users/shelter/anaconda/lib/python2.7/gzip.pyc\u001b[0m in \u001b[0;36mread\u001b[0;34m(self, size)\u001b[0m\n\u001b[1;32m 273\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 274\u001b[0m \u001b[0moffset\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0moffset\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mextrastart\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 275\u001b[0;31m \u001b[0mchunk\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mextrabuf\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0moffset\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0moffset\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0msize\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 276\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mextrasize\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mextrasize\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0msize\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 277\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mTypeError\u001b[0m: only integer scalar arrays can be converted to a scalar index"
]
}
],
"source": [
"import tensorflow as tf\n",
"import numpy as np\n",
"import input_data\n",
"\n",
"mnist_width = 28\n",
"n_visible = mnist_width * mnist_width\n",
"n_hidden = 500\n",
"corruption_level = 0.3\n",
"\n",
"# 输入的一张图片用28x28=784的向量表示.\n",
"X = tf.placeholder(\"float\", [None, n_visible], name='X')\n",
"\n",
"# 用于将部分输入数据置为0\n",
"mask = tf.placeholder(\"float\", [None, n_visible], name='mask')\n",
"\n",
"# create nodes for hidden variables\n",
"W_init_max = 4 * np.sqrt(6. / (n_visible + n_hidden))\n",
"W_init = tf.random_uniform(shape=[n_visible, n_hidden],\n",
" minval=-W_init_max,\n",
" maxval=W_init_max)\n",
"# 编码器\n",
"W = tf.Variable(W_init, name='W')#shape:784x500\n",
"b = tf.Variable(tf.zeros([n_hidden]), name='b')#隐含层的偏置\n",
"#解码器\n",
"W_prime = tf.transpose(W) \n",
"b_prime = tf.Variable(tf.zeros([n_visible]), name='b_prime')\n",
"\n",
"\n",
"def model(X, mask, W, b, W_prime, b_prime):\n",
" tilde_X = mask * X # corrupted X\n",
"\n",
" Y = tf.nn.sigmoid(tf.matmul(tilde_X, W) + b) # hidden state\n",
" Z = tf.nn.sigmoid(tf.matmul(Y, W_prime) + b_prime) # reconstructed input\n",
" return Z\n",
"\n",
"# build model graph\n",
"Z = model(X, mask, W, b, W_prime, b_prime)\n",
"\n",
"# create cost function\n",
"cost = tf.reduce_sum(tf.pow(X - Z, 2)) # minimize squared error\n",
"train_op = tf.train.GradientDescentOptimizer(0.02).minimize(cost) # construct an optimizer\n",
"\n",
"# load MNIST data\n",
"mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n",
"trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels\n",
"\n",
"# Launch the graph in a session\n",
"with tf.Session() as sess:\n",
" # you need to initialize all variables\n",
" tf.initialize_all_variables().run()\n",
"\n",
" for i in range(100):\n",
" for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):\n",
" input_ = trX[start:end]\n",
" mask_np = np.random.binomial(1, 1 - corruption_level, input_.shape)\n",
" sess.run(train_op, feed_dict={X: input_, mask: mask_np})\n",
"\n",
" mask_np = np.random.binomial(1, 1 - corruption_level, teX.shape)\n",
" print(i, sess.run(cost, feed_dict={X: teX, mask: mask_np}))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| {
"pile_set_name": "Github"
} |
#ifndef __LAYOUT_H__
#define __LAYOUT_H__
#include <ZUI.h>
#include <core/carray.h>
//------Js
#define Js_Id_Layout_Add 100
#define Js_Id_Layout_AddAt 101
#define Js_Id_Layout_GetItemIndex 102
#define Js_Id_Layout_GetItemAt 103
#define Js_Id_Layout_GetItemName 104
#define Js_Id_Layout_count 105
#define Js_Id_Layout_inset 106
/**容器基类结构*/
typedef struct _ZuiLayout
{
DArray *m_items; /// 控件数组
ZRect m_rcInset; /// 内边距
ZuiBool m_bMouseChildEnabled;
ZuiInt m_iChildPadding;
ZuiUInt m_iChildAlign;
ZuiUInt m_iChildVAlign;
ZuiBool m_bFocused; //是焦点状态
ZuiBool m_bScrollProcess; // 防止SetPos循环调用
ZuiInt m_nScrollStepSize;
ZuiControl m_pVerticalScrollBar; //纵向滚动条
ZuiControl m_pHorizontalScrollBar; //横向滚动条
ZCtlProc old_call;
}*ZuiLayout, ZLayout;
void* ZCALL ZuiLayoutProc(int ProcId, ZuiControl cp, ZuiLayout p, void* Param1, void* Param2, void* Param3);
#endif // __LAYOUT_H__
| {
"pile_set_name": "Github"
} |
# 1176. Diet Plan Performance
https://leetcode.com/problems/diet-plan-performance/
## Difficulty:
Easy
## Description
A dieter consumes calories[i] calories on the i-th day.
Given an integer k, for every consecutive sequence of k days (calories[i],
calories[i+1], ..., calories[i+k-1] for all 0 <= i <= n-k), they look at T,
the total calories consumed during that sequence of k days (calories[i] +
calories[i+1] + ... + calories[i+k-1]):
- If T < lower, they performed poorly on their diet and lose 1 point;
- If T > upper, they performed well on their diet and gain 1 point;
- Otherwise, they performed normally and there is no change in points.
Initially, the dieter has zero points. Return the total number of points
the dieter has after dieting for calories.length days.
Note that the total points can be negative.
Example 1:
```
Input: calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3
Output: 0
Explanation: Since k = 1, we consider each element of the array separately and compare it to lower and upper.
calories[0] and calories[1] are less than lower so 2 points are lost.
calories[3] and calories[4] are greater than upper so 2 points are gained.
```
Example 2:
```
Input: calories = [3,2], k = 2, lower = 0, upper = 1
Output: 1
Explanation: Since k = 2, we consider subarrays of length 2.
calories[0] + calories[1] > upper so 1 point is gained.
```
Example 3:
```
Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5
Output: 0
Explanation:
calories[0] + calories[1] > upper so 1 point is gained.
lower <= calories[1] + calories[2] <= upper so no change in points.
calories[2] + calories[3] < lower so 1 point is lost.
```
Constraints:
- 1 <= k <= calories.length <= 10^5
- 0 <= calories[i] <= 20000
- 0 <= lower <= upper
| {
"pile_set_name": "Github"
} |
import * as React from "react";
React.createElement('div', {});
createElement('someFunction');
<div>Hi</div>;
| {
"pile_set_name": "Github"
} |
---
- name: "auditConfig.enabled"
yedit:
src: /etc/origin/master/master-config.yaml
key: auditConfig.enabled
value: "{{ omac_auditConfig_enabled }}"
notify: restart openshift master services
- name: "deploy master audit config options"
yedit:
src: /etc/origin/master/master-config.yaml
key: "{{ item.key }}"
value: "{{ item.value }}"
state: "{{ 'present' if item.value != '' else 'absent' }}"
notify: restart openshift master services
with_items:
- key: auditConfig.auditFilePath
value: "{{ omac_auditConfig_auditFilePath | default('') }}"
- key: auditConfig.maximumFileRetentionDays
value: "{{ omac_auditConfig_maximumFileRetentionDays | default('') }}"
- key: auditConfig.maximumRetainedFiles
value: "{{ omac_auditConfig_maximumRetainedFiles | default('') }}"
- key: auditConfig.maximumFileSizeMegabytes
value: "{{ omac_auditConfig_maximumFileSizeMegabytes | default('') }}"
| {
"pile_set_name": "Github"
} |
// Copyright 2017, OpenCensus 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 stats contains support for OpenCensus stats recording.
OpenCensus allows users to create typed measures, record measurements,
aggregate the collected data, and export the aggregated data.
Measures
A measure represents a type of data point to be tracked and recorded.
For example, latency, request Mb/s, and response Mb/s are measures
to collect from a server.
Measure constructors such as Int64 and Float64 automatically
register the measure by the given name. Each registered measure needs
to be unique by name. Measures also have a description and a unit.
Libraries can define and export measures. Application authors can then
create views and collect and break down measures by the tags they are
interested in.
Recording measurements
Measurement is a data point to be collected for a measure. For example,
for a latency (ms) measure, 100 is a measurement that represents a 100ms
latency event. Measurements are created from measures with
the current context. Tags from the current context are recorded with the
measurements if they are any.
Recorded measurements are dropped immediately if no views are registered for them.
There is usually no need to conditionally enable and disable
recording to reduce cost. Recording of measurements is cheap.
Libraries can always record measurements, and applications can later decide
on which measurements they want to collect by registering views. This allows
libraries to turn on the instrumentation by default.
Exemplars
For a given recorded measurement, the associated exemplar is a diagnostic map
that gives more information about the measurement.
When aggregated using a Distribution aggregation, an exemplar is kept for each
bucket in the Distribution. This allows you to easily find an example of a
measurement that fell into each bucket.
For example, if you also use the OpenCensus trace package and you
record a measurement with a context that contains a sampled trace span,
then the trace span will be added to the exemplar associated with the measurement.
When exported to a supporting back end, you should be able to easily navigate
to example traces that fell into each bucket in the Distribution.
*/
package stats // import "go.opencensus.io/stats"
| {
"pile_set_name": "Github"
} |
## func (s *Scanner) Scan() rune
参数列表:
- 无
返回值:
- 下一个字符或token
功能说明:
Scan方法读取源中下一个token或字符,并返回。如果读到源的结尾,返回EOF。
代码实例:
package main
import(
"fmt"
"strings"
"text/scanner"
)
func main(){
src := strings.NewReader("int num = 1;")
var s scanner.Scanner
s.Init(src)
s.Scan()
//this will print the next token "int "to stdout
fmt.Println(s.TokenText())
}
| {
"pile_set_name": "Github"
} |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineSimpleMode = function(name, states) {
CodeMirror.defineMode(name, function(config) {
return CodeMirror.simpleMode(config, states);
});
};
CodeMirror.simpleMode = function(config, states) {
ensureState(states, "start");
var states_ = {}, meta = states.meta || {}, hasIndentation = false;
for (var state in states) if (state != meta && states.hasOwnProperty(state)) {
var list = states_[state] = [], orig = states[state];
for (var i = 0; i < orig.length; i++) {
var data = orig[i];
list.push(new Rule(data, states));
if (data.indent || data.dedent) hasIndentation = true;
}
}
var mode = {
startState: function() {
return {state: "start", pending: null,
local: null, localState: null,
indent: hasIndentation ? [] : null};
},
copyState: function(state) {
var s = {state: state.state, pending: state.pending,
local: state.local, localState: null,
indent: state.indent && state.indent.slice(0)};
if (state.localState)
s.localState = CodeMirror.copyState(state.local.mode, state.localState);
if (state.stack)
s.stack = state.stack.slice(0);
for (var pers = state.persistentStates; pers; pers = pers.next)
s.persistentStates = {mode: pers.mode,
spec: pers.spec,
state: pers.state == state.localState ? s.localState : CodeMirror.copyState(pers.mode, pers.state),
next: s.persistentStates};
return s;
},
token: tokenFunction(states_, config),
innerMode: function(state) { return state.local && {mode: state.local.mode, state: state.localState}; },
indent: indentFunction(states_, meta)
};
if (meta) for (var prop in meta) if (meta.hasOwnProperty(prop))
mode[prop] = meta[prop];
return mode;
};
function ensureState(states, name) {
if (!states.hasOwnProperty(name))
throw new Error("Undefined state " + name + "in simple mode");
}
function toRegex(val, caret) {
if (!val) return /(?:)/;
var flags = "";
if (val instanceof RegExp) {
if (val.ignoreCase) flags = "i";
val = val.source;
} else {
val = String(val);
}
return new RegExp((caret === false ? "" : "^") + "(?:" + val + ")", flags);
}
function asToken(val) {
if (!val) return null;
if (typeof val == "string") return val.replace(/\./g, " ");
var result = [];
for (var i = 0; i < val.length; i++)
result.push(val[i] && val[i].replace(/\./g, " "));
return result;
}
function Rule(data, states) {
if (data.next || data.push) ensureState(states, data.next || data.push);
this.regex = toRegex(data.regex);
this.token = asToken(data.token);
this.data = data;
}
function tokenFunction(states, config) {
return function(stream, state) {
if (state.pending) {
var pend = state.pending.shift();
if (state.pending.length == 0) state.pending = null;
stream.pos += pend.text.length;
return pend.token;
}
if (state.local) {
if (state.local.end && stream.match(state.local.end)) {
var tok = state.local.endToken || null;
state.local = state.localState = null;
return tok;
} else {
var tok = state.local.mode.token(stream, state.localState), m;
if (state.local.endScan && (m = state.local.endScan.exec(stream.current())))
stream.pos = stream.start + m.index;
return tok;
}
}
var curState = states[state.state];
for (var i = 0; i < curState.length; i++) {
var rule = curState[i];
var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex);
if (matches) {
if (rule.data.next) {
state.state = rule.data.next;
} else if (rule.data.push) {
(state.stack || (state.stack = [])).push(state.state);
state.state = rule.data.push;
} else if (rule.data.pop && state.stack && state.stack.length) {
state.state = state.stack.pop();
}
if (rule.data.mode)
enterLocalMode(config, state, rule.data.mode, rule.token);
if (rule.data.indent)
state.indent.push(stream.indentation() + config.indentUnit);
if (rule.data.dedent)
state.indent.pop();
if (matches.length > 2) {
state.pending = [];
for (var j = 2; j < matches.length; j++)
if (matches[j])
state.pending.push({text: matches[j], token: rule.token[j - 1]});
stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));
return rule.token[0];
} else if (rule.token && rule.token.join) {
return rule.token[0];
} else {
return rule.token;
}
}
}
stream.next();
return null;
};
}
function cmp(a, b) {
if (a === b) return true;
if (!a || typeof a != "object" || !b || typeof b != "object") return false;
var props = 0;
for (var prop in a) if (a.hasOwnProperty(prop)) {
if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop])) return false;
props++;
}
for (var prop in b) if (b.hasOwnProperty(prop)) props--;
return props == 0;
}
function enterLocalMode(config, state, spec, token) {
var pers;
if (spec.persistent) for (var p = state.persistentStates; p && !pers; p = p.next)
if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode) pers = p;
var mode = pers ? pers.mode : spec.mode || CodeMirror.getMode(config, spec.spec);
var lState = pers ? pers.state : CodeMirror.startState(mode);
if (spec.persistent && !pers)
state.persistentStates = {mode: mode, spec: spec.spec, state: lState, next: state.persistentStates};
state.localState = lState;
state.local = {mode: mode,
end: spec.end && toRegex(spec.end),
endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false),
endToken: token && token.join ? token[token.length - 1] : token};
}
function indexOf(val, arr) {
for (var i = 0; i < arr.length; i++) if (arr[i] === val) return true;
}
function indentFunction(states, meta) {
return function(state, textAfter, line) {
if (state.local && state.local.mode.indent)
return state.local.mode.indent(state.localState, textAfter, line);
if (state.indent == null || state.local || meta.dontIndentStates && indexOf(state.state, meta.dontIndentStates) > -1)
return CodeMirror.Pass;
var pos = state.indent.length - 1, rules = states[state.state];
scan: for (;;) {
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (rule.data.dedent && rule.data.dedentIfLineStart !== false) {
var m = rule.regex.exec(textAfter);
if (m && m[0]) {
pos--;
if (rule.next || rule.push) rules = states[rule.next || rule.push];
textAfter = textAfter.slice(m[0].length);
continue scan;
}
}
}
break;
}
return pos < 0 ? 0 : state.indent[pos];
};
}
});
| {
"pile_set_name": "Github"
} |
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "NSArray.h"
@interface NSArray (PBXArchiveSelectors)
- (SEL)selectorForArchiveMask:(int)arg1;
@end
| {
"pile_set_name": "Github"
} |
// Copyright 2010 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#if defined(V8_TARGET_ARCH_MIPS)
#include "ic-inl.h"
#include "codegen-inl.h"
#include "stub-cache.h"
namespace v8 {
namespace internal {
#define __ ACCESS_MASM(masm)
void StubCache::GenerateProbe(MacroAssembler* masm,
Code::Flags flags,
Register receiver,
Register name,
Register scratch,
Register extra,
Register extra2) {
UNIMPLEMENTED_MIPS();
}
void StubCompiler::GenerateLoadGlobalFunctionPrototype(MacroAssembler* masm,
int index,
Register prototype) {
UNIMPLEMENTED_MIPS();
}
void StubCompiler::GenerateDirectLoadGlobalFunctionPrototype(
MacroAssembler* masm, int index, Register prototype, Label* miss) {
UNIMPLEMENTED_MIPS();
}
// Load a fast property out of a holder object (src). In-object properties
// are loaded directly otherwise the property is loaded from the properties
// fixed array.
void StubCompiler::GenerateFastPropertyLoad(MacroAssembler* masm,
Register dst, Register src,
JSObject* holder, int index) {
UNIMPLEMENTED_MIPS();
}
void StubCompiler::GenerateLoadArrayLength(MacroAssembler* masm,
Register receiver,
Register scratch,
Label* miss_label) {
UNIMPLEMENTED_MIPS();
}
// Generate code to load the length from a string object and return the length.
// If the receiver object is not a string or a wrapped string object the
// execution continues at the miss label. The register containing the
// receiver is potentially clobbered.
void StubCompiler::GenerateLoadStringLength(MacroAssembler* masm,
Register receiver,
Register scratch1,
Register scratch2,
Label* miss,
bool support_wrappers) {
UNIMPLEMENTED_MIPS();
}
void StubCompiler::GenerateLoadFunctionPrototype(MacroAssembler* masm,
Register receiver,
Register scratch1,
Register scratch2,
Label* miss_label) {
UNIMPLEMENTED_MIPS();
}
// Generate StoreField code, value is passed in a0 register.
// After executing generated code, the receiver_reg and name_reg
// may be clobbered.
void StubCompiler::GenerateStoreField(MacroAssembler* masm,
JSObject* object,
int index,
Map* transition,
Register receiver_reg,
Register name_reg,
Register scratch,
Label* miss_label) {
UNIMPLEMENTED_MIPS();
}
void StubCompiler::GenerateLoadMiss(MacroAssembler* masm, Code::Kind kind) {
UNIMPLEMENTED_MIPS();
}
class CallInterceptorCompiler BASE_EMBEDDED {
public:
CallInterceptorCompiler(StubCompiler* stub_compiler,
const ParameterCount& arguments,
Register name)
: stub_compiler_(stub_compiler),
arguments_(arguments),
name_(name) {}
void Compile(MacroAssembler* masm,
JSObject* object,
JSObject* holder,
String* name,
LookupResult* lookup,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
Label* miss) {
UNIMPLEMENTED_MIPS();
}
private:
void CompileCacheable(MacroAssembler* masm,
JSObject* object,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
JSObject* interceptor_holder,
LookupResult* lookup,
String* name,
const CallOptimization& optimization,
Label* miss_label) {
UNIMPLEMENTED_MIPS();
}
void CompileRegular(MacroAssembler* masm,
JSObject* object,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
String* name,
JSObject* interceptor_holder,
Label* miss_label) {
UNIMPLEMENTED_MIPS();
}
void LoadWithInterceptor(MacroAssembler* masm,
Register receiver,
Register holder,
JSObject* holder_obj,
Register scratch,
Label* interceptor_succeeded) {
UNIMPLEMENTED_MIPS();
}
StubCompiler* stub_compiler_;
const ParameterCount& arguments_;
Register name_;
};
#undef __
#define __ ACCESS_MASM(masm())
Register StubCompiler::CheckPrototypes(JSObject* object,
Register object_reg,
JSObject* holder,
Register holder_reg,
Register scratch1,
Register scratch2,
String* name,
int save_at_depth,
Label* miss) {
UNIMPLEMENTED_MIPS();
return no_reg;
}
void StubCompiler::GenerateLoadField(JSObject* object,
JSObject* holder,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
int index,
String* name,
Label* miss) {
UNIMPLEMENTED_MIPS();
}
void StubCompiler::GenerateLoadConstant(JSObject* object,
JSObject* holder,
Register receiver,
Register scratch1,
Register scratch2,
Register scratch3,
Object* value,
String* name,
Label* miss) {
UNIMPLEMENTED_MIPS();
}
MaybeObject* StubCompiler::GenerateLoadCallback(JSObject* object,
JSObject* holder,
Register receiver,
Register name_reg,
Register scratch1,
Register scratch2,
Register scratch3,
AccessorInfo* callback,
String* name,
Label* miss) {
UNIMPLEMENTED_MIPS();
return NULL;
}
void StubCompiler::GenerateLoadInterceptor(JSObject* object,
JSObject* interceptor_holder,
LookupResult* lookup,
Register receiver,
Register name_reg,
Register scratch1,
Register scratch2,
Register scratch3,
String* name,
Label* miss) {
UNIMPLEMENTED_MIPS();
}
void CallStubCompiler::GenerateNameCheck(String* name, Label* miss) {
UNIMPLEMENTED_MIPS();
}
void CallStubCompiler::GenerateGlobalReceiverCheck(JSObject* object,
JSObject* holder,
String* name,
Label* miss) {
UNIMPLEMENTED_MIPS();
}
void CallStubCompiler::GenerateLoadFunctionFromCell(JSGlobalPropertyCell* cell,
JSFunction* function,
Label* miss) {
UNIMPLEMENTED_MIPS();
}
MaybeObject* CallStubCompiler::GenerateMissBranch() {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileCallField(JSObject* object,
JSObject* holder,
int index,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileArrayPushCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileArrayPopCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileStringCharCodeAtCall(
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileStringCharAtCall(
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileStringFromCharCodeCall(
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileMathFloorCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileMathAbsCall(Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileFastApiCall(
const CallOptimization& optimization,
Object* object,
JSObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileCallConstant(Object* object,
JSObject* holder,
JSFunction* function,
String* name,
CheckType check) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileCallInterceptor(JSObject* object,
JSObject* holder,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* CallStubCompiler::CompileCallGlobal(JSObject* object,
GlobalObject* holder,
JSGlobalPropertyCell* cell,
JSFunction* function,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* StoreStubCompiler::CompileStoreField(JSObject* object,
int index,
Map* transition,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* StoreStubCompiler::CompileStoreCallback(JSObject* object,
AccessorInfo* callback,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* StoreStubCompiler::CompileStoreInterceptor(JSObject* receiver,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* StoreStubCompiler::CompileStoreGlobal(GlobalObject* object,
JSGlobalPropertyCell* cell,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* LoadStubCompiler::CompileLoadNonexistent(String* name,
JSObject* object,
JSObject* last) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* LoadStubCompiler::CompileLoadField(JSObject* object,
JSObject* holder,
int index,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* LoadStubCompiler::CompileLoadCallback(String* name,
JSObject* object,
JSObject* holder,
AccessorInfo* callback) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* LoadStubCompiler::CompileLoadConstant(JSObject* object,
JSObject* holder,
Object* value,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* LoadStubCompiler::CompileLoadInterceptor(JSObject* object,
JSObject* holder,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* LoadStubCompiler::CompileLoadGlobal(JSObject* object,
GlobalObject* holder,
JSGlobalPropertyCell* cell,
String* name,
bool is_dont_delete) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadField(String* name,
JSObject* receiver,
JSObject* holder,
int index) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadCallback(
String* name,
JSObject* receiver,
JSObject* holder,
AccessorInfo* callback) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadConstant(String* name,
JSObject* receiver,
JSObject* holder,
Object* value) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadInterceptor(JSObject* receiver,
JSObject* holder,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadArrayLength(String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadStringLength(String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadFunctionPrototype(String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* KeyedLoadStubCompiler::CompileLoadSpecialized(JSObject* receiver) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* KeyedStoreStubCompiler::CompileStoreField(JSObject* object,
int index,
Map* transition,
String* name) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* KeyedStoreStubCompiler::CompileStoreSpecialized(
JSObject* receiver) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* ConstructStubCompiler::CompileConstructStub(JSFunction* function) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* ExternalArrayStubCompiler::CompileKeyedLoadStub(
JSObject* receiver_object,
ExternalArrayType array_type,
Code::Flags flags) {
UNIMPLEMENTED_MIPS();
return NULL;
}
MaybeObject* ExternalArrayStubCompiler::CompileKeyedStoreStub(
JSObject* receiver_object,
ExternalArrayType array_type,
Code::Flags flags) {
UNIMPLEMENTED_MIPS();
return NULL;
}
#undef __
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_MIPS
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2014 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WKSessionRef.h"
#include "APISession.h"
#include "WKAPICast.h"
using namespace WebKit;
WKSessionRef WKSessionCreate(bool isEphemeral)
{
// The implementation doesn't support non-ephemeral
if (!isEphemeral)
return nullptr;
auto session = API::Session::createEphemeral();
return toAPI(&session.leakRef());
}
WKTypeID WKSessionGetTypeID()
{
return toAPI(API::Session::APIType);
}
bool WKSessionIsEphemeral(WKSessionRef sessionRef)
{
return toAPI(toImpl(sessionRef)->isEphemeral());
}
| {
"pile_set_name": "Github"
} |
import { Rule } from '../types'
export default {
id: 'attr-value-single-quotes',
description: 'Attribute values must be in single quotes.',
init(parser, reporter) {
parser.addListener('tagstart', (event) => {
const attrs = event.attrs
let attr
const col = event.col + event.tagName.length + 1
for (let i = 0, l = attrs.length; i < l; i++) {
attr = attrs[i]
if (
(attr.value !== '' && attr.quote !== "'") ||
(attr.value === '' && attr.quote === '"')
) {
reporter.error(
`The value of attribute [ ${attr.name} ] must be in single quotes.`,
event.line,
col + attr.index,
this,
attr.raw
)
}
}
})
},
} as Rule
| {
"pile_set_name": "Github"
} |
# OpenLDAP Core schema
# $OpenLDAP: pkg/ldap/servers/slapd/schema/core.ldif,v 1.1.2.5 2007/01/02 21:44:09 kurt Exp $
## This work is part of OpenLDAP Software <http://www.openldap.org/>.
##
## Copyright 1998-2007 The OpenLDAP Foundation.
## All rights reserved.
##
## Redistribution and use in source and binary forms, with or without
## modification, are permitted only as authorized by the OpenLDAP
## Public License.
##
## A copy of this license is available in the file LICENSE in the
## top-level directory of the distribution or, alternatively, at
## <http://www.OpenLDAP.org/license.html>.
#
## Portions Copyright (C) The Internet Society (1997-2003).
## All Rights Reserved.
##
## This document and translations of it may be copied and furnished to
## others, and derivative works that comment on or otherwise explain it
## or assist in its implementation may be prepared, copied, published
## and distributed, in whole or in part, without restriction of any
## kind, provided that the above copyright notice and this paragraph are
## included on all such copies and derivative works. However, this
## document itself may not be modified in any way, such as by removing
## the copyright notice or references to the Internet Society or other
## Internet organizations, except as needed for the purpose of
## developing Internet standards in which case the procedures for
## copyrights defined in the Internet Standards process must be
## followed, or as required to translate it into languages other than
## English.
##
## The limited permissions granted above are perpetual and will not be
## revoked by the Internet Society or its successors or assigns.
##
## This document and the information contained herein is provided on an
## "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
## TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
## BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
## HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
## MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
#
#
#
# Includes LDAPv3 schema items from:
# RFC 2252/2256 (LDAPv3)
#
# Select standard track schema items:
# RFC 1274 (uid/dc)
# RFC 2079 (URI)
# RFC 2247 (dc/dcObject)
# RFC 2587 (PKI)
# RFC 2589 (Dynamic Directory Services)
#
# Select informational schema items:
# RFC 2377 (uidObject)
#
#
# Standard attribute types from RFC 2256
#
dn: cn=core,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: core
#
# system schema
#olcAttributeTypes: ( 2.5.4.0 NAME 'objectClass'
# DESC 'RFC2256: object classes of the entity'
# EQUALITY objectIdentifierMatch
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.38 )
#
# system schema
#olcAttributeTypes: ( 2.5.4.1 NAME ( 'aliasedObjectName' 'aliasedEntryName' )
# DESC 'RFC2256: name of aliased object'
# EQUALITY distinguishedNameMatch
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE )
#
olcAttributeTypes: ( 2.5.4.2 NAME 'knowledgeInformation'
DESC 'RFC2256: knowledge information'
EQUALITY caseIgnoreMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{32768} )
#
# system schema
#olcAttributeTypes: ( 2.5.4.3 NAME ( 'cn' 'commonName' )
# DESC 'RFC2256: common name(s) for which the entity is known by'
# SUP name )
#
olcAttributeTypes: ( 2.5.4.4 NAME ( 'sn' 'surname' )
DESC 'RFC2256: last (family) name(s) for which the entity is known by'
SUP name )
#
olcAttributeTypes: ( 2.5.4.5 NAME 'serialNumber'
DESC 'RFC2256: serial number of the entity'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.44{64} )
#
olcAttributeTypes: ( 2.5.4.6 NAME ( 'c' 'countryName' )
DESC 'RFC2256: ISO-3166 country 2-letter code'
SUP name SINGLE-VALUE )
#
olcAttributeTypes: ( 2.5.4.7 NAME ( 'l' 'localityName' )
DESC 'RFC2256: locality which this object resides in'
SUP name )
#
olcAttributeTypes: ( 2.5.4.8 NAME ( 'st' 'stateOrProvinceName' )
DESC 'RFC2256: state or province which this object resides in'
SUP name )
#
olcAttributeTypes: ( 2.5.4.9 NAME ( 'street' 'streetAddress' )
DESC 'RFC2256: street address of this object'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} )
#
olcAttributeTypes: ( 2.5.4.10 NAME ( 'o' 'organizationName' )
DESC 'RFC2256: organization this object belongs to'
SUP name )
#
olcAttributeTypes: ( 2.5.4.11 NAME ( 'ou' 'organizationalUnitName' )
DESC 'RFC2256: organizational unit this object belongs to'
SUP name )
#
olcAttributeTypes: ( 2.5.4.12 NAME 'title'
DESC 'RFC2256: title associated with the entity'
SUP name )
#
# system schema
#olcAttributeTypes: ( 2.5.4.13 NAME 'description'
# DESC 'RFC2256: descriptive information'
# EQUALITY caseIgnoreMatch
# SUBSTR caseIgnoreSubstringsMatch
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
#
# Deprecated by enhancedSearchGuide
olcAttributeTypes: ( 2.5.4.14 NAME 'searchGuide'
DESC 'RFC2256: search guide, deprecated by enhancedSearchGuide'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.25 )
#
olcAttributeTypes: ( 2.5.4.15 NAME 'businessCategory'
DESC 'RFC2256: business category'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} )
#
olcAttributeTypes: ( 2.5.4.16 NAME 'postalAddress'
DESC 'RFC2256: postal address'
EQUALITY caseIgnoreListMatch
SUBSTR caseIgnoreListSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.41 )
#
olcAttributeTypes: ( 2.5.4.17 NAME 'postalCode'
DESC 'RFC2256: postal code'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{40} )
#
olcAttributeTypes: ( 2.5.4.18 NAME 'postOfficeBox'
DESC 'RFC2256: Post Office Box'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{40} )
#
olcAttributeTypes: ( 2.5.4.19 NAME 'physicalDeliveryOfficeName'
DESC 'RFC2256: Physical Delivery Office Name'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} )
#
olcAttributeTypes: ( 2.5.4.20 NAME 'telephoneNumber'
DESC 'RFC2256: Telephone Number'
EQUALITY telephoneNumberMatch
SUBSTR telephoneNumberSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.50{32} )
#
olcAttributeTypes: ( 2.5.4.21 NAME 'telexNumber'
DESC 'RFC2256: Telex Number'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.52 )
#
olcAttributeTypes: ( 2.5.4.22 NAME 'teletexTerminalIdentifier'
DESC 'RFC2256: Teletex Terminal Identifier'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.51 )
#
olcAttributeTypes: ( 2.5.4.23 NAME ( 'facsimileTelephoneNumber' 'fax' )
DESC 'RFC2256: Facsimile (Fax) Telephone Number'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.22 )
#
olcAttributeTypes: ( 2.5.4.24 NAME 'x121Address'
DESC 'RFC2256: X.121 Address'
EQUALITY numericStringMatch
SUBSTR numericStringSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.36{15} )
#
olcAttributeTypes: ( 2.5.4.25 NAME 'internationaliSDNNumber'
DESC 'RFC2256: international ISDN number'
EQUALITY numericStringMatch
SUBSTR numericStringSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.36{16} )
#
olcAttributeTypes: ( 2.5.4.26 NAME 'registeredAddress'
DESC 'RFC2256: registered postal address'
SUP postalAddress
SYNTAX 1.3.6.1.4.1.1466.115.121.1.41 )
#
olcAttributeTypes: ( 2.5.4.27 NAME 'destinationIndicator'
DESC 'RFC2256: destination indicator'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.44{128} )
#
olcAttributeTypes: ( 2.5.4.28 NAME 'preferredDeliveryMethod'
DESC 'RFC2256: preferred delivery method'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.14
SINGLE-VALUE )
#
olcAttributeTypes: ( 2.5.4.29 NAME 'presentationAddress'
DESC 'RFC2256: presentation address'
EQUALITY presentationAddressMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.43
SINGLE-VALUE )
#
olcAttributeTypes: ( 2.5.4.30 NAME 'supportedApplicationContext'
DESC 'RFC2256: supported application context'
EQUALITY objectIdentifierMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.38 )
#
olcAttributeTypes: ( 2.5.4.31 NAME 'member'
DESC 'RFC2256: member of a group'
SUP distinguishedName )
#
olcAttributeTypes: ( 2.5.4.32 NAME 'owner'
DESC 'RFC2256: owner (of the object)'
SUP distinguishedName )
#
olcAttributeTypes: ( 2.5.4.33 NAME 'roleOccupant'
DESC 'RFC2256: occupant of role'
SUP distinguishedName )
#
# system schema
#olcAttributeTypes: ( 2.5.4.34 NAME 'seeAlso'
# DESC 'RFC2256: DN of related object'
# SUP distinguishedName )
#
# system schema
#olcAttributeTypes: ( 2.5.4.35 NAME 'userPassword'
# DESC 'RFC2256/2307: password of user'
# EQUALITY octetStringMatch
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{128} )
#
# Must be transferred using ;binary
# with certificateExactMatch rule (per X.509)
olcAttributeTypes: ( 2.5.4.36 NAME 'userCertificate'
DESC 'RFC2256: X.509 user certificate, use ;binary'
EQUALITY certificateExactMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.8 )
#
# Must be transferred using ;binary
# with certificateExactMatch rule (per X.509)
olcAttributeTypes: ( 2.5.4.37 NAME 'cACertificate'
DESC 'RFC2256: X.509 CA certificate, use ;binary'
EQUALITY certificateExactMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.8 )
#
# Must be transferred using ;binary
olcAttributeTypes: ( 2.5.4.38 NAME 'authorityRevocationList'
DESC 'RFC2256: X.509 authority revocation list, use ;binary'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.9 )
#
# Must be transferred using ;binary
olcAttributeTypes: ( 2.5.4.39 NAME 'certificateRevocationList'
DESC 'RFC2256: X.509 certificate revocation list, use ;binary'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.9 )
#
# Must be stored and requested in the binary form
olcAttributeTypes: ( 2.5.4.40 NAME 'crossCertificatePair'
DESC 'RFC2256: X.509 cross certificate pair, use ;binary'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.10 )
#
# 2.5.4.41 is defined above as it's used for subtyping
#olcAttributeTypes: ( 2.5.4.41 NAME 'name'
# EQUALITY caseIgnoreMatch
# SUBSTR caseIgnoreSubstringsMatch
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{32768} )
#
olcAttributeTypes: ( 2.5.4.42 NAME ( 'givenName' 'gn' )
DESC 'RFC2256: first name(s) for which the entity is known by'
SUP name )
#
olcAttributeTypes: ( 2.5.4.43 NAME 'initials'
DESC 'RFC2256: initials of some or all of names, but not the surname(s).'
SUP name )
#
olcAttributeTypes: ( 2.5.4.44 NAME 'generationQualifier'
DESC 'RFC2256: name qualifier indicating a generation'
SUP name )
#
olcAttributeTypes: ( 2.5.4.45 NAME 'x500UniqueIdentifier'
DESC 'RFC2256: X.500 unique identifier'
EQUALITY bitStringMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.6 )
#
olcAttributeTypes: ( 2.5.4.46 NAME 'dnQualifier'
DESC 'RFC2256: DN qualifier'
EQUALITY caseIgnoreMatch
ORDERING caseIgnoreOrderingMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.44 )
#
olcAttributeTypes: ( 2.5.4.47 NAME 'enhancedSearchGuide'
DESC 'RFC2256: enhanced search guide'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.21 )
#
olcAttributeTypes: ( 2.5.4.48 NAME 'protocolInformation'
DESC 'RFC2256: protocol information'
EQUALITY protocolInformationMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.42 )
#
# 2.5.4.49 is defined above as it's used for subtyping
#olcAttributeTypes: ( 2.5.4.49 NAME 'distinguishedName'
# EQUALITY distinguishedNameMatch
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 )
#
olcAttributeTypes: ( 2.5.4.50 NAME 'uniqueMember'
DESC 'RFC2256: unique member of a group'
EQUALITY uniqueMemberMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.34 )
#
olcAttributeTypes: ( 2.5.4.51 NAME 'houseIdentifier'
DESC 'RFC2256: house identifier'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{32768} )
#
# Must be transferred using ;binary
olcAttributeTypes: ( 2.5.4.52 NAME 'supportedAlgorithms'
DESC 'RFC2256: supported algorithms'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.49 )
#
# Must be transferred using ;binary
olcAttributeTypes: ( 2.5.4.53 NAME 'deltaRevocationList'
DESC 'RFC2256: delta revocation list; use ;binary'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.9 )
#
olcAttributeTypes: ( 2.5.4.54 NAME 'dmdName'
DESC 'RFC2256: name of DMD'
SUP name )
#
olcAttributeTypes: ( 2.5.4.65 NAME 'pseudonym'
DESC 'X.520(4th): pseudonym for the object'
SUP name )
#
# Standard object classes from RFC2256
#
# system schema
#olcObjectClasses: ( 2.5.6.1 NAME 'alias'
# DESC 'RFC2256: an alias'
# SUP top STRUCTURAL
# MUST aliasedObjectName )
#
olcObjectClasses: ( 2.5.6.2 NAME 'country'
DESC 'RFC2256: a country'
SUP top STRUCTURAL
MUST c
MAY ( searchGuide $ description ) )
#
olcObjectClasses: ( 2.5.6.3 NAME 'locality'
DESC 'RFC2256: a locality'
SUP top STRUCTURAL
MAY ( street $ seeAlso $ searchGuide $ st $ l $ description ) )
#
olcObjectClasses: ( 2.5.6.4 NAME 'organization'
DESC 'RFC2256: an organization'
SUP top STRUCTURAL
MUST o
MAY ( userPassword $ searchGuide $ seeAlso $ businessCategory $
x121Address $ registeredAddress $ destinationIndicator $
preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $
telephoneNumber $ internationaliSDNNumber $
facsimileTelephoneNumber $ street $ postOfficeBox $ postalCode $
postalAddress $ physicalDeliveryOfficeName $ st $ l $ description ) )
#
olcObjectClasses: ( 2.5.6.5 NAME 'organizationalUnit'
DESC 'RFC2256: an organizational unit'
SUP top STRUCTURAL
MUST ou
MAY ( userPassword $ searchGuide $ seeAlso $ businessCategory $
x121Address $ registeredAddress $ destinationIndicator $
preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $
telephoneNumber $ internationaliSDNNumber $
facsimileTelephoneNumber $ street $ postOfficeBox $ postalCode $
postalAddress $ physicalDeliveryOfficeName $ st $ l $ description ) )
#
olcObjectClasses: ( 2.5.6.6 NAME 'person'
DESC 'RFC2256: a person'
SUP top STRUCTURAL
MUST ( sn $ cn )
MAY ( userPassword $ telephoneNumber $ seeAlso $ description ) )
#
olcObjectClasses: ( 2.5.6.7 NAME 'organizationalPerson'
DESC 'RFC2256: an organizational person'
SUP person STRUCTURAL
MAY ( title $ x121Address $ registeredAddress $ destinationIndicator $
preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $
telephoneNumber $ internationaliSDNNumber $
facsimileTelephoneNumber $ street $ postOfficeBox $ postalCode $
postalAddress $ physicalDeliveryOfficeName $ ou $ st $ l ) )
#
olcObjectClasses: ( 2.5.6.8 NAME 'organizationalRole'
DESC 'RFC2256: an organizational role'
SUP top STRUCTURAL
MUST cn
MAY ( x121Address $ registeredAddress $ destinationIndicator $
preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $
telephoneNumber $ internationaliSDNNumber $ facsimileTelephoneNumber $
seeAlso $ roleOccupant $ preferredDeliveryMethod $ street $
postOfficeBox $ postalCode $ postalAddress $
physicalDeliveryOfficeName $ ou $ st $ l $ description ) )
#
olcObjectClasses: ( 2.5.6.9 NAME 'groupOfNames'
DESC 'RFC2256: a group of names (DNs)'
SUP top STRUCTURAL
MUST ( member $ cn )
MAY ( businessCategory $ seeAlso $ owner $ ou $ o $ description ) )
#
olcObjectClasses: ( 2.5.6.10 NAME 'residentialPerson'
DESC 'RFC2256: an residential person'
SUP person STRUCTURAL
MUST l
MAY ( businessCategory $ x121Address $ registeredAddress $
destinationIndicator $ preferredDeliveryMethod $ telexNumber $
teletexTerminalIdentifier $ telephoneNumber $ internationaliSDNNumber $
facsimileTelephoneNumber $ preferredDeliveryMethod $ street $
postOfficeBox $ postalCode $ postalAddress $
physicalDeliveryOfficeName $ st $ l ) )
#
olcObjectClasses: ( 2.5.6.11 NAME 'applicationProcess'
DESC 'RFC2256: an application process'
SUP top STRUCTURAL
MUST cn
MAY ( seeAlso $ ou $ l $ description ) )
#
olcObjectClasses: ( 2.5.6.12 NAME 'applicationEntity'
DESC 'RFC2256: an application entity'
SUP top STRUCTURAL
MUST ( presentationAddress $ cn )
MAY ( supportedApplicationContext $ seeAlso $ ou $ o $ l $
description ) )
#
olcObjectClasses: ( 2.5.6.13 NAME 'dSA'
DESC 'RFC2256: a directory system agent (a server)'
SUP applicationEntity STRUCTURAL
MAY knowledgeInformation )
#
olcObjectClasses: ( 2.5.6.14 NAME 'device'
DESC 'RFC2256: a device'
SUP top STRUCTURAL
MUST cn
MAY ( serialNumber $ seeAlso $ owner $ ou $ o $ l $ description ) )
#
olcObjectClasses: ( 2.5.6.15 NAME 'strongAuthenticationUser'
DESC 'RFC2256: a strong authentication user'
SUP top AUXILIARY
MUST userCertificate )
#
olcObjectClasses: ( 2.5.6.16 NAME 'certificationAuthority'
DESC 'RFC2256: a certificate authority'
SUP top AUXILIARY
MUST ( authorityRevocationList $ certificateRevocationList $
cACertificate ) MAY crossCertificatePair )
#
olcObjectClasses: ( 2.5.6.17 NAME 'groupOfUniqueNames'
DESC 'RFC2256: a group of unique names (DN and Unique Identifier)'
SUP top STRUCTURAL
MUST ( uniqueMember $ cn )
MAY ( businessCategory $ seeAlso $ owner $ ou $ o $ description ) )
#
olcObjectClasses: ( 2.5.6.18 NAME 'userSecurityInformation'
DESC 'RFC2256: a user security information'
SUP top AUXILIARY
MAY ( supportedAlgorithms ) )
#
olcObjectClasses: ( 2.5.6.16.2 NAME 'certificationAuthority-V2'
SUP certificationAuthority
AUXILIARY MAY ( deltaRevocationList ) )
#
olcObjectClasses: ( 2.5.6.19 NAME 'cRLDistributionPoint'
SUP top STRUCTURAL
MUST ( cn )
MAY ( certificateRevocationList $ authorityRevocationList $
deltaRevocationList ) )
#
olcObjectClasses: ( 2.5.6.20 NAME 'dmd'
SUP top STRUCTURAL
MUST ( dmdName )
MAY ( userPassword $ searchGuide $ seeAlso $ businessCategory $
x121Address $ registeredAddress $ destinationIndicator $
preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $
telephoneNumber $ internationaliSDNNumber $ facsimileTelephoneNumber $
street $ postOfficeBox $ postalCode $ postalAddress $
physicalDeliveryOfficeName $ st $ l $ description ) )
#
#
# Object Classes from RFC 2587
#
olcObjectClasses: ( 2.5.6.21 NAME 'pkiUser'
DESC 'RFC2587: a PKI user'
SUP top AUXILIARY
MAY userCertificate )
#
olcObjectClasses: ( 2.5.6.22 NAME 'pkiCA'
DESC 'RFC2587: PKI certificate authority'
SUP top AUXILIARY
MAY ( authorityRevocationList $ certificateRevocationList $
cACertificate $ crossCertificatePair ) )
#
olcObjectClasses: ( 2.5.6.23 NAME 'deltaCRL'
DESC 'RFC2587: PKI user'
SUP top AUXILIARY
MAY deltaRevocationList )
#
#
# Standard Track URI label schema from RFC 2079
# system schema
#olcAttributeTypes: ( 1.3.6.1.4.1.250.1.57 NAME 'labeledURI'
# DESC 'RFC2079: Uniform Resource Identifier with optional label'
# EQUALITY caseExactMatch
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
#
olcObjectClasses: ( 1.3.6.1.4.1.250.3.15 NAME 'labeledURIObject'
DESC 'RFC2079: object that contains the URI attribute type'
MAY ( labeledURI )
SUP top AUXILIARY )
#
#
# Derived from RFC 1274, but with new "short names"
#
#olcAttributeTypes: ( 0.9.2342.19200300.100.1.1
# NAME ( 'uid' 'userid' )
# DESC 'RFC1274: user identifier'
# EQUALITY caseIgnoreMatch
# SUBSTR caseIgnoreSubstringsMatch
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} )
#
olcAttributeTypes: ( 0.9.2342.19200300.100.1.3
NAME ( 'mail' 'rfc822Mailbox' )
DESC 'RFC1274: RFC822 Mailbox'
EQUALITY caseIgnoreIA5Match
SUBSTR caseIgnoreIA5SubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} )
#
olcObjectClasses: ( 0.9.2342.19200300.100.4.19 NAME 'simpleSecurityObject'
DESC 'RFC1274: simple security object'
SUP top AUXILIARY
MUST userPassword )
#
# RFC 1274 + RFC 2247
olcAttributeTypes: ( 0.9.2342.19200300.100.1.25
NAME ( 'dc' 'domainComponent' )
DESC 'RFC1274/2247: domain component'
EQUALITY caseIgnoreIA5Match
SUBSTR caseIgnoreIA5SubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE )
#
# RFC 2247
olcObjectClasses: ( 1.3.6.1.4.1.1466.344 NAME 'dcObject'
DESC 'RFC2247: domain component object'
SUP top AUXILIARY MUST dc )
#
# RFC 2377
olcObjectClasses: ( 1.3.6.1.1.3.1 NAME 'uidObject'
DESC 'RFC2377: uid object'
SUP top AUXILIARY MUST uid )
#
# From COSINE Pilot
olcAttributeTypes: ( 0.9.2342.19200300.100.1.37
NAME 'associatedDomain'
DESC 'RFC1274: domain associated with object'
EQUALITY caseIgnoreIA5Match
SUBSTR caseIgnoreIA5SubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
#
# RFC 2459 -- deprecated in favor of 'mail' (in cosine.schema)
olcAttributeTypes: ( 1.2.840.113549.1.9.1
NAME ( 'email' 'emailAddress' 'pkcs9email' )
DESC 'RFC3280: legacy attribute for email addresses in DNs'
EQUALITY caseIgnoreIA5Match
SUBSTR caseIgnoreIA5SubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{128} )
#
| {
"pile_set_name": "Github"
} |
/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020 Vladimír Vondruš <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <tuple>
#include <vector>
#include "Magnum/Math/Color.h"
#include "Magnum/Math/FunctionsBatch.h"
#include "Magnum/MeshTools/CompressIndices.h"
#include "Magnum/MeshTools/Concatenate.h"
#include "Magnum/MeshTools/Duplicate.h"
#include "Magnum/MeshTools/FlipNormals.h"
#include "Magnum/MeshTools/GenerateNormals.h"
#include "Magnum/MeshTools/Interleave.h"
#include "Magnum/MeshTools/RemoveDuplicates.h"
#include "Magnum/MeshTools/Transform.h"
#include "Magnum/Primitives/Cube.h"
#include "Magnum/Trade/MeshData.h"
#ifdef MAGNUM_BUILD_DEPRECATED
#define _MAGNUM_NO_DEPRECATED_COMBINEINDEXEDARRAYS
#include "Magnum/MeshTools/CombineIndexedArrays.h"
#endif
using namespace Magnum;
using namespace Magnum::Math::Literals;
int main() {
#ifdef MAGNUM_BUILD_DEPRECATED
{
CORRADE_IGNORE_DEPRECATED_PUSH
/* [combineIndexedArrays] */
std::vector<UnsignedInt> vertexIndices;
std::vector<Vector3> positions;
std::vector<UnsignedInt> normalTextureIndices;
std::vector<Vector3> normals;
std::vector<Vector2> textureCoordinates;
std::vector<UnsignedInt> indices = MeshTools::combineIndexedArrays(
std::make_pair(std::cref(vertexIndices), std::ref(positions)),
std::make_pair(std::cref(normalTextureIndices), std::ref(normals)),
std::make_pair(std::cref(normalTextureIndices), std::ref(textureCoordinates))
);
/* [combineIndexedArrays] */
CORRADE_IGNORE_DEPRECATED_POP
}
#endif
{
/* [compressIndices-offset] */
Containers::ArrayView<const UnsignedInt> indices;
UnsignedInt offset = Math::min(indices);
std::pair<Containers::Array<char>, MeshIndexType> result =
MeshTools::compressIndices(indices, offset);
// use `offset` to adjust vertex attribute offset …
/* [compressIndices-offset] */
}
#ifdef MAGNUM_BUILD_DEPRECATED
{
CORRADE_IGNORE_DEPRECATED_PUSH
/* [compressIndicesAs] */
std::vector<UnsignedInt> indices;
Containers::Array<UnsignedShort> indexData =
MeshTools::compressIndicesAs<UnsignedShort>(indices);
/* [compressIndicesAs] */
CORRADE_IGNORE_DEPRECATED_POP
}
#endif
{
/* [generateFlatNormals] */
Containers::ArrayView<UnsignedInt> indices;
Containers::ArrayView<Vector3> indexedPositions;
Containers::Array<Vector3> positions =
MeshTools::duplicate<UnsignedInt, Vector3>(indices, indexedPositions);
Containers::Array<Vector3> normals =
MeshTools::generateFlatNormals(positions);
/* [generateFlatNormals] */
}
{
/* [interleave2] */
Containers::ArrayView<const Vector4> positions;
Containers::ArrayView<const UnsignedShort> weights;
Containers::ArrayView<const Color3ub> vertexColors;
auto data = MeshTools::interleave(positions, weights, 2, vertexColors, 1);
/* [interleave2] */
}
{
Trade::MeshData data{MeshPrimitive::Lines, 0};
UnsignedInt vertexCount{};
Containers::Array<char> indexData;
/* [interleavedLayout-extra] */
Containers::ArrayView<const Trade::MeshAttributeData> attributes =
data.attributeData();
/* Take just positions and normals and add a four-byte padding in between */
Trade::MeshData layout = MeshTools::interleavedLayout(
Trade::MeshData{MeshPrimitive::Triangles, 0}, vertexCount, {
attributes[data.attributeId(Trade::MeshAttribute::Position)],
Trade::MeshAttributeData{4},
attributes[data.attributeId(Trade::MeshAttribute::Normal)]
});
/* [interleavedLayout-extra] */
}
{
Trade::MeshData data{MeshPrimitive::Lines, 0};
Containers::ArrayView<Trade::MeshAttributeData> extraAttributes;
UnsignedInt vertexCount{};
Containers::Array<char> indexData;
/* [interleavedLayout-indices] */
Trade::MeshData layout =
MeshTools::interleavedLayout(data, vertexCount, extraAttributes);
Trade::MeshIndexData indices;
Trade::MeshData indexed{data.primitive(),
std::move(indexData), indices,
layout.releaseVertexData(), layout.releaseAttributeData()};
/* [interleavedLayout-indices] */
}
{
/* [removeDuplicates] */
Containers::ArrayView<Vector3i> data;
std::size_t size;
Containers::Array<UnsignedInt> indices;
std::tie(indices, size) = MeshTools::removeDuplicatesInPlace(
Containers::arrayCast<2, char>(data));
data = data.prefix(size);
/* [removeDuplicates] */
}
#ifdef MAGNUM_BUILD_DEPRECATED
{
CORRADE_IGNORE_DEPRECATED_PUSH
/* [removeDuplicates-multiple] */
std::vector<Vector3> positions;
std::vector<Vector2> texCoords;
std::vector<UnsignedInt> positionIndices = MeshTools::removeDuplicates(positions);
std::vector<UnsignedInt> texCoordIndices = MeshTools::removeDuplicates(texCoords);
std::vector<UnsignedInt> indices = MeshTools::combineIndexedArrays(
std::make_pair(std::cref(positionIndices), std::ref(positions)),
std::make_pair(std::cref(texCoordIndices), std::ref(texCoords))
);
/* [removeDuplicates-multiple] */
CORRADE_IGNORE_DEPRECATED_POP
}
#endif
{
/* [transformVectors] */
std::vector<Vector3> vectors;
auto transformation = Quaternion::rotation(35.0_degf, Vector3::yAxis());
MeshTools::transformVectorsInPlace(transformation, vectors);
/* [transformVectors] */
}
{
/* [transformPoints] */
std::vector<Vector3> points;
auto transformation =
DualQuaternion::rotation(35.0_degf, Vector3::yAxis())*
DualQuaternion::translation({0.5f, -1.0f, 3.0f});
MeshTools::transformPointsInPlace(transformation, points);
/* [transformPoints] */
}
}
| {
"pile_set_name": "Github"
} |
@model Nethereum.Web.Sample.ViewModels.ProposalViewModel
@{
ViewBag.Title = "Proposal Detail";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Dao Proposal Detail</h2>
<div>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Index)
</dt>
<dd>
@Html.DisplayFor(model => model.Index)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Recipient)
</dt>
<dd>
@Html.DisplayFor(model => model.Recipient)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Amount)
</dt>
<dd>
@Html.DisplayFor(model => model.Amount)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Description)
</dt>
<dd>
@Html.DisplayFor(model => model.Description)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Open)
</dt>
<dd>
@Html.DisplayFor(model => model.Open)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ProposalPassed)
</dt>
<dd>
@Html.DisplayFor(model => model.ProposalPassed)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ProposalDeposit)
</dt>
<dd>
@Html.DisplayFor(model => model.ProposalDeposit)
</dd>
<dt>
@Html.DisplayNameFor(model => model.NewCurator)
</dt>
<dd>
@Html.DisplayFor(model => model.NewCurator)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Yea)
</dt>
<dd>
@Html.DisplayFor(model => model.Yea)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Nay)
</dt>
<dd>
@Html.DisplayFor(model => model.Nay)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Creator)
</dt>
<dd>
@Html.DisplayFor(model => model.Creator)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Back to Dao Proposals", "DaoProposals")
</p>
| {
"pile_set_name": "Github"
} |
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#ifndef THREADPOOL_H
#define THREADPOOL_H
#include <atomic>
#include <cstdint>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <thread>
#include <vector>
#include "joynr/BlockingQueue.h"
#include "joynr/JoynrExport.h"
#include "joynr/Logger.h"
#include "joynr/PrivateCopyAssign.h"
namespace joynr
{
class Runnable;
/**
* @class ThreadPool
* @brief A container of a fixed number of threads doing work provided
* by @ref Runnable
*/
class JOYNR_EXPORT ThreadPool : public std::enable_shared_from_this<ThreadPool>
{
public:
/**
* Constructor
* @param name Name of the hosted threads
* @param numberOfThreads Number of threads to be allocated and available
*/
ThreadPool(const std::string& name, const std::uint8_t numberOfThreads);
/**
* Destructor
*/
virtual ~ThreadPool();
/**
* @brief Does an ordinary init of @ref ThreadPool
* @note Must be called after constructor is called
* since it requires shared_ptr to own object
*/
void init();
/**
* @brief Does an ordinary shutdown of @ref ThreadPool
* @note Must be called before destructor is called
*/
void shutdown();
/**
* Returns the state of the @ref ThreadPool
* @return @c true if @ref ThreadPool is running
*/
bool isRunning();
/**
* Executes work by adding to the queue
* @param runnable Runnable to be executed
*/
void execute(std::shared_ptr<Runnable> runnable);
private:
/*! Disallow copy and assign */
DISALLOW_COPY_AND_ASSIGN(ThreadPool);
/*! Lifecycle for @ref threads */
void threadLifecycle(std::shared_ptr<ThreadPool> thisSharedptr);
private:
/*! Logger */
ADD_LOGGER(ThreadPool)
/*! Worker threads */
std::vector<std::thread> _threads;
/*! FIFO queue of work that could be done right now */
BlockingQueue _scheduler;
/*! Flag indicating @ref threads to keep running */
std::atomic_bool _keepRunning;
/*! Currently running work in @ref threads */
std::set<std::shared_ptr<Runnable>> _currentlyRunning;
std::mutex _mutex;
std::uint8_t _numberOfThreads;
std::string _name;
};
} // namespace joynr
#endif // THREADPOOL_H
| {
"pile_set_name": "Github"
} |
#import "DDXMLElementAdditions.h"
@implementation DDXMLElement (DDAdditions)
/**
* Quick method to create an element
**/
+ (DDXMLElement *)elementWithName:(NSString *)name xmlns:(NSString *)ns
{
DDXMLElement *element = [DDXMLElement elementWithName:name];
[element setXmlns:ns];
return element;
}
/**
* This method returns the first child element for the given name.
* If no child element exists for the given name, returns nil.
**/
- (DDXMLElement *)elementForName:(NSString *)name
{
NSArray *elements = [self elementsForName:name];
if([elements count] > 0)
{
return [elements objectAtIndex:0];
}
else
{
// Note: If you port this code to work with Apple's NSXML, beware of the following:
//
// There is a bug in the NSXMLElement elementsForName: method.
// Consider the following XML fragment:
//
// <query xmlns="jabber:iq:private">
// <x xmlns="some:other:namespace"></x>
// </query>
//
// Calling [query elementsForName:@"x"] results in an empty array!
//
// However, it will work properly if you use the following:
// [query elementsForLocalName:@"x" URI:@"some:other:namespace"]
//
// The trouble with this is that we may not always know the xmlns in advance,
// so in this particular case there is no way to access the element without looping through the children.
//
// This bug was submitted to apple on June 1st, 2007 and was classified as "serious".
//
// --!!-- This bug does NOT exist in DDXML --!!--
return nil;
}
}
/**
* This method returns the first child element for the given name and given xmlns.
* If no child elements exist for the given name and given xmlns, returns nil.
**/
- (DDXMLElement *)elementForName:(NSString *)name xmlns:(NSString *)xmlns
{
NSArray *elements = [self elementsForLocalName:name URI:xmlns];
if([elements count] > 0)
{
return [elements objectAtIndex:0];
}
else
{
return nil;
}
}
/**
* Returns the common xmlns "attribute", which is only accessible via the namespace methods.
* The xmlns value is often used in jabber elements.
**/
- (NSString *)xmlns
{
return [[self namespaceForPrefix:@""] stringValue];
}
- (void)setXmlns:(NSString *)ns
{
// If you use setURI: then the xmlns won't be displayed in the XMLString.
// Adding the namespace this way works properly.
//
// This applies to both Apple's NSXML and DDXML.
[self addNamespace:[DDXMLNode namespaceWithName:@"" stringValue:ns]];
}
/**
* Shortcut to get a pretty (formatted) string representation of the element.
**/
- (NSString *)prettyXMLString
{
return [self XMLStringWithOptions:(DDXMLNodePrettyPrint | DDXMLNodeCompactEmptyElement)];
}
/**
* Shortcut to get a compact string representation of the element.
**/
- (NSString *)compactXMLString
{
return [self XMLStringWithOptions:DDXMLNodeCompactEmptyElement];
}
/**
* Shortcut to avoid having to manually create a DDXMLNode everytime.
**/
- (void)addAttributeWithName:(NSString *)name stringValue:(NSString *)string
{
[self addAttribute:[DDXMLNode attributeWithName:name stringValue:string]];
}
/**
* Returns all the attributes as a dictionary.
**/
- (NSDictionary *)attributesAsDictionary
{
NSArray *attributes = [self attributes];
NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:[attributes count]];
uint i;
for(i = 0; i < [attributes count]; i++)
{
DDXMLNode *node = [attributes objectAtIndex:i];
[result setObject:[node stringValue] forKey:[node name]];
}
return result;
}
@end
| {
"pile_set_name": "Github"
} |
require 'test/unit'
class TestFunctional < Test::Unit::TestCase
tests = {:simple_annotation => [], :unit_test => ["-u"], :rspec => ["-s"],
:no_warnings => ["--no-warnings"], :bindings => ["--poetry", "-u"],
:add_markers => ["-m"]
}
tests.each_pair do |test, opts|
define_method("test_#{test}") do
dir = File.expand_path(File.dirname(__FILE__))
libdir = File.expand_path(dir + '/../lib')
exec = File.expand_path(dir + '/../bin/xmpfilter')
output = `ruby -I#{libdir} #{exec} #{opts.join(" ")} #{dir}/data/#{test}-input.rb`
outputfile = "#{dir}/data/#{test}-output.rb"
assert_equal(File.read(outputfile), output)
end
end
end
| {
"pile_set_name": "Github"
} |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cases
import "golang.org/x/text/transform"
// A context is used for iterating over source bytes, fetching case info and
// writing to a destination buffer.
//
// Casing operations may need more than one rune of context to decide how a rune
// should be cased. Casing implementations should call checkpoint on context
// whenever it is known to be safe to return the runes processed so far.
//
// It is recommended for implementations to not allow for more than 30 case
// ignorables as lookahead (analogous to the limit in norm) and to use state if
// unbounded lookahead is needed for cased runes.
type context struct {
dst, src []byte
atEOF bool
pDst int // pDst points past the last written rune in dst.
pSrc int // pSrc points to the start of the currently scanned rune.
// checkpoints safe to return in Transform, where nDst <= pDst and nSrc <= pSrc.
nDst, nSrc int
err error
sz int // size of current rune
info info // case information of currently scanned rune
// State preserved across calls to Transform.
isMidWord bool // false if next cased letter needs to be title-cased.
}
func (c *context) Reset() {
c.isMidWord = false
}
// ret returns the return values for the Transform method. It checks whether
// there were insufficient bytes in src to complete and introduces an error
// accordingly, if necessary.
func (c *context) ret() (nDst, nSrc int, err error) {
if c.err != nil || c.nSrc == len(c.src) {
return c.nDst, c.nSrc, c.err
}
// This point is only reached by mappers if there was no short destination
// buffer. This means that the source buffer was exhausted and that c.sz was
// set to 0 by next.
if c.atEOF && c.pSrc == len(c.src) {
return c.pDst, c.pSrc, nil
}
return c.nDst, c.nSrc, transform.ErrShortSrc
}
// retSpan returns the return values for the Span method. It checks whether
// there were insufficient bytes in src to complete and introduces an error
// accordingly, if necessary.
func (c *context) retSpan() (n int, err error) {
_, nSrc, err := c.ret()
return nSrc, err
}
// checkpoint sets the return value buffer points for Transform to the current
// positions.
func (c *context) checkpoint() {
if c.err == nil {
c.nDst, c.nSrc = c.pDst, c.pSrc+c.sz
}
}
// unreadRune causes the last rune read by next to be reread on the next
// invocation of next. Only one unreadRune may be called after a call to next.
func (c *context) unreadRune() {
c.sz = 0
}
func (c *context) next() bool {
c.pSrc += c.sz
if c.pSrc == len(c.src) || c.err != nil {
c.info, c.sz = 0, 0
return false
}
v, sz := trie.lookup(c.src[c.pSrc:])
c.info, c.sz = info(v), sz
if c.sz == 0 {
if c.atEOF {
// A zero size means we have an incomplete rune. If we are atEOF,
// this means it is an illegal rune, which we will consume one
// byte at a time.
c.sz = 1
} else {
c.err = transform.ErrShortSrc
return false
}
}
return true
}
// writeBytes adds bytes to dst.
func (c *context) writeBytes(b []byte) bool {
if len(c.dst)-c.pDst < len(b) {
c.err = transform.ErrShortDst
return false
}
// This loop is faster than using copy.
for _, ch := range b {
c.dst[c.pDst] = ch
c.pDst++
}
return true
}
// writeString writes the given string to dst.
func (c *context) writeString(s string) bool {
if len(c.dst)-c.pDst < len(s) {
c.err = transform.ErrShortDst
return false
}
// This loop is faster than using copy.
for i := 0; i < len(s); i++ {
c.dst[c.pDst] = s[i]
c.pDst++
}
return true
}
// copy writes the current rune to dst.
func (c *context) copy() bool {
return c.writeBytes(c.src[c.pSrc : c.pSrc+c.sz])
}
// copyXOR copies the current rune to dst and modifies it by applying the XOR
// pattern of the case info. It is the responsibility of the caller to ensure
// that this is a rune with a XOR pattern defined.
func (c *context) copyXOR() bool {
if !c.copy() {
return false
}
if c.info&xorIndexBit == 0 {
// Fast path for 6-bit XOR pattern, which covers most cases.
c.dst[c.pDst-1] ^= byte(c.info >> xorShift)
} else {
// Interpret XOR bits as an index.
// TODO: test performance for unrolling this loop. Verify that we have
// at least two bytes and at most three.
idx := c.info >> xorShift
for p := c.pDst - 1; ; p-- {
c.dst[p] ^= xorData[idx]
idx--
if xorData[idx] == 0 {
break
}
}
}
return true
}
// hasPrefix returns true if src[pSrc:] starts with the given string.
func (c *context) hasPrefix(s string) bool {
b := c.src[c.pSrc:]
if len(b) < len(s) {
return false
}
for i, c := range b[:len(s)] {
if c != s[i] {
return false
}
}
return true
}
// caseType returns an info with only the case bits, normalized to either
// cLower, cUpper, cTitle or cUncased.
func (c *context) caseType() info {
cm := c.info & 0x7
if cm < 4 {
return cm
}
if cm >= cXORCase {
// xor the last bit of the rune with the case type bits.
b := c.src[c.pSrc+c.sz-1]
return info(b&1) ^ cm&0x3
}
if cm == cIgnorableCased {
return cLower
}
return cUncased
}
// lower writes the lowercase version of the current rune to dst.
func lower(c *context) bool {
ct := c.caseType()
if c.info&hasMappingMask == 0 || ct == cLower {
return c.copy()
}
if c.info&exceptionBit == 0 {
return c.copyXOR()
}
e := exceptions[c.info>>exceptionShift:]
offset := 2 + e[0]&lengthMask // size of header + fold string
if nLower := (e[1] >> lengthBits) & lengthMask; nLower != noChange {
return c.writeString(e[offset : offset+nLower])
}
return c.copy()
}
func isLower(c *context) bool {
ct := c.caseType()
if c.info&hasMappingMask == 0 || ct == cLower {
return true
}
if c.info&exceptionBit == 0 {
c.err = transform.ErrEndOfSpan
return false
}
e := exceptions[c.info>>exceptionShift:]
if nLower := (e[1] >> lengthBits) & lengthMask; nLower != noChange {
c.err = transform.ErrEndOfSpan
return false
}
return true
}
// upper writes the uppercase version of the current rune to dst.
func upper(c *context) bool {
ct := c.caseType()
if c.info&hasMappingMask == 0 || ct == cUpper {
return c.copy()
}
if c.info&exceptionBit == 0 {
return c.copyXOR()
}
e := exceptions[c.info>>exceptionShift:]
offset := 2 + e[0]&lengthMask // size of header + fold string
// Get length of first special case mapping.
n := (e[1] >> lengthBits) & lengthMask
if ct == cTitle {
// The first special case mapping is for lower. Set n to the second.
if n == noChange {
n = 0
}
n, e = e[1]&lengthMask, e[n:]
}
if n != noChange {
return c.writeString(e[offset : offset+n])
}
return c.copy()
}
// isUpper writes the isUppercase version of the current rune to dst.
func isUpper(c *context) bool {
ct := c.caseType()
if c.info&hasMappingMask == 0 || ct == cUpper {
return true
}
if c.info&exceptionBit == 0 {
c.err = transform.ErrEndOfSpan
return false
}
e := exceptions[c.info>>exceptionShift:]
// Get length of first special case mapping.
n := (e[1] >> lengthBits) & lengthMask
if ct == cTitle {
n = e[1] & lengthMask
}
if n != noChange {
c.err = transform.ErrEndOfSpan
return false
}
return true
}
// title writes the title case version of the current rune to dst.
func title(c *context) bool {
ct := c.caseType()
if c.info&hasMappingMask == 0 || ct == cTitle {
return c.copy()
}
if c.info&exceptionBit == 0 {
if ct == cLower {
return c.copyXOR()
}
return c.copy()
}
// Get the exception data.
e := exceptions[c.info>>exceptionShift:]
offset := 2 + e[0]&lengthMask // size of header + fold string
nFirst := (e[1] >> lengthBits) & lengthMask
if nTitle := e[1] & lengthMask; nTitle != noChange {
if nFirst != noChange {
e = e[nFirst:]
}
return c.writeString(e[offset : offset+nTitle])
}
if ct == cLower && nFirst != noChange {
// Use the uppercase version instead.
return c.writeString(e[offset : offset+nFirst])
}
// Already in correct case.
return c.copy()
}
// isTitle reports whether the current rune is in title case.
func isTitle(c *context) bool {
ct := c.caseType()
if c.info&hasMappingMask == 0 || ct == cTitle {
return true
}
if c.info&exceptionBit == 0 {
if ct == cLower {
c.err = transform.ErrEndOfSpan
return false
}
return true
}
// Get the exception data.
e := exceptions[c.info>>exceptionShift:]
if nTitle := e[1] & lengthMask; nTitle != noChange {
c.err = transform.ErrEndOfSpan
return false
}
nFirst := (e[1] >> lengthBits) & lengthMask
if ct == cLower && nFirst != noChange {
c.err = transform.ErrEndOfSpan
return false
}
return true
}
// foldFull writes the foldFull version of the current rune to dst.
func foldFull(c *context) bool {
if c.info&hasMappingMask == 0 {
return c.copy()
}
ct := c.caseType()
if c.info&exceptionBit == 0 {
if ct != cLower || c.info&inverseFoldBit != 0 {
return c.copyXOR()
}
return c.copy()
}
e := exceptions[c.info>>exceptionShift:]
n := e[0] & lengthMask
if n == 0 {
if ct == cLower {
return c.copy()
}
n = (e[1] >> lengthBits) & lengthMask
}
return c.writeString(e[2 : 2+n])
}
// isFoldFull reports whether the current run is mapped to foldFull
func isFoldFull(c *context) bool {
if c.info&hasMappingMask == 0 {
return true
}
ct := c.caseType()
if c.info&exceptionBit == 0 {
if ct != cLower || c.info&inverseFoldBit != 0 {
c.err = transform.ErrEndOfSpan
return false
}
return true
}
e := exceptions[c.info>>exceptionShift:]
n := e[0] & lengthMask
if n == 0 && ct == cLower {
return true
}
c.err = transform.ErrEndOfSpan
return false
}
| {
"pile_set_name": "Github"
} |
<html>
<head>
<title>AT&T Digital Subscriber Line</title>
<!--Last Revised February 2017 by John Costa-->
<meta name="Revision" content="Revision: 2.01">
<meta name="keywords" content="AT&T, dsl, digital, subscriber, line, internet, service">
<meta http-equiv="Pragma" content="no-cache">
<meta name="description" content="AT&T Digital Subscriber Line Interent Service - Customer Care.">
<link rel="stylesheet" type="text/css" href="css/global.css">
<link rel="stylesheet" type="text/css" href="css/local.css">
<style id="antiClickjack">body{display:none !important;}</style>
<script type="text/javascript">
if (self === top) {
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
} else {
top.location = self.location;
}
</script>
</head>
<body bgcolor="#ffffff" topmargin="0" leftmargin="0"
marginwidth="0" marginheight="0">
<a name="top"></a>
<!--GLOBAL-NAVIGATION-BUSINESS-->
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td bgcolor="#6c6c6c" nowrap align="right">
<a href="http://www.att.com/gen/landing-pages?pid=3308/" onClick="window.open('http://www.att.com/gen/landing-pages?pid=3308/','nav_home','scrollbars=yes,resizable=yes,status=no,location=no,menubar=yes,toolbar=no,width=600,height=400,top=100,left=150,screenx=150,screeny=100')" target="nav_home"><img
src="images/nav/nav_corporate_home.gif" alt="[att.com.]" border="0"
width="69" height="17" name="nav_corporate"></a><a href="http://www.business.att.com" onClick="window.open('http://www.business.att.com','nav_busn','scrollbars=yes,resizable=yes,status=no,location=no,menubar=yes,toolbar=no,width=600,height=400,top=100,left=150,screenx=150,screeny=100')" target="nav_busn"><img
src="images/nav/nav_business_home.gif" alt="[AT&T Business Home.]" border="0"
width="137" height="17" name="nav_business"></a></td>
</tr>
<tr bgcolor="#ffffff">
<td><img src="images/pixel_trans.gif" alt="" border="0"
width="760" height="1"></td>
</tr>
<tr bgcolor="#ffffff">
<td>
<table border="0" cellpadding="3" cellspacing="0" width="100%">
<tr>
<td valign="middle">
<!--LOGO-->
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td nowrap><img
src="images/nav/logo_att_business.gif" alt="[AT&T]" border="0"></td>
</tr>
</table>
<!--LOGO-->
</td>
</tr>
</table>
</td>
</tr>
</table>
<!--/GLOBAL-NAVIGATION-BUSINESS-->
<!-- TOP NAV -->
<!-- START OF SCRIPT -->
<object type="text/x-scriptlet" width=100% height="24" data="includes/topnav2.html">
</object>
<!-- END OF SCRIPT -->
<!-- /TOP NAV -->
</td>
</tr>
<tr>
<td>
<!--TITLE-->
<img src="images/title_dsl.gif"
width="760" height="135" alt="AT&T Digital Subscriber Line - Customer Care." border="0">
<!--/TITLE-->
</td>
</tr>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr valign="top">
<td rowspan="2" width="5"><img src="images/pixel_trans.gif"
width="5" height="1" alt="" border="0"></td>
<td width="155">
<!--COLUMN-ONE-->
<!--LEFT NAV-->
<table border="0" cellspacing="0" cellpadding="4" width="100%">
<tr bgcolor="#336699">
<td class="head-blue">
<strong>Moving?</strong>
</td>
</tr>
</table>
<table border="0" cellspacing="0" cellpadding="4" width="100%">
<tr>
<td>
<p>Let us help you move your DSL service. </p>
</td>
</tr>
<tr>
<td nowrap><img src="images/dots_learn_155.gif" width="60"
height="16" alt="" border="0">
<a href="moving.html" onclick="window.open('moving.html','moving','scrollbars=no,resizable=no,status=no,location=no,menubar=no,toolbar=no,width=300,height=120,top=100,left=150,screenx=150,screeny=100');" target="moving">
<img src="images/btn_learnmore.gif" width="89" height="16" alt="Learn More." border="0"></a></td>
</tr>
</table>
<!--/SECONDARY-NAVIGATION-->
<!--/COLUMN-ONE-->
</td>
<td rowspan="2" width="5"><img src="images/pixel_trans.gif"
width="5" height="1" alt="" border="0"></td>
<td background="images/grey_cccccc.gif" rowspan="2" width="1"><img src="images/white_ffffff.gif"
width="1" height="3" alt="" border="0"></td>
<td rowspan="2" width="9"><img src="images/pixel_trans.gif"
width="9" height="1" alt="" border="0"></td>
<td width="100%">
<!--COLUMN-TWO-->
<table border="0" cellspacing="0" cellpadding="4" width="100%">
<tr>
<td>
<p>
Welcome to the AT&T Digital Subscriber Line (DSL) Internet Service
Care web site. With AT&T DSL Internet Service, your
standard phone line is transformed into an "always on"
connection that provides high-speed access to the Internet.
</p>
</td>
</tr>
</table>
<br>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tr valign="top">
<td width="49%">
<!--TETTING STARTED-->
<table border="0" cellspacing="0" cellpadding="4" width="100%">
<tr bgcolor="#336699">
<td class="head-blue">
<a href="gs/index.html"><img src="images/arrow_green.gif" width="14" height="11"
alt="Your Service." border="0"></a>
<strong><a href="gs/index.html"><span class="head-blue-link">Getting Started</span></a></strong>
</td>
</tr>
</table>
<table border="0" cellspacing="0" cellpadding="4" width="100%">
<tr>
<td>
<p>
Learn how to plan your successful installation of your new DSL service. Find out about important order confirmation information and how to prepare for DSL installation.
</p>
</td>
</tr>
</table>
<!--/GETTING STARTED-->
</td>
<td width="2%"> </td>
<td width="49%">
<!--YOUR SERVICE-->
<table border="0" cellspacing="0" cellpadding="4" width="100%">
<tr bgcolor="#336699">
<td class="head-blue">
<a href="ys/index.html"><img src="images/arrow_green.gif" width="14" height="11"
alt="Your Service." border="0"></a>
<strong><a href="ys/index.html"><span class="head-blue-link">Your Service</span></a></strong>
</td>
</tr>
</table>
<table border="0" cellspacing="0" cellpadding="4" width="100%">
<tr>
<td>
<p>
Learn how to make changes to your service and other features of your AT&T DSL Service.
</p>
</td>
</tr>
</table>
<!--/YOUR SERVICE-->
</td>
</tr>
</table>
<!--GRAPHIC/LINK TO SPECIAL OFFERS AND PROMOTIONS; uncomment and revise when needed
<div align="center">
<br>
<img src="images/home_feature_promo.gif"
width="415" height="90" alt="Special Offers & Promotions."
border="0" usemap="#specials">
</div>
-->
<!--/COLUMN-TWO-->
</td>
<td rowspan="2" width="15"><img src="images/pixel_trans.gif"
width="15" height="1" alt="" border="0"></td>
<td width="155">
<!--COLUMN-THREE-->
<table border="0" cellspacing="0" cellpadding="0" width="155">
<tr>
<td>
<img src="images/home_feature_status.gif"
width="155" height="151" alt="Have your order number? Click here to check the status of your order."
border="0" usemap="#status">
<img src="images/home_feature_order.gif"
width="155" height="129" alt="Order Digital Subscriber Line Now!."
border="0" usemap="#order">
</td>
</tr>
</table>
<map name="specials">
<area shape="rect" coords="315,65,413,87" href="whatsnew.html#specials" alt="Learn More." title="Learn More.">
</map>
<map name="status">
<area shape="rect" coords="110,130,154,151" href="http://iomdsl.ipservices.att.com/orderstatus/status.cgi" alt="Go." title="Go.">
</map>
<map name="order">
<area shape="rect" coords="110,106,154,128" href="http://www.business.att.com/service_fam_overview.jsp?repoid=ProductSub-Category&repoitem=eb_dsl&serv_port=eb_access_and_local_services&serv_fam=eb_dsl&segment=ent_biz" onClick="window.open('http://www.business.att.com/service_fam_overview.jsp?repoid=ProductSub-Category&repoitem=eb_dsl&serv_port=eb_access_and_local_services&serv_fam=eb_dsl&segment=ent_biz','order_dsl','scrollbars=yes,resizable=yes,status=no,location=no,menubar=yes,toolbar=no,width=600,height=400,top=100,left=150,screenx=150,screeny=100')" target="order_dsl" alt="Go." title="Go.">
<area shape="rect" coords="42,93,110,105" href="cu/" alt="Contact Us." title="Contact Us.">
</map>
<!--/COLUMN-THREE-->
</td>
</tr>
<tr>
<td><img src="images/pixel_trans.gif" width="155" height="1"
alt="" border="0"></td>
<td><img src="images/pixel_trans.gif" width="415" height="1"
alt="" border="0"></td>
<td><img src="images/pixel_trans.gif" width="155" height="1"
alt="" border="0"></td>
</tr>
</table>
<!--ATT-FOOTER-CORPORATE-->
<!-- FOOTER CODE MAY NOT BE ALTERED -->
<!-- START OF SCRIPT -->
<object type="text/x-scriptlet" width=100% height="100" data="includes/footer.html">
</object>
<!-- END OF SCRIPT -->
<!--/ATT-FOOTER-CORPORATE-->
</body>
</html>
| {
"pile_set_name": "Github"
} |
{
"name": "AccessiBe",
"website": "https://accessibe.com/",
"matches": [
{
"search": "script",
"regexp": "acsbap\\.com/.*/acsb\\.js"
}
]
} | {
"pile_set_name": "Github"
} |
# Copyright 2017 Rene Rivera
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# The addressing model to generate code for. Currently a limited set only
# specifying the bit size of pointers.
import feature ;
feature.feature address-model
: 16 32 64 32_64
: propagated optional ;
| {
"pile_set_name": "Github"
} |
import FWCore.ParameterSet.Config as cms
from Configuration.Generator.HerwigppDefaults_cfi import *
from Configuration.Generator.HerwigppUE_EE_5C_cfi import *
from Configuration.Generator.HerwigppPDF_CTEQ6_LO_cfi import *
from Configuration.Generator.HerwigppEnergy_13TeV_cfi import *
from Configuration.Generator.HerwigppMECorrections_cfi import *
from Configuration.Generator.HerwigppReshuffle_RestMostOffShell_cfi import *
generator = cms.EDFilter("ThePEGGeneratorFilter",
herwigDefaultsBlock,
herwigppUESettingsBlock,
herwigppPDFSettingsBlock,
herwigppEnergySettingsBlock,
herwigppMECorrectionsSettingsBlock,
herwigppReshuffleSettingsBlock,
configFiles = cms.vstring(),
parameterSets = cms.vstring(
'hwpp_cmsDefaults',
'hwpp_ue_EE5C',
'hwpp_pdf_CTEQ6L1',
'hwpp_cm_13TeV',
'hwpp_MECorr_Off',
'hwpp_reshuffle_RestMostOffShell',
'ttbarprocess',
),
ttbarprocess = cms.vstring(
'insert /Herwig/MatrixElements/SimpleQCD:MatrixElements[0] /Herwig/MatrixElements/MEHeavyQuark',
),
crossSection = cms.untracked.double(-1),
filterEfficiency = cms.untracked.double(1.0),
)
ProductionFilterSequence = cms.Sequence(generator)
| {
"pile_set_name": "Github"
} |
{
"throws": "Unexpected token (1:23)"
} | {
"pile_set_name": "Github"
} |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Shuffling Method"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Inspired by [Statistics for Hackers](https://speakerdeck.com/jakevdp/statistics-for-hackers) by Jake VanderPlas"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's say you have 2 sets of test scores: \n",
" \n",
" 84, 72, 57, 46, 63, 76, 99, 91 \n",
" \n",
"and \n",
" \n",
" 81, 69, 74, 61, 56, 87, 69, 65, 66, 44, 62, 69 \n",
" \n",
"The mean of the first set of test scores is 73.5 and the mean of the second set of test scores is 66.9. \n",
"The difference between the 2 means is 6.58.\n",
"\n",
"Is this difference statistically significant?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The following is my attempt at applying the shuffling method using Python programming language"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# embed the matplotlib charts within this jupyter notebook\n",
"%matplotlib inline\n",
"import numpy as np # library to allow us to use vectorized data structures and has useful stats functions\n",
"import matplotlib.pyplot as plt # plotting library\n",
"\n",
"test1 = [\n",
" 84, 72, 57, 46, 63, 76, 99, 91\n",
"]\n",
"\n",
"test2 = [\n",
" 81, 69, 74, 61, 56, 87, 69, 65, 66, 44, 62, 69\n",
"]\n",
"\n",
"test_scores1 = np.array(test1)\n",
"test_scores2 = np.array(test2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Mean from test scores set 1:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"73.5"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test_scores1.mean()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Mean from test scores set 2:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"66.916666666666671"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test_scores2.mean()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"6.5833333333333286"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"diff = test_scores1.mean() - test_scores2.mean()\n",
"diff"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Is the difference in the means statistically significant?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Let's apply the shuffling method"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create draw space from which we will sample data from which consists of both test scores"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"combined = np.concatenate((test_scores1, test_scores2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Let's double-check that the list has what we want"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([84, 72, 57, 46, 63, 76, 99, 91, 81, 69, 74, 61, 56, 87, 69, 65, 66,\n",
" 44, 62, 69])"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"combined"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### We need to shuffle the values in the combined array"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on built-in function shuffle:\n",
"\n",
"shuffle(...) method of mtrand.RandomState instance\n",
" shuffle(x)\n",
" \n",
" Modify a sequence in-place by shuffling its contents.\n",
" \n",
" Parameters\n",
" ----------\n",
" x : array_like\n",
" The array or list to be shuffled.\n",
" \n",
" Returns\n",
" -------\n",
" None\n",
" \n",
" Examples\n",
" --------\n",
" >>> arr = np.arange(10)\n",
" >>> np.random.shuffle(arr)\n",
" >>> arr\n",
" [1 7 5 2 9 4 3 6 0 8]\n",
" \n",
" This function only shuffles the array along the first index of a\n",
" multi-dimensional array:\n",
" \n",
" >>> arr = np.arange(9).reshape((3, 3))\n",
" >>> np.random.shuffle(arr)\n",
" >>> arr\n",
" array([[3, 4, 5],\n",
" [6, 7, 8],\n",
" [0, 1, 2]])\n",
"\n"
]
}
],
"source": [
"help(np.random.shuffle)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Now, we'll draw shuffled numbers from combined array list"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"length = len(test_scores1)\n",
"diff_means = np.array([]) # array that will contain the difference in the means\n",
"\n",
"# perform the following 10000 times where we draw random test values from the combined list\n",
"# and calculate the difference between the means, then add/append the differnce to the diff_means array\n",
"for i in range(0,10000):\n",
" np.random.shuffle(combined)\n",
" diff_means = np.append(diff_means, combined[:length].mean() - combined[length:].mean())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create a histogram of the difference in the means along with a vertical red line where the stated difference lies on the x-axis (6.58)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlIAAAGCCAYAAAArCS3BAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAHVhJREFUeJzt3X+UXWV5L/DvkwSoghLRKqCEoVhaa6u1XlvxgqJUvSJe\noSwqXimEdbVUewvxWi2ijTFV66/VImIr6lJXSxGLIKD2qpQKmFZKpQFaARE0CYIiiAETCiSw7x/7\nJA6H/Ji8mZmTTD6ftc7KnL33effznp2Z+c5+37N3dV0XAAC23KxRFwAAsL0SpAAAGglSAACNBCkA\ngEaCFABAI0EKAKDRnClq1zUVADZm0aKH/wuMWrW+0BkpAIBGghQAQCNBCgCgkSAFANBIkAIAaDRV\nn9oDgB3O2NhYli9fPuoy2Ih99903y5Ytm9Q2BSkAmCTLly9P17kC0LaqqvkqBxtlaA8AoJEgBQDQ\nSJACAGgkSAHADuqEE07IwoULs2TJkjztaU9bv/zGG2/Ms571rOy+++4544wzct999+UVr3hF5s6d\nm1e96lUjrHjbY7I5AEyhhQtPy4oVK6es/Xnz5mbx4gVb1cZBBx2U66+/fv3z97///XnRi16UpUuX\nJknOOuus3HHHHfnJT34yJRO2t2eCFIzQVP+AnS6T8YMcZqoVK1ZmbGzRlLW/bNnkt718+fK8+tWv\nftjzAw44oClEPfjgg5k9e/ZklrdNEaRghKb6B+x0mYof5MDkW7p0aV772tfmpptuyste9rL1weiy\nyy7Lsccem1tuuSWHHnpoLrvssixZsiQLFizI4YcfnvPOOy9d1+WCCy7Ihz70oZxwwgn55Cc/mQ9+\n8IO5/fbb85u/+Zs588wzM2/evCTJrFmzcsYZZ+S0007Lgw8+mJtvvjk33HBDTjrppFx11VV54hOf\nmMWLF+foo49O0g8x7rrrrlm2bFkuv/zyPP3pT8/ZZ5+d/fbbL0nyrW99K2984xtz1VVXZeedd87J\nJ5+cU045JV3X5X3ve18+8YlP5O67786hhx6aj370o5k7d+60vafmSAHADmDNmjU58sgjc/zxx+eu\nu+7K0UcfnfPOO2/9+nWh6pJLLsnBBx+cj3zkI7nnnnty9tln59RTT80xxxyTe+65JyeccEIuvPDC\nvPe9780FF1yQO+64IwcffPDDzmAlyYUXXpgrr7wy1113Xe6999685CUvybHHHps777wz55xzTt7w\nhjfkhhtuWL/9Zz/72bzzne/MypUrs//+++dtb3tbkmTVqlV58YtfnMMOOyw/+MEPctNNN+XQQw9N\nkpx++um56KKL8vWvfz233XZbHve4x+UNb3jDVL+VDyNIAcAO4IorrsjatWtz0kknZfbs2TnqqKPy\nnOc8p6mtM888M29961tzwAEHZNasWTnllFNy9dVX55Zbblm/zamnnpq5c+dml112yRe/+MXst99+\nOe6441JVeeYzn5mjjjoq55577vrtjzzyyDz72c/OrFmz8prXvCZXX311kuQLX/hC9tprryxYsCA7\n77xzdt111/V1n3nmmXn3u9+dvfbaKzvttFMWLlyYz33uc3nooYe24p3aMob2AGAHcNttt+XJT37y\nw5btu+++TW0tX748J598ct70pjclSbquS1Xl1ltvzT777JMkecpTnvKw7a+44orsscce67d/8MEH\nc9xxx63fZs8991z/9aMf/eisWrUqSfL9738/+++//0brOPLIIzNr1qz17e600065/fbbs9deezX1\nbUsJUgCwA9hrr71y6623PmzZihUr8tSnPnWL25o3b17e/va3P2I4b7zxE9P32WefHHLIIfnKV76y\nxfvaZ599cs4552y0jk9+8pM58MADt7jdyWJoDwB2AAceeGDmzJmTD3/4w1m7dm3OP//8XHnllevX\nb8k9Ak888cS85z3vyXXXXZckufvuu/O5z31uo9sffvjhufHGG3PWWWdl7dq1WbNmTb75zW/m29/+\n9mb3dfjhh+eHP/xhTj/99DzwwANZtWrV+rpPPPHEnHrqqVmxYkWS5I477shFF1004X5MBkEKAHYA\nO+20U84///x86lOfyuMf//ice+65Oeqoo9avH38GaXOXOTjiiCNyyimn5JhjjsncuXPzjGc8I1/+\n8pc3+vrddtstX/3qV3POOedk7733zt57751TTjkl999//2br3m233XLxxRfnoosuyp577pkDDjgg\nl156aZLk5JNPzitf+cq85CUvye67757nPe95DwuH06Gm6C7Vbn0NEzB//qIZc/mDT3960ajL2H4s\nWvTwf5kxquoRZ3a2hwty7ig2dHzWrWpt0xwpAJhCQs7MZmgPAKCRIAUA0EiQAgBoJEgBADQSpAAA\nGglSAACNXP4AACbJvvvuu9mLWTI6rfcW3BRBCgAmybJly0ZdAtPM0B4AQCNBCgCgkSAFANBIkAIA\naCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0mjPqAoDt39Kl12T+\n/EWjLmNSzJs3N4sXLxh1GcB2QpACttrq1V3GxhaNuoxJsWzZolGXAGxHDO0BADQSpAAAGglSAACN\nBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA\n0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglS\nAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCR\nIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAA\nGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EK\nAKCRIAUA0GjOqAuAFgsXnpYVK1aOuoyttnTpdRkbG3UVALQSpNgurVixMmNji0ZdxlZbsuSIUZcA\nwFYwtAcA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQS\npAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGs0ZdQEA25KlS6/J/PmL\npnQfR1x9aZLkgmVTt5958+Zm8eIFU9Y+0BOkAMZZvbrL2NiiKd3H3EGAmsr9LJvCkAb8jKE9AIBG\nghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIA\naCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQp\nAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBI\nkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAA\njQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAF\nANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJ\nUgAAjQQpAIBGghQAQCNBCgCgkSAFANBozqgLYPosXHhaVqxYOeoyJsXSpddlbGzUVQCwoxOkdiAr\nVqzM2NiiUZcxKZYsOWLUJQCAoT0AgFaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACN\nBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA\n0EiQAgBoJEgBADQSpAAAGglSAACN5oy6AAAm39Kl12T+/EWjLmOrzZs3N4sXLxh1GbBRghTADLR6\ndZexsUWjLmOrLVu2aNQlwCYZ2gMAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBI\nkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAA\njQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAF\nANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJ\nUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCg\nkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaDRn1AVsDxYu\nPC0rVqwcdRlbbenS6zI2NuoqAGDmEKQmYMWKlRkbWzTqMrbakiVHjLoEAJhRDO0BADRyRgqAbdbS\npddk/vxFoy5jUsybNzeLFy8YdRlMMkEKgG3W6tXdjJhakSTLli0adQlMAUN7AACNBCkAgEaCFABA\nI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgB\nADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0GjOVDS6du3anH763+T221dNRfPTapddZuW+\n++4bdRkAwDZoyoLUtdf+ME960h9MRfPTasWKL+b+++8fdRkAwDZoSoJUksyaNSuPetQeU9X8tJk9\ne+dRlwAAbKOmJEhdfvnlU9HsNm/ZskszNnbIqMuYdvq9Y9HvHYt+T56lS6/J/PmLJrXNyfbDHy7L\nnnuObXKbefPmZvHiBdNT0DSpqkO6rru05bVTGKR2m4qmt2l+4OxY9HvHot87lqno9+rVXcbGFk1q\nm5Nt2bJFm61x2bJNr99OHZLk0pYX+tQeAECjKZsjNXv2mtxyy9lT1fy0WbPmtlGXAABso6rruslv\ntGryGwUAmCJd11XL66YkSAEA7AjMkQIAaCRIAQA0EqQAABpNWpCqqp2r6qNVdWNV3VNVy6rq/VW1\ny9B2b66q71fVT6vqq1W132TVMCpV9UdVdUVVra6qGzew/h1VtWbwvvx08O+fj6LWybS5fg+2mXHH\ne1hVXVpV9w0d38NGXddkq6pZVfWBqvpRVd1dVedW1eNHXddUqqpPVdUDQ8d2+7/31ZCqelVVXT44\nrg9sYP1xVXVTVa2qqm9U1W+Mos7Jtql+V9XxVfXg0LH/u1HVOpmq6r1V9Z+Dfn+/qj5WVY8b2mbG\nHfPN9bv1mE/mGak5Se5I8vIkuyc5OMmLkrxvXJGvSfKmwTY/n+T6JBdVVdNM+W3Iren7+e5NbPO1\nruse23XdYwb/vnWaaptKm+z3DD7ew7ok7xw6vv8w6qKmwFuTvCLJc5I8JUkl+duRVjQ9Pj10bD86\n6oKmwF1JPpLkEZerrqqDkvxVkhOTPC7J+Un+oapmwlWXN9rvgZuHjv1rprG2qbQ2yWuS7JHkmem/\nnz+9buUMPuab7PfAFh/zSQtSXdfd23Xdn3Zd952ud0uSj6e/Wug6r0tyZtd113Rdd1+SU5P8QpKD\nJquOUei67vyu6z6fPljsMCbQ7xl5vDdipoXDDXldkvd2Xbe867qfJnlLkv9RVfuMuC62Utd1F3dd\n99kk393A6tcmOa/ruku6rlvTdd0HktyX5MhpLXIKbKbfM1bXdW8f/Fx+sOu6Hyf5UJIXjNtkRh7z\nCfS7yVTPkTo0yTXjnj8zyVXrnnRdtzrJdwbLZ7rnDoZEbh6cTnzCqAuaBjvS8V5QVXdW1X9U1SlV\nNWUXux2Fqto9ybwk/75uWdd1301yT2bm8RzvqMGxvWEwXWHXURc0zR72fTxwdWb+cU+Sfarqtqpa\nXlWfqaqxURc0RX47m/hdPTATj/lwv5OGYz6hIDWYJ/DQYOzwoaHHg1W1eAOvWZDk+UneNm7xY5Lc\nPbTpyiSPnUgd062l3xvx90l+peu6J6Yf7nxykgunrPCtNIn93q6O97AteB9OSfKL6Ycv/3f6v+be\nOaq6p8hj0g9hbrfHs9HpSX6567onpP9r/AVJPjbakqbddv19vBUuS/JrXdftnX44+74kF1fVo0Zb\n1uSqqqOS/H6Sk8YtnvHHfCP9bjrmE/2r+Q/Tz3XZmHuHCnxjkjcneWHXdd8ft+qn6edPjTc3/V+1\n26It6vfGdF13/bivl1fVa5PcWlX7dV33va2scSpMSr+z/R3vYRN6H7qu+9dxy66sqj9N8t48/I+I\n7d1P0w9fbs/Hc4t1Xbd03NfXD/5AvLSq5nddt2aEpU2njX0f3zSCWqZN13XLxn39o6p6Xfow8dwk\nXxtVXZOpqo5O8tdJXtF13fgzMzP6mG+s363HfEJBquu6ezPBX56DXyKvS/L8ruuG3/RrkvxGkosG\n2+6W/i/54VNr24Qt6XdL89lG59VMYr+3q+M9bCvfh23y2Lbquu7uqlqR/nhemyRVtX/6v1yvHWVt\nIzKjju9mrPs+Hu9ZSc4bQS3bghlx7KvqhCQfSHJ413VXDK2escd8M/3e6Ms2tXJS50hV1QfSD228\nYAMhKulPiZ9YVb9eVY9O8p70k/yWTGYd062qZld/mYed+6e1S4277ENVHbluTlRVPTl9Ev7mYI7J\ndmtz/c4MPd7jVdXuVfXydfNmqupZSd6R5JzRVjYlPpbkT6pqbDBn6n1Jvtx13YoR1zVlqv94/O6D\nr38xyQeTXNh13SMuEbA9q/7SFrsk2WXwfPz38seT/E5VvbD6y9y8Jf33/OdHVO6k2VS/q+qwwc/r\nVNUe6T/FdkeSif7y3WZV1Unpw8RLNxImZuQx31y/m49513WT8kg/EfWhJP+V/lT/PelPD/7H0HZ/\nnP5TXquSXJxkv8mqYVSP9L84H0ry4ODxUJIHx60/K8ntg/djeZJPJHnSqOue6n7P1OM91L8nJPlG\nkp+kn1NwQ5K3J5kz6tqmoK+zkrx/8IPl7iTnJtlj1HVNcZ+/luTOwffuzYMfwruNuq4p6OfxG/pe\nTjJvsP7YQf9XD36p/Pqoa57qfg/+r986OPa3pp/r+tRR1zxJ/X4oyf1Dv6vvGdpmxh3zzfW79Zi7\naTEAQCO3iAEAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFk6Sq3jF0U+O7qurKqnpX\nVT1paNt9B9sdNm7Zo6vqnKq6c/D64wbLX1dV362qNVX1T9Pdr1EYvJc/mqS23lxVz9/A8oeq6g2T\nsY8NtP2CQftr110peWj9Jwbrd4jjCTOZIAWTa2WS30pyYJJXpb831e8l+Y/B7WPW+UH6G2GOv13O\n65O8PMlrB6//0iCA/VX6WzMcnGRKfvFvgz6e5KWT1NZbkhwySW1tqdXp/x+sV1U7JTky/dWTge3c\nhG5aDEzY2q7r/m3c84ur6q+TfD3JOVX1y13vgSRXDr32l5N8u+u6C9YtqKqD0v/B86mu6/5zawqr\nqp/ruu6+rWljunRdd1uS20ZdxyT4QpJjkvzFuGUvTX9ML01/02dgO+aMFEyxruvuSX9W5BeTvDh5\n5NBeVX0v/Q2/f2Pc0OA7klw+aObaoeG+Xarq/VW1oqruq6qrq+pl4/dbVd+rqg9W1dur6pb098db\nt+7gqrq0qlYPhhI/VlW7jVs/f1DHr1bVV6tqVVVdX1VHDvdvcFPuf62qewdtfbGq9hm3/ler6ktV\ndc/g8ffDQ50baHNRVd0x7vm6obIXDF7/06q6uapev5l2vpdkjySLxr2v44f5ZlfVu6vqR1V1e1Wd\nMThjNL6NfQZDrj8evF9frqoDNrXfgS79zaufXVW/MG75MUkuSPKIGx9PZF9V9edVde3gPbilqs7a\nwNDx96rqA1W1YLDNXVX1map67Lht5gz+fywf/B+6tarOqyp/YMMWEKRgelyaZG364bx1xt/o8ogk\n/5Dk+vxsaPDjSf5wsP7Vg2VfGjw/L8lxSd6V5PAk/5bkoqp6xtB+/1eS56cfNnxVklTVf09/A+nb\nkhyV5OQkhyX55AZq+7skFw7q+06Sz1TV3us2qqrfG9TynSRHJ5mf5MYkPz9Y/9T0w5c7J3lN+pvE\nPj3JRRt5n8bvf0M3Av1YkqsH9XwtyRlV9d820c4R6W9O+on07/2BSf593Po3JdlrUNv7k5yY/v1Y\n17/HJfnn9CH49wd93DX9mcZdNtOHJPlu+mPz6kF7j0ryP5N8ZnjDLdjXk5L8efph4JOT7Jfkkg3s\n+3eTvCjJ69IH+cOTvGfc+lMHdb0tyW8P2ro7yewJ9AtYZ9R3Y/bwmCmPJO9I8qNNrL8tyUcGX++b\n/k7kh41b/6kkVw695gXp70b/K+OWHTpYdtDQtpcl+ey4599LfwfznYa2+3qSfxxa9sJBPb8yeH78\n4Pnx47bZI8maJL8/eF5Jvp/k3E30+W/Th8PZ45Y9NX2ofNlE38vB+/BQkneMWzYnyY+SvGczx+WO\nJAs3sPyhJF8bWvb5JP8y7vmfDV6/+7hlc9PPhXv9Jva5/rglWZDk2sHy301ye/o/Ys9N8k9bs69B\nO08e9OWgccu/lz7czhq37C+T3Dbu+ReSfGDU3zceHtv7wxkpmD41Se0cmuSHSb5RVbMHjzlJ/inJ\n8NmZS7quW7O+gP6MyHOTnDvutbPTnwlZk+TZ417bpT9z1T/purvSB5enDBb9UpK9k3x6M7V+frDv\ndftaNnhs6kzShgzXszZ9WHjKRl+xeRcPPb9uqL1DB9usGlf/qiRXZeL1/32Sp1XV0zP4AELXdQ9t\nYLsJ7auqXlZV/1xVK9MH0lvSvzfDw41fG9rPdUmeOGg36c/snVD9pxp/bYJ9AYYIUjANBkMzj09/\nNmJrPSH9cNSacY8H0p/FGQ4Vw/t7XPqhm78aev196c/w7DO0/cqh5w8k+bnB149P/wv8B5up9U82\nUOt+G9jXRGyqnhaba+8J6cPPcP2HZIL1d/3E+SVJ/iDJy7KBYb2J7quqnpN+qHVFkmPTh+LfSh/S\nh9+HDfWtkqwbJnxXkjPSD/tePZhLddJE+gT8jEmFMD1elP777RuT0NZd6YfUXpnNn+Uanme0crDs\nHennZA3bkk/K/Xiw/702sc1dSc5PP99ruNY7t2Bfo3JXkm8lWZxH1r8lly/4bPrQ8oOu676+Ffs6\nIv2Q56vXraiqeVtQx3pd192fZFH6ifj7pw96p1XVDV3XfbWlTdgRCVIwxapqbpL3pZ+E/Y+T0OQl\nSf5vktVd1924JS/suu7eqroiyS91Xfeurazj2+nnYB2fn02CH3ZJkqd3Xbd0K/e1NbbmrNUl6Sd9\nXzcIHq3OTfKSPHIocUv39aj0Z6rGOzYbnpg/YV3X3ZzkzVX1f9LP6xKkYIIEKZhcc6rqtwZfPyb9\nnKPXp/8F+NKu61p+4T3s7ETXdRdX1VeT/GNVvS/9WYzHJvn1JLt0Xfe2zbT3lsFruySfS3+2Y9/0\nn9w7teu6myZSVNd1XVW9JclZVXVWfjZk9cIkZ3dd9+/pz3j8a1V9Kf2nAu9MP/z42+mvjXX5I1ve\nqNY5ZjckeXlVfSX9nKMbuq5bPcHX/kX6T/R9rao+nD44Pin9ZPKvd1332YnU23Xdj5P8ziTs6+Ik\nJ1fVX6afLP689EFqi1XV+ennXy1N8l/pQ9zs/OySG8AECFIwuXZP8i/pzxDck+SmJH+T5Iyu64Zv\neTLRULWh7Y5M//H1k5PMSz8sdHWSDw+97hGv7brunwfXUnrnoLbZSZYn+XI2P4frYW12XfeZqvqv\n9B+hPzf9lbyvSP/ps3Rd952qem76+Thnpg+Ut6Y/+zKhwDa07y1Zvs6b0w+rfTHJo9MHvcuH+7LB\nhrvux4P6350+6MxNPydsSZJrG+tt3lfXdf+vqv4kyR+lvwL+v6S/DMLwmcnN9i39BwxeleSP08+X\nvS7J7wwCMDBB1fYHMgAAPrUHANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAF\nANDo/wM6r1hTCRpViwAAAABJRU5ErkJggg==\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x7fad659256d8>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"fig, ax = plt.subplots(figsize=(10, 6))\n",
"plt.hist(diff_means, alpha=.5, label='difference')\n",
"plt.legend(loc='best')\n",
"plt.xlabel('Difference in the Means', fontsize=15)\n",
"ax.spines['right'].set_visible(False)\n",
"ax.spines['left'].set_visible(False)\n",
"ax.spines['top'].set_visible(False)\n",
"ax.xaxis.set_ticks_position('bottom')\n",
"plt.tick_params(axis='both', which='major', labelsize=13)\n",
"ax.get_yaxis().set_ticks([])\n",
"plt.axvline(diff, linewidth=2, alpha=0.5, color='red')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Out of 10,000 samples, the probability that the difference in the means is >= 6.58 is 0.1663\n"
]
}
],
"source": [
"# obtain all observations greater than or equal to the stated difference\n",
"gt_diff = diff_means[diff_means >= diff]\n",
"\n",
"# calculate portion of differences that are greater than or equal to the stated difference\n",
"p = len(gt_diff) / 10000\n",
"\n",
"# print results\n",
"print('Out of 10,000 samples, the probability that the difference in the means is >= ' + \n",
" \"{0:.2f}\".format(diff) + ' is ' + str(p))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since the simulated probability that the difference in the means will be greater than or equal to 6.58 is greater than 0.05, the difference in the means of the 2 sets of test scores is **NOT** significant. In other words, there is a probability of more than 16% that the difference in the means will be greater than or equal to 6.58. We want it to be less tha 5% to be considered statistically \"significant\"."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Calculating 90% Confidence Interval for the Difference In the Means"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We'll use numpy's handy percentile() method to calculate 90% confidence interval"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([-10.5 , 10.75])"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.percentile(diff_means, [5, 95])"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"lower_bound = np.percentile(diff_means, [5, 95])[0] # get first element for lower bound\n",
"upper_bound = np.percentile(diff_means, [5, 95])[1] # get second element for upper bound"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Let's double-check the lower and upper bound values"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"-10.5"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"lower_bound"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"10.75"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"upper_bound"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Now we're ready to plot!"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlIAAAGCCAYAAAArCS3BAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAHXBJREFUeJzt3X2UXWV9L/DvLwlQBSWiVUAJoVhaa6u1XlvxgqJUvSJe\noSwqXimEdbVUewvxWi2ijTFV69tqEbEVdamrpYhFEFB7VUoFTCul0gCtgAg6CYIiiAETCiSw7x/7\nJA6HvEyezMxJJp/PWmdlzn559u85O2fme/azz97VdV0AANhys0ZdAADA9kqQAgBoJEgBADQSpAAA\nGglSAACNBCkAgEZzpqhd11SYaRYvfvi/AInfDcwU1bqiI1IAAI0EKQCARoIUAEAjQQoAoJEgBQDQ\naKq+tQcAO5z58+dn+fLloy6Djdh3330zNjY2qW0KUgAwSZYvX56ucwWgbVVV81UONsrQHgBAI0EK\nAKCRIAUA0EiQAoAd1AknnJBFixZl6dKledrTnrZ++o033phnPetZ2X333XPGGWfkvvvuyyte8YrM\nnTs3r3rVq0ZY8bbHyeYAMIUWLTotK1asnLL2582bmyVLFm5VGwcddFCuv/769c/f//7350UvelGW\nLVuWJDnrrLNyxx135Cc/+cmUnLC9PROkYISm+hfsdJmMX+QwU61YsTLz5y+esvbHxia/7eXLl+fV\nr371w54fcMABTSHqwQcfzOzZsyezvG2KIAUjNNW/YKfLVPwiBybfsmXL8trXvjY33XRTXvayl60P\nRpdddlmOPfbY3HLLLTn00ENz2WWXZenSpVm4cGEOP/zwnHfeeem6LhdccEE+9KEP5YQTTsgnP/nJ\nfPCDH8ztt9+e3/zN38yZZ56ZefPmJUlmzZqVM844I6eddloefPDB3Hzzzbnhhhty0kkn5aqrrsoT\nn/jELFmyJEcffXSSfohx1113zdjYWC6//PI8/elPz9lnn5399tsvSfKtb30rb3zjG3PVVVdl5513\nzsknn5xTTjklXdflfe97Xz7xiU/k7rvvzqGHHpqPfvSjmTt37rS9ps6RAoAdwJo1a3LkkUfm+OOP\nz1133ZWjjz4655133vr560LVJZdckoMPPjgf+chHcs899+Tss8/OqaeemmOOOSb33HNPTjjhhFx4\n4YV573vfmwsuuCB33HFHDj744IcdwUqSCy+8MFdeeWWuu+663HvvvXnJS16SY489NnfeeWfOOeec\nvOENb8gNN9ywfvnPfvazeec735mVK1dm//33z9ve9rYkyapVq/LiF784hx12WH7wgx/kpptuyqGH\nHpokOf3003PRRRfl61//em677bY87nGPyxve8IapfikfRpACgB3AFVdckbVr1+akk07K7Nmzc9RR\nR+U5z3lOU1tnnnlm3vrWt+aAAw7IrFmzcsopp+Tqq6/OLbfcsn6ZU089NXPnzs0uu+ySL37xi9lv\nv/1y3HHHparyzGc+M0cddVTOPffc9csfeeSRefazn51Zs2blNa95Ta6++uokyRe+8IXstddeWbhw\nYXbeeefsuuuu6+s+88wz8+53vzt77bVXdtpppyxatCif+9zn8tBDD23FK7VlDO0BwA7gtttuy5Of\n/OSHTdt3332b2lq+fHlOPvnkvOlNb0qSdF2Xqsqtt96affbZJ0nylKc85WHLX3HFFdljjz3WL//g\ngw/muOOOW7/Mnnvuuf7nRz/60Vm1alWS5Pvf/37233//jdZx5JFHZtasWevb3WmnnXL77bdnr732\naurblhKkAGAHsNdee+XWW2992LQVK1bkqU996ha3NW/evLz97W9/xHDeeONPTN9nn31yyCGH5Ctf\n+coWb2ufffbJOeecs9E6PvnJT+bAAw/c4nYni6E9ANgBHHjggZkzZ04+/OEPZ+3atTn//PNz5ZVX\nrp+/JfcIPPHEE/Oe97wn1113XZLk7rvvzuc+97mNLn/44YfnxhtvzFlnnZW1a9dmzZo1+eY3v5lv\nf/vbm93W4Ycfnh/+8Ic5/fTT88ADD2TVqlXr6z7xxBNz6qmnZsWKFUmSO+64IxdddNGE+zEZBCkA\n2AHstNNOOf/88/OpT30qj3/843PuuefmqKOOWj9//BGkzV3m4Igjjsgpp5ySY445JnPnzs0znvGM\nfPnLX97o+rvttlu++tWv5pxzzsnee++dvffeO6ecckruv//+zda922675eKLL85FF12UPffcMwcc\ncEAuvfTSJMnJJ5+cV77ylXnJS16S3XffPc973vMeFg6nQ03RXard+nqmWbz44f8yKRYsWDxjLn/w\n6U8vHnUZjILfDQ9TVY84srM9XJBzR7Gh/bNuVmubzpECgCkk5MxshvYAABoJUgAAjQQpAIBGghQA\nQCNBCgCgkSAFANDI5Q8AYJLsu+++m72YJaPTem/BTRGkAGCSjI2NjboEppmhPQCARoIUAEAjQQoA\noJEgBQDQSJACAGgkSAEANBKkAAAaCVIAAI0EKQCARoIUAEAjQQoAoJEgBQDQSJACAGg0Z9QFANu/\nZcuuyYIFi0ddxqSYN29ulixZOOoygO2EIAVstdWru8yfv3jUZUyKsbHFoy4B2I4Y2gMAaCRIAQA0\nEqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQA\nQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRI\nAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBG\nghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIA\naCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQp\nAIBGghQAQCNBCgCg0ZxRFwAtFi06LStWrBx1GVtt2bLrMn/+qKsAoJUgxXZpxYqVmT9/8ajL2GpL\nlx4x6hIA2AqG9gAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACN\nBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAozmjLgBgW7Js\n2TVZsGDxqMvYavPmzc2SJQtHXQbMeIIUwDirV3eZP3/xqMvYamNji0ddAuwQDO0BADQSpAAAGglS\nAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCR\nIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAA\nGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EK\nAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQS\npAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABA\nI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgB\nADQSpAAAGglSAACNBCkAgEZzRl0A02fRotOyYsXKpnWPuPrSJMkFY4snr6CtsGzZdZk/f9RVALCj\nE6R2ICtWrMz8+Yub1p07CFCt60+2pUuPGHUJAGBoDwCglSAFANBIkAIAaCRIAQA0EqQAABoJUgAA\njQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAF\nANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQKM5oy4AgMm3bNk1WbBg8ZRv54irL02SXDA2\nNduaN29ulixZOCVtw2QQpABmoNWru8yfv3jKtzN3EKCmaltjUxTQYLIY2gMAaCRIAQA0EqQAABoJ\nUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCg\nkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQA\nABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNB\nCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0\nEqQAABoJUgAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIAaCRIAQA0EqQAABoJUgAAjQQpAIBGghQA\nQCNBCgCgkSAFANBIkAIAaDRn1AVsDxYtOi0rVqwcdRlbbdmy6zJ//qirAICZQ5CagBUrVmb+/MWj\nLmOrLV16xKhLAIAZxdAeAEAjR6QA2GYtW3ZNFixYPOoyJsW8eXOzZMnCUZfBJBOkANhmrV7dzYhT\nK5JkbGzxqEtgChjaAwBoJEgBADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgB\nADQSpAAAGglSAACNBCkAgEaCFABAI0EKAKCRIAUA0EiQAgBoJEgBADQSpAAAGglSAACNBCkAgEZz\npqLRtWvX5vTT/ya3375qKpqfVrvsMiv33XffqMsAALZBUxakrr32h3nSk/5gKpqfVitWfDH333//\nqMsAALZBUxKkkmTWrFl51KP2mKrmp83s2TuPugQAYBs1JUHq8ssvn4pmt3ljY5dm/vxDRl3GtNPv\nHYt+71j0e/IsW3ZNFixYPKltTrYf/nAse+45f5PLzJs3N0uWLJyegqZJVR3Sdd2lLetOYZDabSqa\n3qb5hbNj0e8di37vWKai36tXd5k/f/GktjnZxsYWb7bGsbFNz99OHZLk0pYVfWsPAKDRlJ0jNXv2\nmtxyy9lT1fy0WbPmtlGXAABso6rruslvtGryGwUAmCJd11XLelMSpAAAdgTOkQIAaCRIAQA0EqQA\nABpNWpCqqp2r6qNVdWNV3VNVY1X1/qraZWi5N1fV96vqp1X11arab7JqGJWq+qOquqKqVlfVjRuY\n/46qWjN4XX46+PfPR1HrZNpcvwfLzLj9PayqLq2q+4b272GjrmuyVdWsqvpAVf2oqu6uqnOr6vGj\nrmsqVdWnquqBoX27/d/7akhVvaqqLh/s1wc2MP+4qrqpqlZV1Teq6jdGUedk21S/q+r4qnpwaN//\n3ahqnUxV9d6q+s9Bv79fVR+rqscNLTPj9vnm+t26zyfziNScJHckeXmS3ZMcnORFSd43rsjXJHnT\nYJmfT3J9kouqqulM+W3Iren7+e5NLPO1ruse23XdYwb/vnWaaptKm+z3DN7fw7ok7xzav/8w6qKm\nwFuTvCLJc5I8JUkl+duRVjQ9Pj20bz866oKmwF1JPpLkEZerrqqDkvxVkhOTPC7J+Un+oapmwlWX\nN9rvgZuH9v1rprG2qbQ2yWuS7JHkmenfz59eN3MG7/NN9ntgi/f5pAWpruvu7bruT7uu+07XuyXJ\nx9NfLXSd1yU5s+u6a7quuy/JqUl+IclBk1XHKHRdd37XdZ9PHyx2GBPo94zc3xsx08LhhrwuyXu7\nrlvedd1Pk7wlyf+oqn1GXBdbqeu6i7uu+2yS725g9muTnNd13SVd163puu4DSe5LcuS0FjkFNtPv\nGavrurcPfi8/2HXdj5N8KMkLxi0yI/f5BPrdZKrPkTo0yTXjnj8zyVXrnnRdtzrJdwbTZ7rnDoZE\nbh4cTnzCqAuaBjvS/l5YVXdW1X9U1SlVNWUXux2Fqto9ybwk/75uWtd1301yT2bm/hzvqMG+vWFw\nusKuoy5omj3sfTxwdWb+fk+SfarqtqpaXlWfqar5oy5oivx2NvG3emAm7vPhficN+3xCQWpwnsBD\ng7HDh4YeD1bVkg2sszDJ85O8bdzkxyS5e2jRlUkeO5E6pltLvzfi75P8Std1T0w/3PnkJBdOWeFb\naRL7vV3t72Fb8DqckuQX0w9f/u/0n+beOaq6p8hj0g9hbrf7s9HpSX6567onpP80/oIkHxttSdNu\nu34fb4XLkvxa13V7px/Ovi/JxVX1qNGWNbmq6qgkv5/kpHGTZ/w+30i/m/b5RD81/2H6c1025t6h\nAt+Y5M1JXth13ffHzfpp+vOnxpub/lPttmiL+r0xXdddP+7n5VX12iS3VtV+Xdd9bytrnAqT0u9s\nf/t72IReh67r/nXctCur6k+TvDcP/xCxvftp+uHL7Xl/brGu65aN+/n6wQfES6tqQdd1a0ZY2nTa\n2Pv4phHUMm26rhsb9/OPqup16cPEc5N8bVR1TaaqOjrJXyd5Rdd144/MzOh9vrF+t+7zCQWpruvu\nzQT/eA7+iLwuyfO7rht+0a9J8htJLhosu1v6T/LDh9a2CVvS75bms42eVzOJ/d6u9vewrXwdtsl9\n26rrururakX6/XltklTV/uk/uV47ytpGZEbt381Y9z4e71lJzhtBLduCGbHvq+qEJB9IcnjXdVcM\nzZ6x+3wz/d7oapuaOannSFXVB9IPbbxgAyEq6Q+Jn1hVv15Vj07ynvQn+S2dzDqmW1XNrv4yDzv3\nT2uXGnfZh6o6ct05UVX15PRJ+JuDc0y2W5vrd2bo/h6vqnavqpevO2+mqp6V5B1JzhltZVPiY0n+\npKrmD86Zel+SL3ddt2LEdU2Z6r8ev/vg519M8sEkF3Zd94hLBGzPqr+0xS5Jdhk8H/9e/niS36mq\nF1Z/mZu3pH/Pf35E5U6aTfW7qg4b/L5OVe2R/ltsdySZ6B/fbVZVnZQ+TLx0I2FiRu7zzfW7eZ93\nXTcpj/Qnoj6U5L/SH+q/J/3hwf8YWu6P03/La1WSi5PsN1k1jOqR/g/nQ0keHDweSvLguPlnJbl9\n8HosT/KJJE8add1T3e+Zur+H+veEJN9I8pP05xTckOTtSeaMurYp6OusJO8f/GK5O8m5SfYYdV1T\n3OevJblz8N69efBLeLdR1zUF/Tx+Q+/lJPMG848d9H/14I/Kr4+65qnu9+D/+q2DfX9r+nNdnzrq\nmiep3w8luX/ob/U9Q8vMuH2+uX637nM3LQYAaOQWMQAAjQQpAIBGghQAQCNBCgCgkSAFANBIkAIA\naCRIAQA0EqRgklTVO4ZuanxXVV1ZVe+qqicNLbvvYLnDxk17dFWdU1V3DtY/bjD9dVX13apaU1X/\nNN39GoXBa/mjSWrrzVX1/A1Mf6iq3jAZ29hA2y8YtL923ZWSh+Z/YjB/h9ifMJMJUjC5Vib5rSQH\nJnlV+ntT/V6S/xjcPmadH6S/Eeb42+W8PsnLk7x2sP6XBgHsr9LfmuHgJFPyh38b9PEkL52ktt6S\n5JBJamtLrU7//2C9qtopyZHpr54MbOcmdNNiYMLWdl33b+OeX1xVf53k60nOqapf7noPJLlyaN1f\nTvLtrusuWDehqg5K/4HnU13X/efWFFZVP9d13X1b08Z06brutiS3jbqOSfCFJMck+Ytx016afp9e\nmv6mz8B2zBEpmGJd192T/qjILyZ5cfLIob2q+l76G37/xrihwXckuXzQzLVDw327VNX7q2pFVd1X\nVVdX1cvGb7eqvldVH6yqt1fVLenvj7du3sFVdWlVrR4MJX6sqnYbN3/BoI5fraqvVtWqqrq+qo4c\n7t/gptz/WlX3Dtr6YlXtM27+r1bVl6rqnsHj74eHOjfQ5uKqumPc83VDZS8YrP/Tqrq5ql6/mXa+\nl2SPJIvHva7jh/lmV9W7q+pHVXV7VZ0xOGI0vo19BkOuPx68Xl+uqgM2td2BLv3Nq59dVb8wbvox\nSS5I8ogbH09kW1X151V17eA1uKWqztrA0PH3quoDVbVwsMxdVfWZqnrsuGXmDP5/LB/8H7q1qs6r\nKh+wYQsIUjA9Lk2yNv1w3jrjb3R5RJJ/SHJ9fjY0+PEkfziY/+rBtC8Nnp+X5Lgk70pyeJJ/S3JR\nVT1jaLv/K8nz0w8bvipJquq/p7+B9G1JjkpycpLDknxyA7X9XZILB/V9J8lnqmrvdQtV1e8NavlO\nkqOTLEhyY5KfH8x/avrhy52TvCb9TWKfnuSijbxO47e/oRuBfizJ1YN6vpbkjKr6b5to54j0Nyf9\nRPrX/sAk/z5u/puS7DWo7f1JTkz/eqzr3+OS/HP6EPz7gz7umv5I4y6b6UOSfDf9vnn1oL1HJfmf\nST4zvOAWbOtJSf48/TDwyUn2S3LJBrb9u0lelOR16YP84UneM27+qYO63pbktwdt3Z1k9gT6Bawz\n6rsxe3jMlEeSdyT50Sbm35bkI4Of901/J/LDxs3/VJIrh9Z5Qfq70f/KuGmHDqYdNLTsZUk+O+75\n99LfwXynoeW+nuQfh6a9cFDPrwyeHz94fvy4ZfZIsibJ7w+eV5LvJzl3E33+2/ThcPa4aU9NHypf\nNtHXcvA6PJTkHeOmzUnyoyTv2cx+uSPJog1MfyjJ14amfT7Jv4x7/meD9XcfN21u+nPhXr+Jba7f\nb0kWJrl2MP13k9ye/kPsuUn+aWu2NWjnyYO+HDRu+vfSh9tZ46b9ZZLbxj3/QpIPjPp94+GxvT8c\nkYLpU5PUzqFJfpjkG1U1e/CYk+Sfkgwfnbmk67o16wvoj4g8N8m549adnf5IyJokzx63bpf+yFX/\npOvuSh9cnjKY9EtJ9k7y6c3U+vnBttdta2zw2NSRpA0Zrmdt+rDwlI2usXkXDz2/bqi9QwfLrBpX\n/6okV2Xi9f99kqdV1dMz+AJC13UPbWC5CW2rql5WVf9cVSvTB9Jb0r82w8ONXxvaznVJnjhoN+mP\n7J1Q/bcaf22CfQGGCFIwDQZDM49PfzRiaz0h/XDUmnGPB9IfxRkOFcPbe1z6oZu/Glr/vvRHePYZ\nWn7l0PMHkvzc4OfHp/8D/oPN1PonG6h1vw1sayI2VU+LzbX3hPThZ7j+QzLB+rv+xPmlSf4gycuy\ngWG9iW6rqp6Tfqh1RZJj04fi30of0odfhw31rZKsGyZ8V5Iz0g/7Xj04l+qkifQJ+BknFcL0eFH6\n99s3JqGtu9IPqb0ymz/KNXye0crBtHekPydr2JZ8U+7Hg+3vtYll7kpyfvrzvYZrvXMLtjUqdyX5\nVpIleWT9W3L5gs+mDy0/6Lru61uxrSPSD3m+et2Mqpq3BXWs13Xd/UkWpz8Rf//0Qe+0qrqh67qv\ntrQJOyJBCqZYVc1N8r70J2H/4yQ0eUmS/5tkddd1N27Jil3X3VtVVyT5pa7r3rWVdXw7/TlYx+dn\nJ8EPuyTJ07uuW7aV29oaW3PU6pL0J31fNwgerc5N8pI8cihxS7f1qPRHqsY7Nhs+MX/Cuq67Ocmb\nq+r/pD+vS5CCCRKkYHLNqarfGvz8mPTnHL0+/R/Al3Zd1/IH72FHJ7quu7iqvprkH6vqfemPYjw2\nya8n2aXrurdtpr23DNbtknwu/dGOfdN/c+/UrutumkhRXdd1VfWWJGdV1Vn52ZDVC5Oc3XXdv6c/\n4vGvVfWl9N8KvDP98ONvp7821uWPbHmjWs8xuyHJy6vqK+nPObqh67rVE1z3L9J/o+9rVfXh9MHx\nSelPJv9613WfnUi9Xdf9OMnvTMK2Lk5yclX9ZfqTxZ+XPkhtsao6P/35V8uS/Ff6EDc7P7vkBjAB\nghRMrt2T/Ev6IwT3JLkpyd8kOaPruuFbnkw0VG1ouSPTf3395CTz0g8LXZ3kw0PrPWLdruv+eXAt\npXcOapudZHmSL2fz53A9rM2u6z5TVf+V/iv056a/kvcV6b99lq7rvlNVz01/Ps6Z6QPlremPvkwo\nsA1te0umr/Pm9MNqX0zy6PRB7/Lhvmyw4a778aD+d6cPOnPTnxO2NMm1jfU2b6vruv9XVX+S5I/S\nXwH/X9JfBmH4yORm+5b+CwavSvLH6c+XvS7J7wwCMDBB1fYBGQAA39oDAGgkSAEANBKkAAAaCVIA\nAI0EKQCARoIUAEAjQQoAoJEgBQDQSJACAGj0/wGaDmJzeTMN6QAAAABJRU5ErkJggg==\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x7fad657d96a0>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"fig, ax = plt.subplots(figsize=(10, 6))\n",
"plt.hist(diff_means, alpha=.5, label='difference')\n",
"plt.legend(loc='best')\n",
"plt.xlabel('Difference in the Means', fontsize=15)\n",
"ax.spines['right'].set_visible(False)\n",
"ax.spines['left'].set_visible(False)\n",
"ax.spines['top'].set_visible(False)\n",
"ax.xaxis.set_ticks_position('bottom')\n",
"plt.tick_params(axis='both', which='major', labelsize=13)\n",
"ax.get_yaxis().set_ticks([])\n",
"plt.axvline(lower_bound, linewidth=2, alpha=0.5, color='red')\n",
"plt.axvline(upper_bound, linewidth=2, alpha=0.5, color='red')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"With 90% confidence, the true difference in the means will fall between -10.50 and 10.75\n"
]
}
],
"source": [
"print('With 90% confidence, the true difference in the means will fall between ' + \n",
" \"{0:.2f}\".format(lower_bound) + ' and ' + \"{0:.2f}\".format(upper_bound))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
| {
"pile_set_name": "Github"
} |
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
object foamyHexMeshDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#includeEtc "caseDicts/foamyHexMeshDict"
geometry
{
#include "meshDict.geometry"
}
surfaceConformation
{
locationInMesh (-0.078 0.02 0.0);
featurePointControls
{
specialiseFeaturePoints on;
edgeAiming on;
guardFeaturePoints off;
snapFeaturePoints off;
circulateEdges off;
}
geometryToConformTo
{
#include "meshDict.conformationSurfaces"
}
additionalFeatures
{
boundaryAndFaceZones
{
featureMethod extendedFeatureEdgeMesh;
extendedFeatureEdgeMesh "boundaryAndFaceZones.extendedFeatureEdgeMesh";
}
}
}
motionControl
{
defaultCellSize 0.0035;
minimumCellSizeCoeff 0;
maxRefinementIterations 0;
maxSmoothingIterations 100;
shapeControlFunctions
{
#include "meshDict.shapeControlFunctions"
}
objOutput off;
timeChecks off;
printVertexInfo off;
}
polyMeshFiltering
{
filterEdges false;
filterFaces off;
writeTetDualMesh true;
writeCellShapeControlMesh false;
writeBackgroundMeshDecomposition false;
}
meshQualityControls
{
#include "meshQualityDict"
}
// ************************************************************************* //
| {
"pile_set_name": "Github"
} |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/cryptauth/cryptauth_enrollment_manager.h"
#include <utility>
#include "base/base64url.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/test/simple_test_clock.h"
#include "base/time/clock.h"
#include "base/time/time.h"
#include "components/cryptauth/cryptauth_enroller.h"
#include "components/cryptauth/fake_cryptauth_gcm_manager.h"
#include "components/cryptauth/fake_secure_message_delegate.h"
#include "components/cryptauth/mock_sync_scheduler.h"
#include "components/cryptauth/pref_names.h"
#include "components/prefs/testing_pref_service.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::SaveArg;
namespace cryptauth {
namespace {
// The GCM registration id from a successful registration.
const char kGCMRegistrationId[] = "new gcm registration id";
// The user's persistent public key identifying the local device.
const char kUserPublicKey[] = "user public key";
// The initial "Now" time for testing.
const double kInitialTimeNowSeconds = 20000000;
// A later "Now" time for testing.
const double kLaterTimeNow = kInitialTimeNowSeconds + 30;
// The timestamp of a last successful enrollment that is still valid.
const double kLastEnrollmentTimeSeconds =
kInitialTimeNowSeconds - (60 * 60 * 24 * 15);
// The timestamp of a last successful enrollment that is expired.
const double kLastExpiredEnrollmentTimeSeconds =
kInitialTimeNowSeconds - (60 * 60 * 24 * 100);
// Mocks out the actual enrollment flow.
class MockCryptAuthEnroller : public CryptAuthEnroller {
public:
MockCryptAuthEnroller() {}
~MockCryptAuthEnroller() override {}
MOCK_METHOD5(Enroll,
void(const std::string& user_public_key,
const std::string& user_private_key,
const cryptauth::GcmDeviceInfo& device_info,
cryptauth::InvocationReason invocation_reason,
const EnrollmentFinishedCallback& callback));
private:
DISALLOW_COPY_AND_ASSIGN(MockCryptAuthEnroller);
};
// Creates MockCryptAuthEnroller instances, and allows expecations to be set
// before they are returned.
class MockCryptAuthEnrollerFactory : public CryptAuthEnrollerFactory {
public:
MockCryptAuthEnrollerFactory()
: next_cryptauth_enroller_(new NiceMock<MockCryptAuthEnroller>()) {}
~MockCryptAuthEnrollerFactory() override {}
// CryptAuthEnrollerFactory:
std::unique_ptr<CryptAuthEnroller> CreateInstance() override {
auto passed_cryptauth_enroller = std::move(next_cryptauth_enroller_);
next_cryptauth_enroller_.reset(new NiceMock<MockCryptAuthEnroller>());
return std::move(passed_cryptauth_enroller);
}
MockCryptAuthEnroller* next_cryptauth_enroller() {
return next_cryptauth_enroller_.get();
}
private:
// Stores the next CryptAuthEnroller to be created.
// Ownership is passed to the caller of |CreateInstance()|.
std::unique_ptr<MockCryptAuthEnroller> next_cryptauth_enroller_;
DISALLOW_COPY_AND_ASSIGN(MockCryptAuthEnrollerFactory);
};
// Harness for testing CryptAuthEnrollmentManager.
class TestCryptAuthEnrollmentManager : public CryptAuthEnrollmentManager {
public:
TestCryptAuthEnrollmentManager(
std::unique_ptr<base::Clock> clock,
std::unique_ptr<CryptAuthEnrollerFactory> enroller_factory,
std::unique_ptr<SecureMessageDelegate> secure_message_delegate,
const cryptauth::GcmDeviceInfo& device_info,
CryptAuthGCMManager* gcm_manager,
PrefService* pref_service)
: CryptAuthEnrollmentManager(std::move(clock),
std::move(enroller_factory),
std::move(secure_message_delegate),
device_info,
gcm_manager,
pref_service),
scoped_sync_scheduler_(new NiceMock<MockSyncScheduler>()),
weak_sync_scheduler_factory_(scoped_sync_scheduler_.get()) {}
~TestCryptAuthEnrollmentManager() override {}
std::unique_ptr<SyncScheduler> CreateSyncScheduler() override {
EXPECT_TRUE(scoped_sync_scheduler_);
return std::move(scoped_sync_scheduler_);
}
base::WeakPtr<MockSyncScheduler> GetSyncScheduler() {
return weak_sync_scheduler_factory_.GetWeakPtr();
}
private:
// Ownership is passed to |CryptAuthEnrollmentManager| super class when
// |CreateSyncScheduler()| is called.
std::unique_ptr<MockSyncScheduler> scoped_sync_scheduler_;
// Stores the pointer of |scoped_sync_scheduler_| after ownership is passed to
// the super class.
// This should be safe because the life-time this SyncScheduler will always be
// within the life of the TestCryptAuthEnrollmentManager object.
base::WeakPtrFactory<MockSyncScheduler> weak_sync_scheduler_factory_;
DISALLOW_COPY_AND_ASSIGN(TestCryptAuthEnrollmentManager);
};
} // namespace
class CryptAuthEnrollmentManagerTest
: public testing::Test,
public CryptAuthEnrollmentManager::Observer {
protected:
CryptAuthEnrollmentManagerTest()
: public_key_(kUserPublicKey),
clock_(new base::SimpleTestClock()),
enroller_factory_(new MockCryptAuthEnrollerFactory()),
secure_message_delegate_(new FakeSecureMessageDelegate()),
gcm_manager_(kGCMRegistrationId),
enrollment_manager_(base::WrapUnique(clock_),
base::WrapUnique(enroller_factory_),
base::WrapUnique(secure_message_delegate_),
device_info_,
&gcm_manager_,
&pref_service_) {}
// testing::Test:
void SetUp() override {
clock_->SetNow(base::Time::FromDoubleT(kInitialTimeNowSeconds));
enrollment_manager_.AddObserver(this);
private_key_ =
secure_message_delegate_->GetPrivateKeyForPublicKey(public_key_);
secure_message_delegate_->set_next_public_key(public_key_);
CryptAuthEnrollmentManager::RegisterPrefs(pref_service_.registry());
pref_service_.SetUserPref(
prefs::kCryptAuthEnrollmentIsRecoveringFromFailure,
new base::FundamentalValue(false));
pref_service_.SetUserPref(
prefs::kCryptAuthEnrollmentLastEnrollmentTimeSeconds,
new base::FundamentalValue(kLastEnrollmentTimeSeconds));
pref_service_.SetUserPref(
prefs::kCryptAuthEnrollmentReason,
new base::FundamentalValue(cryptauth::INVOCATION_REASON_UNKNOWN));
std::string public_key_b64, private_key_b64;
base::Base64UrlEncode(public_key_,
base::Base64UrlEncodePolicy::INCLUDE_PADDING,
&public_key_b64);
base::Base64UrlEncode(private_key_,
base::Base64UrlEncodePolicy::INCLUDE_PADDING,
&private_key_b64);
pref_service_.SetString(prefs::kCryptAuthEnrollmentUserPublicKey,
public_key_b64);
pref_service_.SetString(prefs::kCryptAuthEnrollmentUserPrivateKey,
private_key_b64);
ON_CALL(*sync_scheduler(), GetStrategy())
.WillByDefault(Return(SyncScheduler::Strategy::PERIODIC_REFRESH));
}
void TearDown() override { enrollment_manager_.RemoveObserver(this); }
// CryptAuthEnrollmentManager::Observer:
void OnEnrollmentStarted() override { OnEnrollmentStartedProxy(); }
void OnEnrollmentFinished(bool success) override {
// Simulate the scheduler changing strategies based on success or failure.
SyncScheduler::Strategy new_strategy =
SyncScheduler::Strategy::AGGRESSIVE_RECOVERY;
ON_CALL(*sync_scheduler(), GetStrategy())
.WillByDefault(Return(new_strategy));
OnEnrollmentFinishedProxy(success);
}
MOCK_METHOD0(OnEnrollmentStartedProxy, void());
MOCK_METHOD1(OnEnrollmentFinishedProxy, void(bool success));
// Simulates firing the SyncScheduler to trigger an enrollment attempt.
CryptAuthEnroller::EnrollmentFinishedCallback FireSchedulerForEnrollment(
cryptauth::InvocationReason expected_invocation_reason) {
CryptAuthEnroller::EnrollmentFinishedCallback completion_callback;
EXPECT_CALL(
*next_cryptauth_enroller(),
Enroll(public_key_, private_key_, _, expected_invocation_reason, _))
.WillOnce(SaveArg<4>(&completion_callback));
auto sync_request = base::MakeUnique<SyncScheduler::SyncRequest>(
enrollment_manager_.GetSyncScheduler());
EXPECT_CALL(*this, OnEnrollmentStartedProxy());
SyncScheduler::Delegate* delegate =
static_cast<SyncScheduler::Delegate*>(&enrollment_manager_);
delegate->OnSyncRequested(std::move(sync_request));
return completion_callback;
}
MockSyncScheduler* sync_scheduler() {
return enrollment_manager_.GetSyncScheduler().get();
}
MockCryptAuthEnroller* next_cryptauth_enroller() {
return enroller_factory_->next_cryptauth_enroller();
}
// The expected persistent keypair.
std::string public_key_;
std::string private_key_;
// Owned by |enrollment_manager_|.
base::SimpleTestClock* clock_;
// Owned by |enrollment_manager_|.
MockCryptAuthEnrollerFactory* enroller_factory_;
// Ownered by |enrollment_manager_|.
FakeSecureMessageDelegate* secure_message_delegate_;
cryptauth::GcmDeviceInfo device_info_;
TestingPrefServiceSimple pref_service_;
FakeCryptAuthGCMManager gcm_manager_;
TestCryptAuthEnrollmentManager enrollment_manager_;
DISALLOW_COPY_AND_ASSIGN(CryptAuthEnrollmentManagerTest);
};
TEST_F(CryptAuthEnrollmentManagerTest, RegisterPrefs) {
TestingPrefServiceSimple pref_service;
CryptAuthEnrollmentManager::RegisterPrefs(pref_service.registry());
EXPECT_TRUE(pref_service.FindPreference(
prefs::kCryptAuthEnrollmentLastEnrollmentTimeSeconds));
EXPECT_TRUE(pref_service.FindPreference(
prefs::kCryptAuthEnrollmentIsRecoveringFromFailure));
EXPECT_TRUE(pref_service.FindPreference(prefs::kCryptAuthEnrollmentReason));
}
TEST_F(CryptAuthEnrollmentManagerTest, GetEnrollmentState) {
enrollment_manager_.Start();
ON_CALL(*sync_scheduler(), GetStrategy())
.WillByDefault(Return(SyncScheduler::Strategy::PERIODIC_REFRESH));
EXPECT_FALSE(enrollment_manager_.IsRecoveringFromFailure());
ON_CALL(*sync_scheduler(), GetStrategy())
.WillByDefault(Return(SyncScheduler::Strategy::AGGRESSIVE_RECOVERY));
EXPECT_TRUE(enrollment_manager_.IsRecoveringFromFailure());
base::TimeDelta time_to_next_sync = base::TimeDelta::FromMinutes(60);
ON_CALL(*sync_scheduler(), GetTimeToNextSync())
.WillByDefault(Return(time_to_next_sync));
EXPECT_EQ(time_to_next_sync, enrollment_manager_.GetTimeToNextAttempt());
ON_CALL(*sync_scheduler(), GetSyncState())
.WillByDefault(Return(SyncScheduler::SyncState::SYNC_IN_PROGRESS));
EXPECT_TRUE(enrollment_manager_.IsEnrollmentInProgress());
ON_CALL(*sync_scheduler(), GetSyncState())
.WillByDefault(Return(SyncScheduler::SyncState::WAITING_FOR_REFRESH));
EXPECT_FALSE(enrollment_manager_.IsEnrollmentInProgress());
}
TEST_F(CryptAuthEnrollmentManagerTest, InitWithDefaultPrefs) {
std::unique_ptr<base::SimpleTestClock> clock(new base::SimpleTestClock());
clock->SetNow(base::Time::FromDoubleT(kInitialTimeNowSeconds));
base::TimeDelta elapsed_time = clock->Now() - base::Time::FromDoubleT(0);
TestingPrefServiceSimple pref_service;
CryptAuthEnrollmentManager::RegisterPrefs(pref_service.registry());
TestCryptAuthEnrollmentManager enrollment_manager(
std::move(clock), base::MakeUnique<MockCryptAuthEnrollerFactory>(),
base::MakeUnique<FakeSecureMessageDelegate>(), device_info_,
&gcm_manager_, &pref_service);
EXPECT_CALL(
*enrollment_manager.GetSyncScheduler(),
Start(elapsed_time, SyncScheduler::Strategy::AGGRESSIVE_RECOVERY));
enrollment_manager.Start();
EXPECT_FALSE(enrollment_manager.IsEnrollmentValid());
EXPECT_TRUE(enrollment_manager.GetLastEnrollmentTime().is_null());
}
TEST_F(CryptAuthEnrollmentManagerTest, InitWithExistingPrefs) {
EXPECT_CALL(
*sync_scheduler(),
Start(clock_->Now() - base::Time::FromDoubleT(kLastEnrollmentTimeSeconds),
SyncScheduler::Strategy::PERIODIC_REFRESH));
enrollment_manager_.Start();
EXPECT_TRUE(enrollment_manager_.IsEnrollmentValid());
EXPECT_EQ(base::Time::FromDoubleT(kLastEnrollmentTimeSeconds),
enrollment_manager_.GetLastEnrollmentTime());
}
TEST_F(CryptAuthEnrollmentManagerTest, InitWithExpiredEnrollment) {
pref_service_.SetUserPref(
prefs::kCryptAuthEnrollmentLastEnrollmentTimeSeconds,
new base::FundamentalValue(kLastExpiredEnrollmentTimeSeconds));
EXPECT_CALL(*sync_scheduler(),
Start(clock_->Now() - base::Time::FromDoubleT(
kLastExpiredEnrollmentTimeSeconds),
SyncScheduler::Strategy::AGGRESSIVE_RECOVERY));
enrollment_manager_.Start();
EXPECT_FALSE(enrollment_manager_.IsEnrollmentValid());
EXPECT_EQ(base::Time::FromDoubleT(kLastExpiredEnrollmentTimeSeconds),
enrollment_manager_.GetLastEnrollmentTime());
}
TEST_F(CryptAuthEnrollmentManagerTest, ForceEnrollment) {
enrollment_manager_.Start();
EXPECT_CALL(*sync_scheduler(), ForceSync());
enrollment_manager_.ForceEnrollmentNow(
cryptauth::INVOCATION_REASON_SERVER_INITIATED);
auto completion_callback =
FireSchedulerForEnrollment(cryptauth::INVOCATION_REASON_SERVER_INITIATED);
clock_->SetNow(base::Time::FromDoubleT(kLaterTimeNow));
EXPECT_CALL(*this, OnEnrollmentFinishedProxy(true));
completion_callback.Run(true);
EXPECT_EQ(clock_->Now(), enrollment_manager_.GetLastEnrollmentTime());
}
TEST_F(CryptAuthEnrollmentManagerTest,
EnrollmentFailsThenSucceeds) {
enrollment_manager_.Start();
base::Time old_enrollment_time = enrollment_manager_.GetLastEnrollmentTime();
// The first periodic enrollment fails.
ON_CALL(*sync_scheduler(), GetStrategy())
.WillByDefault(Return(SyncScheduler::Strategy::PERIODIC_REFRESH));
auto completion_callback =
FireSchedulerForEnrollment(cryptauth::INVOCATION_REASON_PERIODIC);
clock_->SetNow(base::Time::FromDoubleT(kLaterTimeNow));
EXPECT_CALL(*this, OnEnrollmentFinishedProxy(false));
completion_callback.Run(false);
EXPECT_EQ(old_enrollment_time, enrollment_manager_.GetLastEnrollmentTime());
EXPECT_TRUE(pref_service_.GetBoolean(
prefs::kCryptAuthEnrollmentIsRecoveringFromFailure));
// The second recovery enrollment succeeds.
ON_CALL(*sync_scheduler(), GetStrategy())
.WillByDefault(Return(SyncScheduler::Strategy::AGGRESSIVE_RECOVERY));
completion_callback =
FireSchedulerForEnrollment(cryptauth::INVOCATION_REASON_FAILURE_RECOVERY);
clock_->SetNow(base::Time::FromDoubleT(kLaterTimeNow + 30));
EXPECT_CALL(*this, OnEnrollmentFinishedProxy(true));
completion_callback.Run(true);
EXPECT_EQ(clock_->Now(), enrollment_manager_.GetLastEnrollmentTime());
EXPECT_FALSE(pref_service_.GetBoolean(
prefs::kCryptAuthEnrollmentIsRecoveringFromFailure));
}
TEST_F(CryptAuthEnrollmentManagerTest,
EnrollmentSucceedsForFirstTime) {
// Initialize |enrollment_manager_|.
ON_CALL(*sync_scheduler(), GetStrategy())
.WillByDefault(Return(SyncScheduler::Strategy::PERIODIC_REFRESH));
gcm_manager_.set_registration_id(std::string());
pref_service_.ClearPref(prefs::kCryptAuthEnrollmentUserPublicKey);
pref_service_.ClearPref(prefs::kCryptAuthEnrollmentUserPrivateKey);
pref_service_.ClearPref(prefs::kCryptAuthEnrollmentLastEnrollmentTimeSeconds);
enrollment_manager_.Start();
EXPECT_FALSE(enrollment_manager_.IsEnrollmentValid());
// Trigger a sync request.
EXPECT_CALL(*this, OnEnrollmentStartedProxy());
auto sync_request = base::MakeUnique<SyncScheduler::SyncRequest>(
enrollment_manager_.GetSyncScheduler());
static_cast<SyncScheduler::Delegate*>(&enrollment_manager_)
->OnSyncRequested(std::move(sync_request));
// Complete GCM registration successfully, and expect an enrollment.
CryptAuthEnroller::EnrollmentFinishedCallback enrollment_callback;
EXPECT_CALL(*next_cryptauth_enroller(),
Enroll(public_key_, private_key_, _,
cryptauth::INVOCATION_REASON_INITIALIZATION, _))
.WillOnce(SaveArg<4>(&enrollment_callback));
ASSERT_TRUE(gcm_manager_.registration_in_progress());
gcm_manager_.CompleteRegistration(kGCMRegistrationId);
// Complete CryptAuth enrollment.
ASSERT_FALSE(enrollment_callback.is_null());
clock_->SetNow(base::Time::FromDoubleT(kLaterTimeNow));
EXPECT_CALL(*this, OnEnrollmentFinishedProxy(true));
enrollment_callback.Run(true);
EXPECT_EQ(clock_->Now(), enrollment_manager_.GetLastEnrollmentTime());
EXPECT_TRUE(enrollment_manager_.IsEnrollmentValid());
// Check that CryptAuthEnrollmentManager returns the expected key-pair.
EXPECT_EQ(public_key_, enrollment_manager_.GetUserPublicKey());
EXPECT_EQ(private_key_, enrollment_manager_.GetUserPrivateKey());
}
TEST_F(CryptAuthEnrollmentManagerTest, GCMRegistrationFails) {
// Initialize |enrollment_manager_|.
ON_CALL(*sync_scheduler(), GetStrategy())
.WillByDefault(Return(SyncScheduler::Strategy::PERIODIC_REFRESH));
gcm_manager_.set_registration_id(std::string());
enrollment_manager_.Start();
// Trigger a sync request.
EXPECT_CALL(*this, OnEnrollmentStartedProxy());
auto sync_request = base::MakeUnique<SyncScheduler::SyncRequest>(
enrollment_manager_.GetSyncScheduler());
static_cast<SyncScheduler::Delegate*>(&enrollment_manager_)
->OnSyncRequested(std::move(sync_request));
// Complete GCM registration with failure.
EXPECT_CALL(*this, OnEnrollmentFinishedProxy(false));
gcm_manager_.CompleteRegistration(std::string());
}
TEST_F(CryptAuthEnrollmentManagerTest, ReenrollOnGCMPushMessage) {
enrollment_manager_.Start();
// Simulate receiving a GCM push message, forcing the device to re-enroll.
gcm_manager_.PushReenrollMessage();
auto completion_callback =
FireSchedulerForEnrollment(cryptauth::INVOCATION_REASON_SERVER_INITIATED);
EXPECT_CALL(*this, OnEnrollmentFinishedProxy(true));
completion_callback.Run(true);
}
} // namespace cryptauth
| {
"pile_set_name": "Github"
} |
class A {
static int foo(String s) {
s = s.toLowerCase();
if (s.indexOf("hello") != -1) {
return 1;
}
return 0;
}
}
| {
"pile_set_name": "Github"
} |
/*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://[email protected]
class: org.apache.http.auth.NTCredentials
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_APACHE_HTTP_AUTH_NTCREDENTIALS_HPP_DECL
#define J2CPP_ORG_APACHE_HTTP_AUTH_NTCREDENTIALS_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace security { class Principal; } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace auth { class Credentials; } } } } }
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/security/Principal.hpp>
#include <org/apache/http/auth/Credentials.hpp>
namespace j2cpp {
namespace org { namespace apache { namespace http { namespace auth {
class NTCredentials;
class NTCredentials
: public object<NTCredentials>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
J2CPP_DECLARE_METHOD(7)
J2CPP_DECLARE_METHOD(8)
J2CPP_DECLARE_METHOD(9)
explicit NTCredentials(jobject jobj)
: object<NTCredentials>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
operator local_ref<org::apache::http::auth::Credentials>() const;
NTCredentials(local_ref< java::lang::String > const&);
NTCredentials(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&, local_ref< java::lang::String > const&, local_ref< java::lang::String > const&);
local_ref< java::security::Principal > getUserPrincipal();
local_ref< java::lang::String > getUserName();
local_ref< java::lang::String > getPassword();
local_ref< java::lang::String > getDomain();
local_ref< java::lang::String > getWorkstation();
jint hashCode();
jboolean equals(local_ref< java::lang::Object > const&);
local_ref< java::lang::String > toString();
}; //class NTCredentials
} //namespace auth
} //namespace http
} //namespace apache
} //namespace org
} //namespace j2cpp
#endif //J2CPP_ORG_APACHE_HTTP_AUTH_NTCREDENTIALS_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_APACHE_HTTP_AUTH_NTCREDENTIALS_HPP_IMPL
#define J2CPP_ORG_APACHE_HTTP_AUTH_NTCREDENTIALS_HPP_IMPL
namespace j2cpp {
org::apache::http::auth::NTCredentials::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
org::apache::http::auth::NTCredentials::operator local_ref<org::apache::http::auth::Credentials>() const
{
return local_ref<org::apache::http::auth::Credentials>(get_jobject());
}
org::apache::http::auth::NTCredentials::NTCredentials(local_ref< java::lang::String > const &a0)
: object<org::apache::http::auth::NTCredentials>(
call_new_object<
org::apache::http::auth::NTCredentials::J2CPP_CLASS_NAME,
org::apache::http::auth::NTCredentials::J2CPP_METHOD_NAME(0),
org::apache::http::auth::NTCredentials::J2CPP_METHOD_SIGNATURE(0)
>(a0)
)
{
}
org::apache::http::auth::NTCredentials::NTCredentials(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1, local_ref< java::lang::String > const &a2, local_ref< java::lang::String > const &a3)
: object<org::apache::http::auth::NTCredentials>(
call_new_object<
org::apache::http::auth::NTCredentials::J2CPP_CLASS_NAME,
org::apache::http::auth::NTCredentials::J2CPP_METHOD_NAME(1),
org::apache::http::auth::NTCredentials::J2CPP_METHOD_SIGNATURE(1)
>(a0, a1, a2, a3)
)
{
}
local_ref< java::security::Principal > org::apache::http::auth::NTCredentials::getUserPrincipal()
{
return call_method<
org::apache::http::auth::NTCredentials::J2CPP_CLASS_NAME,
org::apache::http::auth::NTCredentials::J2CPP_METHOD_NAME(2),
org::apache::http::auth::NTCredentials::J2CPP_METHOD_SIGNATURE(2),
local_ref< java::security::Principal >
>(get_jobject());
}
local_ref< java::lang::String > org::apache::http::auth::NTCredentials::getUserName()
{
return call_method<
org::apache::http::auth::NTCredentials::J2CPP_CLASS_NAME,
org::apache::http::auth::NTCredentials::J2CPP_METHOD_NAME(3),
org::apache::http::auth::NTCredentials::J2CPP_METHOD_SIGNATURE(3),
local_ref< java::lang::String >
>(get_jobject());
}
local_ref< java::lang::String > org::apache::http::auth::NTCredentials::getPassword()
{
return call_method<
org::apache::http::auth::NTCredentials::J2CPP_CLASS_NAME,
org::apache::http::auth::NTCredentials::J2CPP_METHOD_NAME(4),
org::apache::http::auth::NTCredentials::J2CPP_METHOD_SIGNATURE(4),
local_ref< java::lang::String >
>(get_jobject());
}
local_ref< java::lang::String > org::apache::http::auth::NTCredentials::getDomain()
{
return call_method<
org::apache::http::auth::NTCredentials::J2CPP_CLASS_NAME,
org::apache::http::auth::NTCredentials::J2CPP_METHOD_NAME(5),
org::apache::http::auth::NTCredentials::J2CPP_METHOD_SIGNATURE(5),
local_ref< java::lang::String >
>(get_jobject());
}
local_ref< java::lang::String > org::apache::http::auth::NTCredentials::getWorkstation()
{
return call_method<
org::apache::http::auth::NTCredentials::J2CPP_CLASS_NAME,
org::apache::http::auth::NTCredentials::J2CPP_METHOD_NAME(6),
org::apache::http::auth::NTCredentials::J2CPP_METHOD_SIGNATURE(6),
local_ref< java::lang::String >
>(get_jobject());
}
jint org::apache::http::auth::NTCredentials::hashCode()
{
return call_method<
org::apache::http::auth::NTCredentials::J2CPP_CLASS_NAME,
org::apache::http::auth::NTCredentials::J2CPP_METHOD_NAME(7),
org::apache::http::auth::NTCredentials::J2CPP_METHOD_SIGNATURE(7),
jint
>(get_jobject());
}
jboolean org::apache::http::auth::NTCredentials::equals(local_ref< java::lang::Object > const &a0)
{
return call_method<
org::apache::http::auth::NTCredentials::J2CPP_CLASS_NAME,
org::apache::http::auth::NTCredentials::J2CPP_METHOD_NAME(8),
org::apache::http::auth::NTCredentials::J2CPP_METHOD_SIGNATURE(8),
jboolean
>(get_jobject(), a0);
}
local_ref< java::lang::String > org::apache::http::auth::NTCredentials::toString()
{
return call_method<
org::apache::http::auth::NTCredentials::J2CPP_CLASS_NAME,
org::apache::http::auth::NTCredentials::J2CPP_METHOD_NAME(9),
org::apache::http::auth::NTCredentials::J2CPP_METHOD_SIGNATURE(9),
local_ref< java::lang::String >
>(get_jobject());
}
J2CPP_DEFINE_CLASS(org::apache::http::auth::NTCredentials,"org/apache/http/auth/NTCredentials")
J2CPP_DEFINE_METHOD(org::apache::http::auth::NTCredentials,0,"<init>","(Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(org::apache::http::auth::NTCredentials,1,"<init>","(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(org::apache::http::auth::NTCredentials,2,"getUserPrincipal","()Ljava/security/Principal;")
J2CPP_DEFINE_METHOD(org::apache::http::auth::NTCredentials,3,"getUserName","()Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::apache::http::auth::NTCredentials,4,"getPassword","()Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::apache::http::auth::NTCredentials,5,"getDomain","()Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::apache::http::auth::NTCredentials,6,"getWorkstation","()Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::apache::http::auth::NTCredentials,7,"hashCode","()I")
J2CPP_DEFINE_METHOD(org::apache::http::auth::NTCredentials,8,"equals","(Ljava/lang/Object;)Z")
J2CPP_DEFINE_METHOD(org::apache::http::auth::NTCredentials,9,"toString","()Ljava/lang/String;")
} //namespace j2cpp
#endif //J2CPP_ORG_APACHE_HTTP_AUTH_NTCREDENTIALS_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| {
"pile_set_name": "Github"
} |
import { module } from 'angular';
export const HEALTH_PERCENT_SELECTOR =
'spinnaker.core.serverGroup.configure.wizard.capacity.targetHealthyPercentageSelector';
module(HEALTH_PERCENT_SELECTOR, []).component('targetHealthyPercentageSelector', {
bindings: {
command: '=',
},
templateUrl: require('./targetHealthyPercentageSelector.component.html'),
controller: () => {},
});
| {
"pile_set_name": "Github"
} |
import withMapControl from './withMapControl';
import previewComponent from './MapPreview';
import schema from './schema';
const controlComponent = withMapControl();
const Widget = (opts = {}) => ({
name: 'map',
controlComponent,
previewComponent,
schema,
...opts,
});
export const NetlifyCmsWidgetMap = { Widget, controlComponent, previewComponent };
export default NetlifyCmsWidgetMap;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <fbjni/fbjni.h>
#include "JNativeModulePerfLogger.h"
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) {
return facebook::jni::initialize(vm, [] {});
}
| {
"pile_set_name": "Github"
} |
/*
* MIT License
*
* Copyright (c) 2017-2019 nuls.io
*
* 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.
*
*/
package io.nuls.contract.rpc.form;
import io.nuls.contract.util.ContractUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "调用不上链的智能合约函数表单数据")
public class ContractViewCall {
@ApiModelProperty(name = "contractAddress", value = "智能合约地址", required = true)
private String contractAddress;
@ApiModelProperty(name = "methodName", value = "方法名", required = true)
private String methodName;
@ApiModelProperty(name = "methodDesc", value = "方法签名,如果方法名不重复,可以不传", required = false)
private String methodDesc;
@ApiModelProperty(name = "args", value = "参数列表", required = false)
private Object[] args;
public String getContractAddress() {
return contractAddress;
}
public void setContractAddress(String contractAddress) {
this.contractAddress = contractAddress;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getMethodDesc() {
return methodDesc;
}
public void setMethodDesc(String methodDesc) {
this.methodDesc = methodDesc;
}
public Object[] getArgs() {
return args;
}
public String[][] getArgs(String[] types) {
return ContractUtil.twoDimensionalArray(args, types);
}
public void setArgs(Object[] args) {
this.args = args;
}
}
| {
"pile_set_name": "Github"
} |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Microsoft.AspNetCore.Builder;
using Squidex.Areas.Api.Config;
using Squidex.Areas.Api.Config.OpenApi;
using Squidex.Web;
namespace Squidex.Areas.Api
{
public static class Startup
{
public static void ConfigureApi(this IApplicationBuilder app)
{
app.Map(Constants.ApiPrefix, appApi =>
{
appApi.UseMiddleware<IdentityServerPathMiddleware>();
appApi.UseRouting();
appApi.UseAuthentication();
appApi.UseAuthorization();
appApi.UseSquidexOpenApi();
appApi.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
});
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<site>
<description url="https://spotbugs.github.io/eclipse-latest">
Eclipse update site for SpotBugs.
</description>
<feature url="features/@FEATURE_ID@_@[email protected]"
id="@FEATURE_ID@"
version="@FEATURE_VERSION@">
<category name="SpotBugs"/>
</feature>
<category-def name="SpotBugs" label="SpotBugs">
<description>
SpotBugs is a program which uses static analysis to look for bugs in Java code.
</description>
</category-def>
</site>
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2006-2010 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This code is based on jsch (http://www.jcraft.com/jsch).
All credit should go to the authors of jsch.
*/
using Sharpen;
namespace NSch
{
public interface DH
{
/// <exception cref="System.Exception"></exception>
void Init();
void SetP(byte[] p);
void SetG(byte[] g);
/// <exception cref="System.Exception"></exception>
byte[] GetE();
void SetF(byte[] f);
/// <exception cref="System.Exception"></exception>
byte[] GetK();
}
}
| {
"pile_set_name": "Github"
} |
--TEST--
Bug #48754 (mysql_close() crash php when no handle specified)
--SKIPIF--
<?php
require_once('skipif.inc');
require_once('skipifconnectfailure.inc');
?>
--FILE--
<?php
require_once('connect.inc');
function my_mysql_pconnect($host, $user, $passwd, $db, $port, $socket) {
if ($socket)
$host = sprintf("%s:%s", $host, $socket);
else if ($port)
$host = sprintf("%s:%s", $host, $port);
if (!$link = mysql_pconnect($host, $user, $passwd, true)) {
printf("[000-a] Cannot connect using host '%s', user '%s', password '****', [%d] %s\n",
$host, $user, $passwd,
mysql_errno(), mysql_error());
return false;
}
return $link;
}
echo "Explicit connection on close\n";
$link = my_mysql_connect($host, $user, $passwd, $db, $port, $socket);
$link1_thread_id = mysql_thread_id($link);
$default1_thread_id = mysql_thread_id();
echo 'Expect same thread id for $link and default conn: ';
var_dump($link1_thread_id == $default1_thread_id);
var_dump($link);
mysql_close($link);
var_dump($link);
// we sohuld have no default link anymore
mysql_close();
echo "\nClosing default link\n";
$link = my_mysql_connect($host, $user, $passwd, $db, $port, $socket);
$link2_thread_id = mysql_thread_id($link);
$default2_thread_id = mysql_thread_id();
echo 'Expect same thread id for $link and default conn but not the previous: ';
var_dump($link1_thread_id == $default1_thread_id && $link1_thread_id != $link2_thread_id);
var_dump($link);
mysql_close();
var_dump($link);
mysql_close($link);
var_dump($link);
echo "\nExplicit resource and pconnect\n";
$link = my_mysql_pconnect($host, $user, $passwd, $db, $port, $socket);
var_dump($link);
mysql_close($link);
var_dump($link);
// we sohuld have no default link
mysql_close();
echo "\nDefault link and pconnect\n";
$link = my_mysql_pconnect($host, $user, $passwd, $db, $port, $socket);
var_dump($link);
mysql_close();
var_dump($link);
mysql_close($link);
var_dump($link);
?>
--EXPECTF--
Explicit connection on close
Expect same thread id for $link and default conn: bool(true)
resource(%d) of type (mysql link)
resource(%d) of type (Unknown)
Warning: mysql_close(): no MySQL-Link resource supplied in %s on line %d
Closing default link
Expect same thread id for $link and default conn but not the previous: bool(true)
resource(%d) of type (mysql link)
resource(%d) of type (mysql link)
resource(%d) of type (Unknown)
Explicit resource and pconnect
resource(%d) of type (mysql link persistent)
resource(%d) of type (Unknown)
Warning: mysql_close(): no MySQL-Link resource supplied in %s on line %d
Default link and pconnect
resource(%d) of type (mysql link persistent)
resource(%d) of type (mysql link persistent)
resource(%d) of type (Unknown)
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2010-2013 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.model.impl.sync;
import com.evolveum.midpoint.audit.api.AuditService;
import com.evolveum.midpoint.model.impl.ModelObjectResolver;
import com.evolveum.midpoint.model.impl.lens.ChangeExecutor;
import com.evolveum.midpoint.model.impl.lens.Clockwork;
import com.evolveum.midpoint.model.impl.lens.ContextFactory;
import com.evolveum.midpoint.model.impl.sync.action.BaseAction;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.provisioning.api.ProvisioningService;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import org.apache.commons.lang.Validate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author lazyman
*/
public class ActionManagerImpl<T extends Action> implements ActionManager<T> {
private static final Trace LOGGER = TraceManager.getTrace(ActionManagerImpl.class);
private Map<String, Class<T>> actionMap;
private Clockwork clockwork;
private ChangeExecutor changeExecutor;
private PrismContext prismContext;
private ProvisioningService provisioningService;
private ContextFactory contextFactory;
private AuditService auditService;
private ModelObjectResolver modelObjectResolver;
@Override
public void setActionMapping(Map<String, Class<T>> actionMap) {
Validate.notNull(actionMap, "Action mapping must not be null.");
this.actionMap = actionMap;
}
@Override
public Action getActionInstance(String uri) {
Validate.notEmpty(uri, "Action URI must not be null or empty.");
Class<T> clazz = actionMap.get(uri);
if (clazz == null) {
return null;
}
Action action = null;
try {
action = clazz.newInstance();
if (action instanceof BaseAction) {
BaseAction baseAction = (BaseAction) action;
baseAction.setClockwork(clockwork);
baseAction.setExecutor(changeExecutor);
baseAction.setPrismContext(prismContext);
baseAction.setAuditService(auditService);
baseAction.setProvisioningService(provisioningService);
baseAction.setContextFactory(contextFactory);
baseAction.setModelObjectResolver(modelObjectResolver);
}
} catch (Exception ex) {
LoggingUtils.logException(LOGGER, "Couldn't create action instance", ex);
}
return action;
}
@Override
public List<String> getAvailableActions() {
List<String> actions = new ArrayList<>();
if (actionMap != null) {
actions.addAll(actionMap.keySet());
}
return actions;
}
public void setClockwork(Clockwork clockwork) {
this.clockwork = clockwork;
}
public void setChangeExecutor(ChangeExecutor executor) {
this.changeExecutor = executor;
}
public void setModelObjectResolver(ModelObjectResolver modelObjectResolver) {
this.modelObjectResolver = modelObjectResolver;
}
public void setPrismContext(PrismContext prismContext) {
this.prismContext = prismContext;
}
public void setAuditService(AuditService auditService) {
this.auditService = auditService;
}
public void setProvisioningService(ProvisioningService provisioningService) {
this.provisioningService = provisioningService;
}
public ContextFactory getContextFactory() {
return contextFactory;
}
public void setContextFactory(ContextFactory contextFactory) {
this.contextFactory = contextFactory;
}
}
| {
"pile_set_name": "Github"
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ChanSort.Ui.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ChanSort.Ui.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Donate {
get {
object obj = ResourceManager.GetObject("Donate", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Erase all channel data.
/// </summary>
internal static string MainForm_btnResetChannelData_Click_Caption {
get {
return ResourceManager.GetString("MainForm_btnResetChannelData_Click_Caption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to WARNING: All analog, DVB-C/T and DVB-S channel and transponder data will be deleted.
///You will have to run a full channel scan after loading this file into your TV.
///Proceed?.
/// </summary>
internal static string MainForm_btnResetChannelData_Click_Message {
get {
return ResourceManager.GetString("MainForm_btnResetChannelData_Click_Message", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cancel.
/// </summary>
internal static string MainForm_Cancel {
get {
return ResourceManager.GetString("MainForm_Cancel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The channel list has been copied to the clipboard
///and can be pasted into Excel or any text editor..
/// </summary>
internal static string MainForm_ExportExcelList_Message {
get {
return ResourceManager.GetString("MainForm_ExportExcelList_Message", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Supported Files|{0}|All Files (*.*)|*.
/// </summary>
internal static string MainForm_FileDialog_OpenFileFilter {
get {
return ResourceManager.GetString("MainForm_FileDialog_OpenFileFilter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}-Files|*{0}|All Files (*.*)|*.
/// </summary>
internal static string MainForm_FileDialog_SaveFileFilter {
get {
return ResourceManager.GetString("MainForm_FileDialog_SaveFileFilter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Your TV might not be able to work correctly when there are gaps in the channel numbers.
///Do you want the channel numbers to be rearranged consecutively?.
/// </summary>
internal static string MainForm_HandleChannelNumberGaps {
get {
return ResourceManager.GetString("MainForm_HandleChannelNumberGaps", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modify current list: Start with current list and modify it as needed.
/// </summary>
internal static string MainForm_InitInitialChannelOrder_CurrentList {
get {
return ResourceManager.GetString("MainForm_InitInitialChannelOrder_CurrentList", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Create new list: Start with an empty list and add channels in desired order.
/// </summary>
internal static string MainForm_InitInitialChannelOrder_EmptyList {
get {
return ResourceManager.GetString("MainForm_InitInitialChannelOrder_EmptyList", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to How would you like to edit your channel list?.
/// </summary>
internal static string MainForm_InitInitialChannelOrder_Question {
get {
return ResourceManager.GetString("MainForm_InitInitialChannelOrder_Question", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copy channel list: Order the channels the same way as in a reference list.
/// </summary>
internal static string MainForm_InitInitialChannelOrder_ReferenceList {
get {
return ResourceManager.GetString("MainForm_InitInitialChannelOrder_ReferenceList", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The content of the file is invalid. It has either size 0 or all its bytes have the same value.
///Typical causes are USB sticks with an NTFS file system (try using FAT32 instead)
///or firmware upgrades without running a new channel scan.
///(The new software in the TV might be unable to process the old channel data during the export.).
/// </summary>
internal static string MainForm_LoadFiles_AllZero {
get {
return ResourceManager.GetString("MainForm_LoadFiles_AllZero", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The input file contains multiple records that use the same
///program number. It is possible that the TV will not accept
///the changes made by ChanSort.
///This is typically caused by running a manual transponder scan.
///It is recommended to use a clean input file for any modifications.
///To do that, turn Hotel Mode OFF, reset the TV to
///factory defaults, run a new blind channel scan and turn
///Hotel Mode back ON, then export a new clean TLL file..
/// </summary>
internal static string MainForm_LoadFiles_DupeWarningMsg {
get {
return ResourceManager.GetString("MainForm_LoadFiles_DupeWarningMsg", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error loading file.
/// </summary>
internal static string MainForm_LoadFiles_IOException {
get {
return ResourceManager.GetString("MainForm_LoadFiles_IOException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data validation.
/// </summary>
internal static string MainForm_LoadFiles_ValidationWarningCap {
get {
return ResourceManager.GetString("MainForm_LoadFiles_ValidationWarningCap", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file content shows some anomalies and is possibly corrupt..
/// </summary>
internal static string MainForm_LoadFiles_ValidationWarningMsg {
get {
return ResourceManager.GetString("MainForm_LoadFiles_ValidationWarningMsg", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occured while loading the TV's data file:
///{0}.
/// </summary>
internal static string MainForm_LoadTll_Exception {
get {
return ResourceManager.GetString("MainForm_LoadTll_Exception", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file is not a valid .zip archive.
///TVs often export corrupted files to USB sticks formatted with the NTFS file system.
///Please try exporting to a stick formatted with FAT32.
/// </summary>
internal static string MainForm_LoadTll_InvalidZip {
get {
return ResourceManager.GetString("MainForm_LoadTll_InvalidZip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No plugin found to read/write {0} files..
/// </summary>
internal static string MainForm_LoadTll_SerializerNotFound {
get {
return ResourceManager.GetString("MainForm_LoadTll_SerializerNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Quell-TLL konnte nicht gefunden werden:
///'{0}'.
/// </summary>
internal static string MainForm_LoadTll_SourceTllNotFound {
get {
return ResourceManager.GetString("MainForm_LoadTll_SourceTllNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File not found.
/// </summary>
internal static string MainForm_LoadTvDataFile_FileNotFound_Caption {
get {
return ResourceManager.GetString("MainForm_LoadTvDataFile_FileNotFound_Caption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist..
/// </summary>
internal static string MainForm_LoadTvDataFile_FileNotFound_Message {
get {
return ResourceManager.GetString("MainForm_LoadTvDataFile_FileNotFound_Message", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You are about to restore the backup file. All changes will be lost!
///Do you want to continue?.
/// </summary>
internal static string MainForm_miRestoreOriginal_ItemClick_Confirm {
get {
return ResourceManager.GetString("MainForm_miRestoreOriginal_ItemClick_Confirm", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No backup file found: {0}.
/// </summary>
internal static string MainForm_miRestoreOriginal_ItemClick_NoBackup {
get {
return ResourceManager.GetString("MainForm_miRestoreOriginal_ItemClick_NoBackup", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to copy .bak file to {0}.
/// </summary>
internal static string MainForm_miRestoreOriginal_Message {
get {
return ResourceManager.GetString("MainForm_miRestoreOriginal_Message", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Append unsorted channels the end of the list.
/// </summary>
internal static string MainForm_PromptHandlingOfUnsortedChannels_Append {
get {
return ResourceManager.GetString("MainForm_PromptHandlingOfUnsortedChannels_Append", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Delete unsorted channels from the list.
/// </summary>
internal static string MainForm_PromptHandlingOfUnsortedChannels_Delete {
get {
return ResourceManager.GetString("MainForm_PromptHandlingOfUnsortedChannels_Delete", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to What should happen to unsorted channels?.
/// </summary>
internal static string MainForm_PromptHandlingOfUnsortedChannels_Question {
get {
return ResourceManager.GetString("MainForm_PromptHandlingOfUnsortedChannels_Question", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Discard changes.
/// </summary>
internal static string MainForm_PromptSaveAndContinue_Discard {
get {
return ResourceManager.GetString("MainForm_PromptSaveAndContinue_Discard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want so save your changes?.
/// </summary>
internal static string MainForm_PromptSaveAndContinue_Question {
get {
return ResourceManager.GetString("MainForm_PromptSaveAndContinue_Question", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Save changes.
/// </summary>
internal static string MainForm_PromptSaveAndContinue_Save {
get {
return ResourceManager.GetString("MainForm_PromptSaveAndContinue_Save", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Restore order from channel scan.
/// </summary>
internal static string MainForm_RestoreScanOrder_Caption {
get {
return ResourceManager.GetString("MainForm_RestoreScanOrder_Caption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All custom storing will be lost.
///Are you sure you want to restore the order from the channel scan?.
/// </summary>
internal static string MainForm_RestoreScanOrder_Message {
get {
return ResourceManager.GetString("MainForm_RestoreScanOrder_Message", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There was an error saving the file. Please make sure that
///- you have write permission on the file
///- the file is not open in another program
///
///The error message is:.
/// </summary>
internal static string MainForm_SaveFiles_ErrorMsg {
get {
return ResourceManager.GetString("MainForm_SaveFiles_ErrorMsg", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File write error.
/// </summary>
internal static string MainForm_SaveFiles_ErrorTitle {
get {
return ResourceManager.GetString("MainForm_SaveFiles_ErrorTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occured while writing the TV data file:
///{0}.
/// </summary>
internal static string MainForm_SaveTllFile_Exception {
get {
return ResourceManager.GetString("MainForm_SaveTllFile_Exception", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sorted TV data file was created successfully..
/// </summary>
internal static string MainForm_SaveTllFile_Success {
get {
return ResourceManager.GetString("MainForm_SaveTllFile_Success", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ChanSort Reference List|*.csv|SamToolBox Reference List|*.chl|All Reference Lists|*.csv;*.chl.
/// </summary>
internal static string MainForm_ShowOpenReferenceFileDialog_Filter {
get {
return ResourceManager.GetString("MainForm_ShowOpenReferenceFileDialog_Filter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Open Reference List.
/// </summary>
internal static string MainForm_ShowOpenReferenceFileDialog_Title {
get {
return ResourceManager.GetString("MainForm_ShowOpenReferenceFileDialog_Title", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to To swap channels an equal number of rows must be selected in the left and right table..
/// </summary>
internal static string MainForm_SwapChannels_RowCountMsg {
get {
return ResourceManager.GetString("MainForm_SwapChannels_RowCountMsg", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Swap Channels.
/// </summary>
internal static string MainForm_SwapChannels_RowCountTitle {
get {
return ResourceManager.GetString("MainForm_SwapChannels_RowCountTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unexpected error occured:
///{0}.
/// </summary>
internal static string MainForm_TryExecute_Exception {
get {
return ResourceManager.GetString("MainForm_TryExecute_Exception", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <html>
///<body>
///<p style="font-family:Arial;font-size:12pt">PayPal donation page is being opened...</p>
///<p></p>
///<p style="font-family:Arial;font-size:12pt">PayPal Spendenseite wird ge&ouml;ffnet...</p>
///<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
///<input type="hidden" name="cmd" value="_s-xclick">
///<input type="hidden" name="encrypted" value="-----BEGIN PKCS7-----MIIHVwYJKoZIhvcNAQcEoIIHSDCCB0QCAQExggEwMIIBLAIBADCBlDCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBW [rest of string was truncated]";.
/// </summary>
internal static string paypal_button {
get {
return ResourceManager.GetString("paypal_button", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Antenna,Cable,Sat,IP,Analog,Digital,TV,Radio,Data.
/// </summary>
internal static string ReferenceListForm_AntennaCableSatIPAnalogDigitalTVRadio {
get {
return ResourceManager.GetString("ReferenceListForm_AntennaCableSatIPAnalogDigitalTVRadio", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Clear target list before applying reference list.
/// </summary>
internal static string ReferenceListForm_btnApply_Click_Clear {
get {
return ResourceManager.GetString("ReferenceListForm_btnApply_Click_Clear", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Keep current channel at the Pr#.
/// </summary>
internal static string ReferenceListForm_btnApply_Click_Keep {
get {
return ResourceManager.GetString("ReferenceListForm_btnApply_Click_Keep", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overwrite Pr# with the channel from the reference list.
/// </summary>
internal static string ReferenceListForm_btnApply_Click_Overwrite {
get {
return ResourceManager.GetString("ReferenceListForm_btnApply_Click_Overwrite", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to How do you want to handle it when a Pr# is already taken in the target list?.
/// </summary>
internal static string ReferenceListForm_btnApply_ConflictHandling {
get {
return ResourceManager.GetString("ReferenceListForm_btnApply_ConflictHandling", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Select a reference list to import.
/// </summary>
internal static string ReferenceListForm_ShowOpenFileDialog_Title {
get {
return ResourceManager.GetString("ReferenceListForm_ShowOpenFileDialog_Title", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to New Version.
/// </summary>
internal static string UpdateCheck_NotifyAboutNewVersion_Caption {
get {
return ResourceManager.GetString("UpdateCheck_NotifyAboutNewVersion_Caption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A newer version is available: v{0}.
///Do you want to open the download website?.
/// </summary>
internal static string UpdateCheck_NotifyAboutNewVersion_Message {
get {
return ResourceManager.GetString("UpdateCheck_NotifyAboutNewVersion_Message", resourceCulture);
}
}
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
import static com.yahoo.language.LinguisticsCase.toLowerCase;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import com.yahoo.text.Utf8;
public class CasingVariants {
public static void main(String[] args) throws FileNotFoundException, IOException {
int read = 0;
char[] buffer = new char[5000];
String raw;
String srcDir = System.getenv("SOURCE_DIRECTORY");
if (srcDir == null) {
srcDir = ".";
}
File f = new File(srcDir + "/letters");
StringBuilder s = new StringBuilder();
InputStream in = new FileInputStream(f);
Reader r = new InputStreamReader(in, Utf8.getCharset());
while (read != -1) {
read = r.read(buffer);
if (read > 0) {
s.append(buffer, 0, read);
}
}
raw = s.toString();
System.out.write(Utf8.toBytes(toLowerCase(raw)));
}
}
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 1999-2003 Jaakko Jarvi
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_GREATER_05052005_1142)
#define FUSION_GREATER_05052005_1142
#include <boost/fusion/support/config.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/fusion/iterator/deref.hpp>
#include <boost/fusion/iterator/next.hpp>
#include <boost/fusion/iterator/equal_to.hpp>
#include <boost/fusion/support/as_const.hpp>
namespace boost { namespace fusion { namespace detail
{
template <typename Seq1, typename Seq2>
struct sequence_greater
{
typedef typename result_of::end<Seq1>::type end1_type;
typedef typename result_of::end<Seq2>::type end2_type;
template <typename I1, typename I2>
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static bool
call(I1 const&, I2 const&, mpl::true_)
{
return false;
}
template <typename I1, typename I2>
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static bool
call(I1 const& a, I2 const& b, mpl::false_)
{
return extension::as_const(*a) > extension::as_const(*b) ||
(!(extension::as_const(*b) > extension::as_const(*a)) &&
call(fusion::next(a), fusion::next(b)));
}
template <typename I1, typename I2>
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static bool
call(I1 const& a, I2 const& b)
{
typename result_of::equal_to<I1, end1_type>::type eq;
return call(a, b, eq);
}
};
}}}
#endif
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: f93cbb97b0a9c2242b41249ff19e2c5f
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 0
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
/* $Id: utils.h $ */
/** @file
* ComHostUtils.cpp
*/
/*
* Copyright (C) 2013-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#ifndef _NETLIB_UTILS_H_
#define _NETLIB_UTILS_H_
#include "cpp/utils.h"
typedef ComPtr<IVirtualBox> ComVirtualBoxPtr;
typedef ComPtr<IVirtualBoxClient> ComVirtualBoxClientPtr;
typedef ComPtr<IDHCPServer> ComDhcpServerPtr;
typedef ComPtr<IHost> ComHostPtr;
typedef ComPtr<INATNetwork> ComNatPtr;
typedef com::SafeArray<BSTR> ComBstrArray;
typedef std::vector<RTNETADDRIPV4> AddressList;
typedef std::map<RTNETADDRIPV4, int> AddressToOffsetMapping;
inline bool isDhcpRequired(const ComNatPtr& nat)
{
BOOL fNeedDhcpServer = false;
if (FAILED(nat->COMGETTER(NeedDhcpServer)(&fNeedDhcpServer)))
return false;
return RT_BOOL(fNeedDhcpServer);
}
inline int findDhcpServer(const ComVirtualBoxPtr& vbox, const std::string& name, ComDhcpServerPtr& dhcp)
{
HRESULT hrc = vbox->FindDHCPServerByNetworkName(com::Bstr(name.c_str()).raw(),
dhcp.asOutParam());
AssertComRCReturn(hrc, VERR_NOT_FOUND);
return VINF_SUCCESS;
}
inline int findNatNetwork(const ComVirtualBoxPtr& vbox, const std::string& name, ComNatPtr& nat)
{
HRESULT hrc = vbox->FindNATNetworkByName(com::Bstr(name.c_str()).raw(),
nat.asOutParam());
AssertComRCReturn(hrc, VERR_NOT_FOUND);
return VINF_SUCCESS;
}
inline RTNETADDRIPV4 networkid(const RTNETADDRIPV4& addr, const RTNETADDRIPV4& netmask)
{
RTNETADDRIPV4 netid;
netid.u = addr.u & netmask.u;
return netid;
}
int localMappings(const ComNatPtr&, AddressToOffsetMapping&);
int hostDnsSearchList(const ComHostPtr&, std::vector<std::string>&);
int hostDnsDomain(const ComHostPtr&, std::string& domainStr);
class NATNetworkEventAdapter
{
public:
virtual HRESULT HandleEvent(VBoxEventType_T aEventType, IEvent *pEvent) = 0;
};
class NATNetworkListener
{
public:
NATNetworkListener():m_pNAT(NULL){}
HRESULT init(NATNetworkEventAdapter *pNAT)
{
AssertPtrReturn(pNAT, E_INVALIDARG);
m_pNAT = pNAT;
return S_OK;
}
HRESULT init()
{
m_pNAT = NULL;
return S_OK;
}
void uninit() { m_pNAT = NULL; }
HRESULT HandleEvent(VBoxEventType_T aEventType, IEvent *pEvent)
{
if (m_pNAT)
return m_pNAT->HandleEvent(aEventType, pEvent);
else
return E_FAIL;
}
private:
NATNetworkEventAdapter *m_pNAT;
};
typedef ListenerImpl<NATNetworkListener, NATNetworkEventAdapter*> NATNetworkListenerImpl;
# ifdef VBOX_WITH_XPCOM
class NS_CLASSINFO_NAME(NATNetworkListenerImpl);
# endif
typedef ComPtr<NATNetworkListenerImpl> ComNatListenerPtr;
typedef com::SafeArray<VBoxEventType_T> ComEventTypeArray;
/* XXX: const is commented out because of compilation erro on Windows host, but it's intended that this function
isn't modify event type array */
int createNatListener(ComNatListenerPtr& listener, const ComVirtualBoxPtr& vboxptr,
NATNetworkEventAdapter *adapter, /* const */ ComEventTypeArray& events);
int destroyNatListener(ComNatListenerPtr& listener, const ComVirtualBoxPtr& vboxptr);
int createClientListener(ComNatListenerPtr& listener, const ComVirtualBoxClientPtr& vboxclientptr,
NATNetworkEventAdapter *adapter, /* const */ ComEventTypeArray& events);
int destroyClientListener(ComNatListenerPtr& listener, const ComVirtualBoxClientPtr& vboxclientptr);
#endif
| {
"pile_set_name": "Github"
} |
from __future__ import absolute_import
from . import ssl_match_hostname
| {
"pile_set_name": "Github"
} |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Api\V2010\Account\Usage\Record;
use Twilio\Page;
class DailyPage extends Page
{
public function __construct($version, $response, $solution)
{
parent::__construct($version, $response);
// Path Solution
$this->solution = $solution;
}
public function buildInstance(array $payload)
{
return new DailyInstance($this->version, $payload, $this->solution['accountSid']);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString()
{
return '[Twilio.Api.V2010.DailyPage]';
}
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef InjectedBundlePage_h
#define InjectedBundlePage_h
#include <WebKit/WKBundlePage.h>
#include <WebKit/WKBundleScriptWorld.h>
#include <WebKit/WKRetainPtr.h>
#include <wtf/text/WTFString.h>
namespace WTR {
class InjectedBundlePage {
public:
InjectedBundlePage(WKBundlePageRef);
~InjectedBundlePage();
WKBundlePageRef page() const { return m_page; }
void dump();
void stopLoading();
void prepare();
void resetAfterTest();
void dumpBackForwardList(WTF::StringBuilder&);
private:
// Loader Client
static void didStartProvisionalLoadForFrame(WKBundlePageRef, WKBundleFrameRef, WKTypeRef*, const void*);
static void didReceiveServerRedirectForProvisionalLoadForFrame(WKBundlePageRef, WKBundleFrameRef, WKTypeRef*, const void*);
static void didFailProvisionalLoadWithErrorForFrame(WKBundlePageRef, WKBundleFrameRef, WKErrorRef, WKTypeRef*, const void*);
static void didCommitLoadForFrame(WKBundlePageRef, WKBundleFrameRef, WKTypeRef*, const void*);
static void didFinishLoadForFrame(WKBundlePageRef, WKBundleFrameRef, WKTypeRef*, const void*);
static void didFinishProgress(WKBundlePageRef, const void*);
static void didFinishDocumentLoadForFrame(WKBundlePageRef, WKBundleFrameRef, WKTypeRef*, const void*);
static void didFailLoadWithErrorForFrame(WKBundlePageRef, WKBundleFrameRef, WKErrorRef, WKTypeRef*, const void*);
static void didReceiveTitleForFrame(WKBundlePageRef, WKStringRef title, WKBundleFrameRef, WKTypeRef*, const void*);
static void didClearWindowForFrame(WKBundlePageRef, WKBundleFrameRef, WKBundleScriptWorldRef, const void*);
static void didCancelClientRedirectForFrame(WKBundlePageRef, WKBundleFrameRef, const void*);
static void willPerformClientRedirectForFrame(WKBundlePageRef, WKBundleFrameRef, WKURLRef url, double delay, double date, const void*);
static void didSameDocumentNavigationForFrame(WKBundlePageRef, WKBundleFrameRef, WKSameDocumentNavigationType, WKTypeRef*, const void*);
static void didHandleOnloadEventsForFrame(WKBundlePageRef, WKBundleFrameRef, const void*);
static void didDisplayInsecureContentForFrame(WKBundlePageRef, WKBundleFrameRef, WKTypeRef*, const void*);
static void didRunInsecureContentForFrame(WKBundlePageRef, WKBundleFrameRef, WKTypeRef*, const void*);
static void didDetectXSSForFrame(WKBundlePageRef, WKBundleFrameRef, WKTypeRef*, const void*);
static void didInitiateLoadForResource(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, WKURLRequestRef, bool pageLoadIsProvisional, const void*);
static WKURLRequestRef willSendRequestForFrame(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, WKURLRequestRef, WKURLResponseRef, const void*);
static void didReceiveResponseForResource(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, WKURLResponseRef, const void*);
static void didReceiveContentLengthForResource(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, uint64_t length, const void*);
static void didFinishLoadForResource(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, const void*);
static void didFailLoadForResource(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, WKErrorRef, const void*);
static bool shouldCacheResponse(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, const void*);
void didStartProvisionalLoadForFrame(WKBundleFrameRef);
void didReceiveServerRedirectForProvisionalLoadForFrame(WKBundleFrameRef);
void didFailProvisionalLoadWithErrorForFrame(WKBundleFrameRef, WKErrorRef);
void didCommitLoadForFrame(WKBundleFrameRef);
void didFinishLoadForFrame(WKBundleFrameRef);
void didFinishProgress();
void didFailLoadWithErrorForFrame(WKBundleFrameRef, WKErrorRef);
void didReceiveTitleForFrame(WKStringRef title, WKBundleFrameRef);
void didClearWindowForFrame(WKBundleFrameRef, WKBundleScriptWorldRef);
void didCancelClientRedirectForFrame(WKBundleFrameRef);
void willPerformClientRedirectForFrame(WKBundlePageRef, WKBundleFrameRef, WKURLRef, double delay, double date);
void didSameDocumentNavigationForFrame(WKBundleFrameRef, WKSameDocumentNavigationType);
void didFinishDocumentLoadForFrame(WKBundleFrameRef);
void didHandleOnloadEventsForFrame(WKBundleFrameRef);
void didDisplayInsecureContentForFrame(WKBundleFrameRef);
void didRunInsecureContentForFrame(WKBundleFrameRef);
void didDetectXSSForFrame(WKBundleFrameRef);
// Resource Load Client
void didInitiateLoadForResource(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, WKURLRequestRef, bool pageLoadIsProvisional);
WKURLRequestRef willSendRequestForFrame(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, WKURLRequestRef, WKURLResponseRef);
void didReceiveResponseForResource(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, WKURLResponseRef);
void didReceiveContentLengthForResource(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, uint64_t length);
void didFinishLoadForResource(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier);
void didFailLoadForResource(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier, WKErrorRef);
bool shouldCacheResponse(WKBundlePageRef, WKBundleFrameRef, uint64_t identifier);
// WKBundlePagePolicyClient
static WKBundlePagePolicyAction decidePolicyForNavigationAction(WKBundlePageRef, WKBundleFrameRef, WKBundleNavigationActionRef, WKURLRequestRef, WKTypeRef*, const void*);
static WKBundlePagePolicyAction decidePolicyForNewWindowAction(WKBundlePageRef, WKBundleFrameRef, WKBundleNavigationActionRef, WKURLRequestRef, WKStringRef frameName, WKTypeRef*, const void*);
static WKBundlePagePolicyAction decidePolicyForResponse(WKBundlePageRef, WKBundleFrameRef, WKURLResponseRef, WKURLRequestRef, WKTypeRef*, const void*);
static void unableToImplementPolicy(WKBundlePageRef, WKBundleFrameRef, WKErrorRef, WKTypeRef*, const void*);
WKBundlePagePolicyAction decidePolicyForNavigationAction(WKBundlePageRef, WKBundleFrameRef, WKBundleNavigationActionRef, WKURLRequestRef, WKTypeRef*);
WKBundlePagePolicyAction decidePolicyForNewWindowAction(WKBundlePageRef, WKBundleFrameRef, WKBundleNavigationActionRef, WKURLRequestRef, WKStringRef frameName, WKTypeRef*);
WKBundlePagePolicyAction decidePolicyForResponse(WKBundlePageRef, WKBundleFrameRef, WKURLResponseRef, WKURLRequestRef, WKTypeRef*);
void unableToImplementPolicy(WKBundlePageRef, WKBundleFrameRef, WKErrorRef, WKTypeRef*);
// UI Client
static void willAddMessageToConsole(WKBundlePageRef, WKStringRef message, uint32_t lineNumber, const void* clientInfo);
static void willSetStatusbarText(WKBundlePageRef, WKStringRef statusbarText, const void* clientInfo);
static void willRunJavaScriptAlert(WKBundlePageRef, WKStringRef message, WKBundleFrameRef frame, const void* clientInfo);
static void willRunJavaScriptConfirm(WKBundlePageRef, WKStringRef message, WKBundleFrameRef frame, const void* clientInfo);
static void willRunJavaScriptPrompt(WKBundlePageRef, WKStringRef message, WKStringRef defaultValue, WKBundleFrameRef frame, const void* clientInfo);
static void didReachApplicationCacheOriginQuota(WKBundlePageRef, WKSecurityOriginRef, int64_t totalBytesNeeded, const void* clientInfo);
static uint64_t didExceedDatabaseQuota(WKBundlePageRef, WKSecurityOriginRef, WKStringRef databaseName, WKStringRef databaseDisplayName, uint64_t currentQuotaBytes, uint64_t currentOriginUsageBytes, uint64_t currentDatabaseUsageBytes, uint64_t expectedUsageBytes, const void* clientInfo);
void willAddMessageToConsole(WKStringRef message, uint32_t lineNumber);
void willSetStatusbarText(WKStringRef statusbarText);
void willRunJavaScriptAlert(WKStringRef message, WKBundleFrameRef);
void willRunJavaScriptConfirm(WKStringRef message, WKBundleFrameRef);
void willRunJavaScriptPrompt(WKStringRef message, WKStringRef defaultValue, WKBundleFrameRef);
void didReachApplicationCacheOriginQuota(WKSecurityOriginRef, int64_t totalBytesNeeded);
uint64_t didExceedDatabaseQuota(WKSecurityOriginRef, WKStringRef databaseName, WKStringRef databaseDisplayName, uint64_t currentQuotaBytes, uint64_t currentOriginUsageBytes, uint64_t currentDatabaseUsageBytes, uint64_t expectedUsageBytes);
#if ENABLE(FULLSCREEN_API)
// Full Screen client
static bool supportsFullScreen(WKBundlePageRef, WKFullScreenKeyboardRequestType);
static void setHasCustomFullScreenBehavior(WKBundlePageRef, bool value);
static void enterFullScreenForElement(WKBundlePageRef, WKBundleNodeHandleRef element);
static void exitFullScreenForElement(WKBundlePageRef, WKBundleNodeHandleRef element);
static void beganEnterFullScreen(WKBundlePageRef, WKRect initialFrame, WKRect finalFrame);
static void beganExitFullScreen(WKBundlePageRef, WKRect initialFrame, WKRect finalFrame);
static void closeFullScreen(WKBundlePageRef);
#endif
// Editor client
static bool shouldBeginEditing(WKBundlePageRef, WKBundleRangeHandleRef, const void* clientInfo);
static bool shouldEndEditing(WKBundlePageRef, WKBundleRangeHandleRef, const void* clientInfo);
static bool shouldInsertNode(WKBundlePageRef, WKBundleNodeHandleRef, WKBundleRangeHandleRef rangeToReplace, WKInsertActionType, const void* clientInfo);
static bool shouldInsertText(WKBundlePageRef, WKStringRef, WKBundleRangeHandleRef rangeToReplace, WKInsertActionType, const void* clientInfo);
static bool shouldDeleteRange(WKBundlePageRef, WKBundleRangeHandleRef, const void* clientInfo);
static bool shouldChangeSelectedRange(WKBundlePageRef, WKBundleRangeHandleRef fromRange, WKBundleRangeHandleRef toRange, WKAffinityType, bool stillSelecting, const void* clientInfo);
static bool shouldApplyStyle(WKBundlePageRef, WKBundleCSSStyleDeclarationRef style, WKBundleRangeHandleRef range, const void* clientInfo);
static void didBeginEditing(WKBundlePageRef, WKStringRef notificationName, const void* clientInfo);
static void didEndEditing(WKBundlePageRef, WKStringRef notificationName, const void* clientInfo);
static void didChange(WKBundlePageRef, WKStringRef notificationName, const void* clientInfo);
static void didChangeSelection(WKBundlePageRef, WKStringRef notificationName, const void* clientInfo);
bool shouldBeginEditing(WKBundleRangeHandleRef);
bool shouldEndEditing(WKBundleRangeHandleRef);
bool shouldInsertNode(WKBundleNodeHandleRef, WKBundleRangeHandleRef rangeToReplace, WKInsertActionType);
bool shouldInsertText(WKStringRef, WKBundleRangeHandleRef rangeToReplace, WKInsertActionType);
bool shouldDeleteRange(WKBundleRangeHandleRef);
bool shouldChangeSelectedRange(WKBundleRangeHandleRef fromRange, WKBundleRangeHandleRef toRange, WKAffinityType, bool stillSelecting);
bool shouldApplyStyle(WKBundleCSSStyleDeclarationRef style, WKBundleRangeHandleRef range);
void didBeginEditing(WKStringRef notificationName);
void didEndEditing(WKStringRef notificationName);
void didChange(WKStringRef notificationName);
void didChangeSelection(WKStringRef notificationName);
void dumpAllFramesText(WTF::StringBuilder&);
void dumpAllFrameScrollPositions(WTF::StringBuilder&);
void dumpDOMAsWebArchive(WKBundleFrameRef, WTF::StringBuilder&);
void platformDidStartProvisionalLoadForFrame(WKBundleFrameRef);
String platformResponseMimeType(WKURLResponseRef);
void frameDidChangeLocation(WKBundleFrameRef, bool shouldDump = false);
WKBundlePageRef m_page;
WKRetainPtr<WKBundleScriptWorldRef> m_world;
WKRetainPtr<WKBundleBackForwardListItemRef> m_previousTestBackForwardListItem;
};
} // namespace WTR
#endif // InjectedBundlePage_h
| {
"pile_set_name": "Github"
} |
import { mount, Wrapper } from '@vue/test-utils';
import Vue from 'vue';
import Vuetify from 'vuetify';
import AccountDisplay from '@/components/display/AccountDisplay.vue';
import store from '@/store/store';
import { GeneralAccount } from '@/typing/types';
Vue.use(Vuetify);
describe('AccountDisplay.vue', () => {
let wrapper: Wrapper<AccountDisplay>;
const account: GeneralAccount = {
chain: 'ETH',
address: '0x52bc44d5378309EE2abF1539BF71dE1b7d7bE3b5',
label: 'Test Account',
tags: []
};
function createWrapper() {
const vuetify = new Vuetify();
return mount(AccountDisplay, {
store,
vuetify,
stubs: ['v-tooltip', 'crypto-icon'],
propsData: {
account
}
});
}
beforeEach(() => {
store.dispatch('session/logout');
wrapper = createWrapper();
});
test('does not blur anything by default', async () => {
expect(wrapper.find('.blur-content').exists()).toBe(false);
});
test('blurs address on privacy mode', async () => {
store.commit('session/privacyMode', true);
await wrapper.vm.$nextTick();
expect(wrapper.find('.blur-content').exists()).toBe(true);
});
});
| {
"pile_set_name": "Github"
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
exports.type = 'cat';
| {
"pile_set_name": "Github"
} |
module github.com/NYTimes/gziphandler
go 1.11
require github.com/stretchr/testify v1.3.0
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2015 Princeton University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Princeton University nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY PRINCETON UNIVERSITY "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL PRINCETON UNIVERSITY BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Wraps the sparc_mul_top tieing all unused signals when no SPU is present
module sparc_mul_top_nospu_wrap
(
input rclk,
input grst_l,
input arst_l,
input exu_mul_input_vld,
input [63:0] exu_mul_rs1_data,
input [63:0] exu_mul_rs2_data,
output mul_exu_ack,
output [63:0] mul_data_out
);
sparc_mul_top sparc_mul_top
(
.si (),
.so (),
.grst_l (grst_l),
.arst_l (arst_l),
.mul_exu_ack (mul_exu_ack),
.mul_spu_ack (),
.mul_spu_shf_ack (),
.mul_data_out (mul_data_out),
.rclk (rclk),
.se (),
.exu_mul_input_vld (exu_mul_input_vld),
.exu_mul_rs1_data (exu_mul_rs1_data),
.exu_mul_rs2_data (exu_mul_rs2_data),
.spu_mul_req_vld (1'b0),
.spu_mul_acc (1'b0),
.spu_mul_areg_shf (1'b0),
.spu_mul_areg_rst (1'b0),
.spu_mul_op1_data (64'h0000000000000000),
.spu_mul_op2_data (64'h0000000000000000),
.spu_mul_mulres_lshft ()
);
endmodule
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2020 Snowflake Computing Inc. All right reserved.
#
# Feature flags
feature_use_pyopenssl = True # use pyopenssl API or openssl command
| {
"pile_set_name": "Github"
} |
// +build amd64,darwin
// Created by cgo -godefs - DO NOT EDIT
// cgo -godefs types_darwin.go
package unix
const (
sizeofPtr = 0x8
sizeofShort = 0x2
sizeofInt = 0x4
sizeofLong = 0x8
sizeofLongLong = 0x8
)
type (
_C_short int16
_C_int int32
_C_long int64
_C_long_long int64
)
type Timespec struct {
Sec int64
Nsec int64
}
type Timeval struct {
Sec int64
Usec int32
Pad_cgo_0 [4]byte
}
type Timeval32 struct {
Sec int32
Usec int32
}
type Rusage struct {
Utime Timeval
Stime Timeval
Maxrss int64
Ixrss int64
Idrss int64
Isrss int64
Minflt int64
Majflt int64
Nswap int64
Inblock int64
Oublock int64
Msgsnd int64
Msgrcv int64
Nsignals int64
Nvcsw int64
Nivcsw int64
}
type Rlimit struct {
Cur uint64
Max uint64
}
type _Gid_t uint32
type Stat_t struct {
Dev int32
Mode uint16
Nlink uint16
Ino uint64
Uid uint32
Gid uint32
Rdev int32
Pad_cgo_0 [4]byte
Atimespec Timespec
Mtimespec Timespec
Ctimespec Timespec
Birthtimespec Timespec
Size int64
Blocks int64
Blksize int32
Flags uint32
Gen uint32
Lspare int32
Qspare [2]int64
}
type Statfs_t struct {
Bsize uint32
Iosize int32
Blocks uint64
Bfree uint64
Bavail uint64
Files uint64
Ffree uint64
Fsid Fsid
Owner uint32
Type uint32
Flags uint32
Fssubtype uint32
Fstypename [16]int8
Mntonname [1024]int8
Mntfromname [1024]int8
Reserved [8]uint32
}
type Flock_t struct {
Start int64
Len int64
Pid int32
Type int16
Whence int16
}
type Fstore_t struct {
Flags uint32
Posmode int32
Offset int64
Length int64
Bytesalloc int64
}
type Radvisory_t struct {
Offset int64
Count int32
Pad_cgo_0 [4]byte
}
type Fbootstraptransfer_t struct {
Offset int64
Length uint64
Buffer *byte
}
type Log2phys_t struct {
Flags uint32
Pad_cgo_0 [8]byte
Pad_cgo_1 [8]byte
}
type Fsid struct {
Val [2]int32
}
type Dirent struct {
Ino uint64
Seekoff uint64
Reclen uint16
Namlen uint16
Type uint8
Name [1024]int8
Pad_cgo_0 [3]byte
}
type RawSockaddrInet4 struct {
Len uint8
Family uint8
Port uint16
Addr [4]byte /* in_addr */
Zero [8]int8
}
type RawSockaddrInet6 struct {
Len uint8
Family uint8
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
type RawSockaddrUnix struct {
Len uint8
Family uint8
Path [104]int8
}
type RawSockaddrDatalink struct {
Len uint8
Family uint8
Index uint16
Type uint8
Nlen uint8
Alen uint8
Slen uint8
Data [12]int8
}
type RawSockaddr struct {
Len uint8
Family uint8
Data [14]int8
}
type RawSockaddrAny struct {
Addr RawSockaddr
Pad [92]int8
}
type _Socklen uint32
type Linger struct {
Onoff int32
Linger int32
}
type Iovec struct {
Base *byte
Len uint64
}
type IPMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type IPv6Mreq struct {
Multiaddr [16]byte /* in6_addr */
Interface uint32
}
type Msghdr struct {
Name *byte
Namelen uint32
Pad_cgo_0 [4]byte
Iov *Iovec
Iovlen int32
Pad_cgo_1 [4]byte
Control *byte
Controllen uint32
Flags int32
}
type Cmsghdr struct {
Len uint32
Level int32
Type int32
}
type Inet4Pktinfo struct {
Ifindex uint32
Spec_dst [4]byte /* in_addr */
Addr [4]byte /* in_addr */
}
type Inet6Pktinfo struct {
Addr [16]byte /* in6_addr */
Ifindex uint32
}
type IPv6MTUInfo struct {
Addr RawSockaddrInet6
Mtu uint32
}
type ICMPv6Filter struct {
Filt [8]uint32
}
const (
SizeofSockaddrInet4 = 0x10
SizeofSockaddrInet6 = 0x1c
SizeofSockaddrAny = 0x6c
SizeofSockaddrUnix = 0x6a
SizeofSockaddrDatalink = 0x14
SizeofLinger = 0x8
SizeofIPMreq = 0x8
SizeofIPv6Mreq = 0x14
SizeofMsghdr = 0x30
SizeofCmsghdr = 0xc
SizeofInet4Pktinfo = 0xc
SizeofInet6Pktinfo = 0x14
SizeofIPv6MTUInfo = 0x20
SizeofICMPv6Filter = 0x20
)
const (
PTRACE_TRACEME = 0x0
PTRACE_CONT = 0x7
PTRACE_KILL = 0x8
)
type Kevent_t struct {
Ident uint64
Filter int16
Flags uint16
Fflags uint32
Data int64
Udata *byte
}
type FdSet struct {
Bits [32]int32
}
const (
SizeofIfMsghdr = 0x70
SizeofIfData = 0x60
SizeofIfaMsghdr = 0x14
SizeofIfmaMsghdr = 0x10
SizeofIfmaMsghdr2 = 0x14
SizeofRtMsghdr = 0x5c
SizeofRtMetrics = 0x38
)
type IfMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
Pad_cgo_0 [2]byte
Data IfData
}
type IfData struct {
Type uint8
Typelen uint8
Physical uint8
Addrlen uint8
Hdrlen uint8
Recvquota uint8
Xmitquota uint8
Unused1 uint8
Mtu uint32
Metric uint32
Baudrate uint32
Ipackets uint32
Ierrors uint32
Opackets uint32
Oerrors uint32
Collisions uint32
Ibytes uint32
Obytes uint32
Imcasts uint32
Omcasts uint32
Iqdrops uint32
Noproto uint32
Recvtiming uint32
Xmittiming uint32
Lastchange Timeval32
Unused2 uint32
Hwassist uint32
Reserved1 uint32
Reserved2 uint32
}
type IfaMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
Pad_cgo_0 [2]byte
Metric int32
}
type IfmaMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
Pad_cgo_0 [2]byte
}
type IfmaMsghdr2 struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
Pad_cgo_0 [2]byte
Refcount int32
}
type RtMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Index uint16
Pad_cgo_0 [2]byte
Flags int32
Addrs int32
Pid int32
Seq int32
Errno int32
Use int32
Inits uint32
Rmx RtMetrics
}
type RtMetrics struct {
Locks uint32
Mtu uint32
Hopcount uint32
Expire int32
Recvpipe uint32
Sendpipe uint32
Ssthresh uint32
Rtt uint32
Rttvar uint32
Pksent uint32
Filler [4]uint32
}
const (
SizeofBpfVersion = 0x4
SizeofBpfStat = 0x8
SizeofBpfProgram = 0x10
SizeofBpfInsn = 0x8
SizeofBpfHdr = 0x14
)
type BpfVersion struct {
Major uint16
Minor uint16
}
type BpfStat struct {
Recv uint32
Drop uint32
}
type BpfProgram struct {
Len uint32
Pad_cgo_0 [4]byte
Insns *BpfInsn
}
type BpfInsn struct {
Code uint16
Jt uint8
Jf uint8
K uint32
}
type BpfHdr struct {
Tstamp Timeval32
Caplen uint32
Datalen uint32
Hdrlen uint16
Pad_cgo_0 [2]byte
}
type Termios struct {
Iflag uint64
Oflag uint64
Cflag uint64
Lflag uint64
Cc [20]uint8
Pad_cgo_0 [4]byte
Ispeed uint64
Ospeed uint64
}
const (
AT_FDCWD = -0x2
AT_SYMLINK_NOFOLLOW = 0x20
)
| {
"pile_set_name": "Github"
} |
package com.minecolonies.api.crafting;
import com.minecolonies.api.colony.requestsystem.token.IToken;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
/**
* Interface which describes the RecipeStorage.
*/
public interface IRecipeStorage
{
/**
* Get the list of input items. Suppressing Sonar Rule Squid:S2384 The rule thinks we should return a copy of the list and not the list itself. But in this case the rule does
* not apply because the list is an unmodifiable list already
*
* @return the list.
*/
List<ItemStack> getInput();
/**
* Get the cleaned up list of the recipes. Air gets removed and equal items get put together.
*
* @return the list.
*/
List<ItemStorage> getCleanedInput();
/**
* Getter for the primary output.
*
* @return the itemStack to be produced.
*/
ItemStack getPrimaryOutput();
/**
* Get the grid size.
*
* @return the integer representing it. (2x2 = 4, 3x3 = 9, etc)
*/
int getGridSize();
/**
* Get the required intermediate for the recipe.
*
* @return the block.
*/
Block getIntermediate();
/**
* Method to check if with the help of inventories this recipe can be fullfilled.
*
* @param qty the quantity to craft.
* @param inventories the inventories to check.
* @return true if possible, else false.
*/
boolean canFullFillRecipe(final int qty, @NotNull final IItemHandler... inventories);
default boolean fullFillRecipe(@NotNull final IItemHandler... inventories)
{
return fullfillRecipe(Arrays.asList(inventories));
}
/**
* Check for space, remove items, and insert crafted items.
*
* @param handlers the handlers to use.
* @return true if succesful.
*/
boolean fullfillRecipe(final List<IItemHandler> handlers);
/**
* Get the unique token of the recipe.
*
* @return the IToken.
*/
IToken<?> getToken();
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env bash
set -e
# This file is used to auto-generate Dockerfiles for making debs via 'make deb'
#
# usage: ./generate.sh [versions]
# ie: ./generate.sh
# to update all Dockerfiles in this directory
# or: ./generate.sh ubuntu-xenial
# to only update ubuntu-xenial/Dockerfile
# or: ./generate.sh ubuntu-newversion
# to create a new folder and a Dockerfile within it
cd "$(dirname "$(readlink -f "$BASH_SOURCE")")"
versions=( "$@" )
if [ ${#versions[@]} -eq 0 ]; then
versions=( */ )
fi
versions=( "${versions[@]%/}" )
for version in "${versions[@]}"; do
echo "${versions[@]}"
distro="${version%-*}"
suite="${version##*-}"
from="ppc64le/${distro}:${suite}"
mkdir -p "$version"
echo "$version -> FROM $from"
cat > "$version/Dockerfile" <<-EOF
#
# THIS FILE IS AUTOGENERATED; SEE "contrib/builder/deb/ppc64le/generate.sh"!
#
FROM $from
EOF
extraBuildTags='pkcs11'
runcBuildTags=
# this list is sorted alphabetically; please keep it that way
packages=(
apparmor # for apparmor_parser for testing the profile
bash-completion # for bash-completion debhelper integration
btrfs-tools # for "btrfs/ioctl.h" (and "version.h" if possible)
build-essential # "essential for building Debian packages"
cmake # tini dep
curl ca-certificates # for downloading Go
debhelper # for easy ".deb" building
dh-apparmor # for apparmor debhelper
dh-systemd # for systemd debhelper integration
git # for "git commit" info in "docker -v"
libapparmor-dev # for "sys/apparmor.h"
libdevmapper-dev # for "libdevmapper.h"
libltdl-dev # for pkcs11 "ltdl.h"
pkg-config # for detecting things like libsystemd-journal dynamically
vim-common # tini dep
)
case "$suite" in
trusty)
packages+=( libsystemd-journal-dev )
;;
*)
# libseccomp isn't available until ubuntu xenial and is required for "seccomp.h" & "libseccomp.so"
packages+=( libseccomp-dev )
packages+=( libsystemd-dev )
;;
esac
# buildtags
case "$suite" in
# trusty has no seccomp package
trusty)
runcBuildTags="apparmor selinux"
;;
# ppc64le support was backported into libseccomp 2.2.3-2,
# so enable seccomp by default
*)
extraBuildTags+=' seccomp'
runcBuildTags="apparmor seccomp selinux"
;;
esac
# update and install packages
echo "RUN apt-get update && apt-get install -y ${packages[*]} --no-install-recommends && rm -rf /var/lib/apt/lists/*" >> "$version/Dockerfile"
echo >> "$version/Dockerfile"
awk '$1 == "ENV" && $2 == "GO_VERSION" { print; exit }' ../../../../Dockerfile.ppc64le >> "$version/Dockerfile"
echo 'RUN curl -fsSL "https://golang.org/dl/go${GO_VERSION}.linux-ppc64le.tar.gz" | tar xzC /usr/local' >> "$version/Dockerfile"
echo 'ENV PATH $PATH:/usr/local/go/bin' >> "$version/Dockerfile"
echo >> "$version/Dockerfile"
echo 'ENV AUTO_GOPATH 1' >> "$version/Dockerfile"
echo >> "$version/Dockerfile"
# print build tags in alphabetical order
buildTags=$( echo "apparmor selinux $extraBuildTags" | xargs -n1 | sort -n | tr '\n' ' ' | sed -e 's/[[:space:]]*$//' )
echo "ENV DOCKER_BUILDTAGS $buildTags" >> "$version/Dockerfile"
echo "ENV RUNC_BUILDTAGS $runcBuildTags" >> "$version/Dockerfile"
done
| {
"pile_set_name": "Github"
} |
#@data/values
---
nothing: "something"
string: ""
bool: false
int: 0
float: 0.0
| {
"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>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
''' Functions for arranging bokeh layout objects.
'''
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
import logging # isort:skip
log = logging.getLogger(__name__)
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
import math
from collections import namedtuple
# Bokeh imports
from .core.enums import Location
from .models.layouts import Box, Column, GridBox, LayoutDOM, Row, Spacer, WidgetBox
from .models.plots import Plot
from .models.tools import ProxyToolbar, ToolbarBox
#-----------------------------------------------------------------------------
# Globals and constants
#-----------------------------------------------------------------------------
__all__ = (
'column',
'grid',
'gridplot',
'GridSpec',
'layout',
'row',
'Spacer',
'widgetbox',
)
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
def row(*args, **kwargs):
""" Create a row of Bokeh Layout objects. Forces all objects to
have the same sizing_mode, which is required for complex layouts to work.
Args:
children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for
the row. Can be any of the following - :class:`~bokeh.models.plots.Plot`,
:class:`~bokeh.models.widgets.widget.Widget`,
:class:`~bokeh.models.layouts.Row`,
:class:`~bokeh.models.layouts.Column`,
:class:`~bokeh.models.tools.ToolbarBox`,
:class:`~bokeh.models.layouts.Spacer`.
sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How
will the items in the layout resize to fill the available space.
Default is ``"fixed"``. For more information on the different
modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode`
description on :class:`~bokeh.models.layouts.LayoutDOM`.
Returns:
Row: A row of LayoutDOM objects all with the same sizing_mode.
Examples:
>>> row(plot1, plot2)
>>> row(children=[widgets, plot], sizing_mode='stretch_both')
"""
sizing_mode = kwargs.pop('sizing_mode', None)
children = kwargs.pop('children', None)
children = _parse_children_arg(*args, children=children)
_handle_child_sizing(children, sizing_mode, widget="row")
return Row(children=children, sizing_mode=sizing_mode, **kwargs)
def column(*args, **kwargs):
""" Create a column of Bokeh Layout objects. Forces all objects to
have the same sizing_mode, which is required for complex layouts to work.
Args:
children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for
the column. Can be any of the following - :class:`~bokeh.models.plots.Plot`,
:class:`~bokeh.models.widgets.widget.Widget`,
:class:`~bokeh.models.layouts.Row`,
:class:`~bokeh.models.layouts.Column`,
:class:`~bokeh.models.tools.ToolbarBox`,
:class:`~bokeh.models.layouts.Spacer`.
sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How
will the items in the layout resize to fill the available space.
Default is ``"fixed"``. For more information on the different
modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode`
description on :class:`~bokeh.models.layouts.LayoutDOM`.
Returns:
Column: A column of LayoutDOM objects all with the same sizing_mode.
Examples:
>>> column(plot1, plot2)
>>> column(children=[widgets, plot], sizing_mode='stretch_both')
"""
sizing_mode = kwargs.pop('sizing_mode', None)
children = kwargs.pop('children', None)
children = _parse_children_arg(*args, children=children)
_handle_child_sizing(children, sizing_mode, widget="column")
return Column(children=children, sizing_mode=sizing_mode, **kwargs)
def widgetbox(*args, **kwargs):
""" Create a column of bokeh widgets with predefined styling.
Args:
children (list of :class:`~bokeh.models.widgets.widget.Widget`): A list of widgets.
sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How
will the items in the layout resize to fill the available space.
Default is ``"fixed"``. For more information on the different
modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode`
description on :class:`~bokeh.models.layouts.LayoutDOM`.
Returns:
WidgetBox: A column layout of widget instances all with the same ``sizing_mode``.
Examples:
>>> widgetbox([button, select])
>>> widgetbox(children=[slider], sizing_mode='scale_width')
"""
sizing_mode = kwargs.pop('sizing_mode', None)
children = kwargs.pop('children', None)
children = _parse_children_arg(*args, children=children)
_handle_child_sizing(children, sizing_mode, widget="widget box")
return WidgetBox(children=children, sizing_mode=sizing_mode, **kwargs)
def layout(*args, **kwargs):
""" Create a grid-based arrangement of Bokeh Layout objects.
Args:
children (list of lists of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of lists of instances
for a grid layout. Can be any of the following - :class:`~bokeh.models.plots.Plot`,
:class:`~bokeh.models.widgets.widget.Widget`,
:class:`~bokeh.models.layouts.Row`,
:class:`~bokeh.models.layouts.Column`,
:class:`~bokeh.models.tools.ToolbarBox`,
:class:`~bokeh.models.layouts.Spacer`.
sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How
will the items in the layout resize to fill the available space.
Default is ``"fixed"``. For more information on the different
modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode`
description on :class:`~bokeh.models.layouts.LayoutDOM`.
Returns:
Column: A column of ``Row`` layouts of the children, all with the same sizing_mode.
Examples:
>>> layout([[plot_1, plot_2], [plot_3, plot_4]])
>>> layout(
children=[
[widget_1, plot_1],
[slider],
[widget_2, plot_2, plot_3]
],
sizing_mode='fixed',
)
"""
sizing_mode = kwargs.pop('sizing_mode', None)
children = kwargs.pop('children', None)
children = _parse_children_arg(*args, children=children)
# Make the grid
return _create_grid(children, sizing_mode, **kwargs)
def gridplot(children, sizing_mode=None, toolbar_location='above', ncols=None,
plot_width=None, plot_height=None, toolbar_options=None, merge_tools=True):
''' Create a grid of plots rendered on separate canvases.
The ``gridplot`` function builds a single toolbar for all the plots in the
grid. ``gridplot`` is designed to layout a set of plots. For general
grid layout, use the :func:`~bokeh.layouts.layout` function.
Args:
children (list of lists of :class:`~bokeh.models.plots.Plot` ): An
array of plots to display in a grid, given as a list of lists of Plot
objects. To leave a position in the grid empty, pass None for that
position in the children list. OR list of :class:`~bokeh.models.plots.Plot` if called with
ncols. OR an instance of GridSpec.
sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How
will the items in the layout resize to fill the available space.
Default is ``"fixed"``. For more information on the different
modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode`
description on :class:`~bokeh.models.layouts.LayoutDOM`.
toolbar_location (``above``, ``below``, ``left``, ``right`` ): Where the
toolbar will be located, with respect to the grid. Default is
``above``. If set to None, no toolbar will be attached to the grid.
ncols (int, optional): Specify the number of columns you would like in your grid.
You must only pass an un-nested list of plots (as opposed to a list of lists of plots)
when using ncols.
plot_width (int, optional): The width you would like all your plots to be
plot_height (int, optional): The height you would like all your plots to be.
toolbar_options (dict, optional) : A dictionary of options that will be
used to construct the grid's toolbar (an instance of
:class:`~bokeh.models.tools.ToolbarBox`). If none is supplied,
ToolbarBox's defaults will be used.
merge_tools (``True``, ``False``): Combine tools from all child plots into
a single toolbar.
Returns:
Row or Column: A row or column containing the grid toolbar and the grid
of plots (depending on whether the toolbar is left/right or
above/below. The grid is always a Column of Rows of plots.
Examples:
>>> gridplot([[plot_1, plot_2], [plot_3, plot_4]])
>>> gridplot([plot_1, plot_2, plot_3, plot_4], ncols=2, plot_width=200, plot_height=100)
>>> gridplot(
children=[[plot_1, plot_2], [None, plot_3]],
toolbar_location='right'
sizing_mode='fixed',
toolbar_options=dict(logo='gray')
)
'''
if toolbar_options is None:
toolbar_options = {}
if toolbar_location:
if not hasattr(Location, toolbar_location):
raise ValueError("Invalid value of toolbar_location: %s" % toolbar_location)
children = _parse_children_arg(children=children)
if ncols:
if any(isinstance(child, list) for child in children):
raise ValueError("Cannot provide a nested list when using ncols")
children = list(_chunks(children, ncols))
# Additional children set-up for grid plot
if not children:
children = []
# Make the grid
toolbars = []
items = []
for y, row in enumerate(children):
for x, item in enumerate(row):
if item is None:
continue
elif isinstance(item, LayoutDOM):
if merge_tools:
for plot in item.select(dict(type=Plot)):
toolbars.append(plot.toolbar)
plot.toolbar_location = None
if isinstance(item, Plot):
if plot_width is not None:
item.plot_width = plot_width
if plot_height is not None:
item.plot_height = plot_height
if sizing_mode is not None and _has_auto_sizing(item):
item.sizing_mode = sizing_mode
items.append((item, y, x))
else:
raise ValueError("Only LayoutDOM items can be inserted into a grid")
if not merge_tools or not toolbar_location:
return GridBox(children=items, sizing_mode=sizing_mode)
grid = GridBox(children=items)
tools = sum([ toolbar.tools for toolbar in toolbars ], [])
proxy = ProxyToolbar(toolbars=toolbars, tools=tools, **toolbar_options)
toolbar = ToolbarBox(toolbar=proxy, toolbar_location=toolbar_location)
if toolbar_location == 'above':
return Column(children=[toolbar, grid], sizing_mode=sizing_mode)
elif toolbar_location == 'below':
return Column(children=[grid, toolbar], sizing_mode=sizing_mode)
elif toolbar_location == 'left':
return Row(children=[toolbar, grid], sizing_mode=sizing_mode)
elif toolbar_location == 'right':
return Row(children=[grid, toolbar], sizing_mode=sizing_mode)
def grid(children=[], sizing_mode=None, nrows=None, ncols=None):
"""
Conveniently create a grid of layoutable objects.
Grids are created by using ``GridBox`` model. This gives the most control over
the layout of a grid, but is also tedious and may result in unreadable code in
practical applications. ``grid()`` function remedies this by reducing the level
of control, but in turn providing a more convenient API.
Supported patterns:
1. Nested lists of layoutable objects. Assumes the top-level list represents
a column and alternates between rows and columns in subsequent nesting
levels. One can use ``None`` for padding purpose.
>>> grid([p1, [[p2, p3], p4]])
GridBox(children=[
(p1, 0, 0, 1, 2),
(p2, 1, 0, 1, 1),
(p3, 2, 0, 1, 1),
(p4, 1, 1, 2, 1),
])
2. Nested ``Row`` and ``Column`` instances. Similar to the first pattern, just
instead of using nested lists, it uses nested ``Row`` and ``Column`` models.
This can be much more readable that the former. Note, however, that only
models that don't have ``sizing_mode`` set are used.
>>> grid(column(p1, row(column(p2, p3), p4)))
GridBox(children=[
(p1, 0, 0, 1, 2),
(p2, 1, 0, 1, 1),
(p3, 2, 0, 1, 1),
(p4, 1, 1, 2, 1),
])
3. Flat list of layoutable objects. This requires ``nrows`` and/or ``ncols`` to
be set. The input list will be rearranged into a 2D array accordingly. One
can use ``None`` for padding purpose.
>>> grid([p1, p2, p3, p4], ncols=2)
GridBox(children=[
(p1, 0, 0, 1, 1),
(p2, 0, 1, 1, 1),
(p3, 1, 0, 1, 1),
(p4, 1, 1, 1, 1),
])
"""
row = namedtuple("row", ["children"])
col = namedtuple("col", ["children"])
def flatten(layout):
Item = namedtuple("Item", ["layout", "r0", "c0", "r1", "c1"])
Grid = namedtuple("Grid", ["nrows", "ncols", "items"])
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
def lcm(a, *rest):
for b in rest:
a = (a*b) // gcd(a, b)
return a
nonempty = lambda child: child.nrows != 0 and child.ncols != 0
def _flatten(layout):
if isinstance(layout, row):
children = list(filter(nonempty, map(_flatten, layout.children)))
if not children:
return Grid(0, 0, [])
nrows = lcm(*[ child.nrows for child in children ])
ncols = sum(child.ncols for child in children)
items = []
offset = 0
for child in children:
factor = nrows//child.nrows
for (layout, r0, c0, r1, c1) in child.items:
items.append((layout, factor*r0, c0 + offset, factor*r1, c1 + offset))
offset += child.ncols
return Grid(nrows, ncols, items)
elif isinstance(layout, col):
children = list(filter(nonempty, map(_flatten, layout.children)))
if not children:
return Grid(0, 0, [])
nrows = sum(child.nrows for child in children)
ncols = lcm(*[ child.ncols for child in children ])
items = []
offset = 0
for child in children:
factor = ncols//child.ncols
for (layout, r0, c0, r1, c1) in child.items:
items.append((layout, r0 + offset, factor*c0, r1 + offset, factor*c1))
offset += child.nrows
return Grid(nrows, ncols, items)
else:
return Grid(1, 1, [Item(layout, 0, 0, 1, 1)])
grid = _flatten(layout)
children = []
for (layout, r0, c0, r1, c1) in grid.items:
if layout is not None:
children.append((layout, r0, c0, r1 - r0, c1 - c0))
return GridBox(children=children)
if isinstance(children, list):
if nrows is not None or ncols is not None:
N = len(children)
if ncols is None:
ncols = math.ceil(N/nrows)
layout = col([ row(children[i:i+ncols]) for i in range(0, N, ncols) ])
else:
def traverse(children, level=0):
if isinstance(children, list):
container = col if level % 2 == 0 else row
return container([ traverse(child, level+1) for child in children ])
else:
return children
layout = traverse(children)
elif isinstance(children, LayoutDOM):
def is_usable(child):
return _has_auto_sizing(child) and child.spacing == 0
def traverse(item, top_level=False):
if isinstance(item, Box) and (top_level or is_usable(item)):
container = col if isinstance(item, Column) else row
return container(list(map(traverse, item.children)))
else:
return item
layout = traverse(children, top_level=True)
elif isinstance(children, str):
raise NotImplementedError
else:
raise ValueError("expected a list, string or model")
grid = flatten(layout)
if sizing_mode is not None:
grid.sizing_mode = sizing_mode
for child in grid.children:
layout = child[0]
if _has_auto_sizing(layout):
layout.sizing_mode = sizing_mode
return grid
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
class GridSpec:
""" Simplifies grid layout specification. """
def __init__(self, nrows, ncols):
self.nrows = nrows
self.ncols = ncols
self._arrangement = {}
from .util.deprecation import deprecated
deprecated("'GridSpec' is deprecated and will be removed in Bokeh 3.0")
def __setitem__(self, key, obj):
k1, k2 = key
if isinstance(k1, slice):
row1, row2, _ = k1.indices(self.nrows)
else:
if k1 < 0:
k1 += self.nrows
if k1 >= self.nrows or k1 < 0:
raise IndexError("index out of range")
row1, row2 = k1, None
if isinstance(k2, slice):
col1, col2, _ = k2.indices(self.ncols)
else:
if k2 < 0:
k2 += self.ncols
if k2 >= self.ncols or k2 < 0:
raise IndexError("index out of range")
col1, col2 = k2, None
# gs[row, col] = obj
# gs[row1:row2, col] = [...]
# gs[row, col1:col2] = [...]
# gs[row1:row2, col1:col2] = [[...], ...]
def get_or_else(fn, default):
try:
return fn()
except IndexError:
return default
if row2 is None and col2 is None:
self._arrangement[row1, col1] = obj
elif row2 is None:
for col in range(col1, col2):
self._arrangement[row1, col] = get_or_else(lambda: obj[col-col1], None) # lgtm [py/loop-variable-capture]
elif col2 is None:
for row in range(row1, row2):
self._arrangement[row, col1] = get_or_else(lambda: obj[row-row1], None) # lgtm [py/loop-variable-capture]
else:
for row, col in zip(range(row1, row2), range(col1, col2)):
self._arrangement[row, col] = get_or_else(lambda: obj[row-row1][col-col1], None) # lgtm [py/loop-variable-capture]
def __iter__(self):
array = [ [ None ]*self.ncols for _ in range(0, self.nrows) ]
for (row, col), obj in self._arrangement.items():
array[row][col] = obj
return iter(array)
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
def _has_auto_sizing(item):
return item.sizing_mode is None and item.width_policy == "auto" and item.height_policy == "auto"
def _parse_children_arg(*args, **kwargs):
children = kwargs.get('children')
# Set-up Children from args or kwargs
if len(args) > 0 and children is not None:
raise ValueError("'children' keyword cannot be used with positional arguments")
if not children:
if len(args) == 1 and isinstance(args[0], list):
children = args[0]
elif len(args) == 1 and isinstance(args[0], GridSpec):
children = args[0]
else:
children = list(args)
return children
def _handle_child_sizing(children, sizing_mode, *, widget):
for item in children:
if not isinstance(item, LayoutDOM):
raise ValueError(f"Only LayoutDOM items can be inserted into a {widget}. Tried to insert: {item} of type {type(item)}")
if sizing_mode is not None and _has_auto_sizing(item):
item.sizing_mode = sizing_mode
def _create_grid(iterable, sizing_mode, layer=0, **kwargs):
"""Recursively create grid from input lists."""
return_list = []
for item in iterable:
if isinstance(item, list):
return_list.append(_create_grid(item, sizing_mode, layer+1))
elif isinstance(item, LayoutDOM):
if sizing_mode is not None and _has_auto_sizing(item):
item.sizing_mode = sizing_mode
return_list.append(item)
else:
raise ValueError(
"""Only LayoutDOM items can be inserted into a layout.
Tried to insert: %s of type %s""" % (item, type(item))
)
if layer % 2 == 0:
return column(children=return_list, sizing_mode=sizing_mode, **kwargs)
return row(children=return_list, sizing_mode=sizing_mode, **kwargs)
def _chunks(l, ncols):
"""Yield successive n-sized chunks from list, l."""
assert isinstance(ncols, int), "ncols must be an integer"
for i in range(0, len(l), ncols):
yield l[i: i+ncols]
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| {
"pile_set_name": "Github"
} |
r1bq1r1k/6bp/p1nP1pp1/1p4B1/2Np4/1Q3N2/PP4PP/R3R1K1 w - - 0 1|Pin: UdSSR (1977)<br>Sarkisen-Veremejcik<br>Difficulty **<br>Promising attack.|1. Nce5 Nxe5 2. Nxe5 fxg5 3. Nf7+ Rxf7 4. Qxf7 Bf5 5. d7 Qxd7 (5... Bxd7 6. Re7 ) 6. Re7 Qxe7 7. Qxe7 1-0
5rk1/ppp4p/3p4/3P1b2/2P5/4B3/PP1K3P/R7 w - - 0 1|Pin: Lugano (1987)<br>Seirawan-Nunn<br>Difficulty **<br>Just to get an advantage.|1. Bxa7 b6 2. Rf1 Kg7 3. Bb8 1-0
r1bqkb1r/1p3ppp/p7/3N4/8/3Q1N2/PP3PPP/3R1RK1 w kq - 0 1|Pin: Riga (1935)<br>Aljechin-Strasdinsch<br>Difficulty **|1. Nf6+ Qxf6 2. Rfe1+ Be7 3. Qd8# 1-0
4r2k/6p1/2q4p/p3r3/2P5/1P6/P1Q2R2/5RK1 b - - 0 1|Pin: UdSSR (1961)<br>Bannik-Tscherepkow<br>Difficulty **|1... Rg5+ 2. Rg2 Qc5+ 3. Qf2 (3. Kh1 Rh5+ 4. Rh2 Ree5) 3... Re2 0-1
6k1/8/2R4p/8/5qp1/P7/6P1/1R4K1 w - - 0 2|Pin: Fernpartie (1990)<br>Birkner-Niering<br>Difficulty **|2. Rc8+ Kg7 3. Rb7+ Kg6 4. Rg8+ Kh5 5. Rb5+ Kh4 6. Rxg4+ Kxg4 7. Rb4 1-0
r7/5p1k/1q4pp/3R4/5P2/7P/3Q2P1/7K b - - 0 1|Pin: Moskau (1947)<br>Bogatyrjew-Sagorjanski<br>Difficulty **|1... Ra1+ 2. Kh2 Qg1+ 3. Kg3 Ra3+ 4. Rd3 (4. Kg4 Qb6 5. Rd6 Qb5 6. Rd5 Qb3) 4... Qd4 0-1
r4rk1/pppb1ppp/8/2bR4/3q4/2N5/PPPP1PPP/R1B1Q1K1 b - - 0 1|Pin: Schweden (1967)<br>Danielsson-Blomberg<br>Difficulty **|1... Rfe8 2. Qf1 Qxf2+ 3. Qxf2 Re1# 0-1
4bk1r/Q4ppp/1p2q3/8/4B3/8/P4PPP/4R1K1 w - - 0 1|Pin: USA (1958)<br>Evans-Bisguier<br>Difficulty **|1. Qa3+ Qe7 (1... Kg8 2. Bxh7+) 2. Bc6 1-0
6r1/8/p3k3/1pR2p2/2P1b2p/5p1P/P1PR2P1/7K b - - 0 1|Pin: Daenemark (1962)<br>Hansen-Moeller<br>Difficulty **|1... Rxg2 2. Rxg2 f2 0-1
1k6/1b2b3/p5R1/Q2Bp2r/3p4/8/P5PP/3q2BK w - - 0 1|Pin: Fernpartie (1973)<br>Heemsoth-Weber<br>Difficulty **|1. Rg8+ Ka7 2. Ra8+ Kxa8 3. Qxa6+ 1-0
r4rk1/3n1pp1/ppq2n1p/3p4/PbpP3B/2N1PB2/1PQ2PPP/2RR2K1 w - - 0 1|Pin: 1981<br>Hort-Karpov<br>Difficulty **|1. Nxd5 Nxd5 2. Qe4 1-0
8/1rP2kpp/4b3/1B3p2/1B2n3/7P/6P1/2R3K1 w - - 0 1|Pin: Jaroslawl (1950)<br>Kan-Tschernow<br>Difficulty **|1. Bc4 Rxc7 2. Bxe6+ Kxe6 3. Rxc7 1-0
8/4kpp1/4p1p1/Q2pP1P1/2pR1P2/PrP3Pq/1P6/2K5 w - - 0 1|Pin: Bad Oeyhausen (1940)<br>Kieninger-Herrmann<br>Difficulty **|1. Qc7+ Ke8 2. Qc8+ Ke7 3. Rxd5 1-0
2kr1r2/p6p/5Pp1/2pP4/1qp2Q1P/7R/PP6/1KR5 w - - 0 1|Pin: Leningrad (1937)<br>Klaman-Lissyzin<br>Difficulty **|1. Rb3 cxb3 2. Qxb4 1-0
8/pQRq2pk/4p2p/3r1p2/3P4/4P3/PP3PPP/6K1 b - - 0 1|Pin: Jugoslawien (1949)<br>N.N.-N.N.<br>Difficulty **|1... Rc5 0-1
r5k1/5Rpp/1bqp4/1p1bp3/1P6/1BP4P/1B2QPP1/6K1 w - - 0 1|Pin: Tjumen (1981)<br>Pidoritsch-Tschernoussow<br>Difficulty **|1. Rc7 Bxc7 2. Qe4 1-0
4Rr1k/p1q4p/1p1p2p1/5r2/2pP1b2/2P3B1/PPQ4P/4R1K1 w - - 0 1|Pin: Buenos Aires (1990)<br>Podesta-Madina<br>Difficulty **|1. R1e7 Qc6 2. Qxf5 1-0
3b1rk1/1bqr1pp1/ppp1p2p/4P2Q/1PPPB2P/P5P1/1B3R1K/5R2 w - - 0 1|Pin: Prag (1943)<br>Sajtar-Dietze<br>Difficulty **|1. Qg6 f5 (1... fxg6 2. Rxf8+ Kh7 3. h5) 2. exf6 Bxf6 3. Rxf6 1-0
5k2/p3bp2/2p3p1/1qNb3r/6p1/2Q5/P4RPP/5RK1 w - - 0 1|Pin: UdSSR (1961)<br>Skotorenko-Wladimirow<br>Difficulty **|1. Rxf7+ Bxf7 2. Ne6+ Ke8 3. Nc7+ 1-0
6r1/Qp5k/8/3p3p/5q2/1P3p1B/P6P/5N1K b - - 0 1|Pin: Saltsjoebaden (1952)<br>Stoltz-Kotow<br>Difficulty **|1... f2 2. Bg2 Qf3 0-1
r1br2k1/2q2ppp/5n2/pPb1p3/Rn2P3/1B3N2/3BQPPP/1NR3K1 w - - 0 1|Pin: Aalborg (1989)<br>Thuesen-Vistisen<br>Difficulty **|1. Rxc5 Qxc5 2. Bxb4 1-0
1r2q3/p3b1pk/1p1p2p1/2pPp2P/1PP1Q3/P3B1P1/6P1/5RK1 w - - 0 1|Pin: Moskau (1901)<br>Tschigorin-Beratende<br>Difficulty **|1. hxg6+ Qxg6 2. Rf5 1-0
4R3/8/pp6/k1r5/P3p3/K3PbB1/5P2/8 w - - 0 1|Pin: Polen (1953)<br>Wachtel-Musiol<br>Difficulty **|1. Re5 1-0
r3r1k1/1p3pbp/p2pp1p1/2q2P1n/2PnP3/1PN4P/PBB2QP1/2R2RK1 b - - 0 1|Pin: Puschkin (1985)<br>Wassiljew-Jerofejew<br>Difficulty **|1... Nf3+ 2. gxf3 Bd4 0-1
Q2n4/Rnk2p2/1p2pNp1/1q1pP1P1/1PpP4/2P3P1/6K1/8 w - - 0 1|Pin: Kopenhagen (1990)<br>Sznapik-Hvenegilde<br>Difficulty **|1. Ne8+ Qxe8 (1... Kd7 2. Nd6 Qc6 3. Rxb7+) 2. Rxb7+ Nxb7 3. Qxe8 1-0
r1rn4/1Np1k1p1/p3p2p/5p2/3P1P2/P1R1PP2/1P2K1P1/2R5 b - - 0 1|Pin: Niederlande (1988)<br>Little-Tichelmann<br>Difficulty **|1... Nxb7 2. Rxc7+ Kd8 0-1
5r1k/ppp3p1/1q6/3Rp2p/4P2r/1P2Q3/P1P3P1/4R1K1 b - - 0 1|Pin: Indien (1990)<br>Vijayalakshmi-Bose<br>Difficulty **|1... Rxe4 2. Qxb6 Rxe1+ 0-1
5r1k/pp5p/2pp2p1/4b3/2PpPr2/3P1P1q/PPQ2R1P/1R2N1K1 b - - 0 1|Pin: Biel (1975)<br>Schaffart-Werner<br>Difficulty **|1... Rg4+ 2. Rg2 (2. fxg4 Bxh2+ 3. Kh1 Bg3+) 2... Qxh2+ 3. Kf2 Rxg2+ 0-1
3r2k1/p1q2p2/1p1N2pp/n7/3Q4/P1P4P/5PP1/4R1K1 b - - 0 1|Pin: Bern (1977)<br>Minev-Keller<br>Difficulty **|1... Qb8 (1... Qxd6 2. Re8+ Rxe8 3. Qxd6) (1... Qc6 2. Nf5 Rxd4 3. Ne7+ Kf8 4. Nxc6 Ra4 5. Nxa7 Rxa3 6. Rb1) 2. Rd1 Nb7 0-1
rn2r1k1/ppp2p1p/5p2/3q1b1Q/1b3P2/3B1N2/PPP3PP/R1BK3R b - - 0 1|Pin: N.N.-N.N.<br>Difficulty **|1... Bxd3 2. Qxd5 Be2# 0-1
2r5/p4p1k/1p1Q2pp/7q/1P3P2/6P1/6KP/3R1B2 b - - 0 1|Pin: N.N.-N.N.<br>Difficulty **|1... Rc2+ 2. Rd2 Qd1 0-1
5rk1/q5pp/4p3/r1bp1p2/1p1B1P2/1P1QP3/P4RPP/2R3K1 w - - 0 1|Pin: Moskau (1971)<br>Kotow-Cholmow<br>Difficulty **|1. Rxc5 Rxc5 2. Rc2 Rfc8 3. Qb5 Rxc2 4. Bxa7 1-0
2k1rR2/2p1Q2p/1pq3p1/1pN1b3/6rn/2P1B3/PP5P/3R1K2 b - - 0 1|Pin: Minsk (1952)<br>Awerbach-Goldenow<br>Difficulty **|1... Rf4+ (1... Qg2+ 2. Ke1 Nf3+ 3. Rxf3) 2. Bxf4 Qg2+ 3. Ke1 Nf3# 0-1
rn2k2r/ppp3pp/5b2/5b2/2P1N3/8/PP4PP/2KR1BNR b kq - 0 1|Pin: Bruessel (1935)<br>de Mey-O'Kelly<br>Difficulty **|1... Bxe4 2. Re1 Bg5+ 3. Kd1 O-O 0-1
r3k2r/pp1q1ppp/1b6/3p4/Q7/B7/P4PPP/3R1RK1 w kq - 0 1|Pin: Luzern (1952)<br>Lehmann-Mueller<br>Difficulty **|1. Rxd5 Qxa4 2. Re1+ 1-0
5r1k/5rpp/8/4q3/4P1Q1/2p4R/7P/6RK w - - 0 1|Pin: Bremen (1990)<br>Rust-Wetjen<br>Difficulty **|1. Qg6 h6 (1... h5 2. Rxh5+ Qxh5 3. Qxh5+ Kg8 4. Qc5) 2. Rxh6+ gxh6 3. Qxh6+ Rh7 4. Qxf8# 1-0
5bk1/1p3p1p/1P2p1p1/4P3/5P2/1r2BQP1/2q4P/R6K b - - 0 1|Pin: Kecskemet (1990)<br>Grosspeter-Reeh<br>Difficulty **|1... Rxe3 2. Qxe3 Qc6+ 3. Kg1 Bc5 0-1
5rk1/5pp1/4b2p/q7/n1B5/p3Q3/R2N1PPP/6K1 b - - 0 1|Pin: Groningen (1982)<br>Lanzani-Wiedenkeller<br>Difficulty **|1... Bxc4 2. Nxc4 Qd5 3. Qb3 (3. Qc1 Nb2 4. Rxb2 axb2) 3... Nb2 0-1
8/kp2q3/p3r3/1Pp5/7R/1P2Q2P/4K3/8 w - - 0 2|Pin: N.N.-N.N.<br>Difficulty **|2. b6+ Kxb6 3. Rh6 1-0
1r1rn2k/ppR1Npbp/4b1p1/4B3/8/6P1/qP2PPBP/2Q2RK1 w - - 0 1|Pin: Groningen (1992)<br>Rotstein-Kaminski<br>Difficulty **|1. Qh6 Bd7 (1... Rd7 2. Rxd7 Bxd7 3. Bd5 Qa5 4. Bxf7) 2. Bd5 Qxd5 3. Bxg7+ Nxg7 4. Nxd5 1-0
4r2k/1pR3pP/2b5/p4Q2/8/8/P4P2/2q2NK1 w - - 0 1|Pin: Vilnius (1981)<br>Dolmatow-Tschechow<br>Difficulty **|1. Qg6 (1. Qf7 $2 Qg5+ 2. Ng3 Re1+) 1... Qc3 (1... Qh6 2. Rxc6) 2. Qxe8+ Bxe8 3. Rxc3 1-0
5r1k/2b3pp/3p1p2/pq1Br3/4P1Q1/4B2R/1PP3PP/7K w - - 0 1|Pin: Linares (1981)<br>Bellon-Ribli<br>Difficulty **|1. Qg6 Qf1+ 2. Bg1 1-0
2kr4/pp6/2p1p1pR/3n4/5q2/8/PPPQ1PP1/2KR4 b - - 0 1|Pin: UdSSR (1976)<br>Suisko-Klisa<br>Difficulty **|1... Nc3 2. Rh8 Ne2+ 3. Kb1 Qxd2 0-1
r3r1k1/p4ppp/2q5/8/3p4/P1nP1P2/R2B1KPP/2Q1R3 b - - 0 1|Pin: Bukarest (1981)<br>Adamski-Ambroz<br>Difficulty **|1... Rxe1 2. Qxe1 (2. Bxe1 Ne4+) (2. Kxe1 Qe6+) 2... Nxa2 0-1
2rR1b1k/4nppp/p7/1p5N/4B3/2P3RP/Pn3PP1/6K1 w - - 0 1|Pin: Bernburg (1982)<br>Schuhmacher-Laban<br>Difficulty **|1. Rxg7 Rxd8 2. Rxh7+ Kg8 3. Nf6# 1-0
5r2/1k1b4/1n1P2p1/p1pP4/PpP4q/1P1B4/2Q2R2/3RKN1r b - - 0 1|Pin: Wijk aan Zee Wijk (1980)<br>Kovacevic-Seirawan<br>Difficulty **|1... Re8+ 2. Be2 Rxf1+ 3. Kxf1 Qh1# 0-1
8/2q3kp/6p1/4p1QP/1n2P3/1P1r1P2/1P6/1KR5 b - - 0 1|Pin: Luzern (1982)<br>Van der Wiel-Mestel<br>Difficulty **|1... Rd1 2. Rxd1 Qc2+ 3. Ka1 Qxd1+ 0-1
r1b1r1k1/pp3p1p/6p1/2p1b1q1/3P4/2P1R1P1/PP3QBP/RN4K1 b - - 0 1|Pin: Berlin (1982)<br>Leitert-Wilke<br>Difficulty **|1... Qxe3 2. Qxe3 Bxd4 0-1
5rk1/1pp3p1/p1p5/7p/8/4b3/PPP2RPP/5RK1 b - - 0 1|Pin: Fernpartie (1983)<br>Wanless-Gillam<br>Difficulty **|1... h4 2. g3 h3 0-1
8/8/4pk2/3rbpp1/8/2B5/4R1P1/7K w - - 0 1|Pin: Nach Tarrasch<br>Difficulty **<br>Favorable endgame.|1. Rxe5 Rxe5 2. g3 f4 (2... Kg6 $1 3. Bxe5 Kh5 4. Kg2 f4) 3. g4 1-0
8/1p2kp1p/pq6/6p1/2B2nPP/1P2rb2/P2R1Q1R/6K1 b - - 0 1|Pin: Graz (1979)<br>Saizew-Watzka<br>Difficulty **<br>Several variants.|1... Re1+ 2. Bf1 Bg2 (2... Be2 $1 {Alternative}) 3. Rxg2 Nh3+ 0-1
2r1k2r/3bpp2/p6b/1p1N3R/3NP3/1P2QPq1/PP1R4/1K6 b - - 0 1|Pin: Leningrad (1941)<br>Boleslawski-Bondarenko<br>Difficulty **<br>Several variants.|1... Rg8 2. Qd3 Qg1+ (2... Qe1+ $1 {Alternative}) 3. Rd1 Rc1+ 4. Rxc1 Qxc1# 0-1
r1b2r1k/p2nq1pp/2pn4/5p2/3P1B2/1Q2P1P1/PP3PBP/2RR2K1 w - - 0 1|Pin: 1937<br>Pogrebysski-Kortchmar<br>Difficulty **<br>Several variants.|1. Qb4 (1. Qa3 $18 {Alternative}) 1... Rf6 2. Rxc6 Rb8 3. Bxd6 1-0
8/p3Rpk1/3p1npp/1rqP4/5P2/1P4PP/PQ4BK/8 w - - 0 1|Pin: Amsterdam (1954)<br>Trifunovic-Golombek<br>Difficulty **<br>Several variants.|1. g4 g5 2. h4 Kg6 3. Be4+ (3. h5+ $1 {Alternative} Kg7 4. fxg5 Qf2 5. Rxf7+) 3... Nxe4 4. h5+ Kh7 5. Rxf7+ Kg8 6. Qg7# 1-0
4r3/1p4pk/2b2pqp/8/8/P6P/3BRQP1/6K1 b - - 0 1|Pin: Groningen (1946)<br>Guimard-Kotow<br>Difficulty **<br>Several variants.|1... Bxg2 2. Rxe8 (2. Qxg2 Rxe2) 2... Be4+ (2... Bc6+ $19 {Alternative}) 3. Kh2 Qxe8 0-1
r3r1k1/5p1p/1q4pb/1p1P2N1/2p3B1/2P5/1P1Q2PP/5R1K b - - 0 1|Pin: Luzern (1982)<br>Arjuna-Suttles<br>Difficulty **<br>Several variants.|1... Qf6 (1... Qd8 $19 {Alternative}) 2. Rxf6 Ra1+ 3. Bd1 Bxg5 0-1
| {
"pile_set_name": "Github"
} |
<HTML>
<HEAD>
<meta charset="UTF-8">
<title>GAPaymentMethodDisplayInfo.<init> - tock</title>
<link rel="stylesheet" href="../../../style.css">
</HEAD>
<BODY>
<a href="../../index.html">tock</a> / <a href="../index.html">ai.tock.bot.connector.ga.model.response.transaction.v3</a> / <a href="index.html">GAPaymentMethodDisplayInfo</a> / <a href="./-init-.html"><init></a><br/>
<br/>
<h1><init></h1>
<a name="ai.tock.bot.connector.ga.model.response.transaction.v3.GAPaymentMethodDisplayInfo$<init>(ai.tock.bot.connector.ga.model.request.transaction.v3.GAPaymentType, kotlin.String)"></a>
<code><span class="identifier">GAPaymentMethodDisplayInfo</span><span class="symbol">(</span><span class="identifier" id="ai.tock.bot.connector.ga.model.response.transaction.v3.GAPaymentMethodDisplayInfo$<init>(ai.tock.bot.connector.ga.model.request.transaction.v3.GAPaymentType, kotlin.String)/paymentType">paymentType</span><span class="symbol">:</span> <a href="../../ai.tock.bot.connector.ga.model.request.transaction.v3/-g-a-payment-type/index.html"><span class="identifier">GAPaymentType</span></a><span class="symbol">?</span><span class="symbol">, </span><span class="identifier" id="ai.tock.bot.connector.ga.model.response.transaction.v3.GAPaymentMethodDisplayInfo$<init>(ai.tock.bot.connector.ga.model.request.transaction.v3.GAPaymentType, kotlin.String)/paymentMethodDisplayName">paymentMethodDisplayName</span><span class="symbol">:</span> <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html"><span class="identifier">String</span></a><span class="symbol">?</span><span class="symbol">)</span></code>
</BODY>
</HTML>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square70x70logo src="/themes/FlamingParrot/images/favicon/FlamingParrot_BlueGrey/mstile-70x70.png"/>
<square150x150logo src="/themes/FlamingParrot/images/favicon/FlamingParrot_BlueGrey/mstile-150x150.png"/>
<square310x310logo src="/themes/FlamingParrot/images/favicon/FlamingParrot_BlueGrey/mstile-310x310.png"/>
<wide310x150logo src="/themes/FlamingParrot/images/favicon/FlamingParrot_BlueGrey/mstile-310x150.png"/>
<TileColor>#5b6c79</TileColor>
</tile>
</msapplication>
</browserconfig>
| {
"pile_set_name": "Github"
} |
File: reservedExpressionSyntax.kt - c054123555504f10adc3ee34ee2b365a (WITH_ERRORS)
NL("\n")
packageHeader
PACKAGE("package")
identifier
simpleIdentifier
Identifier("test")
semi
NL("\n")
NL("\n")
importList
topLevelObject
declaration
objectDeclaration
OBJECT("object")
simpleIdentifier
Identifier("ClassMemberMarker")
semis
NL("\n")
NL("\n")
topLevelObject
declaration
classDeclaration
CLASS("class")
simpleIdentifier
Identifier("a")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
classBody
LCURL("{")
NL("\n")
classMemberDeclarations
classMemberDeclaration
declaration
functionDeclaration
FUN("fun")
simpleIdentifier
Identifier("foo")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("ClassMemberMarker")
semis
NL("\n")
RCURL("}")
semis
NL("\n")
NL("\n")
topLevelObject
declaration
classDeclaration
CLASS("class")
simpleIdentifier
Identifier("b")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T1")
COMMA(",")
typeParameter
simpleIdentifier
Identifier("T2")
RANGLE(">")
classBody
LCURL("{")
NL("\n")
classMemberDeclarations
classMemberDeclaration
declaration
functionDeclaration
FUN("fun")
simpleIdentifier
Identifier("foo")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("ClassMemberMarker")
semis
NL("\n")
RCURL("}")
semis
NL("\n")
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Int")
DOT(".")
simpleIdentifier
Identifier("foo")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
block
LCURL("{")
statements
RCURL("}")
semis
NL("\n")
NL("\n")
topLevelObject
declaration
classDeclaration
CLASS("class")
simpleIdentifier
Identifier("Test")
LCURL("{")
NL("\n")
topLevelObject
declaration
propertyDeclaration
VAL("val")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
variableDeclaration
simpleIdentifier
Identifier("a")
COLON(":")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Int")
getter
GET("get")
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("size")
semis
NL("\n")
topLevelObject
declaration
propertyDeclaration
VAL("val")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
variableDeclaration
simpleIdentifier
Identifier("b")
COLON(":")
type
nullableType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Int")
quest
QUEST_WS("? ")
getter
GET("get")
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("size")
semis
NL("\n")
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
simpleIdentifier
Identifier("testCallable1")
functionValueParameters
LPAREN("(")
RPAREN(")")
COLON(":")
type
functionType
functionTypeParameters
LPAREN("(")
RPAREN(")")
ARROW("->")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Unit")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("a")
comparisonOperator
LANGLE("<")
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("T")
comparisonOperator
RANGLE(">")
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
callableReference
COLONCOLON("::")
simpleIdentifier
Identifier("foo")
semis
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
simpleIdentifier
Identifier("testCallable2")
functionValueParameters
LPAREN("(")
RPAREN(")")
COLON(":")
type
functionType
functionTypeParameters
LPAREN("(")
RPAREN(")")
ARROW("->")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Unit")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
callableReference
receiverType
nullableType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("b")
quest
QUEST_NO_WS("?")
COLONCOLON("::")
simpleIdentifier
Identifier("foo")
semis
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
simpleIdentifier
Identifier("testCallable3")
functionValueParameters
LPAREN("(")
RPAREN(")")
COLON(":")
type
functionType
functionTypeParameters
LPAREN("(")
RPAREN(")")
ARROW("->")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Unit")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
callableReference
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("b")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
COMMA(",")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Any")
RANGLE(">")
COLONCOLON("::")
simpleIdentifier
Identifier("foo")
semis
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
simpleIdentifier
Identifier("testCallable4")
functionValueParameters
LPAREN("(")
RPAREN(")")
COLON(":")
type
functionType
functionTypeParameters
LPAREN("(")
RPAREN(")")
ARROW("->")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Unit")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
callableReference
receiverType
nullableType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("b")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
quest
QUEST_NO_WS("?")
COLONCOLON("::")
simpleIdentifier
Identifier("foo")
semis
NL("\n")
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
simpleIdentifier
Identifier("testClassLiteral1")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("a")
comparisonOperator
LANGLE("<")
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("T")
comparisonOperator
RANGLE(">")
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
callableReference
COLONCOLON("::")
CLASS("class")
semis
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
simpleIdentifier
Identifier("testClassLiteral2")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
callableReference
receiverType
nullableType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("b")
quest
QUEST_NO_WS("?")
COLONCOLON("::")
CLASS("class")
semis
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
simpleIdentifier
Identifier("testClassLiteral3")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
callableReference
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("b")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
COMMA(",")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Any")
RANGLE(">")
COLONCOLON("::")
CLASS("class")
semis
NL("\n")
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
simpleIdentifier
Identifier("testUnresolved1")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("unresolved")
comparisonOperator
LANGLE("<")
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("T")
comparisonOperator
RANGLE(">")
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
callableReference
COLONCOLON("::")
simpleIdentifier
Identifier("foo")
semis
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
simpleIdentifier
Identifier("testUnresolved2")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("a")
comparisonOperator
LANGLE("<")
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("unresolved")
comparisonOperator
RANGLE(">")
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
callableReference
COLONCOLON("::")
simpleIdentifier
Identifier("foo")
semis
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
simpleIdentifier
Identifier("testUnresolved3")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("a")
LANGLE("<")
RANGLE(">")
COLONCOLON("::")
Identifier("foo")
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
typeParameters
LANGLE("<")
typeParameter
simpleIdentifier
Identifier("T")
RANGLE(">")
receiverType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("List")
typeArguments
LANGLE("<")
typeProjection
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("T")
RANGLE(">")
DOT(".")
simpleIdentifier
Identifier("testUnresolved4")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
callableReference
receiverType
nullableType
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("unresolved")
quest
QUEST_NO_WS("?")
COLONCOLON("::")
simpleIdentifier
Identifier("foo")
semis
NL("\n")
RCURL("}")
EOF("<EOF>")
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.