repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Laufire/ec
docs/Makefile
6746
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ec.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ec.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/ec" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ec" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
bsd-3-clause
ilius/grpc-gateway
protoc-gen-grpc-gateway/gengateway/template_test.go
13223
package gengateway import ( "strings" "testing" "github.com/golang/protobuf/proto" protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/ilius/grpc-gateway/protoc-gen-grpc-gateway/descriptor" "github.com/ilius/grpc-gateway/protoc-gen-grpc-gateway/httprule" ) func crossLinkFixture(f *descriptor.File) *descriptor.File { for _, m := range f.Messages { m.File = f } for _, svc := range f.Services { svc.File = f for _, m := range svc.Methods { m.Service = svc for _, b := range m.Bindings { b.Method = m for _, param := range b.PathParams { param.Method = m } } } } return f } func TestApplyTemplateHeader(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, MessageType: []*protodescriptor.DescriptorProto{msgdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, }, }, }, }, }, }, } got, err := applyTemplate(param{File: crossLinkFixture(&file)}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want := "package example_pb\n"; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } nesteddesc := &protodescriptor.DescriptorProto{ Name: proto.String("NestedMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("int32"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(false), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } for _, spec := range []struct { serverStreaming bool sigWant string }{ { serverStreaming: false, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {`, }, { serverStreaming: true, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (ExampleService_EchoClient, runtime.ServerMetadata, error) {`, }, } { meth.ServerStreaming = proto.Bool(spec.serverStreaming) msg := &descriptor.Message{ DescriptorProto: msgdesc, } nested := &descriptor.Message{ DescriptorProto: nesteddesc, } nestedField := &descriptor.Field{ Message: msg, FieldDescriptorProto: msg.GetField()[0], } intField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[0], } boolField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg, nested}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, }, PathParams: []descriptor.Parameter{ { FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "int32", Target: intField, }, }), Target: intField, }, }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "bool", Target: boolField, }, }), }, }, }, }, }, }, }, } got, err := applyTemplate(param{File: crossLinkFixture(&file)}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want := spec.sigWant; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `marshaler.NewDecoder(req.Body).Decode(&protoReq.GetNested().Bool)`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `val, ok = pathParams["nested.int32"]`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `protoReq.GetNested().Int32, err = runtime.Int32P(val)`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `func RegisterExampleServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `pattern_ExampleService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{0, 0}, []string(nil), ""))`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } } func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } nesteddesc := &protodescriptor.DescriptorProto{ Name: proto.String("NestedMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("int32"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(true), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } for _, spec := range []struct { serverStreaming bool sigWant string }{ { serverStreaming: false, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {`, }, { serverStreaming: true, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (ExampleService_EchoClient, runtime.ServerMetadata, error) {`, }, } { meth.ServerStreaming = proto.Bool(spec.serverStreaming) msg := &descriptor.Message{ DescriptorProto: msgdesc, } nested := &descriptor.Message{ DescriptorProto: nesteddesc, } nestedField := &descriptor.Field{ Message: msg, FieldDescriptorProto: msg.GetField()[0], } intField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[0], } boolField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg, nested}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, }, PathParams: []descriptor.Parameter{ { FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "int32", Target: intField, }, }), Target: intField, }, }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "bool", Target: boolField, }, }), }, }, }, }, }, }, }, } got, err := applyTemplate(param{File: crossLinkFixture(&file)}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want := spec.sigWant; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `marshaler.NewDecoder(req.Body)`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `func RegisterExampleServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `pattern_ExampleService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{0, 0}, []string(nil), ""))`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } }
bsd-3-clause
SteveXiSong/ECE757-SnoopingPredictions
src/mem/snoop_filter.cc
13192
/* * Copyright (c) 2013 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Stephan Diestelhorst <[email protected]> */ // hello /** * @file * Definition of a snoop filter. */ #include "base/misc.hh" #include "base/trace.hh" #include "debug/SnoopFilter.hh" #include "mem/snoop_filter.hh" #include "sim/system.hh" std::pair<SnoopFilter::SnoopList, Cycles> SnoopFilter::lookupRequest(const Packet* cpkt, const SlavePort& slave_port) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask req_port = portToMask(slave_port); auto sf_it = cachedLocations.find(line_addr); bool is_hit = (sf_it != cachedLocations.end()); // Create a new element through operator[] and modify in-place SnoopItem& sf_item = is_hit ? sf_it->second : cachedLocations[line_addr]; SnoopMask interested = sf_item.holder | sf_item.requested; totRequests++; if (is_hit) { // Single bit set -> value is a power of two if (isPow2(interested)) hitSingleRequests++; else hitMultiRequests++; } DPRINTF(SnoopFilter, "%s: SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); if (cpkt->needsResponse()) { if (!cpkt->memInhibitAsserted()) { // Max one request per address per port panic_if(sf_item.requested & req_port, "double request :( "\ "SF value %x.%x\n", sf_item.requested, sf_item.holder); // Mark in-flight requests to distinguish later on sf_item.requested |= req_port; } else { // NOTE: The memInhibit might have been asserted by a cache closer // to the CPU, already -> the response will not be seen by this // filter -> we do not need to keep the in-flight request, but make // sure that we know that that cluster has a copy panic_if(!(sf_item.holder & req_port), "Need to hold the value!"); DPRINTF(SnoopFilter, "%s: not marking request. SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } return snoopSelected(maskToPortList(interested & ~req_port), lookupLatency); } void SnoopFilter::updateRequest(const Packet* cpkt, const SlavePort& slave_port, bool will_retry) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask req_port = portToMask(slave_port); SnoopItem& sf_item = cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x retry: %i\n", __func__, sf_item.requested, sf_item.holder, will_retry); if (will_retry) { // Unmark a request that will come again. sf_item.requested &= ~req_port; return; } // will_retry == false if (!cpkt->needsResponse()) { // Packets that will not evoke a response but still need updates of the // snoop filter; WRITEBACKs for now only if (cpkt->cmd == MemCmd::Writeback) { // make sure that the sender actually had the line panic_if(sf_item.requested & req_port, "double request :( "\ "SF value %x.%x\n", sf_item.requested, sf_item.holder); panic_if(!(sf_item.holder & req_port), "requester %x is not a "\ "holder :( SF value %x.%x\n", req_port, sf_item.requested, sf_item.holder); // Writebacks -> the sender does not have the line anymore sf_item.holder &= ~req_port; } else { assert(0 == "Handle non-writeback, here"); } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } } std::pair<SnoopFilter::SnoopList, Cycles> SnoopFilter::lookupSnoop(const Packet* cpkt) { DPRINTF(SnoopFilter, "%s: packet addr 0x%x cmd %s\n", __func__, cpkt->getAddr(), cpkt->cmdString()); assert(cpkt->isRequest()); // Broadcast / filter upward snoops const bool filter_upward = true; // @todo: Make configurable if (!filter_upward) return snoopAll(lookupLatency); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); auto sf_it = cachedLocations.find(line_addr); bool is_hit = (sf_it != cachedLocations.end()); // Create a new element through operator[] and modify in-place SnoopItem& sf_item = is_hit ? sf_it->second : cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); SnoopMask interested = (sf_item.holder | sf_item.requested); totSnoops++; if (is_hit) { // Single bit set -> value is a power of two if (isPow2(interested)) hitSingleSnoops++; else hitMultiSnoops++; } assert(cpkt->isInvalidate() == cpkt->needsExclusive()); if (cpkt->isInvalidate() && !sf_item.requested) { // Early clear of the holder, if no other request is currently going on // @todo: This should possibly be updated even though we do not filter // upward snoops sf_item.holder = 0; } DPRINTF(SnoopFilter, "%s: new SF value %x.%x interest: %x \n", __func__, sf_item.requested, sf_item.holder, interested); return snoopSelected(maskToPortList(interested), lookupLatency); } void SnoopFilter::updateSnoopResponse(const Packet* cpkt, const SlavePort& rsp_port, const SlavePort& req_port) { DPRINTF(SnoopFilter, "%s: packet rsp %s req %s addr 0x%x cmd %s\n", __func__, rsp_port.name(), req_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask rsp_mask = portToMask(rsp_port); SnoopMask req_mask = portToMask(req_port); SnoopItem& sf_item = cachedLocations[line_addr]; assert(cpkt->isResponse()); assert(cpkt->memInhibitAsserted()); DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // The source should have the line panic_if(!(sf_item.holder & rsp_mask), "SF value %x.%x does not have "\ "the line\n", sf_item.requested, sf_item.holder); // The destination should have had a request in panic_if(!(sf_item.requested & req_mask), "SF value %x.%x missing "\ "the original request\n", sf_item.requested, sf_item.holder); // Update the residency of the cache line. if (cpkt->needsExclusive() || !cpkt->sharedAsserted()) { DPRINTF(SnoopFilter, "%s: dropping %x because needs: %i shared: %i "\ "SF val: %x.%x\n", __func__, rsp_mask, cpkt->needsExclusive(), cpkt->sharedAsserted(), sf_item.requested, sf_item.holder); sf_item.holder &= ~rsp_mask; // The snoop filter does not see any ACKs from non-responding sharers // that have been invalidated :( So below assert would be nice, but.. //assert(sf_item.holder == 0); sf_item.holder = 0; } assert(cpkt->cmd != MemCmd::Writeback); sf_item.holder |= req_mask; sf_item.requested &= ~req_mask; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::updateSnoopForward(const Packet* cpkt, const SlavePort& rsp_port, const MasterPort& req_port) { DPRINTF(SnoopFilter, "%s: packet rsp %s req %s addr 0x%x cmd %s\n", __func__, rsp_port.name(), req_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopItem& sf_item = cachedLocations[line_addr]; SnoopMask rsp_mask M5_VAR_USED = portToMask(rsp_port); assert(cpkt->isResponse()); assert(cpkt->memInhibitAsserted()); DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // Remote (to this snoop filter) snoops update the filter already when they // arrive from below, because we may not see any response. if (cpkt->needsExclusive()) { // If the request to this snoop response hit an in-flight transaction, // the holder was not reset -> no assertion & do that here, now! //assert(sf_item.holder == 0); sf_item.holder = 0; } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::updateResponse(const Packet* cpkt, const SlavePort& slave_port) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask slave_mask = portToMask(slave_port); SnoopItem& sf_item = cachedLocations[line_addr]; assert(cpkt->isResponse()); DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // Make sure we have seen the actual request, too panic_if(!(sf_item.requested & slave_mask), "SF value %x.%x missing "\ "request bit\n", sf_item.requested, sf_item.holder); // Update the residency of the cache line. if (cpkt->needsExclusive() || !cpkt->sharedAsserted()) sf_item.holder = 0; sf_item.holder |= slave_mask; sf_item.requested &= ~slave_mask; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::regStats() { totRequests .name(name() + ".tot_requests") .desc("Total number of requests made to the snoop filter."); hitSingleRequests .name(name() + ".hit_single_requests") .desc("Number of requests hitting in the snoop filter with a single "\ "holder of the requested data."); hitMultiRequests .name(name() + ".hit_multi_requests") .desc("Number of requests hitting in the snoop filter with multiple "\ "(>1) holders of the requested data."); totSnoops .name(name() + ".tot_snoops") .desc("Total number of snoops made to the snoop filter."); hitSingleSnoops .name(name() + ".hit_single_snoops") .desc("Number of snoops hitting in the snoop filter with a single "\ "holder of the requested data."); hitMultiSnoops .name(name() + ".hit_multi_snoops") .desc("Number of snoops hitting in the snoop filter with multiple "\ "(>1) holders of the requested data."); } SnoopFilter * SnoopFilterParams::create() { return new SnoopFilter(this); }
bsd-3-clause
Bionics4909/Aerial-Assist
src/org/usfirst/frc4909/RealRobo2/OI.java
3765
// RobotBuilder Version: 1.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc4909.RealRobo2; import edu.wpi.first.wpilibj.Joystick; import org.usfirst.frc4909.RealRobo2.commands.*; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { //// CREATING BUTTONS // One type of button is a joystick button which is any button on a joystick. // You create one by telling it which joystick it's on and which button // number it is. // Joystick stick = new Joystick(port); // Button button = new JoystickButton(stick, buttonNumber); // Another type of button you can create is a DigitalIOButton, which is // a button or switch hooked up to the cypress module. These are useful if // you want to build a customized operator interface. // Button button = new DigitalIOButton(1); // There are a few additional built in buttons you can use. Additionally, // by subclassing Button you can create custom triggers and bind those to // commands the same as any other Button. //// TRIGGERING COMMANDS WITH BUTTONS // Once you have a button, it's trivial to bind it to a button in one of // three ways: // Start the command when the button is pressed and let it run the command // until it is finished as determined by it's isFinished method. // button.whenPressed(new ExampleCommand()); // Run the command while the button is being held down and interrupt it once // the button is released. // button.whileHeld(new ExampleCommand()); // Start the command when the button is released and let it run the command // until it is finished as determined by it's isFinished method. // button.whenReleased(new ExampleCommand()); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public Joystick leftJoystick; public Joystick rightJoystick; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public OI() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS rightJoystick = new Joystick(2); leftJoystick = new Joystick(1); // SmartDashboard Buttons SmartDashboard.putData("Autonomous Command", new AutonomousCommand()); SmartDashboard.putData("Tank Drive", new TankDrive()); SmartDashboard.putData("Drive Forward", new DriveForward()); SmartDashboard.putData("Drive Backward", new DriveBackward()); SmartDashboard.putData("Spin", new Spin()); SmartDashboard.putData("Dance", new Dance()); SmartDashboard.putData("Slide Forward", new SlideForward()); SmartDashboard.putData("Slide Backward", new SlideBackward()); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS } // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS public Joystick getLeftJoystick() { return leftJoystick; } public Joystick getRightJoystick() { return rightJoystick; } // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS }
bsd-3-clause
luttero/Maud
src/gov/noaa/pmel/sgt/swing/prop/GridAttributeDialog.java
32899
/* * $Id: GridAttributeDialog.java,v 1.2 2006/01/19 14:45:50 luca Exp $ * * This software is provided by NOAA for full, free and open release. It is * understood by the recipient/user that NOAA assumes no liability for any * errors contained in the code. Although this software is released without * conditions or restrictions in its use, it is expected that appropriate * credit be given to its author and to the National Oceanic and Atmospheric * Administration should the software be included by the recipient as an * element in other product development. */ package gov.noaa.pmel.sgt.swing.prop; import javax.swing.*; import java.awt.*; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumn; import javax.swing.event.TableModelEvent; import java.util.Vector; import java.io.File; import java.io.Reader; import java.io.BufferedReader; import java.io.FileReader; import java.io.StreamTokenizer; import gov.noaa.pmel.sgt.GridCartesianRenderer; import gov.noaa.pmel.sgt.GridAttribute; import gov.noaa.pmel.sgt.ContourLineAttribute; import gov.noaa.pmel.sgt.DefaultContourLineAttribute; import gov.noaa.pmel.sgt.ContourLevels; import gov.noaa.pmel.sgt.ColorMap; import gov.noaa.pmel.sgt.IndexedColor; import gov.noaa.pmel.sgt.swing.ColorSwatchIcon; import gov.noaa.pmel.sgt.IndexedColorMap; import gov.noaa.pmel.sgt.LinearTransform; import gov.noaa.pmel.sgt.JPane; import gov.noaa.pmel.sgt.ContourLevelNotFoundException; import gov.noaa.pmel.sgt.dm.SGTGrid; import gov.noaa.pmel.util.Range2D; import java.awt.event.*; import it.unitn.ing.rista.util.Misc; /** * Edits the <code>GridAttribute</code>. This dialog does not make a * copy of the attribute so changes "Applied" will cause * <code>sgt</code> to redraw the plot using the properties * immediately unless a <code>JPane</code> was supplied. * * <p> Example of <code>GridAttributeDialog</code> use: * <pre> * JPane pane_; * CartesianRenderer rend = ((CartesianGraph)pane_.getFirstLayer().getGraph()).getRenderer(); * ... * GridAttributeDialog gad = new GridAttributeDialog(); * gad.setJPane(pane_); * gad.setGridCartesianRenderer((GridCartesianRenderer)rend); * gad.setVisible(true); * </pre> * * @author Donald Denbo * @version $Revision: 1.2 $, $Date: 2006/01/19 14:45:50 $ * @since 2.0 * @see NewLevelsDialog * @see ContourLineAttributeDialog * @see DefaultContourLineAttributeDialog */ public class GridAttributeDialog extends JDialog { private GridAttribute attr_; private ContourLevels conLevels_; private ColorMap colorMap_; private JPane[] paneList_ = null; private int contourLevelIndex_ = 0; private int colorMapIndex_ = 1; private JTable conLevelTable_; private ConLevelTableModel conLevelModel_; private SGTGrid grid_ = null; private JToggleButton[] colorButtons_ = new JToggleButton[256]; /** * Constructor. */ public GridAttributeDialog(Frame parent) { super(parent); try { jbInit(); pack(); } catch(Exception ex) { ex.printStackTrace(); } } void jbInit() throws Exception { getContentPane().setLayout(new BorderLayout(0,0)); setSize(516,374); setVisible(false); mainPanel.setPreferredSize(new Dimension(516, 36)); getContentPane().add(TabbedPane, "Center"); ContourLevelsPanel.setLayout(new BorderLayout(0,0)); TabbedPane.add(ContourLevelsPanel, "ContourLevelsPanel"); ContourLevelsPanel.setBounds(2,27,511,271); ContourLevelsPanel.setVisible(false); ContourLevelsPanel.add(gridScrollPane, "Center"); controlPanel.setLayout(new GridBagLayout()); ContourLevelsPanel.add(controlPanel, "East"); JPanel1.setBorder(titledBorder1); JPanel1.setLayout(new GridBagLayout()); controlPanel.add(JPanel1, new GridBagConstraints(0,1,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(5,0,0,0),0,0)); editButton.setToolTipText("Edit attribute of selected level."); editButton.setText("Edit Attribute"); editButton.setActionCommand("Change Value"); JPanel1.add(editButton, new GridBagConstraints(0,0,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(5,5,0,5),0,0)); aboveButton.setToolTipText("Insert level above selected level."); aboveButton.setText("Insert Level Above"); aboveButton.setActionCommand("Before Item"); JPanel1.add(aboveButton, new GridBagConstraints(0,1,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(2,5,0,5),0,0)); belowButton.setToolTipText("Insert level below selected level."); belowButton.setText("Insert Level Below"); belowButton.setActionCommand("After Item"); JPanel1.add(belowButton, new GridBagConstraints(0,2,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(2,5,0,5),0,0)); deleteButton.setToolTipText("Delete the selected level."); deleteButton.setText("Delete Level"); deleteButton.setActionCommand("Delete Item"); JPanel1.add(deleteButton, new GridBagConstraints(0,3,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(2,5,2,5),0,0)); JPanel4.setBorder(titledBorder4); JPanel4.setLayout(new GridBagLayout()); controlPanel.add(JPanel4, new GridBagConstraints(0,3,1,1,0.0,0.0, GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(5,0,0,0),0,0)); defaultButton.setToolTipText("Edit default attributes."); defaultButton.setText("Edit Default Attributes"); defaultButton.setActionCommand("Edit Default Attributes"); JPanel4.add(defaultButton, new GridBagConstraints(0,0,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(2,5,2,5),0,0)); sortButton.setToolTipText("Sort levels by value."); sortButton.setText("Sort Levels"); sortButton.setActionCommand("Sort"); controlPanel.add(sortButton, new GridBagConstraints(0,4,1,1,0.0,0.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(5,5,5,5),0,0)); newConLevelButton.setToolTipText("Create new contour level set."); newConLevelButton.setText("New..."); newConLevelButton.setActionCommand("New..."); controlPanel.add(newConLevelButton, new GridBagConstraints(0,0,1,1,1.0,0.0, GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(5,5,0,5),0,0)); ColorMapPanel.setLayout(new BorderLayout(0,0)); TabbedPane.add(ColorMapPanel, "ColorMapPanel"); ColorMapPanel.setBounds(2,27,511,271); ColorMapPanel.setVisible(false); colorControlPanel.setLayout(new GridBagLayout()); ColorMapPanel.add(colorControlPanel, "East"); colorMapPanel.setBorder(titledBorder2); colorMapPanel.setLayout(new GridBagLayout()); colorControlPanel.add(colorMapPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0)); newColorMapButton.setToolTipText("Create new color map."); newColorMapButton.setText("New..."); newColorMapButton.setActionCommand("New..."); colorMapPanel.add(newColorMapButton, new GridBagConstraints(0,0,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0)); loadColorMapButton.setToolTipText("Load color map from disk."); loadColorMapButton.setText("Load..."); loadColorMapButton.setActionCommand("Load..."); colorMapPanel.add(loadColorMapButton, new GridBagConstraints(0,1,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0)); saveColorMapButton.setToolTipText("Save color map to disk."); saveColorMapButton.setText("Save..."); saveColorMapButton.setActionCommand("Save..."); colorMapPanel.add(saveColorMapButton, new GridBagConstraints(0,2,1,1,0.0,0.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0)); colorPanel.setLayout(new CardLayout(0,0)); ColorMapPanel.add(colorPanel, "Center"); CLIndexedPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5)); colorPanel.add("CLIndexed", CLIndexedPanel); CLTransformPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5)); colorPanel.add("CLTransform", CLTransformPanel); CLTransformPanel.setVisible(false); IndexedPanel.setLayout(new GridBagLayout()); colorPanel.add("Indexed", IndexedPanel); IndexedPanel.setVisible(false); colorButtonsPanel.setLayout(new GridLayout(16,16,1,1)); IndexedPanel.add(colorButtonsPanel, new GridBagConstraints(0,0,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(0,0,0,0),0,0)); TransformPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5)); colorPanel.add("Transform", TransformPanel); TransformPanel.setVisible(false); TabbedPane.setSelectedComponent(ContourLevelsPanel); TabbedPane.setSelectedIndex(0); TabbedPane.setTitleAt(0,"Contour Levels"); TabbedPane.setTitleAt(1,"Color Map"); buttonPanel.setBorder(etchedBorder1); buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5)); getContentPane().add(buttonPanel, "South"); okButton.setText("OK"); okButton.setActionCommand("OK"); buttonPanel.add(okButton); applyButton.setText("Apply"); applyButton.setActionCommand("Apply"); buttonPanel.add(applyButton); cancelButton.setText("Cancel"); cancelButton.setActionCommand("Cancel"); buttonPanel.add(cancelButton); mainPanel.setLayout(new GridBagLayout()); getContentPane().add(mainPanel, "North"); JLabel5.setText("Grid Style:"); mainPanel.add(JLabel5, new GridBagConstraints(0,0,1,1,0.0,0.0, GridBagConstraints.EAST,GridBagConstraints.NONE,new Insets(5,5,0,5),0,0)); gridStyleComboBox.setModel(stringComboBoxModel1); mainPanel.add(gridStyleComboBox, new GridBagConstraints(1,0,1,1,0.0,0.0, GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,5,5,5),0,0)); { String[] tempString = new String[5]; tempString[0] = "RASTER"; tempString[1] = "AREA_FILL"; tempString[2] = "CONTOUR"; tempString[3] = "RASTER_CONTOUR"; tempString[4] = "AREA_FILL_CONTOUR"; for(int i=0; i < tempString.length; i++) { stringComboBoxModel1.addElement(tempString[i]); } } gridStyleComboBox.setSelectedIndex(0); setTitle("GridAttribute Properties"); SymWindow aSymWindow = new SymWindow(); this.addWindowListener(aSymWindow); SymAction lSymAction = new SymAction(); cancelButton.addActionListener(lSymAction); okButton.addActionListener(lSymAction); applyButton.addActionListener(lSymAction); gridStyleComboBox.addActionListener(lSymAction); newConLevelButton.addActionListener(lSymAction); newColorMapButton.addActionListener(lSymAction); loadColorMapButton.addActionListener(lSymAction); editButton.addActionListener(lSymAction); aboveButton.addActionListener(lSymAction); belowButton.addActionListener(lSymAction); deleteButton.addActionListener(lSymAction); sortButton.addActionListener(lSymAction); saveColorMapButton.addActionListener(lSymAction); defaultButton.addActionListener(lSymAction); makeColorToggleButtons(); } private void makeColorToggleButtons() { Insets insets = new Insets(0,0,0,0); ButtonGroup bg = new ButtonGroup(); ColorSwatchIcon csi = null; for(int i=0; i < 256; i++) { JToggleButton tb = new JToggleButton(""); if(System.getProperty("mrj.version") == null || !UIManager.getSystemLookAndFeelClassName().equals(UIManager.getLookAndFeel().getClass().getName())) tb.setMargin(insets); csi = new ColorSwatchIcon(Color.white, 8, 8); tb.setIcon(csi); colorButtons_[i] = tb; colorButtonsPanel.add(tb); bg.add(tb); } } /** Used internally. */ public void addNotify() { // Record the size of the window prior to calling parents addNotify. Dimension d = getSize(); super.addNotify(); if (fComponentsAdjusted) return; // Adjust components according to the insets Insets ins = getInsets(); setSize(ins.left + ins.right + d.width, ins.top + ins.bottom + d.height); Component components[] = getContentPane().getComponents(); for (int i = 0; i < components.length; i++) { Point p = components[i].getLocation(); p.translate(ins.left, ins.top); components[i].setLocation(p); } fComponentsAdjusted = true; } // Used for addNotify check. boolean fComponentsAdjusted = false; /** * Constructor. */ public GridAttributeDialog(String title) { this(); setTitle(title); } /** * Default constructor. */ public GridAttributeDialog() { this((Frame)null); } /** * Make the dialog visible. */ public void setVisible(boolean b) { if(b) { setLocation(50, 50); } super.setVisible(b); } class SymWindow extends java.awt.event.WindowAdapter { public void windowClosing(java.awt.event.WindowEvent event) { Object object = event.getSource(); if (object == GridAttributeDialog.this) GridAttributeDialog_WindowClosing(event); } } void GridAttributeDialog_WindowClosing(java.awt.event.WindowEvent event) { dispose(); } //{{DECLARE_CONTROLS javax.swing.JTabbedPane TabbedPane = new javax.swing.JTabbedPane(); javax.swing.JPanel ContourLevelsPanel = new javax.swing.JPanel(); javax.swing.JScrollPane gridScrollPane = new javax.swing.JScrollPane(); javax.swing.JPanel controlPanel = new javax.swing.JPanel(); javax.swing.JPanel JPanel1 = new javax.swing.JPanel(); javax.swing.JButton editButton = new javax.swing.JButton(); javax.swing.JButton aboveButton = new javax.swing.JButton(); javax.swing.JButton belowButton = new javax.swing.JButton(); javax.swing.JButton deleteButton = new javax.swing.JButton(); javax.swing.JPanel JPanel4 = new javax.swing.JPanel(); javax.swing.JButton defaultButton = new javax.swing.JButton(); javax.swing.JButton sortButton = new javax.swing.JButton(); javax.swing.JButton newConLevelButton = new javax.swing.JButton(); javax.swing.JPanel ColorMapPanel = new javax.swing.JPanel(); javax.swing.JPanel colorControlPanel = new javax.swing.JPanel(); javax.swing.JPanel colorMapPanel = new javax.swing.JPanel(); javax.swing.JButton newColorMapButton = new javax.swing.JButton(); javax.swing.JButton loadColorMapButton = new javax.swing.JButton(); javax.swing.JButton saveColorMapButton = new javax.swing.JButton(); javax.swing.JPanel colorPanel = new javax.swing.JPanel(); javax.swing.JPanel CLIndexedPanel = new javax.swing.JPanel(); javax.swing.JPanel CLTransformPanel = new javax.swing.JPanel(); javax.swing.JPanel IndexedPanel = new javax.swing.JPanel(); javax.swing.JPanel colorButtonsPanel = new javax.swing.JPanel(); javax.swing.JPanel TransformPanel = new javax.swing.JPanel(); javax.swing.JPanel buttonPanel = new javax.swing.JPanel(); javax.swing.JButton okButton = new javax.swing.JButton(); javax.swing.JButton applyButton = new javax.swing.JButton(); javax.swing.JButton cancelButton = new javax.swing.JButton(); javax.swing.JPanel mainPanel = new javax.swing.JPanel(); javax.swing.JLabel JLabel5 = new javax.swing.JLabel(); javax.swing.JComboBox gridStyleComboBox = new javax.swing.JComboBox(); javax.swing.border.EtchedBorder etchedBorder1 = new javax.swing.border.EtchedBorder(); DefaultComboBoxModel stringComboBoxModel1 = new DefaultComboBoxModel(); javax.swing.border.EtchedBorder etchedBorder2 = new javax.swing.border.EtchedBorder(); javax.swing.border.TitledBorder titledBorder1 = new javax.swing.border.TitledBorder("Contour Level"); javax.swing.border.EmptyBorder emptyBorder1 = new javax.swing.border.EmptyBorder(5,0,0,0); javax.swing.border.TitledBorder titledBorder4 = new javax.swing.border.TitledBorder("Default Attributes"); javax.swing.border.TitledBorder titledBorder2 = new javax.swing.border.TitledBorder("Color Map"); //}} class SymAction implements java.awt.event.ActionListener { public void actionPerformed(java.awt.event.ActionEvent event) { Object object = event.getSource(); if (object == cancelButton) cancelButton_actionPerformed(event); else if (object == okButton) okButton_actionPerformed(event); else if (object == applyButton) applyButton_actionPerformed(event); else if (object == gridStyleComboBox) gridStyleComboBox_actionPerformed(event); if (object == newConLevelButton) newConLevelButton_actionPerformed(event); if (object == newColorMapButton) newColorMapButton_actionPerformed(event); else if (object == loadColorMapButton) loadColorMapButton_actionPerformed(event); else if (object == editButton) editButton_actionPerformed(event); else if (object == aboveButton) aboveButton_actionPerformed(event); else if (object == belowButton) belowButton_actionPerformed(event); else if (object == deleteButton) deleteButton_actionPerformed(event); else if (object == sortButton) sortButton_actionPerformed(event); else if (object == saveColorMapButton) saveColorMapButton_actionPerformed(event); else if (object == defaultButton) defaultButton_actionPerformed(event); } } void cancelButton_actionPerformed(java.awt.event.ActionEvent event) { this.setVisible(false); } void okButton_actionPerformed(java.awt.event.ActionEvent event) { updateGridAttribute(); this.setVisible(false); } void applyButton_actionPerformed(java.awt.event.ActionEvent event) { updateGridAttribute(); } /** * Set the parent <code>JPane</code>. This reference to * <code>JPane</code> is used to enable/disable * {@link gov.noaa.pmel.sgt.JPane#setBatch(boolean) batching} so * multiple property changes are made at one time. */ public void setJPane(JPane pane) { paneList_ = new JPane[1]; paneList_[0] = pane; } /** * Get the first parent pane. */ public JPane getJPane() { if(paneList_ != null) { return paneList_[0]; } else { return null; } } /** * Set the parent <code>JPane</code>s. These references to * <code>JPane</code> are used to enable/disable * {@link gov.noaa.pmel.sgt.JPane#setBatch(boolean) batching} so * multiple property changes are made at one time. A second * <code>JPane</code> is often used for a <code>ColorKey</code>. */ public void setJPaneList(JPane[] list) { paneList_ = list; } /** Get an array of parent panes. */ public JPane[] getJPaneList() { return paneList_; } /** * Set the <code>GridCartesianRenderer</code>. Specifying the * renderer give <code>GridAttributeDialog</code> a reference to the * data and <code>GridAttribute</code> allowing automated * computation of <code>ColorMap</code> and * <code>ContourLevels</code> ranges. * * @see #setGridAttribute(GridAttribute) */ public void setGridCartesianRenderer(GridCartesianRenderer render) { grid_ = render.getGrid(); setGridAttribute((GridAttribute)render.getAttribute()); } /** * Set the <code>GridAttribute</code>. */ public void setGridAttribute(GridAttribute attr) { attr_ = attr; colorMap_ = attr.getColorMap(); conLevels_ = attr.getContourLevels(); // // style // int style = attr_.getStyle(); gridStyleComboBox.setSelectedIndex(style); // // contour ? // enableContourLevels(style); initContourLevels(); // // raster ? // enableColorMap(style); initColorMap(); // setCurrentTab(); } private void enableContourLevels(int style) { boolean isContour = (style == GridAttribute.CONTOUR || style == GridAttribute.RASTER_CONTOUR || style == GridAttribute.AREA_FILL_CONTOUR); TabbedPane.setEnabledAt(contourLevelIndex_, isContour); Component[] list = ContourLevelsPanel.getComponents(); boolean clExists = conLevels_ != null; for(int i=0; i < list.length; i++) { list[i].setEnabled(clExists); } newConLevelButton.setEnabled(true); } private void enableColorMap(int style) { boolean isRaster = style != GridAttribute.CONTOUR; TabbedPane.setEnabledAt(colorMapIndex_, isRaster); Component[] list = ColorMapPanel.getComponents(); boolean cmExists = colorMap_ != null; for(int i=0; i < list.length; i++) { list[i].setEnabled(cmExists); } newColorMapButton.setEnabled(true); } private void setCurrentTab() { if(!TabbedPane.isEnabledAt(TabbedPane.getSelectedIndex())) { // // change to other tab // if(TabbedPane.getSelectedIndex() == colorMapIndex_) { TabbedPane.setSelectedIndex(contourLevelIndex_); } else { TabbedPane.setSelectedIndex(colorMapIndex_); } } } private void initContourLevels() { createConLevelTable(); } private void initColorMap() { ColorSwatchIcon csi; int i; if(colorMap_ instanceof IndexedColor) { int maxindx = ((IndexedColor)colorMap_).getMaximumIndex(); for(i=0; i <= maxindx; i++) { csi = new ColorSwatchIcon((IndexedColor)colorMap_, i, 8); colorButtons_[i].setIcon(csi); colorButtons_[i].setEnabled(true); } for(i=maxindx+1; i < 256; i++) { csi = new ColorSwatchIcon(Color.white, 8, 8); colorButtons_[i].setIcon(csi); colorButtons_[i].setEnabled(false); } ((CardLayout)colorPanel.getLayout()).show(colorPanel, "Indexed"); } } void updateGridAttribute() { if(paneList_ != null) { for(int i=0; i < paneList_.length; i++) { paneList_[i].setBatch(true, "GridAttributeDialog"); } } updateConLevels(); attr_.setContourLevels(conLevels_); attr_.setColorMap(colorMap_); attr_.setStyle(gridStyleComboBox.getSelectedIndex()); if(paneList_ != null) { for(int i=0; i < paneList_.length; i++) { paneList_[i].setBatch(false, "GridAttributeDialog"); } } } /** * Test entry point. */ public static void main(String[] args) { Range2D range = new Range2D(-20.0f, 45.0f, 5.0f); ContourLevels clevels = ContourLevels.getDefault(range); GridAttribute attr = new GridAttribute(clevels); GridAttributeDialog la = new GridAttributeDialog(); la.setGridAttribute(attr); la.setTitle("Test GridAttribute Dialog"); la.setVisible(true); } void gridStyleComboBox_actionPerformed(java.awt.event.ActionEvent event) { int style = gridStyleComboBox.getSelectedIndex(); // enableContourLevels(style); enableColorMap(style); setCurrentTab(); // } void newConLevelButton_actionPerformed(java.awt.event.ActionEvent event) { NewLevelsDialog nld = new NewLevelsDialog(); int result = nld.showDialog(grid_); if(result == NewLevelsDialog.OK_RESPONSE) { Range2D range = nld.getRange(); conLevels_ = ContourLevels.getDefault(range); initContourLevels(); } } void newColorMapButton_actionPerformed(java.awt.event.ActionEvent event) { // // this will be replaced by a specialized dialog // // // define default colormap (ps.64) // int[] red = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 23, 39, 55, 71, 87,103, 119,135,151,167,183,199,215,231, 247,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255, 255,246,228,211,193,175,158,140}; int[] green = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 27, 43, 59, 75, 91,107, 123,139,155,171,187,203,219,235, 251,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255, 255,247,231,215,199,183,167,151, 135,119,103, 87, 71, 55, 39, 23, 7, 0, 0, 0, 0, 0, 0, 0}; int[] blue = { 0,143,159,175,191,207,223,239, 255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255, 255,247,231,215,199,183,167,151, 135,119,103, 87, 71, 55, 39, 23, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // colorMap_ = new IndexedColorMap(red, green, blue); ((IndexedColorMap)colorMap_).setTransform(new LinearTransform(0.0, (double)red.length, 0.0, 1.0)); initColorMap(); } void loadColorMapButton_actionPerformed(ActionEvent event) { int[] r = new int[256]; int[] g = new int[256]; int[] b = new int[256]; int lastindx = -1; File file = null; StreamTokenizer st = null; JFileChooser chooser = new JFileChooser("C:/local/pal"); int returnVal = chooser.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { file = chooser.getSelectedFile(); try { Reader rdr = new BufferedReader(new FileReader(file)); st = new StreamTokenizer(rdr); } catch (java.io.FileNotFoundException e) { System.out.println(e); return; } try { st.nextToken(); while(st.ttype != StreamTokenizer.TT_EOF) { lastindx++; if(st.ttype == StreamTokenizer.TT_NUMBER) { r[lastindx] = (int)st.nval; st.nextToken(); g[lastindx] = (int)st.nval; st.nextToken(); b[lastindx] = (int)st.nval; } if(st.nextToken() == StreamTokenizer.TT_EOL) st.nextToken(); } } catch (java.io.IOException e) { System.out.println(e); } int[] red = new int[lastindx+1]; int[] green = new int[lastindx+1]; int[] blue = new int[lastindx+1]; for(int i=0; i <= lastindx; i++) { red[i] = r[i]; green[i] = g[i]; blue[i] = b[i]; } colorMap_ = new IndexedColorMap(red, green, blue); ((IndexedColorMap)colorMap_).setTransform(new LinearTransform(0.0, (double)red.length, 0.0, 1.0)); initColorMap(); } } void editButton_actionPerformed(java.awt.event.ActionEvent event) { ContourLineAttribute attr; int index = conLevelTable_.getSelectedRow(); if(index < 0) return; ContourLineAttributeDialog clad = new ContourLineAttributeDialog(); attr = (ContourLineAttribute) ((ContourLineAttribute)conLevelModel_.getValueAt(index,1)).copy(); int result = clad.showDialog(attr); if(result == ContourLineAttributeDialog.OK_RESPONSE) { attr = clad.getContourLineAttribute(); conLevelModel_.setValueAt(attr, index, 1); } } void aboveButton_actionPerformed(java.awt.event.ActionEvent event) { int index = conLevelTable_.getSelectedRow(); if(index < 0) return; conLevelModel_.insert(index, new Double(0.0), new ContourLineAttribute(ContourLineAttribute.SOLID)); } void belowButton_actionPerformed(java.awt.event.ActionEvent event) { int index = conLevelTable_.getSelectedRow(); if(index < 0) return; conLevelModel_.insert(index + 1, new Double(0.0), new ContourLineAttribute(ContourLineAttribute.SOLID)); } void deleteButton_actionPerformed(java.awt.event.ActionEvent event) { int index = conLevelTable_.getSelectedRow(); if(index < 0) return; conLevelModel_.remove(index); } void sortButton_actionPerformed(java.awt.event.ActionEvent event) { conLevelModel_.sort(); } void defaultButton_actionPerformed(java.awt.event.ActionEvent event) { DefaultContourLineAttribute attr; DefaultContourLineAttributeDialog dclad = new DefaultContourLineAttributeDialog(); attr = conLevels_.getDefaultContourLineAttribute(); int result = dclad.showDialog((DefaultContourLineAttribute)attr.copy()); if(result == DefaultContourLineAttributeDialog.OK_RESPONSE) { attr = dclad.getDefaultContourLineAttribute(); conLevels_.setDefaultContourLineAttribute(attr); } } void saveColorMapButton_actionPerformed(java.awt.event.ActionEvent event) { // to do: code goes here. } void createConLevelTable() { Double val; ContourLineAttribute attr; conLevelModel_ = new ConLevelTableModel(); conLevelTable_ = new JTable(conLevelModel_); conLevelTable_.setSize(1000,1000); ListSelectionModel lsm = conLevelTable_.getSelectionModel(); lsm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); TableColumn tc; tc = conLevelTable_.getColumnModel().getColumn(0); tc.setPreferredWidth(250); tc = conLevelTable_.getColumnModel().getColumn(1); tc.setPreferredWidth(750); gridScrollPane.getViewport().add(conLevelTable_); // if(conLevels_ == null) return; int size = conLevels_.size(); for(int i=0; i < size; i++) { try { val = new Double(conLevels_.getLevel(i)); attr = conLevels_.getContourLineAttribute(i); conLevelModel_.add(val, attr); } catch (ContourLevelNotFoundException e) { System.out.println(e); } } } private void updateConLevels() { if(conLevels_ == null) return; ContourLevels cl = new ContourLevels(); Double val; ContourLineAttribute attr; conLevelModel_.sort(); int size = conLevelModel_.getRowCount(); for(int i=0; i < size; i++) { val = (Double)conLevelModel_.getValueAt(i,0); attr = (ContourLineAttribute)conLevelModel_.getValueAt(i,1); cl.addLevel(val.doubleValue(), attr); } cl.setDefaultContourLineAttribute(conLevels_.getDefaultContourLineAttribute()); conLevels_ = cl; } class ConLevelTableModel extends AbstractTableModel { Vector values = new Vector(); Vector attr = new Vector(); String[] titles = {"Value", "Attribute"}; public void add(Double val, ContourLineAttribute cla) { values.addElement(val); attr.addElement(cla); } public void insert(int row, Double val, ContourLineAttribute cla) { values.insertElementAt(val, row); attr.insertElementAt(cla, row); fireTableChanged(new TableModelEvent(this, row, row, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT)); } public void remove(int row) { values.removeElementAt(row); attr.removeElementAt(row); fireTableChanged(new TableModelEvent(this, row, row, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE)); } public void sort() { // // use brain-dead bubble sort (there will be few lines) // int i, temp; int size = values.size(); Double a, b; int[] index = new int[size]; boolean flipped = true; for(i=0; i < size; i++) { index[i] = i; } while(flipped) { flipped = false; for(i=0; i < size-1; i++) { a = (Double)values.elementAt(index[i]); b = (Double)values.elementAt(index[i+1]); if(a.doubleValue() > b.doubleValue()) { // if(a.compareTo(b) > 0) { // jdk1.2 temp = index[i]; index[i] = index[i+1]; index[i+1] = temp; flipped = true; } } } Vector oldValues = values; Vector oldAttr = attr; values = new Vector(size); attr = new Vector(size); for(i=0; i < size; i++) { values.addElement(oldValues.elementAt(index[i])); attr.addElement(oldAttr.elementAt(index[i])); } fireTableChanged(new TableModelEvent(this)); } public Object getValueAt(int row, int col) { if(col == 0) { return values.elementAt(row); } else { return attr.elementAt(row); } } public void setValueAt(Object obj, int row, int col) { if(col == 0) { if(obj instanceof Double) { values.setElementAt(obj, row); } else if(obj instanceof String) { values.setElementAt(new Double((String)obj), row); } } else { attr.setElementAt(obj, row); } fireTableCellUpdated(row, col); } public int getRowCount() { return values.size(); } public int getColumnCount() { return 2; } public String getColumnName(int col) { return titles[col]; } public boolean isCellEditable(int row, int col) { return col == 0; } } }
bsd-3-clause
wukchung/Home-development
documentation/api/core/db_Form_Decorator_Form.html
24599
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link><script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script><script type="text/javascript" src="js/jquery.cookie.js"></script><script type="text/javascript" src="js/jquery.treeview.js"></script><script type="text/javascript"> $(document).ready(function() { $(".filetree").treeview({ collapsed: true, persist: "cookie" }); $("#accordion").accordion({ collapsible: true, autoHeight: false, fillSpace: true }); $(".tabs").tabs(); }); </script></head><body><div xmlns="" class="content"> <div class="sub-page-main-header-api-documentation"><h2>API Documentation</h2></div> <div class="dotted-line"></div> </div> <div xmlns="" id="content"> <script type="text/javascript" src="js/menu.js"></script><script> $(document).ready(function() { $('a.gripper').click(function() { $(this).nextAll('div.code-tabs').slideToggle(); $(this).children('img').toggle(); return false; }); $('div.code-tabs').hide(); $('a.gripper').show(); $('div.file-nav').show(); }); </script><h1 class="file">Form/Decorator/Form.php</h1> <div class="file-nav"><ul id="file-nav"> <li><a href="#top">Global</a></li> <li> <a href="#classes"><img src="images/icons/class.png" height="14"> Classes </a><ul><li><a href="#%5CZend_Form_Decorator_Form">\Zend_Form_Decorator_Form</a></li></ul> </li> </ul></div> <a name="top"></a><div id="file-description"> <p class="short-description">Zend Framework</p> <div class="long-description"><p>LICENSE</p> <p>This source file is subject to the new BSD license that is bundled with this package in the file LICENSE.txt. It is also available through the world-wide-web at this URL: http://framework.zend.com/license/new-bsd If you did not receive a copy of the license and are unable to obtain it through the world-wide-web, please send an email to [email protected] so we can send you a copy immediately.</p> </div> </div> <dl class="file-info"> <dt>category</dt> <dd>Zend   </dd> <dt>copyright</dt> <dd>Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)   </dd> <dt>license</dt> <dd> <a href="http://framework.zend.com/license/new-bsd">New BSD License</a>   </dd> <dt>package</dt> <dd>Zend_Form   </dd> <dt>subpackage</dt> <dd>Decorator   </dd> </dl> <a name="classes"></a><a id="\Zend_Form_Decorator_Form"></a><h2 class="class">\Zend_Form_Decorator_Form<div class="to-top"><a href="#top">jump to top</a></div> </h2> <div class="class"> <p class="short-description">Zend_Form_Decorator_Form</p> <div class="long-description"><p>Render a Zend_Form object.</p> <p>Accepts following options: - separator: Separator to use between elements - helper: which view helper to use when rendering form. Should accept three arguments, string content, a name, and an array of attributes.</p> <p>Any other options passed will be used as HTML attributes of the form tag.</p> </div> <dl class="class-info"> <dt>Extends from</dt> <dd><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></dd> <dt>category</dt> <dd>Zend   </dd> <dt>copyright</dt> <dd>Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)   </dd> <dt>license</dt> <dd> <a href="http://framework.zend.com/license/new-bsd">New BSD License</a>   </dd> <dt>package</dt> <dd>Zend_Form   </dd> <dt>subpackage</dt> <dd>Decorator   </dd> <dt>version</dt> <dd>$Id: Form.php 23775 2011-03-01 17:25:24Z ralph $   </dd> </dl> <h3>Properties</h3> <div> <a id="\Zend_Form_Decorator_Form::$_helper"></a><div class="property"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected">string  <span class="highlight">$_helper</span>= 'form' </code><div class="description"> <p class="short-description">Default view helper</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Default value</strong><code>form</code><strong>Details</strong><dl class="property-info"> <dt>Type</dt> <dd>string</dd> </dl> </div> <div class="clear"></div> </div> </div> <h3>Methods</h3> <div> <a id="\Zend_Form_Decorator_Form::__construct()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">__construct</span><span class="nb-faded-text">( array|\Zend_Config $options = null ) </span> : void</code><div class="description"> <p class="short_description">Constructor</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::__construct()">\Zend_Form_Decorator_Abstract::__construct()</a></small> </div> <div class="code-tabs"> <div class="long-description"><p>Accept options during initialization.</p> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$options</th> <td>array|\Zend_Config</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::clearOptions()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">clearOptions</span><span class="nb-faded-text">( ) </span> : <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></code><div class="description"> <p class="short_description">Clear all options</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::clearOptions()">\Zend_Form_Decorator_Abstract::clearOptions()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::getElement()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getElement</span><span class="nb-faded-text">( ) </span> : <a href="db_Form_Element.html#%5CZend_Form_Element">\Zend_Form_Element</a>|<a href="db_Form.html#%5CZend_Form">\Zend_Form</a></code><div class="description"> <p class="short_description">Retrieve current element</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::getElement()">\Zend_Form_Decorator_Abstract::getElement()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td> <a href="db_Form_Element.html#%5CZend_Form_Element">\Zend_Form_Element</a><a href="db_Form.html#%5CZend_Form">\Zend_Form</a> </td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::getHelper()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getHelper</span><span class="nb-faded-text">( ) </span> : string</code><div class="description"><p class="short_description">Get view helper for rendering form</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>string</td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::getOption()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getOption</span><span class="nb-faded-text">( string $key ) </span> : mixed</code><div class="description"> <p class="short_description">Get option</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::getOption()">\Zend_Form_Decorator_Abstract::getOption()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$key</th> <td>string</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>mixed</td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::getOptions()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getOptions</span><span class="nb-faded-text">( ) </span> : array</code><div class="description"><p class="short_description">Retrieve decorator options</p></div> <div class="code-tabs"> <div class="long-description"><p>Assures that form action and method are set, and sets appropriate encoding type if current method is POST.</p> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>array</td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::getPlacement()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getPlacement</span><span class="nb-faded-text">( ) </span> : string</code><div class="description"> <p class="short_description">Determine if decorator should append or prepend content</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::getPlacement()">\Zend_Form_Decorator_Abstract::getPlacement()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>string</td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::getSeparator()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getSeparator</span><span class="nb-faded-text">( ) </span> : string</code><div class="description"> <p class="short_description">Retrieve separator to use between old and new content</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::getSeparator()">\Zend_Form_Decorator_Abstract::getSeparator()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>string</td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::removeOption()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">removeOption</span><span class="nb-faded-text">( mixed $key ) </span> : void</code><div class="description"> <p class="short_description">Remove single option</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::removeOption()">\Zend_Form_Decorator_Abstract::removeOption()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$key</th> <td>mixed</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::render()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">render</span><span class="nb-faded-text">( string $content ) </span> : string</code><div class="description"><p class="short_description">Render a form</p></div> <div class="code-tabs"> <div class="long-description"><p>Replaces $content entirely from currently set element.</p> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$content</th> <td>string</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>string</td> <td></td> </tr> </table> <strong>Throws</strong><table class="argument-info"> <thead><tr> <th>Exception</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Exception.html#%5CZend_Form_Decorator_Exception">\Zend_Form_Decorator_Exception</a></td> <td><em>when unimplemented</em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::setConfig()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setConfig</span><span class="nb-faded-text">( \Zend_Config $config ) </span> : <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></code><div class="description"> <p class="short_description">Set options from config object</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::setConfig()">\Zend_Form_Decorator_Abstract::setConfig()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$config</th> <td>\Zend_Config</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::setElement()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setElement</span><span class="nb-faded-text">( <a href="db_Form_Element.html#%5CZend_Form_Element">\Zend_Form_Element</a>|<a href="db_Form.html#%5CZend_Form">\Zend_Form</a> $element ) </span> : <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></code><div class="description"> <p class="short_description">Set current form element</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::setElement()">\Zend_Form_Decorator_Abstract::setElement()</a></small> </div> <div class="code-tabs"> <div class="long-description"><p>While the name is "setElement", a form decorator could decorate either an element or a form object.</p> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$element</th> <td> <a href="db_Form_Element.html#%5CZend_Form_Element">\Zend_Form_Element</a>|<a href="db_Form.html#%5CZend_Form">\Zend_Form</a> </td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></td> <td></td> </tr> </table> <strong>Throws</strong><table class="argument-info"> <thead><tr> <th>Exception</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Exception.html#%5CZend_Form_Decorator_Exception">\Zend_Form_Decorator_Exception</a></td> <td><em>on invalid element type</em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::setHelper()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setHelper</span><span class="nb-faded-text">( string $helper ) </span> : <a href="db_Form_Decorator_Form.html#%5CZend_Form_Decorator_Form">\Zend_Form_Decorator_Form</a></code><div class="description"><p class="short_description">Set view helper for rendering form</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$helper</th> <td>string</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Form.html#%5CZend_Form_Decorator_Form">\Zend_Form_Decorator_Form</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::setOption()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setOption</span><span class="nb-faded-text">( string $key, mixed $value ) </span> : <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></code><div class="description"> <p class="short_description">Set option</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::setOption()">\Zend_Form_Decorator_Abstract::setOption()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$key</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$value</th> <td>mixed</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_Form::setOptions()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setOptions</span><span class="nb-faded-text">( array $options ) </span> : <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></code><div class="description"> <p class="short_description">Set options</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::setOptions()">\Zend_Form_Decorator_Abstract::setOptions()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$options</th> <td>array</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> </div> </div> </div> <small xmlns="" class="footer">Documentation was generated by <a href="http://docblox-project.org">DocBlox 0.13.3</a>. </small></body></html>
bsd-3-clause
Chilledheart/chromium
net/proxy/proxy_service_v8.cc
1609
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy/proxy_service_v8.h" #include "base/logging.h" #include "base/thread_task_runner_handle.h" #include "base/threading/thread_checker.h" #include "net/proxy/network_delegate_error_observer.h" #include "net/proxy/proxy_resolver.h" #include "net/proxy/proxy_resolver_factory.h" #include "net/proxy/proxy_resolver_v8_tracing_wrapper.h" #include "net/proxy/proxy_service.h" namespace net { // static ProxyService* CreateProxyServiceUsingV8ProxyResolver( ProxyConfigService* proxy_config_service, ProxyScriptFetcher* proxy_script_fetcher, scoped_ptr<DhcpProxyScriptFetcher> dhcp_proxy_script_fetcher, HostResolver* host_resolver, NetLog* net_log, NetworkDelegate* network_delegate) { DCHECK(proxy_config_service); DCHECK(proxy_script_fetcher); DCHECK(dhcp_proxy_script_fetcher); DCHECK(host_resolver); ProxyService* proxy_service = new ProxyService( proxy_config_service, make_scoped_ptr(new ProxyResolverFactoryV8TracingWrapper( host_resolver, net_log, base::Bind(&NetworkDelegateErrorObserver::Create, network_delegate, base::ThreadTaskRunnerHandle::Get()))), net_log); // Configure fetchers to use for PAC script downloads and auto-detect. proxy_service->SetProxyScriptFetchers(proxy_script_fetcher, dhcp_proxy_script_fetcher.Pass()); return proxy_service; } } // namespace net
bsd-3-clause
wiccano/WDEPRDO
framework/PradoBase.php
19078
<?php /** * PradoBase class file. * * This is the file that establishes the PRADO component model * and error handling mechanism. * * @author Qiang Xue <[email protected]> * @link http://www.pradosoft.com/ * @copyright Copyright &copy; 2005-2011 PradoSoft * @license http://www.pradosoft.com/license/ * @version $Id: PradoBase.php 3168 2012-06-25 10:43:31Z ctrlaltca $ * @package System */ /** * Defines the PRADO framework installation path. */ if(!defined('PRADO_DIR')) define('PRADO_DIR',dirname(__FILE__)); /** * Defines the default permission for writable directories and files */ if(!defined('PRADO_CHMOD')) define('PRADO_CHMOD',0777); /** * PradoBase class. * * PradoBase implements a few fundamental static methods. * * To use the static methods, Use Prado as the class name rather than PradoBase. * PradoBase is meant to serve as the base class of Prado. The latter might be * rewritten for customization. * * @author Qiang Xue <[email protected]> * @version $Id: PradoBase.php 3168 2012-06-25 10:43:31Z ctrlaltca $ * @package System * @since 3.0 */ class PradoBase { /** * File extension for Prado class files. */ const CLASS_FILE_EXT='.php'; /** * @var array list of path aliases */ private static $_aliases=array('System'=>PRADO_DIR); /** * @var array list of namespaces currently in use */ private static $_usings=array(); /** * @var TApplication the application instance */ private static $_application=null; /** * @var TLogger logger instance */ private static $_logger=null; /** * @var array list of class exists checks */ protected static $classExists = array(); /** * @return string the version of Prado framework */ public static function getVersion() { return '3.2.0'; } /** * Initializes error handlers. * This method set error and exception handlers to be functions * defined in this class. */ public static function initErrorHandlers() { /** * Sets error handler to be Prado::phpErrorHandler */ set_error_handler(array('PradoBase','phpErrorHandler')); /** * Sets exception handler to be Prado::exceptionHandler */ set_exception_handler(array('PradoBase','exceptionHandler')); } /** * Class autoload loader. * This method is provided to be invoked within an __autoload() magic method. * @param string class name */ public static function autoload($className) { include_once($className.self::CLASS_FILE_EXT); if(!class_exists($className,false) && !interface_exists($className,false)) self::fatalError("Class file for '$className' cannot be found."); } /** * @param integer the type of "powered logo". Valid values include 0 and 1. * @return string a string that can be displayed on your Web page showing powered-by-PRADO information */ public static function poweredByPrado($logoType=0) { $logoName=$logoType==1?'powered2':'powered'; if(self::$_application!==null) { $am=self::$_application->getAssetManager(); $url=$am->publishFilePath(self::getPathOfNamespace('System.'.$logoName,'.gif')); } else $url='http://www.pradosoft.com/images/'.$logoName.'.gif'; return '<a title="Powered by PRADO" href="http://www.pradosoft.com/" target="_blank"><img src="'.$url.'" style="border-width:0px;" alt="Powered by PRADO" /></a>'; } /** * PHP error handler. * This method should be registered as PHP error handler using * {@link set_error_handler}. The method throws an exception that * contains the error information. * @param integer the level of the error raised * @param string the error message * @param string the filename that the error was raised in * @param integer the line number the error was raised at */ public static function phpErrorHandler($errno,$errstr,$errfile,$errline) { if(error_reporting() & $errno) throw new TPhpErrorException($errno,$errstr,$errfile,$errline); } /** * Default exception handler. * This method should be registered as default exception handler using * {@link set_exception_handler}. The method tries to use the errorhandler * module of the Prado application to handle the exception. * If the application or the module does not exist, it simply echoes the * exception. * @param Exception exception that is not caught */ public static function exceptionHandler($exception) { if(self::$_application!==null && ($errorHandler=self::$_application->getErrorHandler())!==null) { $errorHandler->handleError(null,$exception); } else { echo $exception; } exit(1); } /** * Stores the application instance in the class static member. * This method helps implement a singleton pattern for TApplication. * Repeated invocation of this method or the application constructor * will cause the throw of an exception. * This method should only be used by framework developers. * @param TApplication the application instance * @throws TInvalidOperationException if this method is invoked twice or more. */ public static function setApplication($application) { if(self::$_application!==null) throw new TInvalidOperationException('prado_application_singleton_required'); self::$_application=$application; } /** * @return TApplication the application singleton, null if the singleton has not be created yet. */ public static function getApplication() { return self::$_application; } /** * @return string the path of the framework */ public static function getFrameworkPath() { return PRADO_DIR; } /** * Serializes a data. * The original PHP serialize function has a bug that may not serialize * properly an object. * @param mixed data to be serialized * @return string the serialized data */ public static function serialize($data) { return serialize($data); } /** * Unserializes a data. * The original PHP unserialize function has a bug that may not unserialize * properly an object. * @param string data to be unserialized * @return mixed unserialized data, null if unserialize failed */ public static function unserialize($str) { return unserialize($str); } /** * Creates a component with the specified type. * A component type can be either the component class name * or a namespace referring to the path of the component class file. * For example, 'TButton', 'System.Web.UI.WebControls.TButton' are both * valid component type. * This method can also pass parameters to component constructors. * All parameters passed to this method except the first one (the component type) * will be supplied as component constructor parameters. * @param string component type * @return TComponent component instance of the specified type * @throws TInvalidDataValueException if the component type is unknown */ public static function createComponent($type) { if(!isset(self::$classExists[$type])) self::$classExists[$type] = class_exists($type, false); if( !isset(self::$_usings[$type]) && !self::$classExists[$type]) { self::using($type); self::$classExists[$type] = class_exists($type, false); } if( ($pos = strrpos($type, '.')) !== false) $type = substr($type,$pos+1); if(($n=func_num_args())>1) { $args = func_get_args(); switch($n) { case 2: return new $type($args[1]); break; case 3: return new $type($args[1], $args[2]); break; case 4: return new $type($args[1], $args[2], $args[3]); break; case 5: return new $type($args[1], $args[2], $args[3], $args[4]); break; default: $s='$args[1]'; for($i=2;$i<$n;++$i) $s.=",\$args[$i]"; eval("\$component=new $type($s);"); return $component; break; } } else return new $type; } /** * Uses a namespace. * A namespace ending with an asterisk '*' refers to a directory, otherwise it represents a PHP file. * If the namespace corresponds to a directory, the directory will be appended * to the include path. If the namespace corresponds to a file, it will be included (include_once). * @param string namespace to be used * @param boolean whether to check the existence of the class after the class file is included * @throws TInvalidDataValueException if the namespace is invalid */ public static function using($namespace,$checkClassExistence=true) { if(isset(self::$_usings[$namespace]) || class_exists($namespace,false)) return; if(($pos=strrpos($namespace,'.'))===false) // a class name { try { include_once($namespace.self::CLASS_FILE_EXT); } catch(Exception $e) { if($checkClassExistence && !class_exists($namespace,false)) throw new TInvalidOperationException('prado_component_unknown',$namespace,$e->getMessage()); else throw $e; } } else if(($path=self::getPathOfNamespace($namespace,self::CLASS_FILE_EXT))!==null) { $className=substr($namespace,$pos+1); if($className==='*') // a directory { self::$_usings[$namespace]=$path; set_include_path(get_include_path().PATH_SEPARATOR.$path); } else // a file { self::$_usings[$namespace]=$path; if(!$checkClassExistence || !class_exists($className,false)) { try { include_once($path); } catch(Exception $e) { if($checkClassExistence && !class_exists($className,false)) throw new TInvalidOperationException('prado_component_unknown',$className,$e->getMessage()); else throw $e; } } } } else throw new TInvalidDataValueException('prado_using_invalid',$namespace); } /** * Translates a namespace into a file path. * The first segment of the namespace is considered as a path alias * which is replaced with the actual path. The rest segments are * subdirectory names appended to the aliased path. * If the namespace ends with an asterisk '*', it represents a directory; * Otherwise it represents a file whose extension name is specified by the second parameter (defaults to empty). * Note, this method does not ensure the existence of the resulting file path. * @param string namespace * @param string extension to be appended if the namespace refers to a file * @return string file path corresponding to the namespace, null if namespace is invalid */ public static function getPathOfNamespace($namespace, $ext='') { if(self::CLASS_FILE_EXT === $ext || empty($ext)) { if(isset(self::$_usings[$namespace])) return self::$_usings[$namespace]; if(isset(self::$_aliases[$namespace])) return self::$_aliases[$namespace]; } $segs = explode('.',$namespace); $alias = array_shift($segs); if(null !== ($file = array_pop($segs)) && null !== ($root = self::getPathOfAlias($alias))) return rtrim($root.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR ,$segs),'/\\').(($file === '*') ? '' : DIRECTORY_SEPARATOR.$file.$ext); return null; } /** * @param string alias to the path * @return string the path corresponding to the alias, null if alias not defined. */ public static function getPathOfAlias($alias) { return isset(self::$_aliases[$alias])?self::$_aliases[$alias]:null; } protected static function getPathAliases() { return self::$_aliases; } /** * @param string alias to the path * @param string the path corresponding to the alias * @throws TInvalidOperationException if the alias is already defined * @throws TInvalidDataValueException if the path is not a valid file path */ public static function setPathOfAlias($alias,$path) { if(isset(self::$_aliases[$alias])) throw new TInvalidOperationException('prado_alias_redefined',$alias); else if(($rp=realpath($path))!==false && is_dir($rp)) { if(strpos($alias,'.')===false) self::$_aliases[$alias]=$rp; else throw new TInvalidDataValueException('prado_aliasname_invalid',$alias); } else throw new TInvalidDataValueException('prado_alias_invalid',$alias,$path); } /** * Fatal error handler. * This method displays an error message together with the current call stack. * The application will exit after calling this method. * @param string error message */ public static function fatalError($msg) { echo '<h1>Fatal Error</h1>'; echo '<p>'.$msg.'</p>'; if(!function_exists('debug_backtrace')) return; echo '<h2>Debug Backtrace</h2>'; echo '<pre>'; $index=-1; foreach(debug_backtrace() as $t) { $index++; if($index==0) // hide the backtrace of this function continue; echo '#'.$index.' '; if(isset($t['file'])) echo basename($t['file']) . ':' . $t['line']; else echo '<PHP inner-code>'; echo ' -- '; if(isset($t['class'])) echo $t['class'] . $t['type']; echo $t['function'] . '('; if(isset($t['args']) && sizeof($t['args']) > 0) { $count=0; foreach($t['args'] as $item) { if(is_string($item)) { $str=htmlentities(str_replace("\r\n", "", $item), ENT_QUOTES); if (strlen($item) > 70) echo "'". substr($str, 0, 70) . "...'"; else echo "'" . $str . "'"; } else if (is_int($item) || is_float($item)) echo $item; else if (is_object($item)) echo get_class($item); else if (is_array($item)) echo 'array(' . count($item) . ')'; else if (is_bool($item)) echo $item ? 'true' : 'false'; else if ($item === null) echo 'NULL'; else if (is_resource($item)) echo get_resource_type($item); $count++; if (count($t['args']) > $count) echo ', '; } } echo ")\n"; } echo '</pre>'; exit(1); } /** * Returns a list of user preferred languages. * The languages are returned as an array. Each array element * represents a single language preference. The languages are ordered * according to user preferences. The first language is the most preferred. * @return array list of user preferred languages. */ public static function getUserLanguages() { static $languages=null; if($languages===null) { if(!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $languages[0]='en'; else { $languages=array(); foreach(explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']) as $language) { $array=explode(';q=',trim($language)); $languages[trim($array[0])]=isset($array[1])?(float)$array[1]:1.0; } arsort($languages); $languages=array_keys($languages); if(empty($languages)) $languages[0]='en'; } } return $languages; } /** * Returns the most preferred language by the client user. * @return string the most preferred language by the client user, defaults to English. */ public static function getPreferredLanguage() { static $language=null; if($language===null) { $langs=Prado::getUserLanguages(); $lang=explode('-',$langs[0]); if(empty($lang[0]) || !ctype_alpha($lang[0])) $language='en'; else $language=$lang[0]; } return $language; } /** * Writes a log message. * This method wraps {@link log()} by checking the application mode. * When the application is in Debug mode, debug backtrace information is appended * to the message and the message is logged at DEBUG level. * When the application is in Performance mode, this method does nothing. * Otherwise, the message is logged at INFO level. * @param string message to be logged * @param string category of the message * @param (string|TControl) control of the message * @see log, getLogger */ public static function trace($msg,$category='Uncategorized',$ctl=null) { if(self::$_application && self::$_application->getMode()===TApplicationMode::Performance) return; if(!self::$_application || self::$_application->getMode()===TApplicationMode::Debug) { $trace=debug_backtrace(); if(isset($trace[0]['file']) && isset($trace[0]['line'])) $msg.=" (line {$trace[0]['line']}, {$trace[0]['file']})"; $level=TLogger::DEBUG; } else $level=TLogger::INFO; self::log($msg,$level,$category,$ctl); } /** * Logs a message. * Messages logged by this method may be retrieved via {@link TLogger::getLogs} * and may be recorded in different media, such as file, email, database, using * {@link TLogRouter}. * @param string message to be logged * @param integer level of the message. Valid values include * TLogger::DEBUG, TLogger::INFO, TLogger::NOTICE, TLogger::WARNING, * TLogger::ERROR, TLogger::ALERT, TLogger::FATAL. * @param string category of the message * @param (string|TControl) control of the message */ public static function log($msg,$level=TLogger::INFO,$category='Uncategorized',$ctl=null) { if(self::$_logger===null) self::$_logger=new TLogger; self::$_logger->log($msg,$level,$category,$ctl); } /** * @return TLogger message logger */ public static function getLogger() { if(self::$_logger===null) self::$_logger=new TLogger; return self::$_logger; } /** * Converts a variable into a string representation. * This method achieves the similar functionality as var_dump and print_r * but is more robust when handling complex objects such as PRADO controls. * @param mixed variable to be dumped * @param integer maximum depth that the dumper should go into the variable. Defaults to 10. * @param boolean whether to syntax highlight the output. Defaults to false. * @return string the string representation of the variable */ public static function varDump($var,$depth=10,$highlight=false) { Prado::using('System.Util.TVarDumper'); return TVarDumper::dump($var,$depth,$highlight); } /** * Localize a text to the locale/culture specified in the globalization handler. * @param string text to be localized. * @param array a set of parameters to substitute. * @param string a different catalogue to find the localize text. * @param string the input AND output charset. * @return string localized text. * @see TTranslate::formatter() * @see TTranslate::init() */ public static function localize($text, $parameters=array(), $catalogue=null, $charset=null) { Prado::using('System.I18N.Translation'); $app = Prado::getApplication()->getGlobalization(false); $params = array(); foreach($parameters as $key => $value) $params['{'.$key.'}'] = $value; //no translation handler provided if($app===null || ($config = $app->getTranslationConfiguration())===null) return strtr($text, $params); if ($catalogue===null) $catalogue=isset($config['catalogue'])?$config['catalogue']:'messages'; Translation::init($catalogue); //globalization charset $appCharset = $app===null ? '' : $app->getCharset(); //default charset $defaultCharset = ($app===null) ? 'UTF-8' : $app->getDefaultCharset(); //fall back if(empty($charset)) $charset = $appCharset; if(empty($charset)) $charset = $defaultCharset; return Translation::formatter($catalogue)->format($text,$params,$catalogue,$charset); } } /** * Includes the classes essential for PradoBase class */ PradoBase::using('System.TComponent'); PradoBase::using('System.Exceptions.TException'); PradoBase::using('System.Util.TLogger');
bsd-3-clause
centip3de/GSoC
src/macports1.0/get_systemconfiguration_proxies.c
7575
/* * get_systemconfiguration_proxies.c * $Id: get_systemconfiguration_proxies.c 113342 2013-11-13 20:51:15Z [email protected] $ * * Copyright (c) 2008-2009, The MacPorts Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of MacPorts Team nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "get_systemconfiguration_proxies.h" #ifdef HAVE_FRAMEWORK_SYSTEMCONFIGURATION #include <CoreFoundation/CoreFoundation.h> #include <SystemConfiguration/SystemConfiguration.h> int appendProxyInformationForKeys( CFDictionaryRef proxies, Tcl_Obj *tclList, const char *listKey, const void *proxyEnabledKey, const void *proxyHostKey, const void *proxyPortKey ); char *cfStringToCStringASCII( CFStringRef cfString ); #endif /* HAVE_FRAMEWORK_SYSTEMCONFIGURATION */ /** * * Query SystemConfiguration for proxy information, returning this * information in a Tcl list ready to be 'array set' (key, name pairs). * * Synopsis: array set someArray get_systemconfiguration_proxies */ int GetSystemConfigurationProxiesCmd( ClientData clientData UNUSED, Tcl_Interp *interp, int objc UNUSED, Tcl_Obj *CONST objv[] UNUSED ) { int cmdResult = TCL_OK; #ifdef HAVE_FRAMEWORK_SYSTEMCONFIGURATION CFDictionaryRef proxies = SCDynamicStoreCopyProxies( NULL ); if( proxies != NULL ) { Tcl_Obj *proxyList = Tcl_NewListObj( 0, NULL ); if( appendProxyInformationForKeys( proxies, proxyList, "proxy_http", kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPProxy, kSCPropNetProxiesHTTPPort ) == 0 && appendProxyInformationForKeys( proxies, proxyList, "proxy_https", kSCPropNetProxiesHTTPSEnable, kSCPropNetProxiesHTTPSProxy, kSCPropNetProxiesHTTPSPort ) == 0 && appendProxyInformationForKeys( proxies, proxyList, "proxy_ftp", kSCPropNetProxiesFTPEnable, kSCPropNetProxiesFTPProxy, kSCPropNetProxiesFTPPort ) == 0 ) { CFArrayRef exceptionsCFArray = CFDictionaryGetValue( proxies, kSCPropNetProxiesExceptionsList ); if( exceptionsCFArray != NULL ) { CFStringRef exceptionsCFString = CFStringCreateByCombiningStrings( kCFAllocatorDefault, exceptionsCFArray, CFSTR( "," ) ); char *exceptionsString = cfStringToCStringASCII( exceptionsCFString ); if( exceptionsString != NULL ) { Tcl_Obj *exceptionsKey = Tcl_NewStringObj( "proxy_skip", 10 ); Tcl_Obj *exceptionsTclString = Tcl_NewStringObj( exceptionsString, strlen( exceptionsString ) ); Tcl_ListObjAppendElement( interp, proxyList, exceptionsKey ); Tcl_ListObjAppendElement( interp, proxyList, exceptionsTclString ); free( exceptionsString ); } else cmdResult = TCL_ERROR; CFRelease( exceptionsCFString ); } Tcl_SetObjResult( interp, proxyList ); } else cmdResult = TCL_ERROR; CFRelease( proxies ); } if( cmdResult == TCL_ERROR ) { Tcl_SetErrno( errno ); Tcl_SetResult( interp, (char *) Tcl_PosixError( interp ), TCL_STATIC ); } #endif return cmdResult; } #ifdef HAVE_FRAMEWORK_SYSTEMCONFIGURATION /** * * Extract the proxy information (given by proxyEnabledKey, proxyHostKey, * and proxyPortKey) from the proxies dictionary, then append listKey and * the pertinent proxy information to the Tcl list. * * Returns 0 on success; -1 on failure */ int appendProxyInformationForKeys( CFDictionaryRef proxies, Tcl_Obj *tclList, const char *listKey, const void *proxyEnabledKey, const void *proxyHostKey, const void *proxyPortKey ) { int result = 0; CFNumberRef proxyEnabledNumber = CFDictionaryGetValue( proxies, proxyEnabledKey ); int proxyEnabled = 0; if( proxyEnabledNumber != NULL && CFNumberGetValue( proxyEnabledNumber, kCFNumberIntType, &proxyEnabled ) && proxyEnabled ) { CFStringRef proxyHostString = CFDictionaryGetValue( proxies, proxyHostKey ); char *hostname = NULL; if( proxyHostString != NULL && ( hostname = cfStringToCStringASCII( proxyHostString ) ) != NULL ) { CFNumberRef proxyPortNumber = CFDictionaryGetValue( proxies, proxyPortKey ); int proxyPort = 0; if( proxyPortNumber != NULL && CFNumberGetValue( proxyPortNumber, kCFNumberIntType, &proxyPort ) && proxyPort > 0 ) { /* * We are adding :<port>\0 to the end, which is up to 7 * bytes additional (up to 5 for the port) */ size_t newLength = strlen( hostname ) + 7; char *hostnameAndPort = calloc( 1, newLength ); if( hostnameAndPort != NULL ) { Tcl_Obj *hostnameAndPortTcl; Tcl_Obj *listKeyTcl = Tcl_NewStringObj( listKey, strlen( listKey ) ); Tcl_ListObjAppendElement( NULL, tclList, listKeyTcl ); snprintf( hostnameAndPort, newLength, "%s:%d", hostname, proxyPort ); hostnameAndPortTcl = Tcl_NewStringObj( hostnameAndPort, strlen( hostnameAndPort ) ); Tcl_ListObjAppendElement( NULL, tclList, hostnameAndPortTcl ); free( hostnameAndPort ); } else result = -1; } else result = -1; } else result = -1; } return result; } /** * * Convert a CFStringRef to an ASCII-encoded C string; be sure to free() * the returned string when done with it. */ char *cfStringToCStringASCII( CFStringRef cfString ) { CFIndex strLen = CFStringGetMaximumSizeForEncoding( CFStringGetLength( cfString ), kCFStringEncodingASCII ) + 1; char *cString = calloc( 1, (size_t)strLen ); if( cString != NULL ) CFStringGetCString( cfString, cString, strLen, kCFStringEncodingASCII ); return cString; } #endif
bsd-3-clause
codestation/go
src/os/user/lookup_stubs.go
1709
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !cgo,!windows,!plan9 android vita package user import ( "errors" "fmt" "os" "runtime" "strconv" ) func init() { groupImplemented = false } func current() (*User, error) { u := &User{ Uid: currentUID(), Gid: currentGID(), Username: os.Getenv("USER"), Name: "", // ignored HomeDir: os.Getenv("HOME"), } // On NaCL and Android, return a dummy user instead of failing. switch runtime.GOOS { case "nacl": if u.Uid == "" { u.Uid = "1" } if u.Username == "" { u.Username = "nacl" } if u.HomeDir == "" { u.HomeDir = "/" } case "android": if u.Uid == "" { u.Uid = "1" } if u.Username == "" { u.Username = "android" } if u.HomeDir == "" { u.HomeDir = "/sdcard" } } // cgo isn't available, but if we found the minimum information // without it, use it: if u.Uid != "" && u.Username != "" && u.HomeDir != "" { return u, nil } return u, fmt.Errorf("user: Current not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) } func listGroups(*User) ([]string, error) { if runtime.GOOS == "android" { return nil, errors.New("user: GroupIds not implemented on Android") } return nil, errors.New("user: GroupIds requires cgo") } func currentUID() string { if id := os.Getuid(); id >= 0 { return strconv.Itoa(id) } // Note: Windows returns -1, but this file isn't used on // Windows anyway, so this empty return path shouldn't be // used. return "" } func currentGID() string { if id := os.Getgid(); id >= 0 { return strconv.Itoa(id) } return "" }
bsd-3-clause
immortal/sandbox
go/goroutine/ping-pong/main.go
480
package main import "fmt" import "time" type Ball struct{ hits int } func main() { table := make(chan *Ball) go player("ping", table) go player("pong", table) table <- new(Ball) // game on; toss the ball time.Sleep(1 * time.Second) <-table // game over; grab the ball panic("show the stack") } func player(name string, table chan *Ball) { for { ball := <-table ball.hits++ fmt.Println(name, ball.hits) time.Sleep(100 * time.Millisecond) table <- ball } }
bsd-3-clause
svoos/CorpusConverter
src/main/java/tigerxml/Head.java
3131
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.03.15 at 01:54:55 PM MEZ // // Based on the XML schmema: TigerXMLHeader.xsd // Reference: http://www.coli.uni-saarland.de/projects/salsa/ // package tigerxml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for headType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="headType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="meta" type="{}metaType" minOccurs="0"/> * &lt;element name="annotation" type="{}annotationType" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="external" type="{http://www.w3.org/2001/XMLSchema}anyURI" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "headType", propOrder = { "meta", "annotation" }) public class Head { protected Meta meta; protected Annotation annotation; @XmlAttribute @XmlSchemaType(name = "anyURI") protected String external; /** * Gets the value of the meta property. * * @return * possible object is * {@link Meta } * */ public Meta getMeta() { return meta; } /** * Sets the value of the meta property. * * @param value * allowed object is * {@link Meta } * */ public void setMeta(Meta value) { this.meta = value; } /** * Gets the value of the annotation property. * * @return * possible object is * {@link Annotation } * */ public Annotation getAnnotation() { if (annotation == null) { annotation = new Annotation(); } return annotation; } /** * Sets the value of the annotation property. * * @param value * allowed object is * {@link Annotation } * */ public void setAnnotation(Annotation value) { this.annotation = value; } /** * Gets the value of the external property. * * @return * possible object is * {@link String } * */ public String getExternal() { return external; } /** * Sets the value of the external property. * * @param value * allowed object is * {@link String } * */ public void setExternal(String value) { this.external = value; } }
bsd-3-clause
dterei/Scraps
amqp/gs3/recv.go
1522
package main // Single sender // Multiple receivers - round-robin // Durable // Delayed acknowledgment import ( "fmt" "time" "github.com/streadway/amqp" ) const ( broker = "amqp://localhost" queue1 = "gs3-queue" // Should queue persist beyond broker restart? durable = true // Should queue be deleted once all clients have disconnected? autoDelete = false exclusive = false nowait = false nolocal = false // not supported autoAck = false ) func main() { conn, err := amqp.Dial(broker) if err != nil { fmt.Printf("Couldn't open amqp connection: %v\n", err) return } defer conn.Close() chn, err := conn.Channel() if err != nil { fmt.Printf("Couldn't open amqp channel: %v\n", err) return } defer chn.Close() qq, err := chn.QueueDeclare(queue1, durable, autoDelete, exclusive, nowait, nil) if err != nil { fmt.Printf("Couldn't open amqp queue: %v\n", err) return } fmt.Printf("Queue declared: %s (%d, %d)\n", qq.Name, qq.Consumers, qq.Messages) recv, err := chn.Consume(queue1, "", autoAck, exclusive, nolocal, nowait, nil) if err != nil { fmt.Printf("Couldn't open amqp queue for receiving: %v\n", err) return } var msg amqp.Delivery lastAckd := 0 i := 1 go func() { for { if len(msg.Body) > 0 && lastAckd < i { fmt.Printf("acking up to %d\n", i) msg.Ack(true) lastAckd = i } time.Sleep(5000 * time.Millisecond) } }() for msg = range recv { fmt.Printf("[%03d] msg: %v\n", i, msg) i++ } fmt.Printf("messages done...\n") }
bsd-3-clause
sholsapp/cryptography
src/cryptography/hazmat/backends/openssl/backend.py
49028
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import collections import itertools from contextlib import contextmanager import six from cryptography import utils from cryptography.exceptions import ( InternalError, UnsupportedAlgorithm, _Reasons ) from cryptography.hazmat.backends.interfaces import ( CMACBackend, CipherBackend, DERSerializationBackend, DSABackend, EllipticCurveBackend, HMACBackend, HashBackend, PBKDF2HMACBackend, PEMSerializationBackend, RSABackend, X509Backend ) from cryptography.hazmat.backends.openssl.ciphers import ( _AESCTRCipherContext, _CipherContext ) from cryptography.hazmat.backends.openssl.cmac import _CMACContext from cryptography.hazmat.backends.openssl.dsa import ( _DSAParameters, _DSAPrivateKey, _DSAPublicKey ) from cryptography.hazmat.backends.openssl.ec import ( _EllipticCurvePrivateKey, _EllipticCurvePublicKey ) from cryptography.hazmat.backends.openssl.hashes import _HashContext from cryptography.hazmat.backends.openssl.hmac import _HMACContext from cryptography.hazmat.backends.openssl.rsa import ( _RSAPrivateKey, _RSAPublicKey ) from cryptography.hazmat.backends.openssl.x509 import ( _Certificate, _CertificateSigningRequest ) from cryptography.hazmat.bindings.openssl.binding import Binding from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa from cryptography.hazmat.primitives.asymmetric.padding import ( MGF1, OAEP, PKCS1v15, PSS ) from cryptography.hazmat.primitives.ciphers.algorithms import ( AES, ARC4, Blowfish, CAST5, Camellia, IDEA, SEED, TripleDES ) from cryptography.hazmat.primitives.ciphers.modes import ( CBC, CFB, CFB8, CTR, ECB, GCM, OFB ) _MemoryBIO = collections.namedtuple("_MemoryBIO", ["bio", "char_ptr"]) _OpenSSLError = collections.namedtuple("_OpenSSLError", ["code", "lib", "func", "reason"]) @utils.register_interface(CipherBackend) @utils.register_interface(CMACBackend) @utils.register_interface(DERSerializationBackend) @utils.register_interface(DSABackend) @utils.register_interface(EllipticCurveBackend) @utils.register_interface(HashBackend) @utils.register_interface(HMACBackend) @utils.register_interface(PBKDF2HMACBackend) @utils.register_interface(RSABackend) @utils.register_interface(PEMSerializationBackend) @utils.register_interface(X509Backend) class Backend(object): """ OpenSSL API binding interfaces. """ name = "openssl" def __init__(self): self._binding = Binding() self._ffi = self._binding.ffi self._lib = self._binding.lib self._binding.init_static_locks() # adds all ciphers/digests for EVP self._lib.OpenSSL_add_all_algorithms() # registers available SSL/TLS ciphers and digests self._lib.SSL_library_init() # loads error strings for libcrypto and libssl functions self._lib.SSL_load_error_strings() self._cipher_registry = {} self._register_default_ciphers() self.activate_osrandom_engine() def activate_builtin_random(self): # Obtain a new structural reference. e = self._lib.ENGINE_get_default_RAND() if e != self._ffi.NULL: self._lib.ENGINE_unregister_RAND(e) # Reset the RNG to use the new engine. self._lib.RAND_cleanup() # decrement the structural reference from get_default_RAND res = self._lib.ENGINE_finish(e) assert res == 1 def activate_osrandom_engine(self): # Unregister and free the current engine. self.activate_builtin_random() # Fetches an engine by id and returns it. This creates a structural # reference. e = self._lib.ENGINE_by_id(self._lib.Cryptography_osrandom_engine_id) assert e != self._ffi.NULL # Initialize the engine for use. This adds a functional reference. res = self._lib.ENGINE_init(e) assert res == 1 # Set the engine as the default RAND provider. res = self._lib.ENGINE_set_default_RAND(e) assert res == 1 # Decrement the structural ref incremented by ENGINE_by_id. res = self._lib.ENGINE_free(e) assert res == 1 # Decrement the functional ref incremented by ENGINE_init. res = self._lib.ENGINE_finish(e) assert res == 1 # Reset the RNG to use the new engine. self._lib.RAND_cleanup() def openssl_version_text(self): """ Friendly string name of the loaded OpenSSL library. This is not necessarily the same version as it was compiled against. Example: OpenSSL 1.0.1e 11 Feb 2013 """ return self._ffi.string( self._lib.SSLeay_version(self._lib.SSLEAY_VERSION) ).decode("ascii") def create_hmac_ctx(self, key, algorithm): return _HMACContext(self, key, algorithm) def hash_supported(self, algorithm): digest = self._lib.EVP_get_digestbyname(algorithm.name.encode("ascii")) return digest != self._ffi.NULL def hmac_supported(self, algorithm): return self.hash_supported(algorithm) def create_hash_ctx(self, algorithm): return _HashContext(self, algorithm) def cipher_supported(self, cipher, mode): if self._evp_cipher_supported(cipher, mode): return True elif isinstance(mode, CTR) and isinstance(cipher, AES): return True else: return False def _evp_cipher_supported(self, cipher, mode): try: adapter = self._cipher_registry[type(cipher), type(mode)] except KeyError: return False evp_cipher = adapter(self, cipher, mode) return self._ffi.NULL != evp_cipher def register_cipher_adapter(self, cipher_cls, mode_cls, adapter): if (cipher_cls, mode_cls) in self._cipher_registry: raise ValueError("Duplicate registration for: {0} {1}.".format( cipher_cls, mode_cls) ) self._cipher_registry[cipher_cls, mode_cls] = adapter def _register_default_ciphers(self): for mode_cls in [CBC, CTR, ECB, OFB, CFB, CFB8]: self.register_cipher_adapter( AES, mode_cls, GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}") ) for mode_cls in [CBC, CTR, ECB, OFB, CFB]: self.register_cipher_adapter( Camellia, mode_cls, GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}") ) for mode_cls in [CBC, CFB, CFB8, OFB]: self.register_cipher_adapter( TripleDES, mode_cls, GetCipherByName("des-ede3-{mode.name}") ) self.register_cipher_adapter( TripleDES, ECB, GetCipherByName("des-ede3") ) for mode_cls in [CBC, CFB, OFB, ECB]: self.register_cipher_adapter( Blowfish, mode_cls, GetCipherByName("bf-{mode.name}") ) for mode_cls in [CBC, CFB, OFB, ECB]: self.register_cipher_adapter( SEED, mode_cls, GetCipherByName("seed-{mode.name}") ) for cipher_cls, mode_cls in itertools.product( [CAST5, IDEA], [CBC, OFB, CFB, ECB], ): self.register_cipher_adapter( cipher_cls, mode_cls, GetCipherByName("{cipher.name}-{mode.name}") ) self.register_cipher_adapter( ARC4, type(None), GetCipherByName("rc4") ) self.register_cipher_adapter( AES, GCM, GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}") ) def create_symmetric_encryption_ctx(self, cipher, mode): if (isinstance(mode, CTR) and isinstance(cipher, AES) and not self._evp_cipher_supported(cipher, mode)): # This is needed to provide support for AES CTR mode in OpenSSL # 0.9.8. It can be removed when we drop 0.9.8 support (RHEL 5 # extended life ends 2020). return _AESCTRCipherContext(self, cipher, mode) else: return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT) def create_symmetric_decryption_ctx(self, cipher, mode): if (isinstance(mode, CTR) and isinstance(cipher, AES) and not self._evp_cipher_supported(cipher, mode)): # This is needed to provide support for AES CTR mode in OpenSSL # 0.9.8. It can be removed when we drop 0.9.8 support (RHEL 5 # extended life ends 2020). return _AESCTRCipherContext(self, cipher, mode) else: return _CipherContext(self, cipher, mode, _CipherContext._DECRYPT) def pbkdf2_hmac_supported(self, algorithm): if self._lib.Cryptography_HAS_PBKDF2_HMAC: return self.hmac_supported(algorithm) else: # OpenSSL < 1.0.0 has an explicit PBKDF2-HMAC-SHA1 function, # so if the PBKDF2_HMAC function is missing we only support # SHA1 via PBKDF2_HMAC_SHA1. return isinstance(algorithm, hashes.SHA1) def derive_pbkdf2_hmac(self, algorithm, length, salt, iterations, key_material): buf = self._ffi.new("char[]", length) if self._lib.Cryptography_HAS_PBKDF2_HMAC: evp_md = self._lib.EVP_get_digestbyname( algorithm.name.encode("ascii")) assert evp_md != self._ffi.NULL res = self._lib.PKCS5_PBKDF2_HMAC( key_material, len(key_material), salt, len(salt), iterations, evp_md, length, buf ) assert res == 1 else: if not isinstance(algorithm, hashes.SHA1): raise UnsupportedAlgorithm( "This version of OpenSSL only supports PBKDF2HMAC with " "SHA1.", _Reasons.UNSUPPORTED_HASH ) res = self._lib.PKCS5_PBKDF2_HMAC_SHA1( key_material, len(key_material), salt, len(salt), iterations, length, buf ) assert res == 1 return self._ffi.buffer(buf)[:] def _err_string(self, code): err_buf = self._ffi.new("char[]", 256) self._lib.ERR_error_string_n(code, err_buf, 256) return self._ffi.string(err_buf, 256)[:] def _consume_errors(self): errors = [] while True: code = self._lib.ERR_get_error() if code == 0: break lib = self._lib.ERR_GET_LIB(code) func = self._lib.ERR_GET_FUNC(code) reason = self._lib.ERR_GET_REASON(code) errors.append(_OpenSSLError(code, lib, func, reason)) return errors def _unknown_error(self, error): return InternalError( "Unknown error code {0} from OpenSSL, " "you should probably file a bug. {1}.".format( error.code, self._err_string(error.code) ) ) def _bn_to_int(self, bn): assert bn != self._ffi.NULL if six.PY3: # Python 3 has constant time from_bytes, so use that. bn_num_bytes = (self._lib.BN_num_bits(bn) + 7) // 8 bin_ptr = self._ffi.new("unsigned char[]", bn_num_bytes) bin_len = self._lib.BN_bn2bin(bn, bin_ptr) # A zero length means the BN has value 0 assert bin_len >= 0 assert bin_ptr != self._ffi.NULL return int.from_bytes(self._ffi.buffer(bin_ptr)[:bin_len], "big") else: # Under Python 2 the best we can do is hex() hex_cdata = self._lib.BN_bn2hex(bn) assert hex_cdata != self._ffi.NULL hex_str = self._ffi.string(hex_cdata) self._lib.OPENSSL_free(hex_cdata) return int(hex_str, 16) def _int_to_bn(self, num, bn=None): """ Converts a python integer to a BIGNUM. The returned BIGNUM will not be garbage collected (to support adding them to structs that take ownership of the object). Be sure to register it for GC if it will be discarded after use. """ assert bn is None or bn != self._ffi.NULL if bn is None: bn = self._ffi.NULL if six.PY3: # Python 3 has constant time to_bytes, so use that. binary = num.to_bytes(int(num.bit_length() / 8.0 + 1), "big") bn_ptr = self._lib.BN_bin2bn(binary, len(binary), bn) assert bn_ptr != self._ffi.NULL return bn_ptr else: # Under Python 2 the best we can do is hex() hex_num = hex(num).rstrip("L").lstrip("0x").encode("ascii") or b"0" bn_ptr = self._ffi.new("BIGNUM **") bn_ptr[0] = bn res = self._lib.BN_hex2bn(bn_ptr, hex_num) assert res != 0 assert bn_ptr[0] != self._ffi.NULL return bn_ptr[0] def generate_rsa_private_key(self, public_exponent, key_size): rsa._verify_rsa_parameters(public_exponent, key_size) rsa_cdata = self._lib.RSA_new() assert rsa_cdata != self._ffi.NULL rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) bn = self._int_to_bn(public_exponent) bn = self._ffi.gc(bn, self._lib.BN_free) res = self._lib.RSA_generate_key_ex( rsa_cdata, key_size, bn, self._ffi.NULL ) assert res == 1 evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) return _RSAPrivateKey(self, rsa_cdata, evp_pkey) def generate_rsa_parameters_supported(self, public_exponent, key_size): return (public_exponent >= 3 and public_exponent & 1 != 0 and key_size >= 512) def load_rsa_private_numbers(self, numbers): rsa._check_private_key_components( numbers.p, numbers.q, numbers.d, numbers.dmp1, numbers.dmq1, numbers.iqmp, numbers.public_numbers.e, numbers.public_numbers.n ) rsa_cdata = self._lib.RSA_new() assert rsa_cdata != self._ffi.NULL rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) rsa_cdata.p = self._int_to_bn(numbers.p) rsa_cdata.q = self._int_to_bn(numbers.q) rsa_cdata.d = self._int_to_bn(numbers.d) rsa_cdata.dmp1 = self._int_to_bn(numbers.dmp1) rsa_cdata.dmq1 = self._int_to_bn(numbers.dmq1) rsa_cdata.iqmp = self._int_to_bn(numbers.iqmp) rsa_cdata.e = self._int_to_bn(numbers.public_numbers.e) rsa_cdata.n = self._int_to_bn(numbers.public_numbers.n) res = self._lib.RSA_blinding_on(rsa_cdata, self._ffi.NULL) assert res == 1 evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) return _RSAPrivateKey(self, rsa_cdata, evp_pkey) def load_rsa_public_numbers(self, numbers): rsa._check_public_key_components(numbers.e, numbers.n) rsa_cdata = self._lib.RSA_new() assert rsa_cdata != self._ffi.NULL rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) rsa_cdata.e = self._int_to_bn(numbers.e) rsa_cdata.n = self._int_to_bn(numbers.n) res = self._lib.RSA_blinding_on(rsa_cdata, self._ffi.NULL) assert res == 1 evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) return _RSAPublicKey(self, rsa_cdata, evp_pkey) def _rsa_cdata_to_evp_pkey(self, rsa_cdata): evp_pkey = self._lib.EVP_PKEY_new() assert evp_pkey != self._ffi.NULL evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) res = self._lib.EVP_PKEY_set1_RSA(evp_pkey, rsa_cdata) assert res == 1 return evp_pkey def _bytes_to_bio(self, data): """ Return a _MemoryBIO namedtuple of (BIO, char*). The char* is the storage for the BIO and it must stay alive until the BIO is finished with. """ data_char_p = self._ffi.new("char[]", data) bio = self._lib.BIO_new_mem_buf( data_char_p, len(data) ) assert bio != self._ffi.NULL return _MemoryBIO(self._ffi.gc(bio, self._lib.BIO_free), data_char_p) def _create_mem_bio(self): """ Creates an empty memory BIO. """ bio_method = self._lib.BIO_s_mem() assert bio_method != self._ffi.NULL bio = self._lib.BIO_new(bio_method) assert bio != self._ffi.NULL bio = self._ffi.gc(bio, self._lib.BIO_free) return bio def _read_mem_bio(self, bio): """ Reads a memory BIO. This only works on memory BIOs. """ buf = self._ffi.new("char **") buf_len = self._lib.BIO_get_mem_data(bio, buf) assert buf_len > 0 assert buf[0] != self._ffi.NULL bio_data = self._ffi.buffer(buf[0], buf_len)[:] return bio_data def _evp_pkey_to_private_key(self, evp_pkey): """ Return the appropriate type of PrivateKey given an evp_pkey cdata pointer. """ key_type = evp_pkey.type if key_type == self._lib.EVP_PKEY_RSA: rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey) assert rsa_cdata != self._ffi.NULL rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) return _RSAPrivateKey(self, rsa_cdata, evp_pkey) elif key_type == self._lib.EVP_PKEY_DSA: dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey) assert dsa_cdata != self._ffi.NULL dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free) return _DSAPrivateKey(self, dsa_cdata, evp_pkey) elif (self._lib.Cryptography_HAS_EC == 1 and key_type == self._lib.EVP_PKEY_EC): ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey) assert ec_cdata != self._ffi.NULL ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey) else: raise UnsupportedAlgorithm("Unsupported key type.") def _evp_pkey_to_public_key(self, evp_pkey): """ Return the appropriate type of PublicKey given an evp_pkey cdata pointer. """ key_type = evp_pkey.type if key_type == self._lib.EVP_PKEY_RSA: rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey) assert rsa_cdata != self._ffi.NULL rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) return _RSAPublicKey(self, rsa_cdata, evp_pkey) elif key_type == self._lib.EVP_PKEY_DSA: dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey) assert dsa_cdata != self._ffi.NULL dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free) return _DSAPublicKey(self, dsa_cdata, evp_pkey) elif (self._lib.Cryptography_HAS_EC == 1 and key_type == self._lib.EVP_PKEY_EC): ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey) assert ec_cdata != self._ffi.NULL ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey) else: raise UnsupportedAlgorithm("Unsupported key type.") def _pem_password_cb(self, password): """ Generate a pem_password_cb function pointer that copied the password to OpenSSL as required and returns the number of bytes copied. typedef int pem_password_cb(char *buf, int size, int rwflag, void *userdata); Useful for decrypting PKCS8 files and so on. Returns a tuple of (cdata function pointer, callback function). """ def pem_password_cb(buf, size, writing, userdata): pem_password_cb.called += 1 if not password: pem_password_cb.exception = TypeError( "Password was not given but private key is encrypted." ) return 0 elif len(password) < size: pw_buf = self._ffi.buffer(buf, size) pw_buf[:len(password)] = password return len(password) else: pem_password_cb.exception = ValueError( "Passwords longer than {0} bytes are not supported " "by this backend.".format(size - 1) ) return 0 pem_password_cb.called = 0 pem_password_cb.exception = None return ( self._ffi.callback("int (char *, int, int, void *)", pem_password_cb), pem_password_cb ) def _mgf1_hash_supported(self, algorithm): if self._lib.Cryptography_HAS_MGF1_MD: return self.hash_supported(algorithm) else: return isinstance(algorithm, hashes.SHA1) def rsa_padding_supported(self, padding): if isinstance(padding, PKCS1v15): return True elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1): return self._mgf1_hash_supported(padding._mgf._algorithm) elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1): return isinstance(padding._mgf._algorithm, hashes.SHA1) else: return False def generate_dsa_parameters(self, key_size): if key_size not in (1024, 2048, 3072): raise ValueError( "Key size must be 1024 or 2048 or 3072 bits.") if (self._lib.OPENSSL_VERSION_NUMBER < 0x1000000f and key_size > 1024): raise ValueError( "Key size must be 1024 because OpenSSL < 1.0.0 doesn't " "support larger key sizes.") ctx = self._lib.DSA_new() assert ctx != self._ffi.NULL ctx = self._ffi.gc(ctx, self._lib.DSA_free) res = self._lib.DSA_generate_parameters_ex( ctx, key_size, self._ffi.NULL, 0, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL ) assert res == 1 return _DSAParameters(self, ctx) def generate_dsa_private_key(self, parameters): ctx = self._lib.DSA_new() assert ctx != self._ffi.NULL ctx = self._ffi.gc(ctx, self._lib.DSA_free) ctx.p = self._lib.BN_dup(parameters._dsa_cdata.p) ctx.q = self._lib.BN_dup(parameters._dsa_cdata.q) ctx.g = self._lib.BN_dup(parameters._dsa_cdata.g) self._lib.DSA_generate_key(ctx) evp_pkey = self._dsa_cdata_to_evp_pkey(ctx) return _DSAPrivateKey(self, ctx, evp_pkey) def generate_dsa_private_key_and_parameters(self, key_size): parameters = self.generate_dsa_parameters(key_size) return self.generate_dsa_private_key(parameters) def load_dsa_private_numbers(self, numbers): dsa._check_dsa_private_numbers(numbers) parameter_numbers = numbers.public_numbers.parameter_numbers dsa_cdata = self._lib.DSA_new() assert dsa_cdata != self._ffi.NULL dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free) dsa_cdata.p = self._int_to_bn(parameter_numbers.p) dsa_cdata.q = self._int_to_bn(parameter_numbers.q) dsa_cdata.g = self._int_to_bn(parameter_numbers.g) dsa_cdata.pub_key = self._int_to_bn(numbers.public_numbers.y) dsa_cdata.priv_key = self._int_to_bn(numbers.x) evp_pkey = self._dsa_cdata_to_evp_pkey(dsa_cdata) return _DSAPrivateKey(self, dsa_cdata, evp_pkey) def load_dsa_public_numbers(self, numbers): dsa._check_dsa_parameters(numbers.parameter_numbers) dsa_cdata = self._lib.DSA_new() assert dsa_cdata != self._ffi.NULL dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free) dsa_cdata.p = self._int_to_bn(numbers.parameter_numbers.p) dsa_cdata.q = self._int_to_bn(numbers.parameter_numbers.q) dsa_cdata.g = self._int_to_bn(numbers.parameter_numbers.g) dsa_cdata.pub_key = self._int_to_bn(numbers.y) evp_pkey = self._dsa_cdata_to_evp_pkey(dsa_cdata) return _DSAPublicKey(self, dsa_cdata, evp_pkey) def load_dsa_parameter_numbers(self, numbers): dsa._check_dsa_parameters(numbers) dsa_cdata = self._lib.DSA_new() assert dsa_cdata != self._ffi.NULL dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free) dsa_cdata.p = self._int_to_bn(numbers.p) dsa_cdata.q = self._int_to_bn(numbers.q) dsa_cdata.g = self._int_to_bn(numbers.g) return _DSAParameters(self, dsa_cdata) def _dsa_cdata_to_evp_pkey(self, dsa_cdata): evp_pkey = self._lib.EVP_PKEY_new() assert evp_pkey != self._ffi.NULL evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) res = self._lib.EVP_PKEY_set1_DSA(evp_pkey, dsa_cdata) assert res == 1 return evp_pkey def dsa_hash_supported(self, algorithm): if self._lib.OPENSSL_VERSION_NUMBER < 0x1000000f: return isinstance(algorithm, hashes.SHA1) else: return self.hash_supported(algorithm) def dsa_parameters_supported(self, p, q, g): if self._lib.OPENSSL_VERSION_NUMBER < 0x1000000f: return utils.bit_length(p) <= 1024 and utils.bit_length(q) <= 160 else: return True def cmac_algorithm_supported(self, algorithm): return ( self._lib.Cryptography_HAS_CMAC == 1 and self.cipher_supported( algorithm, CBC(b"\x00" * algorithm.block_size) ) ) def create_cmac_ctx(self, algorithm): return _CMACContext(self, algorithm) def load_pem_private_key(self, data, password): return self._load_key( self._lib.PEM_read_bio_PrivateKey, self._evp_pkey_to_private_key, data, password, ) def load_pem_public_key(self, data): mem_bio = self._bytes_to_bio(data) evp_pkey = self._lib.PEM_read_bio_PUBKEY( mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL ) if evp_pkey != self._ffi.NULL: evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) return self._evp_pkey_to_public_key(evp_pkey) else: # It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still # need to check to see if it is a pure PKCS1 RSA public key (not # embedded in a subjectPublicKeyInfo) self._consume_errors() res = self._lib.BIO_reset(mem_bio.bio) assert res == 1 rsa_cdata = self._lib.PEM_read_bio_RSAPublicKey( mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL ) if rsa_cdata != self._ffi.NULL: rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) return _RSAPublicKey(self, rsa_cdata, evp_pkey) else: self._handle_key_loading_error() def load_der_private_key(self, data, password): # OpenSSL has a function called d2i_AutoPrivateKey that can simplify # this. Unfortunately it doesn't properly support PKCS8 on OpenSSL # 0.9.8 so we can't use it. Instead we sequentially try to load it 3 # different ways. First we'll try to load it as a traditional key bio_data = self._bytes_to_bio(data) key = self._evp_pkey_from_der_traditional_key(bio_data, password) if not key: # Okay so it's not a traditional key. Let's try # PKCS8 unencrypted. OpenSSL 0.9.8 can't load unencrypted # PKCS8 keys using d2i_PKCS8PrivateKey_bio so we do this instead. # Reset the memory BIO so we can read the data again. res = self._lib.BIO_reset(bio_data.bio) assert res == 1 key = self._evp_pkey_from_der_unencrypted_pkcs8(bio_data, password) if key: return self._evp_pkey_to_private_key(key) else: # Finally we try to load it with the method that handles encrypted # PKCS8 properly. return self._load_key( self._lib.d2i_PKCS8PrivateKey_bio, self._evp_pkey_to_private_key, data, password, ) def _evp_pkey_from_der_traditional_key(self, bio_data, password): key = self._lib.d2i_PrivateKey_bio(bio_data.bio, self._ffi.NULL) if key != self._ffi.NULL: key = self._ffi.gc(key, self._lib.EVP_PKEY_free) if password is not None: raise TypeError( "Password was given but private key is not encrypted." ) return key else: self._consume_errors() return None def _evp_pkey_from_der_unencrypted_pkcs8(self, bio_data, password): info = self._lib.d2i_PKCS8_PRIV_KEY_INFO_bio( bio_data.bio, self._ffi.NULL ) info = self._ffi.gc(info, self._lib.PKCS8_PRIV_KEY_INFO_free) if info != self._ffi.NULL: key = self._lib.EVP_PKCS82PKEY(info) assert key != self._ffi.NULL key = self._ffi.gc(key, self._lib.EVP_PKEY_free) if password is not None: raise TypeError( "Password was given but private key is not encrypted." ) return key else: self._consume_errors() return None def load_der_public_key(self, data): mem_bio = self._bytes_to_bio(data) evp_pkey = self._lib.d2i_PUBKEY_bio(mem_bio.bio, self._ffi.NULL) if evp_pkey != self._ffi.NULL: evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) return self._evp_pkey_to_public_key(evp_pkey) else: # It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still # need to check to see if it is a pure PKCS1 RSA public key (not # embedded in a subjectPublicKeyInfo) self._consume_errors() res = self._lib.BIO_reset(mem_bio.bio) assert res == 1 rsa_cdata = self._lib.d2i_RSAPublicKey_bio( mem_bio.bio, self._ffi.NULL ) if rsa_cdata != self._ffi.NULL: rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) return _RSAPublicKey(self, rsa_cdata, evp_pkey) else: self._handle_key_loading_error() def load_pem_x509_certificate(self, data): mem_bio = self._bytes_to_bio(data) x509 = self._lib.PEM_read_bio_X509( mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL ) if x509 == self._ffi.NULL: self._consume_errors() raise ValueError("Unable to load certificate") x509 = self._ffi.gc(x509, self._lib.X509_free) return _Certificate(self, x509) def load_der_x509_certificate(self, data): mem_bio = self._bytes_to_bio(data) x509 = self._lib.d2i_X509_bio(mem_bio.bio, self._ffi.NULL) if x509 == self._ffi.NULL: self._consume_errors() raise ValueError("Unable to load certificate") x509 = self._ffi.gc(x509, self._lib.X509_free) return _Certificate(self, x509) def load_pem_x509_csr(self, data): mem_bio = self._bytes_to_bio(data) x509_req = self._lib.PEM_read_bio_X509_REQ( mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL ) if x509_req == self._ffi.NULL: self._consume_errors() raise ValueError("Unable to load request") x509_req = self._ffi.gc(x509_req, self._lib.X509_REQ_free) return _CertificateSigningRequest(self, x509_req) def load_der_x509_csr(self, data): mem_bio = self._bytes_to_bio(data) x509_req = self._lib.d2i_X509_REQ_bio(mem_bio.bio, self._ffi.NULL) if x509_req == self._ffi.NULL: self._consume_errors() raise ValueError("Unable to load request") x509_req = self._ffi.gc(x509_req, self._lib.X509_REQ_free) return _CertificateSigningRequest(self, x509_req) def _load_key(self, openssl_read_func, convert_func, data, password): mem_bio = self._bytes_to_bio(data) password_callback, password_func = self._pem_password_cb(password) evp_pkey = openssl_read_func( mem_bio.bio, self._ffi.NULL, password_callback, self._ffi.NULL ) if evp_pkey == self._ffi.NULL: if password_func.exception is not None: errors = self._consume_errors() assert errors raise password_func.exception else: self._handle_key_loading_error() evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) if password is not None and password_func.called == 0: raise TypeError( "Password was given but private key is not encrypted.") assert ( (password is not None and password_func.called == 1) or password is None ) return convert_func(evp_pkey) def _handle_key_loading_error(self): errors = self._consume_errors() if not errors: raise ValueError("Could not unserialize key data.") elif errors[0][1:] in ( ( self._lib.ERR_LIB_EVP, self._lib.EVP_F_EVP_DECRYPTFINAL_EX, self._lib.EVP_R_BAD_DECRYPT ), ( self._lib.ERR_LIB_PKCS12, self._lib.PKCS12_F_PKCS12_PBE_CRYPT, self._lib.PKCS12_R_PKCS12_CIPHERFINAL_ERROR, ) ): raise ValueError("Bad decrypt. Incorrect password?") elif errors[0][1:] in ( ( self._lib.ERR_LIB_PEM, self._lib.PEM_F_PEM_GET_EVP_CIPHER_INFO, self._lib.PEM_R_UNSUPPORTED_ENCRYPTION ), ( self._lib.ERR_LIB_EVP, self._lib.EVP_F_EVP_PBE_CIPHERINIT, self._lib.EVP_R_UNKNOWN_PBE_ALGORITHM ) ): raise UnsupportedAlgorithm( "PEM data is encrypted with an unsupported cipher", _Reasons.UNSUPPORTED_CIPHER ) elif any( error[1:] == ( self._lib.ERR_LIB_EVP, self._lib.EVP_F_EVP_PKCS82PKEY, self._lib.EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM ) for error in errors ): raise UnsupportedAlgorithm( "Unsupported public key algorithm.", _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM ) else: assert errors[0][1] in ( self._lib.ERR_LIB_EVP, self._lib.ERR_LIB_PEM, self._lib.ERR_LIB_ASN1, ) raise ValueError("Could not unserialize key data.") def elliptic_curve_supported(self, curve): if self._lib.Cryptography_HAS_EC != 1: return False try: curve_nid = self._elliptic_curve_to_nid(curve) except UnsupportedAlgorithm: curve_nid = self._lib.NID_undef ctx = self._lib.EC_GROUP_new_by_curve_name(curve_nid) if ctx == self._ffi.NULL: errors = self._consume_errors() assert ( curve_nid == self._lib.NID_undef or errors[0][1:] == ( self._lib.ERR_LIB_EC, self._lib.EC_F_EC_GROUP_NEW_BY_CURVE_NAME, self._lib.EC_R_UNKNOWN_GROUP ) ) return False else: assert curve_nid != self._lib.NID_undef self._lib.EC_GROUP_free(ctx) return True def elliptic_curve_signature_algorithm_supported( self, signature_algorithm, curve ): if self._lib.Cryptography_HAS_EC != 1: return False # We only support ECDSA right now. if not isinstance(signature_algorithm, ec.ECDSA): return False # Before 0.9.8m OpenSSL can't cope with digests longer than the curve. if ( self._lib.OPENSSL_VERSION_NUMBER < 0x009080df and curve.key_size < signature_algorithm.algorithm.digest_size * 8 ): return False return self.elliptic_curve_supported(curve) def generate_elliptic_curve_private_key(self, curve): """ Generate a new private key on the named curve. """ if self.elliptic_curve_supported(curve): curve_nid = self._elliptic_curve_to_nid(curve) ec_cdata = self._lib.EC_KEY_new_by_curve_name(curve_nid) assert ec_cdata != self._ffi.NULL ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) res = self._lib.EC_KEY_generate_key(ec_cdata) assert res == 1 res = self._lib.EC_KEY_check_key(ec_cdata) assert res == 1 evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey) else: raise UnsupportedAlgorithm( "Backend object does not support {0}.".format(curve.name), _Reasons.UNSUPPORTED_ELLIPTIC_CURVE ) def load_elliptic_curve_private_numbers(self, numbers): public = numbers.public_numbers curve_nid = self._elliptic_curve_to_nid(public.curve) ec_cdata = self._lib.EC_KEY_new_by_curve_name(curve_nid) assert ec_cdata != self._ffi.NULL ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) ec_cdata = self._ec_key_set_public_key_affine_coordinates( ec_cdata, public.x, public.y) res = self._lib.EC_KEY_set_private_key( ec_cdata, self._int_to_bn(numbers.private_value)) assert res == 1 evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey) def load_elliptic_curve_public_numbers(self, numbers): curve_nid = self._elliptic_curve_to_nid(numbers.curve) ec_cdata = self._lib.EC_KEY_new_by_curve_name(curve_nid) assert ec_cdata != self._ffi.NULL ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) ec_cdata = self._ec_key_set_public_key_affine_coordinates( ec_cdata, numbers.x, numbers.y) evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey) def _ec_cdata_to_evp_pkey(self, ec_cdata): evp_pkey = self._lib.EVP_PKEY_new() assert evp_pkey != self._ffi.NULL evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) res = self._lib.EVP_PKEY_set1_EC_KEY(evp_pkey, ec_cdata) assert res == 1 def _elliptic_curve_to_nid(self, curve): """ Get the NID for a curve name. """ curve_aliases = { "secp192r1": "prime192v1", "secp256r1": "prime256v1" } curve_name = curve_aliases.get(curve.name, curve.name) curve_nid = self._lib.OBJ_sn2nid(curve_name.encode()) if curve_nid == self._lib.NID_undef: raise UnsupportedAlgorithm( "{0} is not a supported elliptic curve".format(curve.name), _Reasons.UNSUPPORTED_ELLIPTIC_CURVE ) return curve_nid @contextmanager def _tmp_bn_ctx(self): bn_ctx = self._lib.BN_CTX_new() assert bn_ctx != self._ffi.NULL bn_ctx = self._ffi.gc(bn_ctx, self._lib.BN_CTX_free) self._lib.BN_CTX_start(bn_ctx) try: yield bn_ctx finally: self._lib.BN_CTX_end(bn_ctx) def _ec_key_determine_group_get_set_funcs(self, ctx): """ Given an EC_KEY determine the group and what methods are required to get/set point coordinates. """ assert ctx != self._ffi.NULL nid_two_field = self._lib.OBJ_sn2nid(b"characteristic-two-field") assert nid_two_field != self._lib.NID_undef group = self._lib.EC_KEY_get0_group(ctx) assert group != self._ffi.NULL method = self._lib.EC_GROUP_method_of(group) assert method != self._ffi.NULL nid = self._lib.EC_METHOD_get_field_type(method) assert nid != self._lib.NID_undef if nid == nid_two_field and self._lib.Cryptography_HAS_EC2M: set_func = self._lib.EC_POINT_set_affine_coordinates_GF2m get_func = self._lib.EC_POINT_get_affine_coordinates_GF2m else: set_func = self._lib.EC_POINT_set_affine_coordinates_GFp get_func = self._lib.EC_POINT_get_affine_coordinates_GFp assert set_func and get_func return set_func, get_func, group def _ec_key_set_public_key_affine_coordinates(self, ctx, x, y): """ This is a port of EC_KEY_set_public_key_affine_coordinates that was added in 1.0.1. Sets the public key point in the EC_KEY context to the affine x and y values. """ if x < 0 or y < 0: raise ValueError( "Invalid EC key. Both x and y must be non-negative." ) set_func, get_func, group = ( self._ec_key_determine_group_get_set_funcs(ctx) ) point = self._lib.EC_POINT_new(group) assert point != self._ffi.NULL point = self._ffi.gc(point, self._lib.EC_POINT_free) bn_x = self._int_to_bn(x) bn_y = self._int_to_bn(y) with self._tmp_bn_ctx() as bn_ctx: check_x = self._lib.BN_CTX_get(bn_ctx) check_y = self._lib.BN_CTX_get(bn_ctx) res = set_func(group, point, bn_x, bn_y, bn_ctx) assert res == 1 res = get_func(group, point, check_x, check_y, bn_ctx) assert res == 1 res = self._lib.BN_cmp(bn_x, check_x) assert res == 0 res = self._lib.BN_cmp(bn_y, check_y) assert res == 0 res = self._lib.EC_KEY_set_public_key(ctx, point) assert res == 1 res = self._lib.EC_KEY_check_key(ctx) if res != 1: self._consume_errors() raise ValueError("Invalid EC key.") return ctx def _private_key_bytes(self, encoding, format, encryption_algorithm, evp_pkey, cdata): if not isinstance(encoding, serialization.Encoding): raise TypeError("encoding must be an item from the Encoding enum") if not isinstance(format, serialization.PrivateFormat): raise TypeError( "format must be an item from the PrivateFormat enum" ) if not isinstance(encryption_algorithm, serialization.KeySerializationEncryption): raise TypeError( "Encryption algorithm must be a KeySerializationEncryption " "instance" ) if isinstance(encryption_algorithm, serialization.NoEncryption): password = b"" passlen = 0 evp_cipher = self._ffi.NULL elif isinstance(encryption_algorithm, serialization.BestAvailableEncryption): # This is a curated value that we will update over time. evp_cipher = self._lib.EVP_get_cipherbyname( b"aes-256-cbc" ) password = encryption_algorithm.password passlen = len(password) if passlen > 1023: raise ValueError( "Passwords longer than 1023 bytes are not supported by " "this backend" ) else: raise ValueError("Unsupported encryption type") if encoding is serialization.Encoding.PEM: if format is serialization.PrivateFormat.PKCS8: write_bio = self._lib.PEM_write_bio_PKCS8PrivateKey key = evp_pkey elif format is serialization.PrivateFormat.TraditionalOpenSSL: if evp_pkey.type == self._lib.EVP_PKEY_RSA: write_bio = self._lib.PEM_write_bio_RSAPrivateKey elif evp_pkey.type == self._lib.EVP_PKEY_DSA: write_bio = self._lib.PEM_write_bio_DSAPrivateKey elif (self._lib.Cryptography_HAS_EC == 1 and evp_pkey.type == self._lib.EVP_PKEY_EC): write_bio = self._lib.PEM_write_bio_ECPrivateKey key = cdata elif encoding is serialization.Encoding.DER: if format is serialization.PrivateFormat.TraditionalOpenSSL: if not isinstance( encryption_algorithm, serialization.NoEncryption ): raise ValueError( "Encryption is not supported for DER encoded " "traditional OpenSSL keys" ) return self._private_key_bytes_traditional_der( evp_pkey.type, cdata ) elif format is serialization.PrivateFormat.PKCS8: write_bio = self._lib.i2d_PKCS8PrivateKey_bio key = evp_pkey bio = self._create_mem_bio() res = write_bio( bio, key, evp_cipher, password, passlen, self._ffi.NULL, self._ffi.NULL ) assert res == 1 return self._read_mem_bio(bio) def _private_key_bytes_traditional_der(self, key_type, cdata): if key_type == self._lib.EVP_PKEY_RSA: write_bio = self._lib.i2d_RSAPrivateKey_bio elif (self._lib.Cryptography_HAS_EC == 1 and key_type == self._lib.EVP_PKEY_EC): write_bio = self._lib.i2d_ECPrivateKey_bio elif key_type == self._lib.EVP_PKEY_DSA: write_bio = self._lib.i2d_DSAPrivateKey_bio bio = self._create_mem_bio() res = write_bio(bio, cdata) assert res == 1 return self._read_mem_bio(bio) def _public_key_bytes(self, encoding, format, evp_pkey, cdata): if not isinstance(encoding, serialization.Encoding): raise TypeError("encoding must be an item from the Encoding enum") if not isinstance(format, serialization.PublicFormat): raise TypeError( "format must be an item from the PublicFormat enum" ) if format is serialization.PublicFormat.SubjectPublicKeyInfo: if encoding is serialization.Encoding.PEM: write_bio = self._lib.PEM_write_bio_PUBKEY elif encoding is serialization.Encoding.DER: write_bio = self._lib.i2d_PUBKEY_bio key = evp_pkey elif format is serialization.PublicFormat.PKCS1: # Only RSA is supported here. assert evp_pkey.type == self._lib.EVP_PKEY_RSA if encoding is serialization.Encoding.PEM: write_bio = self._lib.PEM_write_bio_RSAPublicKey elif encoding is serialization.Encoding.DER: write_bio = self._lib.i2d_RSAPublicKey_bio key = cdata bio = self._create_mem_bio() res = write_bio(bio, key) assert res == 1 return self._read_mem_bio(bio) class GetCipherByName(object): def __init__(self, fmt): self._fmt = fmt def __call__(self, backend, cipher, mode): cipher_name = self._fmt.format(cipher=cipher, mode=mode).lower() return backend._lib.EVP_get_cipherbyname(cipher_name.encode("ascii")) backend = Backend()
bsd-3-clause
grnrbt/grass
web/media/scripts/link.js
781
$(function(){ function openPanel(){ require(['panel']); $('#admin_link').hide(); } if($.cookie('grass_panel')){ openPanel(); } $('#admin_link').on('click', function(e){ e.preventDefault(); openPanel(); }); }); require.config({ baseUrl: 'media/scripts', paths: { // 'doT': 'vendor/dot', 'riotjs': 'vendor/riot+compiler', 'panel': 'admin/panel', 'text': 'vendor/text' }, shim: { riotjs: { exports: 'riot' } } }); var riot; function loadCss(url) { var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = url; document.getElementsByTagName("head")[0].appendChild(link); }
bsd-3-clause
reuleaux/pire
src/Pire/Refactor/Range.hs
30759
-- {-# LANGUAGE DeriveFunctor #-} -- {-# LANGUAGE DeriveFoldable #-} -- {-# LANGUAGE DeriveTraversable #-} -- {-# LANGUAGE DeriveGeneric #-} -- {-# LANGUAGE BangPatterns #-} -- {-# LANGUAGE TemplateHaskell #-} -- {-# LANGUAGE RecordWildCards #-} -- {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE CPP #-} -- {-# OPTIONS_GHC -cpp -DPiForallInstalled #-} -- | -- Copyright : (c) Andreas Reuleaux 2015 -- License : BSD2 -- Maintainer: Andreas Reuleaux <[email protected]> -- Stability : experimental -- Portability: non-portable -- -- This module provides Pire's refactoring features: -- calculate token ranges (ie. exact position information), -- based upon Trifecta Delta's and LineColunn numbers, module Pire.Refactor.Range ( module Pire.Refactor.Range ) where import Pire.Syntax.Ws import Pire.Syntax.Nm import Pire.Syntax.Token import Pire.Syntax.Modules import Pire.Syntax.Expr import Pire.Syntax.Decl import Pire.Syntax.Binder import Pire.Syntax.Eps import Pire.Syntax.Telescope import Pire.Syntax.Pattern import Pire.Syntax.Constructor import Pire.Refactor.Pos import qualified Data.Text as T import Text.Trifecta.Delta -- import Control.Monad.Error #ifdef MIN_VERSION_GLASGOW_HASKELL #if MIN_VERSION_GLASGOW_HASKELL(7,10,3,0) -- ghc >= 7.10.3 -- import Control.Monad.Except #else -- older ghc versions, but MIN_VERSION_GLASGOW_HASKELL defined #endif #else -- MIN_VERSION_GLASGOW_HASKELL not even defined yet (ghc <= 7.8.x) import Data.Monoid -- import Data.Foldable (foldMap) import Data.Foldable hiding (elem) #endif import Data.Bifoldable #ifdef DocTest -- for the doctests import Pire.Refactor.Decorate (decorate) import Pire.Wrap (wrap) import Pire.Parser.ParseUtils (parse) import Pire.Parser.Expr (expr_) import Pire.Parser.Parser (beginning) import System.IO.Silently (silence) import Control.Monad.Except (runExceptT) import Control.Monad.Except (runExceptT) import Data.Either.Combinators (fromRight') import Pire.Modules (getModules_) import Pire.Refactor.Navigation (body, toDecl, focus, fromExp, ezipper, right, Tr(Mod)) import Pire.Refactor.Decorate (decorateM) #endif import Control.Lens hiding (from, to) {-| @(Pos 8 100) `inRange` ("hello \n \n \n", Range (Pos 7 0) (To 9 2))@ ? No: there is no 100th char in line 8 (the understanding is, that lines are not just infinitely long, that way we get more precise position info) @ 7 "hello \n" 8 " \n" 9 " \n" @ >>> let range = rangeS "hello \n \n \n" (Pos 7 0) >>> range Range (Pos 7 0) (Pos 9 2) >>> let detailed = detailedRangeS "hello \n \n \n" (Pos 7 0) >>> detailed DetailedRange [Pos 7 0,Pos 7 1,Pos 7 2,Pos 7 3,Pos 7 4,Pos 7 5,Pos 7 6,Pos 7 7,Pos 8 0,Pos 8 1,Pos 9 0,Pos 9 1,Pos 9 2] >>> (Pos 8 100) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) False but @(Pos 8 2)@ deserves more attention: it seems: yes, but details inspection reveals: no >>> (Pos 8 100) `inRange` range True >>> (Pos 8 100) `inRange` detailed False -} {-| >>> detailedRangeS " " (Pos 4 6) DetailedRange [Pos 4 6] >>> (Pos 4 6) `inRange` (detailedRangeS " " (Pos 4 6)) True >>> (Pos 4 7) `inRange` (detailedRangeS " " (Pos 4 6)) False >>> (detailedRangeS "\n\n" (Pos 4 17)) DetailedRange [Pos 4 17,Pos 5 0] >>> (Pos 4 17) `inRange` (detailedRangeS "\n\n" (Pos 4 17)) True >>> rangeS "hello \n \n \n" (Pos 7 0) Range (Pos 7 0) (Pos 9 2) >>> detailedRangeS "hello \n \n \n" (Pos 7 0) DetailedRange [Pos 7 0,Pos 7 1,Pos 7 2,Pos 7 3,Pos 7 4,Pos 7 5,Pos 7 6,Pos 7 7,Pos 8 0,Pos 8 1,Pos 9 0,Pos 9 1,Pos 9 2] >>> (Pos 7 2) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) True >>> rangeS "hello \n \n \n" (Pos 4 6) Range (Pos 4 6) (Pos 6 2) >>> detailedRangeS "hello \n \n \n" (Pos 4 6) DetailedRange [Pos 4 6,Pos 4 7,Pos 4 8,Pos 4 9,Pos 4 10,Pos 4 11,Pos 4 12,Pos 4 13,Pos 5 0,Pos 5 1,Pos 6 0,Pos 6 1,Pos 6 2] >>> (Pos 4 6) `inRange` (detailedRangeS "hello \n \n \n" (Pos 4 6)) True >>> detailedRangeS "hello \n \n \n" (Pos 7 0) DetailedRange [Pos 7 0,Pos 7 1,Pos 7 2,Pos 7 3,Pos 7 4,Pos 7 5,Pos 7 6,Pos 7 7,Pos 8 0,Pos 8 1,Pos 9 0,Pos 9 1,Pos 9 2] >>> (Pos 7 0) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) True >>> (Pos 7 8) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) False >>> (Pos 8 1) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) True >>> (Pos 8 100) `inRange` (detailedRangeS "hello \n \n \n" (Pos 7 0)) False -} data Range = Range Pos Pos | NoRange deriving (Show) data DetailedRange = DetailedRange [Pos] deriving (Show) -- helper nextpos '\n' (Pos x _) = Pos (x+1) 0 nextpos _ (Pos x y) = Pos x (y+1) -- another helper: accumulate the Pos pos found so far in the first param -- | -- >>> foo [] "hi\n " (Pos 4 16) -- [Pos 4 16,Pos 4 17,Pos 4 18,Pos 5 0,Pos 5 1] foo :: [Pos] -> String -> Pos -> [Pos] foo found [] _ = found foo found (c:rest) usepos = foo (found ++ [usepos]) rest (nextpos c usepos) fooT :: [Pos] -> T.Text -> Pos -> [Pos] fooT found chars usepos | T.length chars == 0 = found | otherwise = fooT (found ++ [usepos]) rest (nextpos c usepos) where c = T.head chars rest = T.tail chars rangeS :: [Char] -> Pos -> Range rangeS [] _ = NoRange rangeS (_:[]) from = Range from from rangeS s from = Range from to where to = last $ foo [] s from rangeT :: T.Text -> Pos -> Range rangeT txt from | T.length txt == 0 = NoRange | T.length txt == 1 = Range from from | otherwise = Range from to where to = last $ fooT [] txt from -- | helpers take a @Pos@ (not a @Delta@) detailedRangeS :: [Char] -> Pos -> DetailedRange detailedRangeS s from = DetailedRange $ foo [] s from detailedRangeT :: T.Text -> Pos -> DetailedRange detailedRangeT t from = DetailedRange $ fooT [] t from -- | -- range of a token (ie. of the text parts within the token), -- but also more generally: of any piece of the syntax tree: exprs, decls class HasRange t where range :: t -> Range class HasDetailedRange t where -- | "detailed range" drange :: t -> DetailedRange instance HasRange (String, Delta) where range (s, (Lines l c _ _)) = rangeS s (Pos l c) instance HasDetailedRange (String, Delta) where drange (s, (Lines l c _ _)) = detailedRangeS s (Pos l c) instance HasRange (T.Text, Delta) where range (s, (Lines l c _ _)) = rangeT s (Pos l c) instance HasDetailedRange (T.Text, Delta) where drange (s, (Lines l c _ _)) = detailedRangeT s (Pos l c) -- -------------------------------------------------- -- pos < (Range from _) = compare pos from == LT class InRange x where inRange :: Pos -> x -> Bool instance InRange Range where pos `inRange` (Range from to) | from <= pos && pos <= to = True | otherwise = False _ `inRange` NoRange = False instance InRange DetailedRange where pos `inRange` (DetailedRange ls) = pos `elem` ls instance InRange (T.Text, Delta) where pos `inRange` pair@(_,_) = pos `inRange` range pair && pos `inRange` drange pair instance InRange (String, Delta) where pos `inRange` pair@(_,_) = pos `inRange` range pair && pos `inRange` drange pair -- -------------------------------------------------- -- ranges of token, Decls etc -- can add ranges, and therefore understand them as monoids -- (*) -- refined version of addRange: -- a range being added should only contribute it's larger -- examples: -- w/ tst parsed from file tst -- fromExp $ fromRight' $ (ezipper $ Mod $ decorateM $ wrap tst) >>= navigate [Decl 5, Rhs, Body, Rhs, Rhs, Body] >>= focus -- range $ fromExp $ fromRight' $ (ezipper $ Mod $ decorateM $ wrap tst) >>= navigate [Decl 5, Rhs, Body, Rhs, Rhs, Body] >>= focus -- drange $ fromExp $ fromRight' $ (ezipper $ Mod $ decorateM $ wrap tst) >>= navigate [Decl 5, Rhs, Body, Rhs, Rhs, Body] >>= focus -- (ezipper $ Mod tst) >>= lineColumn 19 22 -- by hand: -- >>> decorate( wrap $ nopos $ t2s $ parse expr "\\a . x a") (Lines 0 0 0 0) -- LamPAs [(RuntimeP,("a",Lines 0 0 0 0),Annot Nothing)] (Scope (V (F (V ("x",Lines 0 1 0 0))) :@ BndV ("a",Lines 0 2 0 0) (V (B 0)))) -- -- >>> instantiate1 (V ("a",Lines 0 0 0 0 )) $ scopepl $ decorate( wrap $ nopos $ t2s $ parse expr "\\a . x a") (Lines 0 0 0 0) -- V ("x",Lines 0 1 0 0) :@ BndV ("a",Lines 0 2 0 0) (V ("a",Lines 0 0 0 0)) -- it appears that that last "a" is at a smaller postion (ie. because the binder was), -- the range should nevertheless be -- >>> range $ instantiate1 (V ("a",Lines 0 0 0 0 )) $ scopepl $ decorate( wrap $ nopos $ t2s $ parse expr "\\a . x a") (Lines 0 0 0 0) -- Range (Pos 0 1) (Pos 0 2) {- wo/ any of these precautions this is what happens: fromExp $ fromRight' $ (ezipper $ Mod $ decorateM $ wrap tst) >>= navigate [Decl 5, Rhs, Body, Rhs, Rhs, Body] >>= focus >>> range (Ws_ (V ("x",Lines 19 20 0 0)) (Ws (" ",Lines 19 21 0 0)) :@ Ws_ (BndV ("a",Lines 19 22 0 0) (V ("a",Lines 19 16 0 0))) (Ws ("",Lines 19 23 0 0))) Range (Pos 19 20) (Pos 19 16) >>> drange (Ws_ (V ("x",Lines 19 20 0 0)) (Ws (" ",Lines 19 21 0 0)) :@ Ws_ (BndV ("a",Lines 19 22 0 0) (V ("a",Lines 19 16 0 0))) (Ws ("",Lines 19 23 0 0))) DetailedRange [Pos 19 20,Pos 19 21,Pos 19 22,Pos 19 16] -} -- formerly just -- addRange (Range f _) (Range _ t') = Range f t' -- but need to watch out for instantiated vars, cf (*) above addRange (Range f t) (Range _ t') | t <= t' = Range f t' -- stick with the old Range | otherwise = Range f t addRange (Range f t) NoRange = Range f t addRange NoRange (Range f t) = Range f t addRange _ _ = NoRange -- likewise we want only positions to contribute to addition that are larger than the previous ones -- addDetailedRange (DetailedRange l) (DetailedRange l') = DetailedRange $ l ++ l' -- ok, but not necessary maybe -- addDetailedRange (DetailedRange l) (DetailedRange l') = DetailedRange $ l ++ [x | x <- l', (x >=) `all` l ] -- this should be enough, and faster addDetailedRange (DetailedRange []) (DetailedRange l') = DetailedRange l' addDetailedRange (DetailedRange l@(_:_)) (DetailedRange l') = DetailedRange $ l ++ [x | x <- l', x >= last l ] -- maybe ">" -- addDetailedRange (DetailedRange l@(_:_)) (DetailedRange l') -- = DetailedRange $ l ++ [x | x <- l', x > last l ] -- [drange d| d <- _decls $ decorateM $ wrap $ tst] instance Monoid Range where mempty = NoRange mappend = addRange instance Monoid DetailedRange where mempty = DetailedRange [] mappend = addDetailedRange class Decorated t where instance Decorated (t', Delta) -- think of (t', Delta) when t is Decorated -- (but there may be other kinds of decorations as well in the future), -- eg. (t', Pos) -- instance (HasRange (t, Delta)) => HasRange (Ws (t, Delta)) where -- range = foldMap range -- instance (HasDetailedRange (t, Delta)) => HasDetailedRange (Ws (t, Delta)) where -- drange = foldMap drange -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange (Ws t) where range = foldMap range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Ws t) where drange = foldMap drange {-| Ws >>> range $ Ws (" ",Lines 6 6 0 0) Range (Pos 6 6) (Pos 6 8) >>> drange $ Ws (" ",Lines 6 6 0 0) DetailedRange [Pos 6 6,Pos 6 7,Pos 6 8] -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Ws t) where pos `inRange` ws = pos `inRange` range ws && pos `inRange` drange ws -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange (Token ty t) where range = foldMap range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Token ty t) where drange = foldMap drange {-| ImportTok >>> range $ ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)) Range (Pos 6 0) (Pos 6 8) >>> drange $ ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)) DetailedRange [Pos 6 0,Pos 6 1,Pos 6 2,Pos 6 3,Pos 6 4,Pos 6 5,Pos 6 6,Pos 6 7,Pos 6 8] -} {-| Equal >>> range $ Equal ("=",Lines 11 2 0 0) (Ws (" ",Lines 11 3 0 0)) Range (Pos 11 2) (Pos 11 3) >>> drange $ Equal ("=",Lines 11 2 0 0) (Ws (" ",Lines 11 3 0 0)) DetailedRange [Pos 11 2,Pos 11 3] -} {-| LamTok >>> range $ LamTok ("\\",Lines 9 4 0 0) (Ws (" ",Lines 9 5 0 0)) Range (Pos 9 4) (Pos 9 6) >>> drange $ LamTok ("\\",Lines 9 4 0 0) (Ws (" ",Lines 9 5 0 0)) DetailedRange [Pos 9 4,Pos 9 5,Pos 9 6] -} {-| Dot >>> range $ (Dot (".",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) Range (Pos 9 7) (Pos 9 8) >>> drange $ (Dot (".",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) DetailedRange [Pos 9 7,Pos 9 8] -} {-| ParenOpen >>> range $ (ParenOpen ("(",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) Range (Pos 9 7) (Pos 9 8) >>> drange $ (ParenOpen ("(",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) DetailedRange [Pos 9 7,Pos 9 8] -} {-| ParenClose >>> range $ (ParenClose (")",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) Range (Pos 9 7) (Pos 9 8) >>> drange $ (ParenClose (")",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) DetailedRange [Pos 9 7,Pos 9 8] -} {-| BracketOpen >>> range $ (BracketOpen ("[",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) Range (Pos 9 7) (Pos 9 8) >>> drange $ (BracketOpen ("[",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) DetailedRange [Pos 9 7,Pos 9 8] -} {-| BracketClose >>> range $ (BracketClose ("[",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) Range (Pos 9 7) (Pos 9 8) >>> drange $ (BracketClose ("[",Lines 9 7 0 0) (Ws (" ",Lines 9 8 0 0))) DetailedRange [Pos 9 7,Pos 9 8] -} {-| missing still: doctests/examples for @VBar@, @Comma@, @Of@, @PcaseTok@, @CaseTok@, @SubsTok@, @By@ -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Token ty t) where pos `inRange` itok = pos `inRange` range itok && pos `inRange` drange itok -- -------------------------------------------------- instance (HasRange t) => HasRange (Maybe t) where range = foldMap range instance (HasDetailedRange t) => HasDetailedRange (Maybe t) where drange = foldMap drange instance InRange t => InRange (Maybe t) where _ `inRange` Nothing = False pos `inRange` Just t = pos `inRange` t -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange (Nm1 t) where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange (Nm1 t) where drange = foldMap drange {-| >>> range $ Nm1_ ("g",Lines 15 0 0 0) (Ws (" ",Lines 15 1 0 0)) Range (Pos 15 0) (Pos 15 1) >>> drange $ Nm1_ ("g",Lines 15 0 0 0) (Ws (" ",Lines 15 1 0 0)) DetailedRange [Pos 15 0,Pos 15 1] -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Nm1 t) where pos `inRange` nm = pos `inRange` range nm && pos `inRange` drange nm -- -------------------------------------------------- instance ( Decorated t , HasRange t ) => HasRange (ModuleImport t) where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange (ModuleImport t) where drange = foldMap drange {-| ModuleImport >>> range $ ModuleImport_ {_importtok = ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)), _importnm = Nm1_ ("Nat",Lines 6 9 0 0) (Ws ("\n",Lines 6 12 0 0))} Range (Pos 6 0) (Pos 6 12) >>> drange $ ModuleImport_ {_importtok = ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)), _importnm = Nm1_ ("Nat",Lines 6 9 0 0) (Ws ("\n",Lines 6 12 0 0))} DetailedRange [Pos 6 0,Pos 6 1,Pos 6 2,Pos 6 3,Pos 6 4,Pos 6 5,Pos 6 6,Pos 6 7,Pos 6 8,Pos 6 9,Pos 6 10,Pos 6 11,Pos 6 12] -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (ModuleImport t) where pos `inRange` mi = pos `inRange` range mi && pos `inRange` drange mi -- -------------------------------------------------- {-| cf @inRange@ below -} instance ( Decorated t , HasRange t ) => HasRange [ModuleImport t] where range = foldMap range {-| cf @inRange@ below -} instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [ModuleImport t] where drange = foldMap drange {-| \[ModuleImport\] >>> range $ [ModuleImport_ {_importtok = ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)), _importnm = Nm1_ ("Nat",Lines 6 9 0 0) (Ws ("\n",Lines 6 12 0 0))},ModuleImport_ {_importtok = ImportTok ("import",Lines 7 0 0 0) (Ws (" ",Lines 7 6 0 0)), _importnm = Nm1_ ("Sample",Lines 7 7 0 0) (Ws ("\n\n",Lines 7 13 0 0))}] Range (Pos 6 0) (Pos 8 0) >>> drange $ [ModuleImport_ {_importtok = ImportTok ("import",Lines 6 0 0 0) (Ws (" ",Lines 6 6 0 0)), _importnm = Nm1_ ("Nat",Lines 6 9 0 0) (Ws ("\n",Lines 6 12 0 0))},ModuleImport_ {_importtok = ImportTok ("import",Lines 7 0 0 0) (Ws (" ",Lines 7 6 0 0)), _importnm = Nm1_ ("Sample",Lines 7 7 0 0) (Ws ("\n\n",Lines 7 13 0 0))}] DetailedRange [Pos 6 0,Pos 6 1,Pos 6 2,Pos 6 3,Pos 6 4,Pos 6 5,Pos 6 6,Pos 6 7,Pos 6 8,Pos 6 9,Pos 6 10,Pos 6 11,Pos 6 12,Pos 7 0,Pos 7 1,Pos 7 2,Pos 7 3,Pos 7 4,Pos 7 5,Pos 7 6,Pos 7 7,Pos 7 8,Pos 7 9,Pos 7 10,Pos 7 11,Pos 7 12,Pos 7 13,Pos 8 0] -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [ModuleImport t] where pos `inRange` mis = pos `inRange` range mis && pos `inRange` drange mis -- -------------------------------------------------- {-| cf @inRange@ below -} instance (Decorated t, HasRange t) => HasRange (Expr t t) where range = bifoldMap range range {-| cf @inRange@ below -} instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Expr t t) where drange = bifoldMap drange drange {-| ranges of exprs >>> range $ decorate (wrap $ parse expr_ "f ") beginning Range (Pos 0 0) (Pos 0 3) >>> range $ decorate (wrap $ parse expr_ "f a b ") beginning Range (Pos 0 0) (Pos 0 6) -} {- those examples, that contain {-ws-} comments we better test in regular (doctest) "--" comments, otherwise (within the {-| ... -} above) we need extra escaping à la {\-ws-\}, and things soon get unreadable -} -- | -- >>> range $ decorate (wrap $ parse expr_ "\\ x . f a b{-ws-}") beginning -- Range (Pos 0 0) (Pos 0 16) -- -- >>> drange $ (decorate (wrap $ parse expr_ "f a b{-ws-}") beginning) -- DetailedRange [Pos 0 0,Pos 0 1,Pos 0 2,Pos 0 3,Pos 0 4,Pos 0 5,Pos 0 6,Pos 0 7,Pos 0 8,Pos 0 9,Pos 0 10] instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Expr t t) where pos `inRange` ex = pos `inRange` range ex && pos `inRange` drange ex -- -------------------------------------------------- -- need to handle [Expr t t] as well, for TCon_ at least instance ( Decorated t , HasRange t ) => HasRange [Expr t t] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [Expr t t] where drange = foldMap drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [Expr t t] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange (Decl t t) where range = bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Decl t t) where drange = bifoldMap drange drange {-| ranges of decls, examples/tests! -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Decl t t) where pos `inRange` dcl = pos `inRange` range dcl && pos `inRange` drange dcl -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange [Decl t t] where range = foldMap $ bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange [Decl t t] where drange = foldMap $ bifoldMap drange drange {-| ranges of lists of decls, examples/tests! -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [Decl t t] where pos `inRange` dcls = pos `inRange` range dcls && pos `inRange` drange dcls -- -------------------------------------------------- instance (Decorated t, HasRange t) => HasRange (Binder t) where range = foldMap range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Binder t) where drange = foldMap drange {-| ranges of binders, examples/tests! -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Binder t) where pos `inRange` bndr = pos `inRange` range bndr && pos `inRange` drange bndr -- for the binders of a LamPAs_, the triple list ie. instance (Decorated t, HasRange t) => HasRange (Eps, Binder t, Annot t t) where range = foldMap range . (^. _2) instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Eps, Binder t, Annot t t) where drange = foldMap drange . (^. _2) instance (Decorated t, HasRange t) => HasRange [(Eps, Binder t, Annot t t)] where range = foldMap $ foldMap range . (^. _2) instance (Decorated t, HasDetailedRange t) => HasDetailedRange [(Eps, Binder t, Annot t t)] where drange = foldMap $ foldMap drange . (^. _2) instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Eps, Binder t, Annot t t) where pos `inRange` trpl = pos `inRange` range trpl && pos `inRange` drange trpl instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [(Eps, Binder t, Annot t t)] where pos `inRange` trpls = pos `inRange` range trpls && pos `inRange` drange trpls -- nov2015, telescopes instance (Decorated t, HasRange t) => HasRange (Telescope t t) where range = bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Telescope t t) where drange = bifoldMap drange drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Telescope t t) where pos `inRange` tele = pos `inRange` range tele && pos `inRange` drange tele -- match/case - Nov 2015 instance (Decorated t, HasRange t) => HasRange (Match t t) where range = bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Match t t) where drange = bifoldMap drange drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Match t t) where pos `inRange` tele = pos `inRange` range tele && pos `inRange` drange tele -- uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu instance (Decorated t, HasRange a, HasRange t) => HasRange (Pattern t a) where range = foldMap range instance (Decorated t, HasDetailedRange a, HasDetailedRange t) => HasDetailedRange (Pattern t a) where drange = foldMap drange instance (Decorated t, HasRange a, HasRange t, HasDetailedRange a, HasDetailedRange t) => InRange (Pattern t a) where pos `inRange` tele = pos `inRange` range tele && pos `inRange` drange tele -- instance ( Decorated t , HasRange a , HasRange t ) => HasRange (Pattern t a, Eps) where range = range . fst instance ( Decorated t , HasDetailedRange a , HasDetailedRange t ) => HasDetailedRange (Pattern t a, Eps) where drange = drange . fst instance (Decorated t, HasRange a, HasRange t, HasDetailedRange a, HasDetailedRange t) => InRange (Pattern t a, Eps) where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches instance ( Decorated t , HasRange a , HasRange t ) => HasRange [(Pattern t a, Eps)] where range = foldMap (range . fst) instance ( Decorated t , HasDetailedRange a , HasDetailedRange t ) => HasDetailedRange [(Pattern t a, Eps)] where drange = foldMap (drange . fst) instance (Decorated t, HasRange a, HasRange t, HasDetailedRange a, HasDetailedRange t) => InRange [(Pattern t a, Eps)] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- and the other way around instance ( Decorated t , HasRange a , HasRange t ) => HasRange (Eps, Pattern t a) where range = range . snd instance ( Decorated t , HasDetailedRange a , HasDetailedRange t ) => HasDetailedRange (Eps, Pattern t a) where drange = drange . snd instance (Decorated t, HasRange a, HasRange t, HasDetailedRange a, HasDetailedRange t) => InRange (Eps, Pattern t a) where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches instance ( Decorated t , HasRange a , HasRange t ) => HasRange [(Eps, Pattern t a)] where range = foldMap (range . snd) instance ( Decorated t , HasDetailedRange a , HasDetailedRange t ) => HasDetailedRange [(Eps, Pattern t a)] where drange = foldMap (drange . snd) instance (Decorated t, HasRange a, HasRange t, HasDetailedRange a, HasDetailedRange t) => InRange [(Eps, Pattern t a)] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu -- hm, do I really need to add these ranges by hand ? - it seems so ! (foldMap is of no use here) instance ( Decorated t , HasRange t ) => HasRange (Match t t, Maybe (Token 'SemiColonTy t)) where range (match, may) = range match `addRange` range may instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange (Match t t, Maybe (Token 'SemiColonTy t)) where drange (match, may) = drange match `addDetailedRange` drange may instance ( Decorated t , HasRange t , HasDetailedRange t ) => InRange (Match t t, Maybe (Token 'SemiColonTy t)) where pos `inRange` pair = pos `inRange` range pair && pos `inRange` drange pair -- -- guess I need them the other way around now instance ( Decorated t , HasRange t ) => HasRange (Maybe (Token 'SemiColonTy t), Match t t) where range (may, match) = range match `addRange` range may instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange (Maybe (Token 'SemiColonTy t), Match t t) where drange (may, match) = drange match `addDetailedRange` drange may instance ( Decorated t , HasRange t , HasDetailedRange t ) => InRange (Maybe (Token 'SemiColonTy t), Match t t) where pos `inRange` pair = pos `inRange` range pair && pos `inRange` drange pair -- -------------------------------------------------- -- ... instance ( Decorated t , HasRange t ) => HasRange [Match t t] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [Match t t] where drange = foldMap drange {-| >>> nat <- (silence $ runExceptT $ getModules_ ["samples"] "Nat") >>= return . last . fromRight' >>> let Case_ casetok exp of' mayopen matches mayclose annot = fromExp $ fromRight' $ (ezipper $ Mod $ decorateM $ wrap nat) >>= toDecl 2 >>= right >>= body >>= focus >>> range (snd $ matches !! 0) Range (Pos 17 2) (Pos 18 1) >>> range (matches !! 0) Range (Pos 17 2) (Pos 18 1) >>> (Pos 17 10) `inRange` (snd $ matches !! 0) True >>> (Pos 17 10) `inRange` (matches !! 0) True -} instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [Match t t] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- -------------------------------------------------- instance ( Decorated t , HasRange t ) => HasRange [(Match t t, Maybe (Token 'SemiColonTy t))] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [(Match t t, Maybe (Token 'SemiColonTy t))] where drange = foldMap drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [(Match t t, Maybe (Token 'SemiColonTy t))] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- ...and the other way around instance ( Decorated t , HasRange t ) => HasRange [(Maybe (Token 'SemiColonTy t), Match t t)] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [(Maybe (Token 'SemiColonTy t), Match t t)] where drange = foldMap drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [(Maybe (Token 'SemiColonTy t), Match t t)] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- DCon_/Arg - Nov 2015 instance (Decorated t, HasRange t) => HasRange (Arg t t) where range = bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (Arg t t) where drange = bifoldMap drange drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (Arg t t) where pos `inRange` tele = pos `inRange` range tele && pos `inRange` drange tele instance ( Decorated t , HasRange t ) => HasRange [Arg t t] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [Arg t t] where drange = foldMap drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange [Arg t t] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches -- similar to Match above instance (Decorated t, HasRange t) => HasRange (ConstructorDef t t) where range = bifoldMap range range instance (Decorated t, HasDetailedRange t) => HasDetailedRange (ConstructorDef t t) where drange = bifoldMap drange drange instance (Decorated t, HasRange t, HasDetailedRange t) => InRange (ConstructorDef t t) where pos `inRange` tele = pos `inRange` range tele && pos `inRange` drange tele instance ( Decorated t , HasRange t ) => HasRange (ConstructorDef t t, Maybe (Token 'SemiColonTy t)) where range (match, may) = range match `addRange` range may instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange (ConstructorDef t t, Maybe (Token 'SemiColonTy t)) where drange (match, may) = drange match `addDetailedRange` drange may instance ( Decorated t , HasRange t , HasDetailedRange t ) => InRange (ConstructorDef t t, Maybe (Token 'SemiColonTy t)) where pos `inRange` pair = pos `inRange` range pair && pos `inRange` drange pair instance ( Decorated t , HasRange t ) => HasRange [(ConstructorDef t t, Maybe (Token 'SemiColonTy t))] where range = foldMap range instance ( Decorated t , HasDetailedRange t ) => HasDetailedRange [(ConstructorDef t t, Maybe (Token 'SemiColonTy t))] where drange = foldMap drange instance ( Decorated t , HasRange t , HasDetailedRange t ) => InRange [(ConstructorDef t t, Maybe (Token 'SemiColonTy t))] where pos `inRange` matches = pos `inRange` range matches && pos `inRange` drange matches
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s07/CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnvp_44.c
4166
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnvp_44.c Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-44.tmpl.c */ /* * @description * CWE: 78 OS Command Injection * BadSource: environment Read input from an environment variable * GoodSource: Fixed string * Sinks: w32_spawnvp * BadSink : execute command with wspawnvp * Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" #define COMMAND_INT L"cmd.exe" #define COMMAND_ARG1 L"/c" #define COMMAND_ARG2 L"dir " #define COMMAND_ARG3 data #else /* NOT _WIN32 */ #include <unistd.h> #define COMMAND_INT_PATH L"/bin/sh" #define COMMAND_INT L"sh" #define COMMAND_ARG1 L"-c" #define COMMAND_ARG2 L"ls " #define COMMAND_ARG3 data #endif #define ENV_VARIABLE L"ADD" #ifdef _WIN32 #define GETENV _wgetenv #else #define GETENV getenv #endif #include <process.h> #ifndef OMITBAD static void badSink(wchar_t * data) { { wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL}; /* wspawnvp - searches for the location of the command among * the directories specified by the PATH environment variable */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ _wspawnvp(_P_WAIT, COMMAND_INT, args); } } void CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnvp_44_bad() { wchar_t * data; /* define a function pointer */ void (*funcPtr) (wchar_t *) = badSink; wchar_t dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; { /* Append input from an environment variable to data */ size_t dataLen = wcslen(data); wchar_t * environment = GETENV(ENV_VARIABLE); /* If there is data in the environment variable */ if (environment != NULL) { /* POTENTIAL FLAW: Read data from an environment variable */ wcsncat(data+dataLen, environment, 100-dataLen-1); } } /* use the function pointer */ funcPtr(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSink(wchar_t * data) { { wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL}; /* wspawnvp - searches for the location of the command among * the directories specified by the PATH environment variable */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ _wspawnvp(_P_WAIT, COMMAND_INT, args); } } static void goodG2B() { wchar_t * data; void (*funcPtr) (wchar_t *) = goodG2BSink; wchar_t dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); funcPtr(data); } void CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnvp_44_good() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnvp_44_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnvp_44_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
dcui/FreeBSD-9.3_kernel
sys/boot/i386/kgzldr/kgzldr.h
1717
/* * Copyright (c) 1999 Global Technology Associates, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $FreeBSD: releng/9.3/sys/boot/i386/kgzldr/kgzldr.h 50477 1999-08-28 01:08:13Z peter $ */ #define KGZ_CRT 0x1 /* Video console */ #define KGZ_SIO 0x2 /* Serial console */ extern int kgz_con; int boot(int); unsigned char *kzipmalloc(int); void kzipfree(void *); void putstr(const char *); void crt_putchr(int); void sio_putchr(int);
bsd-3-clause
metpy/MetPy
v0.8/api/generated/metpy.io.Level2File.html
28273
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Level2File &mdash; MetPy 0.8</title> <link rel="shortcut icon" href="../../_static/metpy_32x32.ico"/> <link rel="canonical" href="https://unidata.github.io/MetPy/latest/api/generated/metpy.io.Level2File.html"/> <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="../../_static/gallery.css" type="text/css" /> <link rel="stylesheet" href="../../_static/theme_override.css" type="text/css" /> <link rel="index" title="Index" href="../../genindex.html"/> <link rel="search" title="Search" href="../../search.html"/> <link rel="top" title="MetPy 0.8" href="../../index.html"/> <link rel="up" title="io" href="metpy.io.html"/> <link rel="next" title="Level3File" href="metpy.io.Level3File.html"/> <link rel="prev" title="GiniFile" href="metpy.io.GiniFile.html"/> <script src="../../_static/js/modernizr.min.js"></script> </head> <body class="wy-body-for-nav" role="document"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search"> <a href="../../index.html" class="icon icon-home"> MetPy <img src="../../_static/metpy_150x150.png" class="logo" /> </a> <div class="version"> <div class="version-dropdown"> <select class="version-list" id="version-list"> <option value=''>0.8</option> <option value="../latest">latest</option> <option value="../dev">dev</option> </select> </div> </div> <div role="search"> <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <ul class="current"> <li class="toctree-l1"><a class="reference internal" href="../../installguide.html">Installation Guide</a></li> <li class="toctree-l1"><a class="reference internal" href="../../units.html">Unit Support</a></li> <li class="toctree-l1"><a class="reference internal" href="../../examples/index.html">MetPy Examples</a></li> <li class="toctree-l1"><a class="reference internal" href="../../tutorials/index.html">MetPy Tutorials</a></li> <li class="toctree-l1 current"><a class="reference internal" href="../index.html">The MetPy API</a><ul class="current"> <li class="toctree-l2"><a class="reference internal" href="metpy.constants.html">constants</a></li> <li class="toctree-l2"><a class="reference internal" href="metpy.units.html">units</a></li> <li class="toctree-l2 current"><a class="reference internal" href="metpy.io.html">io</a><ul class="current"> <li class="toctree-l3"><a class="reference internal" href="metpy.io.is_precip_mode.html">is_precip_mode</a></li> <li class="toctree-l3"><a class="reference internal" href="metpy.io.GiniFile.html">GiniFile</a></li> <li class="toctree-l3 current"><a class="current reference internal" href="#">Level2File</a><ul> <li class="toctree-l4"><a class="reference internal" href="#examples-using-metpy-io-level2file">Examples using <code class="docutils literal notranslate"><span class="pre">metpy.io.Level2File</span></code></a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="metpy.io.Level3File.html">Level3File</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="metpy.io.cdm.html">cdm</a></li> <li class="toctree-l2"><a class="reference internal" href="metpy.calc.html">calc</a></li> <li class="toctree-l2"><a class="reference internal" href="metpy.plots.html">plots</a></li> <li class="toctree-l2"><a class="reference internal" href="metpy.plots.ctables.html">ctables</a></li> <li class="toctree-l2"><a class="reference internal" href="metpy.gridding.html">gridding</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../gempak.html">GEMPAK Conversion Guide</a></li> <li class="toctree-l1"><a class="reference internal" href="../../CONTRIBUTING.html">Contributors Guide</a></li> <li class="toctree-l1"><a class="reference internal" href="../../infrastructureguide.html">Infrastructure Guide</a></li> <li class="toctree-l1"><a class="reference internal" href="../../citing.html">Citing MetPy</a></li> <li class="toctree-l1"><a class="reference internal" href="../../references.html">References</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" role="navigation" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="../../index.html">MetPy</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="../../index.html">Docs</a> &raquo;</li> <li><a href="../index.html">The MetPy API</a> &raquo;</li> <li><a href="metpy.io.html">io</a> &raquo;</li> <li>Level2File</li> <li class="source-link"> <a href="https://github.com/Unidata/MetPy/issues/new?title=Suggested%20improvement%20for%20api/generated/metpy.io.Level2File&body=Please%20describe%20what%20could%20be%20improved%20about%20this%20page%20or%20the%20typo/mistake%20that%20you%20found%3A" class="fa fa-github"> Improve this page</a> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <div class="section" id="level2file"> <h1>Level2File<a class="headerlink" href="#level2file" title="Permalink to this headline">¶</a></h1> <dl class="class"> <dt id="metpy.io.Level2File"> <em class="property">class </em><code class="descclassname">metpy.io.</code><code class="descname">Level2File</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/metpy/io/nexrad.html#Level2File"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#metpy.io.Level2File" title="Permalink to this definition">¶</a></dt> <dd><p>Handle reading the NEXRAD Level 2 data and its various messages.</p> <p>This class attempts to decode every byte that is in a given data file. It supports both external compression, as well as the internal BZ2 compression that is used.</p> <dl class="attribute"> <dt id="metpy.io.Level2File.stid"> <code class="descname">stid</code><a class="headerlink" href="#metpy.io.Level2File.stid" title="Permalink to this definition">¶</a></dt> <dd><p><em>str</em> – The ID of the radar station</p> </dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.dt"> <code class="descname">dt</code><a class="headerlink" href="#metpy.io.Level2File.dt" title="Permalink to this definition">¶</a></dt> <dd><p><em>Datetime instance</em> – The date and time of the data</p> </dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.vol_hdr"> <code class="descname">vol_hdr</code><a class="headerlink" href="#metpy.io.Level2File.vol_hdr" title="Permalink to this definition">¶</a></dt> <dd><p><em>namedtuple</em> – The unpacked volume header</p> </dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.sweeps"> <code class="descname">sweeps</code><a class="headerlink" href="#metpy.io.Level2File.sweeps" title="Permalink to this definition">¶</a></dt> <dd><p><em>list of tuples</em> – Data for each of the sweeps found in the file</p> </dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.rda_status"> <code class="descname">rda_status</code><a class="headerlink" href="#metpy.io.Level2File.rda_status" title="Permalink to this definition">¶</a></dt> <dd><p><em>namedtuple, optional</em> – Unpacked RDA status information, if found</p> </dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.maintenance_data"> <code class="descname">maintenance_data</code><a class="headerlink" href="#metpy.io.Level2File.maintenance_data" title="Permalink to this definition">¶</a></dt> <dd><p><em>namedtuple, optional</em> – Unpacked maintenance data information, if found</p> </dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.maintenance_data_desc"> <code class="descname">maintenance_data_desc</code><a class="headerlink" href="#metpy.io.Level2File.maintenance_data_desc" title="Permalink to this definition">¶</a></dt> <dd><p><em>dict, optional</em> – Descriptions of maintenance data fields, if maintenance data present</p> </dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.vcp_info"> <code class="descname">vcp_info</code><a class="headerlink" href="#metpy.io.Level2File.vcp_info" title="Permalink to this definition">¶</a></dt> <dd><p><em>namedtuple, optional</em> – Unpacked VCP information, if found</p> </dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.clutter_filter_bypass_map"> <code class="descname">clutter_filter_bypass_map</code><a class="headerlink" href="#metpy.io.Level2File.clutter_filter_bypass_map" title="Permalink to this definition">¶</a></dt> <dd><p><em>dict, optional</em> – Unpacked clutter filter bypass map, if present</p> </dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.rda"> <code class="descname">rda</code><a class="headerlink" href="#metpy.io.Level2File.rda" title="Permalink to this definition">¶</a></dt> <dd><p><em>dict, optional</em> – Unpacked RDA adaptation data, if present</p> </dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.rda_adaptation_desc"> <code class="descname">rda_adaptation_desc</code><a class="headerlink" href="#metpy.io.Level2File.rda_adaptation_desc" title="Permalink to this definition">¶</a></dt> <dd><p><em>dict, optional</em> – Descriptions of RDA adaptation data, if adaptation data present</p> </dd></dl> <p class="rubric">Notes</p> <p>The internal data structure that things are decoded into is still to be determined.</p> <p>Create instance of <a class="reference internal" href="#metpy.io.Level2File" title="metpy.io.Level2File"><code class="xref py py-obj docutils literal notranslate"><span class="pre">Level2File</span></code></a>.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>filename</strong> (<a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.6)"><em>str</em></a><em> or </em><em>file-like object</em>) – If str, the name of the file to be opened. Gzip-ed files are recognized with the extension ‘.gz’, as are bzip2-ed files with the extension <a class="reference external" href="https://docs.python.org/3/library/bz2.html#module-bz2" title="(in Python v3.6)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">bz2</span></code></a> If <em class="xref py py-obj">fname</em> is a file-like object, this will be read from directly.</td> </tr> </tbody> </table> <p class="rubric">Attributes Summary</p> <table border="1" class="longtable docutils"> <colgroup> <col width="10%" /> <col width="90%" /> </colgroup> <tbody valign="top"> <tr class="row-odd"><td><a class="reference internal" href="#metpy.io.Level2File.AR2_BLOCKSIZE" title="metpy.io.Level2File.AR2_BLOCKSIZE"><code class="xref py py-obj docutils literal notranslate"><span class="pre">AR2_BLOCKSIZE</span></code></a></td> <td></td> </tr> <tr class="row-even"><td><a class="reference internal" href="#metpy.io.Level2File.CTM_HEADER_SIZE" title="metpy.io.Level2File.CTM_HEADER_SIZE"><code class="xref py py-obj docutils literal notranslate"><span class="pre">CTM_HEADER_SIZE</span></code></a></td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="#metpy.io.Level2File.MISSING" title="metpy.io.Level2File.MISSING"><code class="xref py py-obj docutils literal notranslate"><span class="pre">MISSING</span></code></a></td> <td></td> </tr> <tr class="row-even"><td><a class="reference internal" href="#metpy.io.Level2File.RANGE_FOLD" title="metpy.io.Level2File.RANGE_FOLD"><code class="xref py py-obj docutils literal notranslate"><span class="pre">RANGE_FOLD</span></code></a></td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="#metpy.io.Level2File.data_block_fmt" title="metpy.io.Level2File.data_block_fmt"><code class="xref py py-obj docutils literal notranslate"><span class="pre">data_block_fmt</span></code></a></td> <td></td> </tr> <tr class="row-even"><td><a class="reference internal" href="#metpy.io.Level2File.msg15_code_map" title="metpy.io.Level2File.msg15_code_map"><code class="xref py py-obj docutils literal notranslate"><span class="pre">msg15_code_map</span></code></a></td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="#metpy.io.Level2File.msg1_fmt" title="metpy.io.Level2File.msg1_fmt"><code class="xref py py-obj docutils literal notranslate"><span class="pre">msg1_fmt</span></code></a></td> <td></td> </tr> <tr class="row-even"><td><a class="reference internal" href="#metpy.io.Level2File.msg2_fmt" title="metpy.io.Level2File.msg2_fmt"><code class="xref py py-obj docutils literal notranslate"><span class="pre">msg2_fmt</span></code></a></td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="#metpy.io.Level2File.msg31_data_hdr_fmt" title="metpy.io.Level2File.msg31_data_hdr_fmt"><code class="xref py py-obj docutils literal notranslate"><span class="pre">msg31_data_hdr_fmt</span></code></a></td> <td></td> </tr> <tr class="row-even"><td><a class="reference internal" href="#metpy.io.Level2File.msg31_el_const_fmt" title="metpy.io.Level2File.msg31_el_const_fmt"><code class="xref py py-obj docutils literal notranslate"><span class="pre">msg31_el_const_fmt</span></code></a></td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="#metpy.io.Level2File.msg31_vol_const_fmt" title="metpy.io.Level2File.msg31_vol_const_fmt"><code class="xref py py-obj docutils literal notranslate"><span class="pre">msg31_vol_const_fmt</span></code></a></td> <td></td> </tr> <tr class="row-even"><td><a class="reference internal" href="#metpy.io.Level2File.msg_hdr_fmt" title="metpy.io.Level2File.msg_hdr_fmt"><code class="xref py py-obj docutils literal notranslate"><span class="pre">msg_hdr_fmt</span></code></a></td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="#metpy.io.Level2File.rad_const_fmt_v1" title="metpy.io.Level2File.rad_const_fmt_v1"><code class="xref py py-obj docutils literal notranslate"><span class="pre">rad_const_fmt_v1</span></code></a></td> <td></td> </tr> <tr class="row-even"><td><a class="reference internal" href="#metpy.io.Level2File.rad_const_fmt_v2" title="metpy.io.Level2File.rad_const_fmt_v2"><code class="xref py py-obj docutils literal notranslate"><span class="pre">rad_const_fmt_v2</span></code></a></td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="#metpy.io.Level2File.vcp_el_fmt" title="metpy.io.Level2File.vcp_el_fmt"><code class="xref py py-obj docutils literal notranslate"><span class="pre">vcp_el_fmt</span></code></a></td> <td></td> </tr> <tr class="row-even"><td><a class="reference internal" href="#metpy.io.Level2File.vcp_fmt" title="metpy.io.Level2File.vcp_fmt"><code class="xref py py-obj docutils literal notranslate"><span class="pre">vcp_fmt</span></code></a></td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="#metpy.io.Level2File.vol_hdr_fmt" title="metpy.io.Level2File.vol_hdr_fmt"><code class="xref py py-obj docutils literal notranslate"><span class="pre">vol_hdr_fmt</span></code></a></td> <td></td> </tr> </tbody> </table> <p class="rubric">Methods Summary</p> <table border="1" class="longtable docutils"> <colgroup> <col width="10%" /> <col width="90%" /> </colgroup> <tbody valign="top"> <tr class="row-odd"><td><a class="reference internal" href="#metpy.io.Level2File.__init__" title="metpy.io.Level2File.__init__"><code class="xref py py-obj docutils literal notranslate"><span class="pre">__init__</span></code></a>(filename)</td> <td>Create instance of <a class="reference internal" href="#metpy.io.Level2File" title="metpy.io.Level2File"><code class="xref py py-obj docutils literal notranslate"><span class="pre">Level2File</span></code></a>.</td> </tr> </tbody> </table> <p class="rubric">Attributes Documentation</p> <dl class="attribute"> <dt id="metpy.io.Level2File.AR2_BLOCKSIZE"> <code class="descname">AR2_BLOCKSIZE</code><em class="property"> = 2432</em><a class="headerlink" href="#metpy.io.Level2File.AR2_BLOCKSIZE" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.CTM_HEADER_SIZE"> <code class="descname">CTM_HEADER_SIZE</code><em class="property"> = 12</em><a class="headerlink" href="#metpy.io.Level2File.CTM_HEADER_SIZE" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.MISSING"> <code class="descname">MISSING</code><em class="property"> = nan</em><a class="headerlink" href="#metpy.io.Level2File.MISSING" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.RANGE_FOLD"> <code class="descname">RANGE_FOLD</code><em class="property"> = nan</em><a class="headerlink" href="#metpy.io.Level2File.RANGE_FOLD" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.data_block_fmt"> <code class="descname">data_block_fmt</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.data_block_fmt" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.msg15_code_map"> <code class="descname">msg15_code_map</code><em class="property"> = {0: 'Bypass Filter', 1: 'Bypass map in Control', 2: 'Force Filter'}</em><a class="headerlink" href="#metpy.io.Level2File.msg15_code_map" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.msg1_fmt"> <code class="descname">msg1_fmt</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.msg1_fmt" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.msg2_fmt"> <code class="descname">msg2_fmt</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.msg2_fmt" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.msg31_data_hdr_fmt"> <code class="descname">msg31_data_hdr_fmt</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.msg31_data_hdr_fmt" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.msg31_el_const_fmt"> <code class="descname">msg31_el_const_fmt</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.msg31_el_const_fmt" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.msg31_vol_const_fmt"> <code class="descname">msg31_vol_const_fmt</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.msg31_vol_const_fmt" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.msg_hdr_fmt"> <code class="descname">msg_hdr_fmt</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.msg_hdr_fmt" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.rad_const_fmt_v1"> <code class="descname">rad_const_fmt_v1</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.rad_const_fmt_v1" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.rad_const_fmt_v2"> <code class="descname">rad_const_fmt_v2</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.rad_const_fmt_v2" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.vcp_el_fmt"> <code class="descname">vcp_el_fmt</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.vcp_el_fmt" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.vcp_fmt"> <code class="descname">vcp_fmt</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.vcp_fmt" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="attribute"> <dt id="metpy.io.Level2File.vol_hdr_fmt"> <code class="descname">vol_hdr_fmt</code><em class="property"> = &lt;metpy.io._tools.NamedStruct object&gt;</em><a class="headerlink" href="#metpy.io.Level2File.vol_hdr_fmt" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p class="rubric">Methods Documentation</p> <dl class="method"> <dt id="metpy.io.Level2File.__init__"> <code class="descname">__init__</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/metpy/io/nexrad.html#Level2File.__init__"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#metpy.io.Level2File.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Create instance of <a class="reference internal" href="#metpy.io.Level2File" title="metpy.io.Level2File"><code class="xref py py-obj docutils literal notranslate"><span class="pre">Level2File</span></code></a>.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>filename</strong> (<a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.6)"><em>str</em></a><em> or </em><em>file-like object</em>) – If str, the name of the file to be opened. Gzip-ed files are recognized with the extension ‘.gz’, as are bzip2-ed files with the extension <a class="reference external" href="https://docs.python.org/3/library/bz2.html#module-bz2" title="(in Python v3.6)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">bz2</span></code></a> If <em class="xref py py-obj">fname</em> is a file-like object, this will be read from directly.</td> </tr> </tbody> </table> </dd></dl> </dd></dl> <div class="section" id="examples-using-metpy-io-level2file"> <h2>Examples using <code class="docutils literal notranslate"><span class="pre">metpy.io.Level2File</span></code><a class="headerlink" href="#examples-using-metpy-io-level2file" title="Permalink to this headline">¶</a></h2> <div class="sphx-glr-thumbcontainer" tooltip="Use MetPy to read information from a NEXRAD Level 2 (volume) file and plot "><div class="figure" id="id1"> <img alt="../../_images/sphx_glr_NEXRAD_Level_2_File_thumb.png" src="../../_images/sphx_glr_NEXRAD_Level_2_File_thumb.png" /> <p class="caption"><span class="caption-text"><a class="reference internal" href="../../examples/formats/NEXRAD_Level_2_File.html#sphx-glr-examples-formats-nexrad-level-2-file-py"><span class="std std-ref">NEXRAD Level 2 File</span></a></span></p> </div> </div><div style='clear:both'></div></div> </div> </div> <div class="articleComments"> </div> </div> <footer> <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation"> <a href="metpy.io.Level3File.html" class="btn btn-neutral float-right" title="Level3File" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a> <a href="metpy.io.GiniFile.html" class="btn btn-neutral" title="GiniFile" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a> </div> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2017, MetPy Developers. Last updated on May 17, 2018 at 20:56:37. </p> </div> Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-92978945-1', 'auto'); ga('send', 'pageview'); </script> <script>var version_json_loc = "../../../versions.json";</script> <p>Do you enjoy using MetPy? <a href="https://saythanks.io/to/unidata" class="btn btn-neutral" title="Say Thanks!" accesskey="n">Say Thanks!</a> </p> </footer> </div> </div> </section> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'../../', VERSION:'0.8.0', LANGUAGE:'None', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="../../_static/pop_ver.js"></script> <script type="text/javascript" src="../../_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.StickyNav.enable(); }); </script> </body> </html>
bsd-3-clause
capira12/capira-socrates-channels
app/elements/account-dialog/account-dialog.html
2977
<link rel="import" href="../../bower_components/polymer/polymer.html"> <dom-module id="account-dialog"> <style> :host { display: block; } paper-dialog { width: 400px; } </style> <template> <iron-a11y-keys target="{{}}" keys="enter" on-keys-pressed="_confirm"></iron-a11y-keys> <paper-dialog id="login" with-backdrop entry-animation="scale-up-animation" exit-animation="fade-out-animation" with-backdrop> <h2>Capira Login</h2> <p> <paper-input label="Enter your Username" value="{{username}}" autofocus></paper-input> <paper-input label="Enter your Password" value="{{password}}" type="password"></paper-input> </p> <div class="buttons"> <paper-button dialog-dismiss>Cancel</paper-button> <paper-button on-click="_confirm">Login</paper-button> </div> </paper-dialog> <paper-dialog id="logout" with-backdrop entry-animation="scale-up-animation" exit-animation="fade-out-animation" with-backdrop> <h2><span>{{user.name}}</span>'s Profile</h2> <p> Email: <span>{{user.email}}</span> </p> <div class="buttons"> <paper-button on-click="_confirmLogout">Logout</paper-button> <paper-button dialog-dismiss>Close</paper-button> </div> </paper-dialog> </template> </dom-module> <script> (function() { 'use strict'; Polymer({ is: 'account-dialog', open: function() { this.username = ''; this.password = ''; var that = this; app.services.fetchMe().then(function(req) { console.log(req.response); that.user = req.response; if (!that.user.name) { that.$.login.open(); } else { that.$.logout.open(); } }); }, _confirm: function() { var that = this; app.services.login(this.username,this.password).then(function(req) { var resp = req.response; console.log(resp); switch (resp) { case 42: that.$.login.close(); that.fire('change-user'); break; case -42: console.log('Wrong username or Password!'); break; default: console.log('Sth went terribly wrong!'); } }); }, _confirmLogout: function() { var that = this; app.services.logout().then(function() { that.$.logout.close(); that.fire('change-user'); }); } }); })(); </script>
bsd-3-clause
inamjung/fct
modules/fct/views/fct/indexcaseok.php
8182
<?php use yii\helpers\Html; use kartik\grid\GridView; use yii\widgets\ActiveForm; use yii\bootstrap\Modal; use yii\widgets\Pjax; /* @var $this yii\web\View */ /* @var $searchModel app\modules\fct\models\FctSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'ผู้ป่วยในระบบ FCT'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="fct-index"> <!-- <h1><?= Html::encode($this->title) ?></h1>--> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <!-- <p> <?= Html::a('Create Fct', ['create'], ['class' => 'btn btn-success']) ?> </p>--> <div class="panel panel-success"> <div class="panel-heading"> รายชื่อผู้ป่วย</div> <div class="panel-body"> <?php Pjax::begin(['id' => 'fct_id']); ?> <?= GridView::widget([ 'dataProvider' => $dataProvider, //'filterModel' => $searchModel, 'formatter' => ['class' => 'yii\i18n\Formatter', 'nullDisplay' => '-'], 'striped' => false, 'hover' => true, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], //'id', //'fcttype_id', //'pass', //'colour_id', 'senddate', 'cid', //'hn', // 'an', 'ptname', //'birthday', [ 'attribute' => 'sex', 'format' => 'html', 'value' => function($model, $key, $index, $column) { return $model->sex == 1 ? "<span style=\"color:green;\">ชาย</span>" : "<span style=\"color:red;\">หญิง</span>"; } ], // 'ptage', // 'diage', // 'pps', // 'pain', // 'painnote', // 'cc', // 'pi', // 'bt', // 'pr', // 'rr', // 'bp', // 'drugallergy', // 'admit', // 'dc', // 'or', // 'ordate', // 'disease', // 'receive', 'address', // 'ptcate', // 'hossub', // 'tra', // 'retng', // 'retfo', // 'colobag', // 'lesion', // 'lesioncare', // 'recov', // 'recovcare', // 'oxygen', // 'lr01', // 'lr02', // 'lr03', // 'lr04', // 'lr05', // 'lr06', // 'lr07', // 'lr08', // 'lr09', // 'lr10', // 'lrl01', // 'lrl02', // 'lrl03', // 'lrl04', // 'lrl05', // 'lrl06', // 'lrl07', // 'lrl08', // 'lr', // 'lrl09', // 'lrl10', // 'lrl11', // 'lrl12', // 'lrl13', // 'other', // 'appdate', // 'doctorapp', // 'appdate2', // 'doctorapp2', // 'appdate3', // 'doctorapp3', // 'windpipe', // 'insulin', // 'equip', // 'depart', // 'hosin', // 'officer', // 'confirm', // 'confirmfct', //'tmbpart', 'phone', //'bloodgrp', // [ // 'class' => 'kartik\grid\BooleanColumn', // 'attribute' => 'send', // ], // [ // 'class' => 'kartik\grid\BooleanColumn', // 'attribute' => 'okcase', // ], [ 'class' => 'yii\grid\ActionColumn', 'options' => ['style' => 'width:100px;'], 'template' => '<div class="btn-group btn-group-sm" role="group" aria-label="...">{update}</div>', 'buttons' => [ // 'view'=>function($url,$model,$key){ // return Html::a('<i class="glyphicon glyphicon-search"></i>',$url,['class'=>'btn btn-default']); // }, 'update' => function($url, $model, $key) { return Html::a('<i class="glyphicon glyphicon-pencil"></i> ', ['/fct/fcthhc/update', 'id' => $model->id], [ 'class' => 'activity-update-link btn btn-info', 'title' => 'บันทึก', // 'data-toggle' => 'modal', // 'data-target' => '#activity-modal', // 'data-id' => $key, // 'data-pjax' => '0', ]); }, // // 'delete'=>function($url,$model,$key){ // return Html::a('<i class="glyphicon glyphicon-trash"></i>', $url,[ // 'title' => Yii::t('yii', 'Delete'), // 'data-confirm' => Yii::t('yii', 'คุณต้องการลบไฟล์นี้?'), // 'data-method' => 'post', // 'data-pjax' => '0', // 'class'=>'btn btn-default' // ]); // } ] ], ], ]); ?> <?php Pjax::end() ?> </div> </div> </div> <?php Modal::begin([ 'id' => 'activity-modal', 'header' => '<h4 class="modal-title"></h4>', 'size' => 'modal-lg', 'footer' => '<a href="#" class="btn btn-primary" data-dismiss="modal">ปิด</a>', ]); Modal::end(); ?> <?php $this->registerJs(' function init_click_handlers(){ $(".activity-update-link").click(function(e) { var fID = $(this).closest("tr").data("key"); $.get( "?r=fct/fcthhc/update", { fct_id: fID }, function (data) { $("#activity-modal").find(".modal-body").html(data); $(".modal-body").html(data); $(".modal-title").html("รับผู้ป่วยที่มีความเสี่ยงเข้าระบบ"); $("#activity-modal").modal("show"); } ); }); } init_click_handlers(); //first run $("#fct_id").on("pjax:success", function() { init_click_handlers(); //reactivate links in grid after pjax update });'); ?>
bsd-3-clause
abstools/easyinterface
server/config/envisage/offlineabsexamples.sh
652
#!/bin/bash root="${1%/}/" n=1 leadingchas() { for ((i=0; i<$n; i++)) do echo -n " " done } recursiverm() { ((n++)) for d in *; do if [ -d $d ]; then (leadingchas) echo "<folder name='$d'>" (cd $d; recursiverm) (leadingchas) echo "</folder>" else x="`pwd`/$d" (leadingchas) echo -n "<file name='$d' url='" echo -n "/absexamples/" echo -n ${x#$root} echo "' />" fi done ((n--)) } echo "<examples>" echo "<exset id='set1'>" echo "<folder name='collaboratory'>" (cd $root/collaboratory; recursiverm) echo "</folder>" echo "</exset>" echo "</examples>"
bsd-3-clause
nwjs/chromium.src
third_party/blink/renderer/core/inspector/inspector_emulation_agent.h
7396
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTOR_EMULATION_AGENT_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTOR_EMULATION_AGENT_H_ #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/inspector/inspector_base_agent.h" #include "third_party/blink/renderer/core/inspector/protocol/Emulation.h" #include "third_party/blink/renderer/core/loader/frame_loader_types.h" #include "third_party/blink/renderer/core/timezone/timezone_controller.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h" #include "third_party/blink/renderer/platform/scheduler/public/page_scheduler.h" namespace blink { class DocumentLoader; class ResourceRequest; class WebLocalFrameImpl; class WebViewImpl; enum class ResourceType : uint8_t; namespace protocol { namespace DOM { class RGBA; } // namespace DOM } // namespace protocol class CORE_EXPORT InspectorEmulationAgent final : public InspectorBaseAgent<protocol::Emulation::Metainfo> { public: explicit InspectorEmulationAgent(WebLocalFrameImpl*); InspectorEmulationAgent(const InspectorEmulationAgent&) = delete; InspectorEmulationAgent& operator=(const InspectorEmulationAgent&) = delete; ~InspectorEmulationAgent() override; // protocol::Dispatcher::EmulationCommandHandler implementation. protocol::Response resetPageScaleFactor() override; protocol::Response setPageScaleFactor(double) override; protocol::Response setScriptExecutionDisabled(bool value) override; protocol::Response setScrollbarsHidden(bool hidden) override; protocol::Response setDocumentCookieDisabled(bool disabled) override; protocol::Response setTouchEmulationEnabled( bool enabled, protocol::Maybe<int> max_touch_points) override; protocol::Response setEmulatedMedia( protocol::Maybe<String> media, protocol::Maybe<protocol::Array<protocol::Emulation::MediaFeature>> features) override; protocol::Response setEmulatedVisionDeficiency(const String&) override; protocol::Response setCPUThrottlingRate(double) override; protocol::Response setFocusEmulationEnabled(bool) override; protocol::Response setAutoDarkModeOverride(protocol::Maybe<bool>) override; protocol::Response setVirtualTimePolicy( const String& policy, protocol::Maybe<double> virtual_time_budget_ms, protocol::Maybe<int> max_virtual_time_task_starvation_count, protocol::Maybe<bool> wait_for_navigation, protocol::Maybe<double> initial_virtual_time, double* virtual_time_ticks_base_ms) override; protocol::Response setTimezoneOverride(const String& timezone_id) override; protocol::Response setNavigatorOverrides(const String& platform) override; protocol::Response setDefaultBackgroundColorOverride( protocol::Maybe<protocol::DOM::RGBA>) override; protocol::Response setDeviceMetricsOverride( int width, int height, double device_scale_factor, bool mobile, protocol::Maybe<double> scale, protocol::Maybe<int> screen_width, protocol::Maybe<int> screen_height, protocol::Maybe<int> position_x, protocol::Maybe<int> position_y, protocol::Maybe<bool> dont_set_visible_size, protocol::Maybe<protocol::Emulation::ScreenOrientation>, protocol::Maybe<protocol::Page::Viewport>, protocol::Maybe<protocol::Emulation::DisplayFeature>) override; protocol::Response clearDeviceMetricsOverride() override; protocol::Response setUserAgentOverride( const String& user_agent, protocol::Maybe<String> accept_language, protocol::Maybe<String> platform, protocol::Maybe<protocol::Emulation::UserAgentMetadata> ua_metadata_override) override; protocol::Response setLocaleOverride(protocol::Maybe<String>) override; protocol::Response setDisabledImageTypes( std::unique_ptr<protocol::Array<protocol::Emulation::DisabledImageType>>) override; // InspectorInstrumentation API void ApplyAcceptLanguageOverride(String* accept_lang); void ApplyUserAgentOverride(String* user_agent); void ApplyUserAgentMetadataOverride( absl::optional<blink::UserAgentMetadata>* ua_metadata); void FrameStartedLoading(LocalFrame*); void PrepareRequest(DocumentLoader*, ResourceRequest&, ResourceLoaderOptions&, ResourceType); void GetDisabledImageTypes(HashSet<String>* result); void WillCommitLoad(LocalFrame*, DocumentLoader*); // InspectorBaseAgent overrides. protocol::Response disable() override; void Restore() override; void Trace(Visitor*) const override; static AtomicString OverrideAcceptImageHeader(const HashSet<String>*); private: WebViewImpl* GetWebViewImpl(); protocol::Response AssertPage(); void VirtualTimeBudgetExpired(); void InnerEnable(); struct PendingVirtualTimePolicy { PageScheduler::VirtualTimePolicy policy; absl::optional<double> virtual_time_budget_ms; absl::optional<int> max_virtual_time_task_starvation_count; }; void ApplyVirtualTimePolicy(const PendingVirtualTimePolicy& new_policy); Member<WebLocalFrameImpl> web_local_frame_; base::TimeTicks virtual_time_base_ticks_; HeapVector<Member<DocumentLoader>> pending_document_loaders_; std::unique_ptr<TimeZoneController::TimeZoneOverride> timezone_override_; // Supports a virtual time policy change scheduled to occur after any // navigation has started. absl::optional<PendingVirtualTimePolicy> pending_virtual_time_policy_; bool enabled_ = false; InspectorAgentState::Bytes default_background_color_override_rgba_; InspectorAgentState::Boolean script_execution_disabled_; InspectorAgentState::Boolean scrollbars_hidden_; InspectorAgentState::Boolean document_cookie_disabled_; InspectorAgentState::Boolean touch_event_emulation_enabled_; InspectorAgentState::Integer max_touch_points_; InspectorAgentState::String emulated_media_; InspectorAgentState::StringMap emulated_media_features_; InspectorAgentState::String emulated_vision_deficiency_; InspectorAgentState::String navigator_platform_override_; InspectorAgentState::String user_agent_override_; InspectorAgentState::Bytes serialized_ua_metadata_override_; absl::optional<blink::UserAgentMetadata> ua_metadata_override_; InspectorAgentState::String accept_language_override_; InspectorAgentState::String locale_override_; InspectorAgentState::Double virtual_time_budget_; InspectorAgentState::Double initial_virtual_time_; InspectorAgentState::String virtual_time_policy_; InspectorAgentState::Integer virtual_time_task_starvation_count_; InspectorAgentState::Boolean wait_for_navigation_; InspectorAgentState::Boolean emulate_focus_; InspectorAgentState::Boolean emulate_auto_dark_mode_; InspectorAgentState::Boolean auto_dark_mode_override_; InspectorAgentState::String timezone_id_override_; InspectorAgentState::BooleanMap disabled_image_types_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTOR_EMULATION_AGENT_H_
bsd-3-clause
HarkerRobo/robocode14
src/RobotCode2014/commands/manipulator/PitchAccelerationCommand.java
1076
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package RobotCode2014.commands.manipulator; import RobotCode2014.commands.CommandBase; /** * * @author me */ public class PitchAccelerationCommand extends CommandBase { public PitchAccelerationCommand() { } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { manipPitch.updatePitchSpeed(); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
bsd-3-clause
kivi8/ars-poetica
vendor/nette/di/src/DI/ContainerBuilder.php
27588
<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ namespace Nette\DI; use Nette; use Nette\Utils\Validators; use Nette\Utils\Strings; use Nette\PhpGenerator\Helpers as PhpHelpers; use ReflectionClass; /** * Basic container builder. */ class ContainerBuilder extends Nette\Object { const THIS_SERVICE = 'self', THIS_CONTAINER = 'container'; /** @var array */ public $parameters = array(); /** @var string */ private $className = 'Container'; /** @var ServiceDefinition[] */ private $definitions = array(); /** @var array of alias => service */ private $aliases = array(); /** @var array for auto-wiring */ private $classes; /** @var string[] of classes excluded from auto-wiring */ private $excludedClasses = array(); /** @var array of file names */ private $dependencies = array(); /** @var Nette\PhpGenerator\ClassType[] */ private $generatedClasses = array(); /** @var string */ /*private in 5.4*/public $currentService; /** * Adds new service definition. * @param string * @return ServiceDefinition */ public function addDefinition($name, ServiceDefinition $definition = NULL) { if (!is_string($name) || !$name) { // builder is not ready for falsy names such as '0' throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($name))); } $name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name; if (isset($this->definitions[$name])) { throw new Nette\InvalidStateException("Service '$name' has already been added."); } return $this->definitions[$name] = $definition ?: new ServiceDefinition; } /** * Removes the specified service definition. * @param string * @return void */ public function removeDefinition($name) { $name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name; unset($this->definitions[$name]); if ($this->classes) { foreach ($this->classes as & $tmp) { foreach ($tmp as & $names) { $names = array_values(array_diff($names, array($name))); } } } } /** * Gets the service definition. * @param string * @return ServiceDefinition */ public function getDefinition($name) { $service = isset($this->aliases[$name]) ? $this->aliases[$name] : $name; if (!isset($this->definitions[$service])) { throw new MissingServiceException("Service '$name' not found."); } return $this->definitions[$service]; } /** * Gets all service definitions. * @return ServiceDefinition[] */ public function getDefinitions() { return $this->definitions; } /** * Does the service definition or alias exist? * @param string * @return bool */ public function hasDefinition($name) { $name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name; return isset($this->definitions[$name]); } /** * @param string * @param string */ public function addAlias($alias, $service) { if (!is_string($alias) || !$alias) { // builder is not ready for falsy names such as '0' throw new Nette\InvalidArgumentException(sprintf('Alias name must be a non-empty string, %s given.', gettype($alias))); } elseif (!is_string($service) || !$service) { // builder is not ready for falsy names such as '0' throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($service))); } elseif (isset($this->aliases[$alias])) { throw new Nette\InvalidStateException("Alias '$alias' has already been added."); } elseif (isset($this->definitions[$alias])) { throw new Nette\InvalidStateException("Service '$alias' has already been added."); } $this->aliases[$alias] = $service; } /** * Removes the specified alias. * @return void */ public function removeAlias($alias) { unset($this->aliases[$alias]); } /** * Gets all service aliases. * @return array */ public function getAliases() { return $this->aliases; } /** * @return self */ public function setClassName($name) { $this->className = (string) $name; return $this; } /** * @return string */ public function getClassName() { return $this->className; } /********************* class resolving ****************d*g**/ /** * Resolves service name by type. * @param string class or interface * @return string|NULL service name or NULL * @throws ServiceCreationException */ public function getByType($class) { $class = ltrim($class, '\\'); if ($this->currentService !== NULL) { $curClass = $this->definitions[$this->currentService]->getClass(); if ($curClass === $class || is_subclass_of($curClass, $class)) { return $this->currentService; } } if (empty($this->classes[$class][TRUE])) { self::checkCase($class); return; } elseif (count($this->classes[$class][TRUE]) === 1) { return $this->classes[$class][TRUE][0]; } else { throw new ServiceCreationException("Multiple services of type $class found: " . implode(', ', $this->classes[$class][TRUE])); } } /** * Gets the service names and definitions of the specified type. * @param string * @return ServiceDefinition[] */ public function findByType($class) { $class = ltrim($class, '\\'); self::checkCase($class); $found = array(); if (!empty($this->classes[$class])) { foreach (call_user_func_array('array_merge', $this->classes[$class]) as $name) { $found[$name] = $this->definitions[$name]; } } return $found; } /** * Gets the service objects of the specified tag. * @param string * @return array of [service name => tag attributes] */ public function findByTag($tag) { $found = array(); foreach ($this->definitions as $name => $def) { if (($tmp = $def->getTag($tag)) !== NULL) { $found[$name] = $tmp; } } return $found; } /** * Creates a list of arguments using autowiring. * @return array */ public function autowireArguments($class, $method, array $arguments) { $rc = new ReflectionClass($class); if (!$rc->hasMethod($method)) { if (!Nette\Utils\Arrays::isList($arguments)) { throw new ServiceCreationException("Unable to pass specified arguments to $class::$method()."); } return $arguments; } $rm = $rc->getMethod($method); if (!$rm->isPublic()) { throw new ServiceCreationException("$class::$method() is not callable."); } $this->addDependency($rm->getFileName()); return Helpers::autowireArguments($rm, $arguments, $this); } /** * Generates $dependencies, $classes and normalizes class names. * @return array * @internal */ public function prepareClassList() { unset($this->definitions[self::THIS_CONTAINER]); $this->addDefinition(self::THIS_CONTAINER)->setClass('Nette\DI\Container'); $this->classes = FALSE; foreach ($this->definitions as $name => $def) { // prepare generated factories if ($def->getImplement()) { $this->resolveImplement($def, $name); } if ($def->isDynamic()) { if (!$def->getClass()) { throw new ServiceCreationException("Class is missing in definition of service '$name'."); } $def->setFactory(NULL); continue; } // complete class-factory pairs if (!$def->getEntity()) { if (!$def->getClass()) { throw new ServiceCreationException("Class and factory are missing in definition of service '$name'."); } $def->setFactory($def->getClass(), ($factory = $def->getFactory()) ? $factory->arguments : array()); } // auto-disable autowiring for aliases if (($alias = $this->getServiceName($def->getFactory()->getEntity())) && (!$def->getImplement() || (!Strings::contains($alias, '\\') && $this->definitions[$alias]->getImplement())) ) { $def->setAutowired(FALSE); } } // resolve and check classes foreach ($this->definitions as $name => $def) { $this->resolveServiceClass($name); } // build auto-wiring list $excludedClasses = array(); foreach ($this->excludedClasses as $class) { self::checkCase($class); $excludedClasses += class_parents($class) + class_implements($class) + array($class => $class); } $this->classes = array(); foreach ($this->definitions as $name => $def) { if ($class = $def->getImplement() ?: $def->getClass()) { foreach (class_parents($class) + class_implements($class) + array($class) as $parent) { $this->classes[$parent][$def->isAutowired() && empty($excludedClasses[$parent])][] = (string) $name; } } } foreach ($this->classes as $class => $foo) { $rc = new ReflectionClass($class); $this->addDependency($rc->getFileName()); } } private function resolveImplement(ServiceDefinition $def, $name) { $interface = $def->getImplement(); if (!interface_exists($interface)) { throw new ServiceCreationException("Interface $interface used in service '$name' not found."); } self::checkCase($interface); $rc = new ReflectionClass($interface); $method = $rc->hasMethod('create') ? $rc->getMethod('create') : ($rc->hasMethod('get') ? $rc->getMethod('get') : NULL); if (count($rc->getMethods()) !== 1 || !$method || $method->isStatic()) { throw new ServiceCreationException("Interface $interface used in service '$name' must have just one non-static method create() or get()."); } $def->setImplementType($methodName = $rc->hasMethod('create') ? 'create' : 'get'); if (!$def->getClass() && !$def->getEntity()) { $returnType = PhpReflection::getReturnType($method); if (!$returnType) { throw new ServiceCreationException("Method $interface::$methodName() used in service '$name' has no @return annotation."); } elseif (!class_exists($returnType)) { throw new ServiceCreationException("Check a @return annotation of the $interface::$methodName() method used in service '$name', class '$returnType' cannot be found."); } $def->setClass($returnType); } if ($methodName === 'get') { if ($method->getParameters()) { throw new ServiceCreationException("Method $interface::get() used in service '$name' must have no arguments."); } if (!$def->getEntity()) { $def->setFactory('@\\' . ltrim($def->getClass(), '\\')); } elseif (!$this->getServiceName($def->getFactory()->getEntity())) { throw new ServiceCreationException("Invalid factory in service '$name' definition."); } } if (!$def->parameters) { $ctorParams = array(); if (!$def->getEntity()) { $def->setFactory($def->getClass(), $def->getFactory() ? $def->getFactory()->arguments : array()); } if (($class = $this->resolveEntityClass($def->getFactory(), array($name => 1))) && ($rc = new ReflectionClass($class)) && ($ctor = $rc->getConstructor()) ) { foreach ($ctor->getParameters() as $param) { $ctorParams[$param->getName()] = $param; } } foreach ($method->getParameters() as $param) { $hint = PhpReflection::getParameterType($param); if (isset($ctorParams[$param->getName()])) { $arg = $ctorParams[$param->getName()]; if ($hint !== PhpReflection::getParameterType($arg)) { throw new ServiceCreationException("Type hint for \${$param->getName()} in $interface::$methodName() doesn't match type hint in $class constructor."); } $def->getFactory()->arguments[$arg->getPosition()] = self::literal('$' . $arg->getName()); } elseif (!$def->getSetup()) { $hint = Nette\Utils\ObjectMixin::getSuggestion(array_keys($ctorParams), $param->getName()); throw new ServiceCreationException("Unused parameter \${$param->getName()} when implementing method $interface::$methodName()" . ($hint ? ", did you mean \${$hint}?" : '.')); } $paramDef = $hint . ' ' . $param->getName(); if ($param->isOptional()) { $def->parameters[$paramDef] = $param->getDefaultValue(); } else { $def->parameters[] = $paramDef; } } } } /** @return string|NULL */ private function resolveServiceClass($name, $recursive = array()) { if (isset($recursive[$name])) { throw new ServiceCreationException(sprintf('Circular reference detected for services: %s.', implode(', ', array_keys($recursive)))); } $recursive[$name] = TRUE; $def = $this->definitions[$name]; $class = $def->getFactory() ? $this->resolveEntityClass($def->getFactory()->getEntity(), $recursive) : NULL; // call always to check entities if ($class = $def->getClass() ?: $class) { $def->setClass($class); if (!class_exists($class) && !interface_exists($class)) { throw new ServiceCreationException("Type $class used in service '$name' not found or is not class or interface."); } self::checkCase($class); } elseif ($def->isAutowired()) { trigger_error("Type of service '$name' is unknown.", E_USER_NOTICE); } return $class; } /** @return string|NULL */ private function resolveEntityClass($entity, $recursive = array()) { $entity = $this->normalizeEntity($entity instanceof Statement ? $entity->getEntity() : $entity); if (is_array($entity)) { if (($service = $this->getServiceName($entity[0])) || $entity[0] instanceof Statement) { $entity[0] = $this->resolveEntityClass($entity[0], $recursive); if (!$entity[0]) { return; } elseif (isset($this->definitions[$service]) && $this->definitions[$service]->getImplement()) { // @Implement::create return $entity[1] === 'create' ? $this->resolveServiceClass($service, $recursive) : NULL; } } try { $reflection = Nette\Utils\Callback::toReflection($entity[0] === '' ? $entity[1] : $entity); $refClass = $reflection instanceof \ReflectionMethod ? $reflection->getDeclaringClass() : NULL; } catch (\ReflectionException $e) { } if (isset($e) || ($refClass && (!$reflection->isPublic() || (PHP_VERSION_ID >= 50400 && $refClass->isTrait() && !$reflection->isStatic()) ))) { $name = array_slice(array_keys($recursive), -1); throw new ServiceCreationException(sprintf("Factory '%s' used in service '%s' is not callable.", Nette\Utils\Callback::toString($entity), $name[0])); } return PhpReflection::getReturnType($reflection); } elseif ($service = $this->getServiceName($entity)) { // alias or factory if (Strings::contains($service, '\\')) { // @\Class return ltrim($service, '\\'); } return $this->definitions[$service]->getImplement() ?: $this->resolveServiceClass($service, $recursive); } elseif (is_string($entity)) { if (!class_exists($entity) || !($rc = new ReflectionClass($entity)) || !$rc->isInstantiable()) { $name = array_slice(array_keys($recursive), -1); throw new ServiceCreationException("Class $entity used in service '$name[0]' not found or is not instantiable."); } return ltrim($entity, '\\'); } } private function checkCase($class) { if ((class_exists($class) || interface_exists($class)) && ($rc = new ReflectionClass($class)) && $class !== $rc->getName()) { throw new ServiceCreationException("Case mismatch on class name '$class', correct name is '{$rc->getName()}'."); } } /** * @param string[] * @return self */ public function addExcludedClasses(array $classes) { $this->excludedClasses = array_merge($this->excludedClasses, $classes); return $this; } /** * Adds a file to the list of dependencies. * @return self * @internal */ public function addDependency($file) { $this->dependencies[$file] = TRUE; return $this; } /** * Returns the list of dependent files. * @return array */ public function getDependencies() { unset($this->dependencies[FALSE]); return array_keys($this->dependencies); } /********************* code generator ****************d*g**/ /** * Generates PHP classes. First class is the container. * @return Nette\PhpGenerator\ClassType[] */ public function generateClasses($className = NULL, $parentName = NULL) { $this->prepareClassList(); $this->generatedClasses = array(); $this->className = $className ?: $this->className; $containerClass = $this->generatedClasses[] = new Nette\PhpGenerator\ClassType($this->className); $containerClass->setExtends($parentName ?: 'Nette\DI\Container'); $containerClass->addMethod('__construct') ->addBody('parent::__construct(?);', array($this->parameters)); $definitions = $this->definitions; ksort($definitions); $meta = $containerClass->addProperty('meta') ->setVisibility('protected') ->setValue(array(Container::TYPES => $this->classes)); foreach ($definitions as $name => $def) { $meta->value[Container::SERVICES][$name] = $def->getClass() ?: NULL; foreach ($def->getTags() as $tag => $value) { $meta->value[Container::TAGS][$tag][$name] = $value; } } foreach ($definitions as $name => $def) { try { $name = (string) $name; $methodName = Container::getMethodName($name); if (!PhpHelpers::isIdentifier($methodName)) { throw new ServiceCreationException('Name contains invalid characters.'); } $containerClass->addMethod($methodName) ->addComment('@return ' . ($def->getImplement() ?: $def->getClass())) ->setBody($name === self::THIS_CONTAINER ? 'return $this;' : $this->generateService($name)) ->setParameters($def->getImplement() ? array() : $this->convertParameters($def->parameters)); } catch (\Exception $e) { throw new ServiceCreationException("Service '$name': " . $e->getMessage(), NULL, $e); } } $aliases = $this->aliases; ksort($aliases); $meta->value[Container::ALIASES] = $aliases; return $this->generatedClasses; } /** * Generates body of service method. * @return string */ private function generateService($name) { $this->currentService = NULL; $def = $this->definitions[$name]; if ($def->isDynamic()) { return PhpHelpers::formatArgs('throw new Nette\\DI\\ServiceCreationException(?);', array("Unable to create dynamic service '$name', it must be added using addService()") ); } $entity = $def->getFactory()->getEntity(); $serviceRef = $this->getServiceName($entity); $factory = $serviceRef && !$def->getFactory()->arguments && !$def->getSetup() && $def->getImplementType() !== 'create' ? new Statement(array('@' . self::THIS_CONTAINER, 'getService'), array($serviceRef)) : $def->getFactory(); $code = '$service = ' . $this->formatStatement($factory) . ";\n"; $this->currentService = $name; if (($class = $def->getClass()) && !$serviceRef && $class !== $entity && !(is_string($entity) && preg_match('#^[\w\\\\]+\z#', $entity) && is_subclass_of($entity, $class)) ) { $code .= PhpHelpers::formatArgs("if (!\$service instanceof $class) {\n" . "\tthrow new Nette\\UnexpectedValueException(?);\n}\n", array("Unable to create service '$name', value returned by factory is not $class type.") ); } foreach ($def->getSetup() as $setup) { if (is_string($setup->getEntity()) && strpbrk($setup->getEntity(), ':@?\\') === FALSE) { // auto-prepend @self $setup->setEntity(array('@self', $setup->getEntity())); } $code .= $this->formatStatement($setup) . ";\n"; } $this->currentService = NULL; $code .= 'return $service;'; if (!$def->getImplement()) { return $code; } $factoryClass = $this->generatedClasses[] = new Nette\PhpGenerator\ClassType; $factoryClass->setName(str_replace(array('\\', '.'), '_', "{$this->className}_{$def->getImplement()}Impl_{$name}")) ->addImplement($def->getImplement()) ->setFinal(TRUE); $factoryClass->addProperty('container') ->setVisibility('private'); $factoryClass->addMethod('__construct') ->addBody('$this->container = $container;') ->addParameter('container') ->setTypeHint($this->className); $factoryClass->addMethod($def->getImplementType()) ->setParameters($this->convertParameters($def->parameters)) ->setBody(str_replace('$this', '$this->container', $code)) ->setReturnType(PHP_VERSION_ID >= 70000 ? $def->getClass() : NULL); return "return new {$factoryClass->getName()}(\$this);"; } /** * Converts parameters from ServiceDefinition to PhpGenerator. * @return Nette\PhpGenerator\Parameter[] */ private function convertParameters(array $parameters) { $res = array(); foreach ($parameters as $k => $v) { $tmp = explode(' ', is_int($k) ? $v : $k); $param = $res[] = new Nette\PhpGenerator\Parameter; $param->setName(end($tmp)); if (!is_int($k)) { $param = $param->setOptional(TRUE)->setDefaultValue($v); } if (isset($tmp[1])) { $param->setTypeHint($tmp[0]); } } return $res; } /** * Formats PHP code for class instantiating, function calling or property setting in PHP. * @return string * @internal */ public function formatStatement(Statement $statement) { $entity = $this->normalizeEntity($statement->getEntity()); $arguments = $statement->arguments; if (is_string($entity) && Strings::contains($entity, '?')) { // PHP literal return $this->formatPhp($entity, $arguments); } elseif ($service = $this->getServiceName($entity)) { // factory calling $params = array(); foreach ($this->definitions[$service]->parameters as $k => $v) { $params[] = preg_replace('#\w+\z#', '\$$0', (is_int($k) ? $v : $k)) . (is_int($k) ? '' : ' = ' . PhpHelpers::dump($v)); } $rm = new \ReflectionFunction(create_function(implode(', ', $params), '')); $arguments = Helpers::autowireArguments($rm, $arguments, $this); return $this->formatPhp('$this->?(?*)', array(Container::getMethodName($service), $arguments)); } elseif ($entity === 'not') { // operator return $this->formatPhp('!?', array($arguments[0])); } elseif (is_string($entity)) { // class name $rc = new ReflectionClass($entity); if ($constructor = $rc->getConstructor()) { $this->addDependency($constructor->getFileName()); $arguments = Helpers::autowireArguments($constructor, $arguments, $this); } elseif ($arguments) { throw new ServiceCreationException("Unable to pass arguments, class $entity has no constructor."); } return $this->formatPhp("new $entity" . ($arguments ? '(?*)' : ''), array($arguments)); } elseif (!Nette\Utils\Arrays::isList($entity) || count($entity) !== 2) { throw new ServiceCreationException(sprintf('Expected class, method or property, %s given.', PhpHelpers::dump($entity))); } elseif (!preg_match('#^\$?' . PhpHelpers::PHP_IDENT . '\z#', $entity[1])) { throw new ServiceCreationException("Expected function, method or property name, '$entity[1]' given."); } elseif ($entity[0] === '') { // globalFunc return $this->formatPhp("$entity[1](?*)", array($arguments)); } elseif ($entity[0] instanceof Statement) { $inner = $this->formatPhp('?', array($entity[0])); if (substr($inner, 0, 4) === 'new ') { $inner = PHP_VERSION_ID < 50400 ? "current(array($inner))" : "($inner)"; } return $this->formatPhp("$inner->?(?*)", array($entity[1], $arguments)); } elseif (Strings::contains($entity[1], '$')) { // property setter Validators::assert($arguments, 'list:1', "setup arguments for '" . Nette\Utils\Callback::toString($entity) . "'"); if ($this->getServiceName($entity[0])) { return $this->formatPhp('?->? = ?', array($entity[0], substr($entity[1], 1), $arguments[0])); } else { return $this->formatPhp($entity[0] . '::$? = ?', array(substr($entity[1], 1), $arguments[0])); } } elseif ($service = $this->getServiceName($entity[0])) { // service method $class = $this->definitions[$service]->getImplement(); if (!$class || !method_exists($class, $entity[1])) { $class = $this->definitions[$service]->getClass(); } if ($class) { $arguments = $this->autowireArguments($class, $entity[1], $arguments); } return $this->formatPhp('?->?(?*)', array($entity[0], $entity[1], $arguments)); } else { // static method $arguments = $this->autowireArguments($entity[0], $entity[1], $arguments); return $this->formatPhp("$entity[0]::$entity[1](?*)", array($arguments)); } } /** * Formats PHP statement. * @return string * @internal */ public function formatPhp($statement, $args) { $that = $this; array_walk_recursive($args, function (& $val) use ($that) { if ($val instanceof Statement) { $val = ContainerBuilder::literal($that->formatStatement($val)); } elseif ($val === $that) { $val = ContainerBuilder::literal('$this'); } elseif ($val instanceof ServiceDefinition) { $val = '@' . current(array_keys($that->getDefinitions(), $val, TRUE)); } if (!is_string($val)) { return; } elseif (substr($val, 0, 2) === '@@') { $val = substr($val, 1); } elseif (substr($val, 0, 1) === '@' && strlen($val) > 1) { $pair = explode('::', $val, 2); $name = $that->getServiceName($pair[0]); if (isset($pair[1]) && preg_match('#^[A-Z][A-Z0-9_]*\z#', $pair[1], $m)) { $val = $that->getDefinition($name)->getClass() . '::' . $pair[1]; } else { if ($name === ContainerBuilder::THIS_CONTAINER) { $val = '$this'; } elseif ($name === $that->currentService) { $val = '$service'; } else { $val = $that->formatStatement(new Statement(array('@' . ContainerBuilder::THIS_CONTAINER, 'getService'), array($name))); } $val .= (isset($pair[1]) ? PhpHelpers::formatArgs('->?', array($pair[1])) : ''); } $val = ContainerBuilder::literal($val); } }); return PhpHelpers::formatArgs($statement, $args); } /** * Expands %placeholders% in strings. * @return mixed * @deprecated */ public function expand($value) { return Helpers::expand($value, $this->parameters); } /** * @return Nette\PhpGenerator\PhpLiteral */ public static function literal($phpCode) { return new Nette\PhpGenerator\PhpLiteral($phpCode); } /** @internal */ public function normalizeEntity($entity) { if (is_string($entity) && Strings::contains($entity, '::') && !Strings::contains($entity, '?')) { // Class::method -> [Class, method] $entity = explode('::', $entity); } if (is_array($entity) && $entity[0] instanceof ServiceDefinition) { // [ServiceDefinition, ...] -> [@serviceName, ...] $entity[0] = '@' . current(array_keys($this->definitions, $entity[0], TRUE)); } elseif ($entity instanceof ServiceDefinition) { // ServiceDefinition -> @serviceName $entity = '@' . current(array_keys($this->definitions, $entity, TRUE)); } elseif (is_array($entity) && $entity[0] === $this) { // [$this, ...] -> [@container, ...] $entity[0] = '@' . self::THIS_CONTAINER; } return $entity; // Class, @service, [Class, member], [@service, member], [, globalFunc], Statement } /** * Converts @service or @\Class -> service name and checks its existence. * @return string of FALSE, if argument is not service name * @internal */ public function getServiceName($arg) { $arg = $this->normalizeEntity($arg); if (!is_string($arg) || !preg_match('#^@[\w\\\\.].*\z#', $arg)) { return FALSE; } $service = substr($arg, 1); if ($service === self::THIS_SERVICE) { $service = $this->currentService; } if (Strings::contains($service, '\\')) { if ($this->classes === FALSE) { // may be disabled by prepareClassList return $service; } $res = $this->getByType($service); if (!$res) { throw new ServiceCreationException("Reference to missing service of type $service."); } return $res; } $service = isset($this->aliases[$service]) ? $this->aliases[$service] : $service; if (!isset($this->definitions[$service])) { throw new ServiceCreationException("Reference to missing service '$service'."); } return $service; } }
bsd-3-clause
statsmodels/statsmodels.github.io
v0.12.2/generated/statsmodels.regression.quantile_regression.QuantRegResults.cov_params.html
23365
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.regression.quantile_regression.QuantRegResults.cov_params &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.regression.quantile_regression.QuantRegResults.f_test" href="statsmodels.regression.quantile_regression.QuantRegResults.f_test.html" /> <link rel="prev" title="statsmodels.regression.quantile_regression.QuantRegResults.conf_int" href="statsmodels.regression.quantile_regression.QuantRegResults.conf_int.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.regression.quantile_regression.QuantRegResults.cov_params" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.2</span> <span class="md-header-nav__topic"> statsmodels.regression.quantile_regression.QuantRegResults.cov_params </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../regression.html" class="md-tabs__link">Linear Regression</a></li> <li class="md-tabs__item"><a href="statsmodels.regression.quantile_regression.QuantRegResults.html" class="md-tabs__link">statsmodels.regression.quantile_regression.QuantRegResults</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.2</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../regression.html" class="md-nav__link">Linear Regression</a> </li> <li class="md-nav__item"> <a href="../glm.html" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a> </li> <li class="md-nav__item"> <a href="../rlm.html" class="md-nav__link">Robust Linear Models</a> </li> <li class="md-nav__item"> <a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a> </li> <li class="md-nav__item"> <a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../anova.html" class="md-nav__link">ANOVA</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.regression.quantile_regression.QuantRegResults.cov_params.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-regression-quantile-regression-quantregresults-cov-params--page-root">statsmodels.regression.quantile_regression.QuantRegResults.cov_params<a class="headerlink" href="#generated-statsmodels-regression-quantile-regression-quantregresults-cov-params--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py method"> <dt id="statsmodels.regression.quantile_regression.QuantRegResults.cov_params"> <code class="sig-prename descclassname">QuantRegResults.</code><code class="sig-name descname">cov_params</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">r_matrix</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">column</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">scale</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">cov_p</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">other</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.regression.quantile_regression.QuantRegResults.cov_params" title="Permalink to this definition">¶</a></dt> <dd><p>Compute the variance/covariance matrix.</p> <p>The variance/covariance matrix can be of a linear contrast of the estimated parameters or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar.</p> <dl class="field-list"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"><dl> <dt><strong>r_matrix</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array-like" title="(in NumPy v1.20)"><span>array_like</span></a></span></dt><dd><p>Can be 1d, or 2d. Can be used alone or with other.</p> </dd> <dt><strong>column</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array-like" title="(in NumPy v1.20)"><span>array_like</span></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>Must be used on its own. Can be 0d or 1d see below.</p> </dd> <dt><strong>scale</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/functions.html#float" title="(in Python v3.9)"><code class="docutils literal notranslate"><span class="pre">float</span></code></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>Can be specified or not. Default is None, which means that the scale argument is taken from the model.</p> </dd> <dt><strong>cov_p</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v1.20)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">ndarray</span></code></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>The covariance of the parameters. If not provided, this value is read from <cite>self.normalized_cov_params</cite> or <cite>self.cov_params_default</cite>.</p> </dd> <dt><strong>other</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array-like" title="(in NumPy v1.20)"><span>array_like</span></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>Can be used when r_matrix is specified.</p> </dd> </dl> </dd> <dt class="field-even">Returns</dt> <dd class="field-even"><dl class="simple"> <dt><a class="reference external" href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v1.20)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">ndarray</span></code></a></dt><dd><p>The covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes.</p> </dd> </dl> </dd> </dl> <p class="rubric">Notes</p> <p>(The below are assumed to be in matrix notation.)</p> <p>If no argument is specified returns the covariance matrix of a model <code class="docutils literal notranslate"><span class="pre">(scale)*(X.T</span> <span class="pre">X)^(-1)</span></code></p> <p>If contrast is specified it pre and post-multiplies as follows <code class="docutils literal notranslate"><span class="pre">(scale)</span> <span class="pre">*</span> <span class="pre">r_matrix</span> <span class="pre">(X.T</span> <span class="pre">X)^(-1)</span> <span class="pre">r_matrix.T</span></code></p> <p>If contrast and other are specified returns <code class="docutils literal notranslate"><span class="pre">(scale)</span> <span class="pre">*</span> <span class="pre">r_matrix</span> <span class="pre">(X.T</span> <span class="pre">X)^(-1)</span> <span class="pre">other.T</span></code></p> <p>If column is specified returns <code class="docutils literal notranslate"><span class="pre">(scale)</span> <span class="pre">*</span> <span class="pre">(X.T</span> <span class="pre">X)^(-1)[column,column]</span></code> if column is 0d</p> <p>OR</p> <p><code class="docutils literal notranslate"><span class="pre">(scale)</span> <span class="pre">*</span> <span class="pre">(X.T</span> <span class="pre">X)^(-1)[column][:,column]</span></code> if column is 1d</p> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.regression.quantile_regression.QuantRegResults.conf_int.html" title="statsmodels.regression.quantile_regression.QuantRegResults.conf_int" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.regression.quantile_regression.QuantRegResults.conf_int </span> </div> </a> <a href="statsmodels.regression.quantile_regression.QuantRegResults.f_test.html" title="statsmodels.regression.quantile_regression.QuantRegResults.f_test" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.regression.quantile_regression.QuantRegResults.f_test </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Feb 02, 2021. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.4.3. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
bsd-3-clause
NCIP/cagrid-core
caGrid/projects/dorian/src/org/cagrid/gaards/dorian/federation/ReportUtils.java
9870
/** *============================================================================ * Copyright The Ohio State University Research Foundation, The University of Chicago - * Argonne National Laboratory, Emory University, SemanticBits LLC, and * Ekagra Software Technologies Ltd. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cagrid-core/LICENSE.txt for details. *============================================================================ **/ package org.cagrid.gaards.dorian.federation; import gov.nih.nci.cagrid.common.Utils; import java.util.Arrays; public class ReportUtils { public static String generateReport(TrustedIdP original, TrustedIdP updated) { StringBuffer sb = new StringBuffer(); sb.append("The following changes were made to the Trusted IdP, " + original.getName() + " (" + original.getId() + "): \n"); int count = 0; if ((Utils.clean(updated.getDisplayName()) != null) && (!updated.getDisplayName().equals(original.getDisplayName()))) { count = count + 1; sb.append(count + ". Display Name changed from " + original.getDisplayName() + " to " + updated.getDisplayName() + ".\n"); } if ((Utils.clean(updated.getUserPolicyClass()) != null) && (!updated.getUserPolicyClass().equals(original.getUserPolicyClass()))) { count = count + 1; sb.append(count + ". User policy changed from " + original.getUserPolicyClass() + " to " + updated.getUserPolicyClass() + ".\n"); } if ((updated.getStatus() != null) && (!updated.getStatus().equals(original.getStatus()))) { count = count + 1; sb.append(count + ". Status changed from " + original.getStatus().getValue() + " to " + updated.getStatus().getValue() + ".\n"); } if ((Utils.clean(updated.getIdPCertificate()) != null) && (!updated.getIdPCertificate().equals(original.getIdPCertificate()))) { count = count + 1; sb.append(count + ". Signing certificate changed.\n"); } if (updated.getAuthenticationServiceURL() == null) { updated.setAuthenticationServiceURL(""); } if (!updated.getAuthenticationServiceURL().equals(original.getAuthenticationServiceURL())) { count = count + 1; sb.append(count + ". Authentication Service URL changed from " + original.getAuthenticationServiceURL() + " to " + updated.getAuthenticationServiceURL() + ".\n"); } if (updated.getAuthenticationServiceIdentity() == null) { updated.setAuthenticationServiceIdentity(""); } if (!updated.getAuthenticationServiceIdentity().equals(original.getAuthenticationServiceIdentity())) { count = count + 1; sb.append(count + ". Authentication Service Identity changed from " + original.getAuthenticationServiceIdentity() + " to " + updated.getAuthenticationServiceIdentity() + ".\n"); } if ((updated.getUserIdAttributeDescriptor() != null) && (!updated.getUserIdAttributeDescriptor().equals(original.getUserIdAttributeDescriptor()))) { count = count + 1; sb.append(count + ". User Id Attribute changed from " + original.getUserIdAttributeDescriptor().getNamespaceURI() + ":" + original.getUserIdAttributeDescriptor().getName() + " to " + updated.getUserIdAttributeDescriptor().getNamespaceURI() + ":" + updated.getUserIdAttributeDescriptor().getName() + ".\n"); } if ((updated.getFirstNameAttributeDescriptor() != null) && (!updated.getFirstNameAttributeDescriptor().equals(original.getFirstNameAttributeDescriptor()))) { count = count + 1; sb.append(count + ". First Name Attribute changed from " + original.getFirstNameAttributeDescriptor().getNamespaceURI() + ":" + original.getFirstNameAttributeDescriptor().getName() + " to " + updated.getFirstNameAttributeDescriptor().getNamespaceURI() + ":" + updated.getFirstNameAttributeDescriptor().getName() + ".\n"); } if ((updated.getLastNameAttributeDescriptor() != null) && (!updated.getLastNameAttributeDescriptor().equals(original.getLastNameAttributeDescriptor()))) { count = count + 1; sb.append(count + ". Last Name Attribute changed from " + original.getLastNameAttributeDescriptor().getNamespaceURI() + ":" + original.getLastNameAttributeDescriptor().getName() + " to " + updated.getLastNameAttributeDescriptor().getNamespaceURI() + ":" + updated.getLastNameAttributeDescriptor().getName() + ".\n"); } if ((updated.getEmailAttributeDescriptor() != null) && (!updated.getEmailAttributeDescriptor().equals(original.getEmailAttributeDescriptor()))) { count = count + 1; sb.append(count + ". Email Attribute changed from " + original.getEmailAttributeDescriptor().getNamespaceURI() + ":" + original.getEmailAttributeDescriptor().getName() + " to " + updated.getEmailAttributeDescriptor().getNamespaceURI() + ":" + updated.getEmailAttributeDescriptor().getName() + ".\n"); } if (!Arrays.equals(original.getAuthenticationMethod(), updated.getAuthenticationMethod())) { count = count + 1; sb.append(count + ". Authentication methods changed from ("); boolean first = true; if (original.getAuthenticationMethod() != null) { for (int i = 0; i < original.getAuthenticationMethod().length; i++) { if (!first) { sb.append(", "); } sb.append(original.getAuthenticationMethod(i)); first = false; } } sb.append(") to ("); first = true; if (updated.getAuthenticationMethod() != null) { for (int i = 0; i < updated.getAuthenticationMethod().length; i++) { if (!first) { sb.append(", "); } sb.append(updated.getAuthenticationMethod(i)); first = false; } } sb.append(")."); } return sb.toString(); } public static String generateReport(GridUser original, GridUser updated) { StringBuffer sb = new StringBuffer(); sb.append("The following changes were made to the Grid user, " + original.getGridId() + ": \n"); int count = 0; if ((updated.getFirstName() != null) && (!updated.getFirstName().equals(original.getFirstName()))) { count = count + 1; sb.append(count + ". First Name changed from " + original.getFirstName() + " to " + updated.getFirstName() + ".\n"); } if ((updated.getLastName() != null) && (!updated.getLastName().equals(original.getLastName()))) { count = count + 1; sb.append(count + ". Last Name changed from " + original.getLastName() + " to " + updated.getLastName() + ".\n"); } if ((updated.getEmail() != null) && (!updated.getEmail().equals(original.getEmail()))) { count = count + 1; sb.append(count + ". Email changed from " + original.getEmail() + " to " + updated.getEmail() + ".\n"); } if ((updated.getUserStatus() != null) && (!updated.getUserStatus().equals(original.getUserStatus()))) { count = count + 1; sb.append(count + ". Status changed from " + original.getUserStatus().getValue() + " to " + updated.getUserStatus().getValue() + ".\n"); } return sb.toString(); } public static String generateReport(HostCertificateRecord original, HostCertificateRecord updated) { StringBuffer sb = new StringBuffer(); sb.append("The following changes were made to the host certificate, " + original.getHost() + "(" + original.getId() + "): \n"); int count = 0; if ((updated.getStatus() != null) && (!updated.getStatus().equals(original.getStatus()))) { count = count + 1; sb.append(count + ". Status changed from " + original.getStatus().getValue() + " to " + updated.getStatus().getValue() + ".\n"); } if ((updated.getOwner() != null) && (!updated.getOwner().equals(original.getOwner()))) { count = count + 1; sb.append(count + ". Owner changed from " + original.getOwner() + " to " + updated.getOwner() + ".\n"); } return sb.toString(); } public static String generateReport(UserCertificateRecord original, UserCertificateRecord updated) { StringBuffer sb = new StringBuffer(); sb.append("The following changes were made to the user certificate, " + original.getSerialNumber() + ": \n"); int count = 0; if ((updated.getStatus() != null) && (!updated.getStatus().equals(original.getStatus()))) { count = count + 1; sb.append(count + ". Status changed from " + original.getStatus().getValue() + " to " + updated.getStatus().getValue() + ".\n"); } if ((updated.getNotes() != null) && (!updated.getNotes().equals(original.getNotes()))) { count = count + 1; sb.append(count + ". Notes updated.\n"); } return sb.toString(); } }
bsd-3-clause
statsmodels/statsmodels.github.io
v0.10.2/generated/statsmodels.sandbox.regression.gmm.IV2SLS.hessian.html
7515
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>statsmodels.sandbox.regression.gmm.IV2SLS.hessian &#8212; statsmodels v0.10.2 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.sandbox.regression.gmm.IV2SLS.information" href="statsmodels.sandbox.regression.gmm.IV2SLS.information.html" /> <link rel="prev" title="statsmodels.sandbox.regression.gmm.IV2SLS.from_formula" href="statsmodels.sandbox.regression.gmm.IV2SLS.from_formula.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.sandbox.regression.gmm.IV2SLS.information.html" title="statsmodels.sandbox.regression.gmm.IV2SLS.information" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.sandbox.regression.gmm.IV2SLS.from_formula.html" title="statsmodels.sandbox.regression.gmm.IV2SLS.from_formula" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../gmm.html" >Generalized Method of Moments <code class="xref py py-mod docutils literal notranslate"><span class="pre">gmm</span></code></a> |</li> <li class="nav-item nav-item-2"><a href="statsmodels.sandbox.regression.gmm.IV2SLS.html" accesskey="U">statsmodels.sandbox.regression.gmm.IV2SLS</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-sandbox-regression-gmm-iv2sls-hessian"> <h1>statsmodels.sandbox.regression.gmm.IV2SLS.hessian<a class="headerlink" href="#statsmodels-sandbox-regression-gmm-iv2sls-hessian" title="Permalink to this headline">¶</a></h1> <p>method</p> <dl class="method"> <dt id="statsmodels.sandbox.regression.gmm.IV2SLS.hessian"> <code class="sig-prename descclassname">IV2SLS.</code><code class="sig-name descname">hessian</code><span class="sig-paren">(</span><em class="sig-param">params</em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.sandbox.regression.gmm.IV2SLS.hessian" title="Permalink to this definition">¶</a></dt> <dd><p>The Hessian matrix of the model</p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.sandbox.regression.gmm.IV2SLS.from_formula.html" title="previous chapter">statsmodels.sandbox.regression.gmm.IV2SLS.from_formula</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.sandbox.regression.gmm.IV2SLS.information.html" title="next chapter">statsmodels.sandbox.regression.gmm.IV2SLS.information</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.sandbox.regression.gmm.IV2SLS.hessian.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.2.1. </div> </body> </html>
bsd-3-clause
scheib/chromium
content/browser/devtools/protocol/devtools_download_manager_delegate.h
3868
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_DEVTOOLS_PROTOCOL_DEVTOOLS_DOWNLOAD_MANAGER_DELEGATE_H_ #define CONTENT_BROWSER_DEVTOOLS_PROTOCOL_DEVTOOLS_DOWNLOAD_MANAGER_DELEGATE_H_ #include <stdint.h> #include <string> #include "base/callback_forward.h" #include "base/compiler_specific.h" #include "base/files/file_util.h" #include "base/memory/ref_counted.h" #include "base/memory/singleton.h" #include "base/memory/weak_ptr.h" #include "content/common/content_export.h" #include "content/public/browser/download_manager_delegate.h" namespace content { class DownloadManager; namespace protocol { class CONTENT_EXPORT DevToolsDownloadManagerDelegate : public base::SupportsUserData::Data, public content::DownloadManagerDelegate { public: enum class DownloadBehavior { // All downloads are denied. DENY, // All downloads are accepted. ALLOW, // All downloads are accepted and named using Guids. ALLOW_AND_NAME, // Use default download behavior if available, otherwise deny. DEFAULT }; // Takes over the |browser_Context|'s download manager. // When existing delegate is set, this proxy will use the original's // |GetNextId| function to ensure compatibility. It will also call its // |Shutdown| method when sutting down and it will fallback to the original // delegate if it cannot find any DevToolsDownloadManagerHelper associated // with the download. static DevToolsDownloadManagerDelegate* GetOrCreateInstance( content::BrowserContext* browser_Context); static DevToolsDownloadManagerDelegate* GetInstance( content::BrowserContext* browser_Context); DevToolsDownloadManagerDelegate(const DevToolsDownloadManagerDelegate&) = delete; DevToolsDownloadManagerDelegate& operator=( const DevToolsDownloadManagerDelegate&) = delete; ~DevToolsDownloadManagerDelegate() override = default; void set_download_behavior(DownloadBehavior behavior) { download_behavior_ = behavior; } void set_download_path(const std::string& path) { download_path_ = path; } // DownloadManagerDelegate overrides. void Shutdown() override; bool DetermineDownloadTarget( download::DownloadItem* download, content::DownloadTargetCallback* callback) override; bool ShouldOpenDownload( download::DownloadItem* item, content::DownloadOpenDelayedCallback callback) override; void GetNextId(content::DownloadIdCallback callback) override; download::DownloadItem* GetDownloadByGuid(const std::string& guid) override; private: friend class base::RefCounted<DevToolsDownloadManagerDelegate>; explicit DevToolsDownloadManagerDelegate(BrowserContext* browser_context); using FilenameDeterminedCallback = base::OnceCallback<void(const base::FilePath&)>; static void GenerateFilename(const GURL& url, const std::string& content_disposition, const std::string& suggested_filename, const std::string& mime_type, const base::FilePath& suggested_directory, FilenameDeterminedCallback callback); void OnDownloadPathGenerated(uint32_t download_id, content::DownloadTargetCallback callback, const base::FilePath& suggested_path); content::DownloadManager* download_manager_; content::DownloadManagerDelegate* original_download_delegate_; DownloadBehavior download_behavior_ = DownloadBehavior::DEFAULT; std::string download_path_; }; } // namespace protocol } // namespace content #endif // CONTENT_BROWSER_DEVTOOLS_PROTOCOL_DEVTOOLS_DOWNLOAD_MANAGER_DELEGATE_H_
bsd-3-clause
endlessm/chromium-browser
third_party/llvm/clang/lib/Sema/SemaStmtAsm.cpp
36063
//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for inline asm statements. // //===----------------------------------------------------------------------===// #include "clang/AST/ExprCXX.h" #include "clang/AST/GlobalDecl.h" #include "clang/AST/RecordLayout.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Scope.h" #include "clang/Sema/ScopeInfo.h" #include "clang/Sema/SemaInternal.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringSet.h" #include "llvm/MC/MCParser/MCAsmParser.h" using namespace clang; using namespace sema; /// Remove the upper-level LValueToRValue cast from an expression. static void removeLValueToRValueCast(Expr *E) { Expr *Parent = E; Expr *ExprUnderCast = nullptr; SmallVector<Expr *, 8> ParentsToUpdate; while (true) { ParentsToUpdate.push_back(Parent); if (auto *ParenE = dyn_cast<ParenExpr>(Parent)) { Parent = ParenE->getSubExpr(); continue; } Expr *Child = nullptr; CastExpr *ParentCast = dyn_cast<CastExpr>(Parent); if (ParentCast) Child = ParentCast->getSubExpr(); else return; if (auto *CastE = dyn_cast<CastExpr>(Child)) if (CastE->getCastKind() == CK_LValueToRValue) { ExprUnderCast = CastE->getSubExpr(); // LValueToRValue cast inside GCCAsmStmt requires an explicit cast. ParentCast->setSubExpr(ExprUnderCast); break; } Parent = Child; } // Update parent expressions to have same ValueType as the underlying. assert(ExprUnderCast && "Should be reachable only if LValueToRValue cast was found!"); auto ValueKind = ExprUnderCast->getValueKind(); for (Expr *E : ParentsToUpdate) E->setValueKind(ValueKind); } /// Emit a warning about usage of "noop"-like casts for lvalues (GNU extension) /// and fix the argument with removing LValueToRValue cast from the expression. static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument, Sema &S) { if (!S.getLangOpts().HeinousExtensions) { S.Diag(LVal->getBeginLoc(), diag::err_invalid_asm_cast_lvalue) << BadArgument->getSourceRange(); } else { S.Diag(LVal->getBeginLoc(), diag::warn_invalid_asm_cast_lvalue) << BadArgument->getSourceRange(); } removeLValueToRValueCast(BadArgument); } /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently /// ignore "noop" casts in places where an lvalue is required by an inline asm. /// We emulate this behavior when -fheinous-gnu-extensions is specified, but /// provide a strong guidance to not use it. /// /// This method checks to see if the argument is an acceptable l-value and /// returns false if it is a case we can handle. static bool CheckAsmLValue(Expr *E, Sema &S) { // Type dependent expressions will be checked during instantiation. if (E->isTypeDependent()) return false; if (E->isLValue()) return false; // Cool, this is an lvalue. // Okay, this is not an lvalue, but perhaps it is the result of a cast that we // are supposed to allow. const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); if (E != E2 && E2->isLValue()) { emitAndFixInvalidAsmCastLValue(E2, E, S); // Accept, even if we emitted an error diagnostic. return false; } // None of the above, just randomly invalid non-lvalue. return true; } /// isOperandMentioned - Return true if the specified operand # is mentioned /// anywhere in the decomposed asm string. static bool isOperandMentioned(unsigned OpNo, ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) { for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) { const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p]; if (!Piece.isOperand()) continue; // If this is a reference to the input and if the input was the smaller // one, then we have to reject this asm. if (Piece.getOperandNo() == OpNo) return true; } return false; } static bool CheckNakedParmReference(Expr *E, Sema &S) { FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext); if (!Func) return false; if (!Func->hasAttr<NakedAttr>()) return false; SmallVector<Expr*, 4> WorkList; WorkList.push_back(E); while (WorkList.size()) { Expr *E = WorkList.pop_back_val(); if (isa<CXXThisExpr>(E)) { S.Diag(E->getBeginLoc(), diag::err_asm_naked_this_ref); S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); return true; } if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { if (isa<ParmVarDecl>(DRE->getDecl())) { S.Diag(DRE->getBeginLoc(), diag::err_asm_naked_parm_ref); S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); return true; } } for (Stmt *Child : E->children()) { if (Expr *E = dyn_cast_or_null<Expr>(Child)) WorkList.push_back(E); } } return false; } /// Returns true if given expression is not compatible with inline /// assembly's memory constraint; false otherwise. static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E, TargetInfo::ConstraintInfo &Info, bool is_input_expr) { enum { ExprBitfield = 0, ExprVectorElt, ExprGlobalRegVar, ExprSafeType } EType = ExprSafeType; // Bitfields, vector elements and global register variables are not // compatible. if (E->refersToBitField()) EType = ExprBitfield; else if (E->refersToVectorElement()) EType = ExprVectorElt; else if (E->refersToGlobalRegisterVar()) EType = ExprGlobalRegVar; if (EType != ExprSafeType) { S.Diag(E->getBeginLoc(), diag::err_asm_non_addr_value_in_memory_constraint) << EType << is_input_expr << Info.getConstraintStr() << E->getSourceRange(); return true; } return false; } // Extracting the register name from the Expression value, // if there is no register name to extract, returns "" static StringRef extractRegisterName(const Expr *Expression, const TargetInfo &Target) { Expression = Expression->IgnoreImpCasts(); if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Expression)) { // Handle cases where the expression is a variable const VarDecl *Variable = dyn_cast<VarDecl>(AsmDeclRef->getDecl()); if (Variable && Variable->getStorageClass() == SC_Register) { if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>()) if (Target.isValidGCCRegisterName(Attr->getLabel())) return Target.getNormalizedGCCRegisterName(Attr->getLabel(), true); } } return ""; } // Checks if there is a conflict between the input and output lists with the // clobbers list. If there's a conflict, returns the location of the // conflicted clobber, else returns nullptr static SourceLocation getClobberConflictLocation(MultiExprArg Exprs, StringLiteral **Constraints, StringLiteral **Clobbers, int NumClobbers, unsigned NumLabels, const TargetInfo &Target, ASTContext &Cont) { llvm::StringSet<> InOutVars; // Collect all the input and output registers from the extended asm // statement in order to check for conflicts with the clobber list for (unsigned int i = 0; i < Exprs.size() - NumLabels; ++i) { StringRef Constraint = Constraints[i]->getString(); StringRef InOutReg = Target.getConstraintRegister( Constraint, extractRegisterName(Exprs[i], Target)); if (InOutReg != "") InOutVars.insert(InOutReg); } // Check for each item in the clobber list if it conflicts with the input // or output for (int i = 0; i < NumClobbers; ++i) { StringRef Clobber = Clobbers[i]->getString(); // We only check registers, therefore we don't check cc and memory // clobbers if (Clobber == "cc" || Clobber == "memory") continue; Clobber = Target.getNormalizedGCCRegisterName(Clobber, true); // Go over the output's registers we collected if (InOutVars.count(Clobber)) return Clobbers[i]->getBeginLoc(); } return SourceLocation(); } StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg constraints, MultiExprArg Exprs, Expr *asmString, MultiExprArg clobbers, unsigned NumLabels, SourceLocation RParenLoc) { unsigned NumClobbers = clobbers.size(); StringLiteral **Constraints = reinterpret_cast<StringLiteral**>(constraints.data()); StringLiteral *AsmString = cast<StringLiteral>(asmString); StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data()); SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; // The parser verifies that there is a string literal here. assert(AsmString->isAscii()); FunctionDecl *FD = dyn_cast<FunctionDecl>(getCurLexicalContext()); llvm::StringMap<bool> FeatureMap; Context.getFunctionFeatureMap(FeatureMap, FD); for (unsigned i = 0; i != NumOutputs; i++) { StringLiteral *Literal = Constraints[i]; assert(Literal->isAscii()); StringRef OutputName; if (Names[i]) OutputName = Names[i]->getName(); TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); if (!Context.getTargetInfo().validateOutputConstraint(Info)) { targetDiag(Literal->getBeginLoc(), diag::err_asm_invalid_output_constraint) << Info.getConstraintStr(); return new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names, Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, NumLabels, RParenLoc); } ExprResult ER = CheckPlaceholderExpr(Exprs[i]); if (ER.isInvalid()) return StmtError(); Exprs[i] = ER.get(); // Check that the output exprs are valid lvalues. Expr *OutputExpr = Exprs[i]; // Referring to parameters is not allowed in naked functions. if (CheckNakedParmReference(OutputExpr, *this)) return StmtError(); // Check that the output expression is compatible with memory constraint. if (Info.allowsMemory() && checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false)) return StmtError(); OutputConstraintInfos.push_back(Info); // If this is dependent, just continue. if (OutputExpr->isTypeDependent()) continue; Expr::isModifiableLvalueResult IsLV = OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr); switch (IsLV) { case Expr::MLV_Valid: // Cool, this is an lvalue. break; case Expr::MLV_ArrayType: // This is OK too. break; case Expr::MLV_LValueCast: { const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context); emitAndFixInvalidAsmCastLValue(LVal, OutputExpr, *this); // Accept, even if we emitted an error diagnostic. break; } case Expr::MLV_IncompleteType: case Expr::MLV_IncompleteVoidType: if (RequireCompleteType(OutputExpr->getBeginLoc(), Exprs[i]->getType(), diag::err_dereference_incomplete_type)) return StmtError(); LLVM_FALLTHROUGH; default: return StmtError(Diag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_lvalue_in_output) << OutputExpr->getSourceRange()); } unsigned Size = Context.getTypeSize(OutputExpr->getType()); if (!Context.getTargetInfo().validateOutputSize( FeatureMap, Literal->getString(), Size)) { targetDiag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_output_size) << Info.getConstraintStr(); return new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names, Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, NumLabels, RParenLoc); } } SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { StringLiteral *Literal = Constraints[i]; assert(Literal->isAscii()); StringRef InputName; if (Names[i]) InputName = Names[i]->getName(); TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos, Info)) { targetDiag(Literal->getBeginLoc(), diag::err_asm_invalid_input_constraint) << Info.getConstraintStr(); return new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names, Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, NumLabels, RParenLoc); } ExprResult ER = CheckPlaceholderExpr(Exprs[i]); if (ER.isInvalid()) return StmtError(); Exprs[i] = ER.get(); Expr *InputExpr = Exprs[i]; // Referring to parameters is not allowed in naked functions. if (CheckNakedParmReference(InputExpr, *this)) return StmtError(); // Check that the input expression is compatible with memory constraint. if (Info.allowsMemory() && checkExprMemoryConstraintCompat(*this, InputExpr, Info, true)) return StmtError(); // Only allow void types for memory constraints. if (Info.allowsMemory() && !Info.allowsRegister()) { if (CheckAsmLValue(InputExpr, *this)) return StmtError(Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_lvalue_in_input) << Info.getConstraintStr() << InputExpr->getSourceRange()); } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) { if (!InputExpr->isValueDependent()) { Expr::EvalResult EVResult; if (InputExpr->EvaluateAsRValue(EVResult, Context, true)) { // For compatibility with GCC, we also allow pointers that would be // integral constant expressions if they were cast to int. llvm::APSInt IntResult; if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(), Context)) if (!Info.isValidAsmImmediate(IntResult)) return StmtError(Diag(InputExpr->getBeginLoc(), diag::err_invalid_asm_value_for_constraint) << IntResult.toString(10) << Info.getConstraintStr() << InputExpr->getSourceRange()); } } } else { ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]); if (Result.isInvalid()) return StmtError(); Exprs[i] = Result.get(); } if (Info.allowsRegister()) { if (InputExpr->getType()->isVoidType()) { return StmtError( Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input) << InputExpr->getType() << Info.getConstraintStr() << InputExpr->getSourceRange()); } } InputConstraintInfos.push_back(Info); const Type *Ty = Exprs[i]->getType().getTypePtr(); if (Ty->isDependentType()) continue; if (!Ty->isVoidType() || !Info.allowsMemory()) if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(), diag::err_dereference_incomplete_type)) return StmtError(); unsigned Size = Context.getTypeSize(Ty); if (!Context.getTargetInfo().validateInputSize(FeatureMap, Literal->getString(), Size)) return StmtResult( targetDiag(InputExpr->getBeginLoc(), diag::err_asm_invalid_input_size) << Info.getConstraintStr()); } // Check that the clobbers are valid. for (unsigned i = 0; i != NumClobbers; i++) { StringLiteral *Literal = Clobbers[i]; assert(Literal->isAscii()); StringRef Clobber = Literal->getString(); if (!Context.getTargetInfo().isValidClobber(Clobber)) { targetDiag(Literal->getBeginLoc(), diag::err_asm_unknown_register_name) << Clobber; return new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names, Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, NumLabels, RParenLoc); } } GCCAsmStmt *NS = new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names, Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, NumLabels, RParenLoc); // Validate the asm string, ensuring it makes sense given the operands we // have. SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces; unsigned DiagOffs; if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { targetDiag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) << AsmString->getSourceRange(); return NS; } // Validate constraints and modifiers. for (unsigned i = 0, e = Pieces.size(); i != e; ++i) { GCCAsmStmt::AsmStringPiece &Piece = Pieces[i]; if (!Piece.isOperand()) continue; // Look for the correct constraint index. unsigned ConstraintIdx = Piece.getOperandNo(); unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs(); // Labels are the last in the Exprs list. if (NS->isAsmGoto() && ConstraintIdx >= NumOperands) continue; // Look for the (ConstraintIdx - NumOperands + 1)th constraint with // modifier '+'. if (ConstraintIdx >= NumOperands) { unsigned I = 0, E = NS->getNumOutputs(); for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I) if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) { ConstraintIdx = I; break; } assert(I != E && "Invalid operand number should have been caught in " " AnalyzeAsmString"); } // Now that we have the right indexes go ahead and check. StringLiteral *Literal = Constraints[ConstraintIdx]; const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr(); if (Ty->isDependentType() || Ty->isIncompleteType()) continue; unsigned Size = Context.getTypeSize(Ty); std::string SuggestedModifier; if (!Context.getTargetInfo().validateConstraintModifier( Literal->getString(), Piece.getModifier(), Size, SuggestedModifier)) { targetDiag(Exprs[ConstraintIdx]->getBeginLoc(), diag::warn_asm_mismatched_size_modifier); if (!SuggestedModifier.empty()) { auto B = targetDiag(Piece.getRange().getBegin(), diag::note_asm_missing_constraint_modifier) << SuggestedModifier; SuggestedModifier = "%" + SuggestedModifier + Piece.getString(); B << FixItHint::CreateReplacement(Piece.getRange(), SuggestedModifier); } } } // Validate tied input operands for type mismatches. unsigned NumAlternatives = ~0U; for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) { TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; StringRef ConstraintStr = Info.getConstraintStr(); unsigned AltCount = ConstraintStr.count(',') + 1; if (NumAlternatives == ~0U) { NumAlternatives = AltCount; } else if (NumAlternatives != AltCount) { targetDiag(NS->getOutputExpr(i)->getBeginLoc(), diag::err_asm_unexpected_constraint_alternatives) << NumAlternatives << AltCount; return NS; } } SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(), ~0U); for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; StringRef ConstraintStr = Info.getConstraintStr(); unsigned AltCount = ConstraintStr.count(',') + 1; if (NumAlternatives == ~0U) { NumAlternatives = AltCount; } else if (NumAlternatives != AltCount) { targetDiag(NS->getInputExpr(i)->getBeginLoc(), diag::err_asm_unexpected_constraint_alternatives) << NumAlternatives << AltCount; return NS; } // If this is a tied constraint, verify that the output and input have // either exactly the same type, or that they are int/ptr operands with the // same size (int/long, int*/long, are ok etc). if (!Info.hasTiedOperand()) continue; unsigned TiedTo = Info.getTiedOperand(); unsigned InputOpNo = i+NumOutputs; Expr *OutputExpr = Exprs[TiedTo]; Expr *InputExpr = Exprs[InputOpNo]; // Make sure no more than one input constraint matches each output. assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range"); if (InputMatchedToOutput[TiedTo] != ~0U) { targetDiag(NS->getInputExpr(i)->getBeginLoc(), diag::err_asm_input_duplicate_match) << TiedTo; targetDiag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(), diag::note_asm_input_duplicate_first) << TiedTo; return NS; } InputMatchedToOutput[TiedTo] = i; if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent()) continue; QualType InTy = InputExpr->getType(); QualType OutTy = OutputExpr->getType(); if (Context.hasSameType(InTy, OutTy)) continue; // All types can be tied to themselves. // Decide if the input and output are in the same domain (integer/ptr or // floating point. enum AsmDomain { AD_Int, AD_FP, AD_Other } InputDomain, OutputDomain; if (InTy->isIntegerType() || InTy->isPointerType()) InputDomain = AD_Int; else if (InTy->isRealFloatingType()) InputDomain = AD_FP; else InputDomain = AD_Other; if (OutTy->isIntegerType() || OutTy->isPointerType()) OutputDomain = AD_Int; else if (OutTy->isRealFloatingType()) OutputDomain = AD_FP; else OutputDomain = AD_Other; // They are ok if they are the same size and in the same domain. This // allows tying things like: // void* to int* // void* to int if they are the same size. // double to long double if they are the same size. // uint64_t OutSize = Context.getTypeSize(OutTy); uint64_t InSize = Context.getTypeSize(InTy); if (OutSize == InSize && InputDomain == OutputDomain && InputDomain != AD_Other) continue; // If the smaller input/output operand is not mentioned in the asm string, // then we can promote the smaller one to a larger input and the asm string // won't notice. bool SmallerValueMentioned = false; // If this is a reference to the input and if the input was the smaller // one, then we have to reject this asm. if (isOperandMentioned(InputOpNo, Pieces)) { // This is a use in the asm string of the smaller operand. Since we // codegen this by promoting to a wider value, the asm will get printed // "wrong". SmallerValueMentioned |= InSize < OutSize; } if (isOperandMentioned(TiedTo, Pieces)) { // If this is a reference to the output, and if the output is the larger // value, then it's ok because we'll promote the input to the larger type. SmallerValueMentioned |= OutSize < InSize; } // If the smaller value wasn't mentioned in the asm string, and if the // output was a register, just extend the shorter one to the size of the // larger one. if (!SmallerValueMentioned && InputDomain != AD_Other && OutputConstraintInfos[TiedTo].allowsRegister()) continue; // Either both of the operands were mentioned or the smaller one was // mentioned. One more special case that we'll allow: if the tied input is // integer, unmentioned, and is a constant, then we'll allow truncating it // down to the size of the destination. if (InputDomain == AD_Int && OutputDomain == AD_Int && !isOperandMentioned(InputOpNo, Pieces) && InputExpr->isEvaluatable(Context)) { CastKind castKind = (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast); InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get(); Exprs[InputOpNo] = InputExpr; NS->setInputExpr(i, InputExpr); continue; } targetDiag(InputExpr->getBeginLoc(), diag::err_asm_tying_incompatible_types) << InTy << OutTy << OutputExpr->getSourceRange() << InputExpr->getSourceRange(); return NS; } // Check for conflicts between clobber list and input or output lists SourceLocation ConstraintLoc = getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers, NumLabels, Context.getTargetInfo(), Context); if (ConstraintLoc.isValid()) targetDiag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber); // Check for duplicate asm operand name between input, output and label lists. typedef std::pair<StringRef , Expr *> NamedOperand; SmallVector<NamedOperand, 4> NamedOperandList; for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i) if (Names[i]) NamedOperandList.emplace_back( std::make_pair(Names[i]->getName(), Exprs[i])); // Sort NamedOperandList. std::stable_sort(NamedOperandList.begin(), NamedOperandList.end(), [](const NamedOperand &LHS, const NamedOperand &RHS) { return LHS.first < RHS.first; }); // Find adjacent duplicate operand. SmallVector<NamedOperand, 4>::iterator Found = std::adjacent_find(begin(NamedOperandList), end(NamedOperandList), [](const NamedOperand &LHS, const NamedOperand &RHS) { return LHS.first == RHS.first; }); if (Found != NamedOperandList.end()) { Diag((Found + 1)->second->getBeginLoc(), diag::error_duplicate_asm_operand_name) << (Found + 1)->first; Diag(Found->second->getBeginLoc(), diag::note_duplicate_asm_operand_name) << Found->first; return StmtError(); } if (NS->isAsmGoto()) setFunctionHasBranchIntoScope(); return NS; } void Sema::FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info) { QualType T = Res->getType(); Expr::EvalResult Eval; if (T->isFunctionType() || T->isDependentType()) return Info.setLabel(Res); if (Res->isRValue()) { bool IsEnum = isa<clang::EnumType>(T); if (DeclRefExpr *DRE = dyn_cast<clang::DeclRefExpr>(Res)) if (DRE->getDecl()->getKind() == Decl::EnumConstant) IsEnum = true; if (IsEnum && Res->EvaluateAsRValue(Eval, Context)) return Info.setEnum(Eval.Val.getInt().getSExtValue()); return Info.setLabel(Res); } unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); unsigned Type = Size; if (const auto *ATy = Context.getAsArrayType(T)) Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity(); bool IsGlobalLV = false; if (Res->EvaluateAsLValue(Eval, Context)) IsGlobalLV = Eval.isGlobalLValue(); Info.setVar(Res, IsGlobalLV, Size, Type); } ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext) { if (IsUnevaluatedContext) PushExpressionEvaluationContext( ExpressionEvaluationContext::UnevaluatedAbstract, ReuseLambdaContextDecl); ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id, /*trailing lparen*/ false, /*is & operand*/ false, /*CorrectionCandidateCallback=*/nullptr, /*IsInlineAsmIdentifier=*/ true); if (IsUnevaluatedContext) PopExpressionEvaluationContext(); if (!Result.isUsable()) return Result; Result = CheckPlaceholderExpr(Result.get()); if (!Result.isUsable()) return Result; // Referring to parameters is not allowed in naked functions. if (CheckNakedParmReference(Result.get(), *this)) return ExprError(); QualType T = Result.get()->getType(); if (T->isDependentType()) { return Result; } // Any sort of function type is fine. if (T->isFunctionType()) { return Result; } // Otherwise, it needs to be a complete type. if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) { return ExprError(); } return Result; } bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc) { Offset = 0; SmallVector<StringRef, 2> Members; Member.split(Members, "."); NamedDecl *FoundDecl = nullptr; // MS InlineAsm uses 'this' as a base if (getLangOpts().CPlusPlus && Base.equals("this")) { if (const Type *PT = getCurrentThisType().getTypePtrOrNull()) FoundDecl = PT->getPointeeType()->getAsTagDecl(); } else { LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(), LookupOrdinaryName); if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult()) FoundDecl = BaseResult.getFoundDecl(); } if (!FoundDecl) return true; for (StringRef NextMember : Members) { const RecordType *RT = nullptr; if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl)) RT = VD->getType()->getAs<RecordType>(); else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) { MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); // MS InlineAsm often uses struct pointer aliases as a base QualType QT = TD->getUnderlyingType(); if (const auto *PT = QT->getAs<PointerType>()) QT = PT->getPointeeType(); RT = QT->getAs<RecordType>(); } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl)) RT = TD->getTypeForDecl()->getAs<RecordType>(); else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl)) RT = TD->getType()->getAs<RecordType>(); if (!RT) return true; if (RequireCompleteType(AsmLoc, QualType(RT, 0), diag::err_asm_incomplete_type)) return true; LookupResult FieldResult(*this, &Context.Idents.get(NextMember), SourceLocation(), LookupMemberName); if (!LookupQualifiedName(FieldResult, RT->getDecl())) return true; if (!FieldResult.isSingleResult()) return true; FoundDecl = FieldResult.getFoundDecl(); // FIXME: Handle IndirectFieldDecl? FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl); if (!FD) return true; const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl()); unsigned i = FD->getFieldIndex(); CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i)); Offset += (unsigned)Result.getQuantity(); } return false; } ExprResult Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member, SourceLocation AsmLoc) { QualType T = E->getType(); if (T->isDependentType()) { DeclarationNameInfo NameInfo; NameInfo.setLoc(AsmLoc); NameInfo.setName(&Context.Idents.get(Member)); return CXXDependentScopeMemberExpr::Create( Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(), SourceLocation(), /*FirstQualifierFoundInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr); } const RecordType *RT = T->getAs<RecordType>(); // FIXME: Diagnose this as field access into a scalar type. if (!RT) return ExprResult(); LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc, LookupMemberName); if (!LookupQualifiedName(FieldResult, RT->getDecl())) return ExprResult(); // Only normal and indirect field results will work. ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl()); if (!FD) FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl()); if (!FD) return ExprResult(); // Make an Expr to thread through OpDecl. ExprResult Result = BuildMemberReferenceExpr( E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(), SourceLocation(), nullptr, FieldResult, nullptr, nullptr); return Result; } StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc) { bool IsSimple = (NumOutputs != 0 || NumInputs != 0); setFunctionHasBranchProtectedScope(); MSAsmStmt *NS = new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple, /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs, Constraints, Exprs, AsmString, Clobbers, EndLoc); return NS; } LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate) { LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName), Location); if (Label->isMSAsmLabel()) { // If we have previously created this label implicitly, mark it as used. Label->markUsed(Context); } else { // Otherwise, insert it, but only resolve it if we have seen the label itself. std::string InternalName; llvm::raw_string_ostream OS(InternalName); // Create an internal name for the label. The name should not be a valid // mangled name, and should be unique. We use a dot to make the name an // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a // unique label is generated each time this blob is emitted, even after // inlining or LTO. OS << "__MSASMLABEL_.${:uid}__"; for (char C : ExternalLabelName) { OS << C; // We escape '$' in asm strings by replacing it with "$$" if (C == '$') OS << '$'; } Label->setMSAsmLabel(OS.str()); } if (AlwaysCreate) { // The label might have been created implicitly from a previously encountered // goto statement. So, for both newly created and looked up labels, we mark // them as resolved. Label->setMSAsmLabelResolved(); } // Adjust their location for being able to generate accurate diagnostics. Label->setLocation(Location); return Label; }
bsd-3-clause
dalifreire/rultor
src/test/java/com/rultor/spi/package-info.java
1692
/** * Copyright (c) 2009-2016, rultor.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. 3) Neither the name of the rultor.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * SPI, tests. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @since 1.28 */ package com.rultor.spi;
bsd-3-clause
pongad/api-client-staging
generated/java/proto-google-cloud-dlp-v2beta1/src/main/java/com/google/privacy/dlp/v2beta1/InfoTypeDescription.java
37925
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/privacy/dlp/v2beta1/dlp.proto package com.google.privacy.dlp.v2beta1; /** * <pre> * Description of the information type (infoType). * </pre> * * Protobuf type {@code google.privacy.dlp.v2beta1.InfoTypeDescription} */ public final class InfoTypeDescription extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.privacy.dlp.v2beta1.InfoTypeDescription) InfoTypeDescriptionOrBuilder { private static final long serialVersionUID = 0L; // Use InfoTypeDescription.newBuilder() to construct. private InfoTypeDescription(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private InfoTypeDescription() { name_ = ""; displayName_ = ""; categories_ = java.util.Collections.emptyList(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private InfoTypeDescription( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); displayName_ = s; break; } case 26: { if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { categories_ = new java.util.ArrayList<com.google.privacy.dlp.v2beta1.CategoryDescription>(); mutable_bitField0_ |= 0x00000004; } categories_.add( input.readMessage(com.google.privacy.dlp.v2beta1.CategoryDescription.parser(), extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { categories_ = java.util.Collections.unmodifiableList(categories_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.privacy.dlp.v2beta1.InfoTypeDescription.class, com.google.privacy.dlp.v2beta1.InfoTypeDescription.Builder.class); } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DISPLAY_NAME_FIELD_NUMBER = 2; private volatile java.lang.Object displayName_; /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public java.lang.String getDisplayName() { java.lang.Object ref = displayName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); displayName_ = s; return s; } } /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public com.google.protobuf.ByteString getDisplayNameBytes() { java.lang.Object ref = displayName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); displayName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CATEGORIES_FIELD_NUMBER = 3; private java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> categories_; /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> getCategoriesList() { return categories_; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public java.util.List<? extends com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder> getCategoriesOrBuilderList() { return categories_; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public int getCategoriesCount() { return categories_.size(); } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescription getCategories(int index) { return categories_.get(index); } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder getCategoriesOrBuilder( int index) { return categories_.get(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!getDisplayNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, displayName_); } for (int i = 0; i < categories_.size(); i++) { output.writeMessage(3, categories_.get(i)); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!getDisplayNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, displayName_); } for (int i = 0; i < categories_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, categories_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.privacy.dlp.v2beta1.InfoTypeDescription)) { return super.equals(obj); } com.google.privacy.dlp.v2beta1.InfoTypeDescription other = (com.google.privacy.dlp.v2beta1.InfoTypeDescription) obj; boolean result = true; result = result && getName() .equals(other.getName()); result = result && getDisplayName() .equals(other.getDisplayName()); result = result && getCategoriesList() .equals(other.getCategoriesList()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + DISPLAY_NAME_FIELD_NUMBER; hash = (53 * hash) + getDisplayName().hashCode(); if (getCategoriesCount() > 0) { hash = (37 * hash) + CATEGORIES_FIELD_NUMBER; hash = (53 * hash) + getCategoriesList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.privacy.dlp.v2beta1.InfoTypeDescription prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Description of the information type (infoType). * </pre> * * Protobuf type {@code google.privacy.dlp.v2beta1.InfoTypeDescription} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.privacy.dlp.v2beta1.InfoTypeDescription) com.google.privacy.dlp.v2beta1.InfoTypeDescriptionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.privacy.dlp.v2beta1.InfoTypeDescription.class, com.google.privacy.dlp.v2beta1.InfoTypeDescription.Builder.class); } // Construct using com.google.privacy.dlp.v2beta1.InfoTypeDescription.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getCategoriesFieldBuilder(); } } public Builder clear() { super.clear(); name_ = ""; displayName_ = ""; if (categoriesBuilder_ == null) { categories_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); } else { categoriesBuilder_.clear(); } return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_descriptor; } public com.google.privacy.dlp.v2beta1.InfoTypeDescription getDefaultInstanceForType() { return com.google.privacy.dlp.v2beta1.InfoTypeDescription.getDefaultInstance(); } public com.google.privacy.dlp.v2beta1.InfoTypeDescription build() { com.google.privacy.dlp.v2beta1.InfoTypeDescription result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.google.privacy.dlp.v2beta1.InfoTypeDescription buildPartial() { com.google.privacy.dlp.v2beta1.InfoTypeDescription result = new com.google.privacy.dlp.v2beta1.InfoTypeDescription(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.name_ = name_; result.displayName_ = displayName_; if (categoriesBuilder_ == null) { if (((bitField0_ & 0x00000004) == 0x00000004)) { categories_ = java.util.Collections.unmodifiableList(categories_); bitField0_ = (bitField0_ & ~0x00000004); } result.categories_ = categories_; } else { result.categories_ = categoriesBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.privacy.dlp.v2beta1.InfoTypeDescription) { return mergeFrom((com.google.privacy.dlp.v2beta1.InfoTypeDescription)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.privacy.dlp.v2beta1.InfoTypeDescription other) { if (other == com.google.privacy.dlp.v2beta1.InfoTypeDescription.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (!other.getDisplayName().isEmpty()) { displayName_ = other.displayName_; onChanged(); } if (categoriesBuilder_ == null) { if (!other.categories_.isEmpty()) { if (categories_.isEmpty()) { categories_ = other.categories_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureCategoriesIsMutable(); categories_.addAll(other.categories_); } onChanged(); } } else { if (!other.categories_.isEmpty()) { if (categoriesBuilder_.isEmpty()) { categoriesBuilder_.dispose(); categoriesBuilder_ = null; categories_ = other.categories_; bitField0_ = (bitField0_ & ~0x00000004); categoriesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getCategoriesFieldBuilder() : null; } else { categoriesBuilder_.addAllMessages(other.categories_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.privacy.dlp.v2beta1.InfoTypeDescription parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.privacy.dlp.v2beta1.InfoTypeDescription) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private java.lang.Object displayName_ = ""; /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public java.lang.String getDisplayName() { java.lang.Object ref = displayName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); displayName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public com.google.protobuf.ByteString getDisplayNameBytes() { java.lang.Object ref = displayName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); displayName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public Builder setDisplayName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } displayName_ = value; onChanged(); return this; } /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public Builder clearDisplayName() { displayName_ = getDefaultInstance().getDisplayName(); onChanged(); return this; } /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public Builder setDisplayNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); displayName_ = value; onChanged(); return this; } private java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> categories_ = java.util.Collections.emptyList(); private void ensureCategoriesIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { categories_ = new java.util.ArrayList<com.google.privacy.dlp.v2beta1.CategoryDescription>(categories_); bitField0_ |= 0x00000004; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.privacy.dlp.v2beta1.CategoryDescription, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder, com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder> categoriesBuilder_; /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> getCategoriesList() { if (categoriesBuilder_ == null) { return java.util.Collections.unmodifiableList(categories_); } else { return categoriesBuilder_.getMessageList(); } } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public int getCategoriesCount() { if (categoriesBuilder_ == null) { return categories_.size(); } else { return categoriesBuilder_.getCount(); } } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescription getCategories(int index) { if (categoriesBuilder_ == null) { return categories_.get(index); } else { return categoriesBuilder_.getMessage(index); } } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder setCategories( int index, com.google.privacy.dlp.v2beta1.CategoryDescription value) { if (categoriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCategoriesIsMutable(); categories_.set(index, value); onChanged(); } else { categoriesBuilder_.setMessage(index, value); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder setCategories( int index, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder builderForValue) { if (categoriesBuilder_ == null) { ensureCategoriesIsMutable(); categories_.set(index, builderForValue.build()); onChanged(); } else { categoriesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder addCategories(com.google.privacy.dlp.v2beta1.CategoryDescription value) { if (categoriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCategoriesIsMutable(); categories_.add(value); onChanged(); } else { categoriesBuilder_.addMessage(value); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder addCategories( int index, com.google.privacy.dlp.v2beta1.CategoryDescription value) { if (categoriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCategoriesIsMutable(); categories_.add(index, value); onChanged(); } else { categoriesBuilder_.addMessage(index, value); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder addCategories( com.google.privacy.dlp.v2beta1.CategoryDescription.Builder builderForValue) { if (categoriesBuilder_ == null) { ensureCategoriesIsMutable(); categories_.add(builderForValue.build()); onChanged(); } else { categoriesBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder addCategories( int index, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder builderForValue) { if (categoriesBuilder_ == null) { ensureCategoriesIsMutable(); categories_.add(index, builderForValue.build()); onChanged(); } else { categoriesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder addAllCategories( java.lang.Iterable<? extends com.google.privacy.dlp.v2beta1.CategoryDescription> values) { if (categoriesBuilder_ == null) { ensureCategoriesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, categories_); onChanged(); } else { categoriesBuilder_.addAllMessages(values); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder clearCategories() { if (categoriesBuilder_ == null) { categories_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); } else { categoriesBuilder_.clear(); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder removeCategories(int index) { if (categoriesBuilder_ == null) { ensureCategoriesIsMutable(); categories_.remove(index); onChanged(); } else { categoriesBuilder_.remove(index); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescription.Builder getCategoriesBuilder( int index) { return getCategoriesFieldBuilder().getBuilder(index); } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder getCategoriesOrBuilder( int index) { if (categoriesBuilder_ == null) { return categories_.get(index); } else { return categoriesBuilder_.getMessageOrBuilder(index); } } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public java.util.List<? extends com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder> getCategoriesOrBuilderList() { if (categoriesBuilder_ != null) { return categoriesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(categories_); } } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescription.Builder addCategoriesBuilder() { return getCategoriesFieldBuilder().addBuilder( com.google.privacy.dlp.v2beta1.CategoryDescription.getDefaultInstance()); } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescription.Builder addCategoriesBuilder( int index) { return getCategoriesFieldBuilder().addBuilder( index, com.google.privacy.dlp.v2beta1.CategoryDescription.getDefaultInstance()); } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription.Builder> getCategoriesBuilderList() { return getCategoriesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.privacy.dlp.v2beta1.CategoryDescription, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder, com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder> getCategoriesFieldBuilder() { if (categoriesBuilder_ == null) { categoriesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.privacy.dlp.v2beta1.CategoryDescription, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder, com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder>( categories_, ((bitField0_ & 0x00000004) == 0x00000004), getParentForChildren(), isClean()); categories_ = null; } return categoriesBuilder_; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.privacy.dlp.v2beta1.InfoTypeDescription) } // @@protoc_insertion_point(class_scope:google.privacy.dlp.v2beta1.InfoTypeDescription) private static final com.google.privacy.dlp.v2beta1.InfoTypeDescription DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.privacy.dlp.v2beta1.InfoTypeDescription(); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<InfoTypeDescription> PARSER = new com.google.protobuf.AbstractParser<InfoTypeDescription>() { public InfoTypeDescription parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new InfoTypeDescription(input, extensionRegistry); } }; public static com.google.protobuf.Parser<InfoTypeDescription> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<InfoTypeDescription> getParserForType() { return PARSER; } public com.google.privacy.dlp.v2beta1.InfoTypeDescription getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
bsd-3-clause
nwjs/chromium.src
media/filters/vpx_video_decoder.cc
21197
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/filters/vpx_video_decoder.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <string> #include <vector> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/feature_list.h" #include "base/location.h" #include "base/logging.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" #include "base/sys_byteorder.h" #include "base/trace_event/trace_event.h" #include "media/base/bind_to_current_loop.h" #include "media/base/decoder_buffer.h" #include "media/base/limits.h" #include "media/base/media_switches.h" #include "media/base/video_aspect_ratio.h" #include "media/filters/frame_buffer_pool.h" #include "third_party/libvpx/source/libvpx/vpx/vp8dx.h" #include "third_party/libvpx/source/libvpx/vpx/vpx_decoder.h" #include "third_party/libvpx/source/libvpx/vpx/vpx_frame_buffer.h" #include "third_party/libyuv/include/libyuv/convert.h" #include "third_party/libyuv/include/libyuv/planar_functions.h" namespace media { // Returns the number of threads. static int GetVpxVideoDecoderThreadCount(const VideoDecoderConfig& config) { // vp8a doesn't really need more threads. int desired_threads = limits::kMinVideoDecodeThreads; // For VP9 decoding increase the number of decode threads to equal the // maximum number of tiles possible for higher resolution streams. if (config.codec() == VideoCodec::kVP9) { const int width = config.coded_size().width(); if (width >= 3840) desired_threads = 16; else if (width >= 2560) desired_threads = 8; else if (width >= 1280) desired_threads = 4; } return VideoDecoder::GetRecommendedThreadCount(desired_threads); } static std::unique_ptr<vpx_codec_ctx> InitializeVpxContext( const VideoDecoderConfig& config) { auto context = std::make_unique<vpx_codec_ctx>(); vpx_codec_dec_cfg_t vpx_config = {0}; vpx_config.w = config.coded_size().width(); vpx_config.h = config.coded_size().height(); vpx_config.threads = GetVpxVideoDecoderThreadCount(config); vpx_codec_err_t status = vpx_codec_dec_init(context.get(), config.codec() == VideoCodec::kVP9 ? vpx_codec_vp9_dx() : vpx_codec_vp8_dx(), &vpx_config, 0 /* flags */); if (status == VPX_CODEC_OK) return context; DLOG(ERROR) << "vpx_codec_dec_init() failed: " << vpx_codec_error(context.get()); return nullptr; } static int32_t GetVP9FrameBuffer(void* user_priv, size_t min_size, vpx_codec_frame_buffer* fb) { DCHECK(user_priv); DCHECK(fb); FrameBufferPool* pool = static_cast<FrameBufferPool*>(user_priv); fb->data = pool->GetFrameBuffer(min_size, &fb->priv); fb->size = min_size; return fb->data ? 0 : VPX_CODEC_MEM_ERROR; } static int32_t ReleaseVP9FrameBuffer(void* user_priv, vpx_codec_frame_buffer* fb) { DCHECK(user_priv); DCHECK(fb); if (!fb->priv) return -1; FrameBufferPool* pool = static_cast<FrameBufferPool*>(user_priv); pool->ReleaseFrameBuffer(fb->priv); return 0; } // static SupportedVideoDecoderConfigs VpxVideoDecoder::SupportedConfigs() { SupportedVideoDecoderConfigs supported_configs; supported_configs.emplace_back(/*profile_min=*/VP8PROFILE_ANY, /*profile_max=*/VP8PROFILE_ANY, /*coded_size_min=*/kDefaultSwDecodeSizeMin, /*coded_size_max=*/kDefaultSwDecodeSizeMax, /*allow_encrypted=*/false, /*require_encrypted=*/false); supported_configs.emplace_back(/*profile_min=*/VP9PROFILE_PROFILE0, /*profile_max=*/VP9PROFILE_PROFILE2, /*coded_size_min=*/kDefaultSwDecodeSizeMin, /*coded_size_max=*/kDefaultSwDecodeSizeMax, /*allow_encrypted=*/false, /*require_encrypted=*/false); return supported_configs; } VpxVideoDecoder::VpxVideoDecoder(OffloadState offload_state) : bind_callbacks_(offload_state == OffloadState::kNormal) { DETACH_FROM_SEQUENCE(sequence_checker_); } VpxVideoDecoder::~VpxVideoDecoder() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); CloseDecoder(); } VideoDecoderType VpxVideoDecoder::GetDecoderType() const { return VideoDecoderType::kVpx; } void VpxVideoDecoder::Initialize(const VideoDecoderConfig& config, bool /* low_delay */, CdmContext* /* cdm_context */, InitCB init_cb, const OutputCB& output_cb, const WaitingCB& /* waiting_cb */) { DVLOG(1) << __func__ << ": " << config.AsHumanReadableString(); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(config.IsValidConfig()); CloseDecoder(); InitCB bound_init_cb = bind_callbacks_ ? BindToCurrentLoop(std::move(init_cb)) : std::move(init_cb); if (config.is_encrypted()) { std::move(bound_init_cb).Run(StatusCode::kEncryptedContentUnsupported); return; } if (!ConfigureDecoder(config)) { std::move(bound_init_cb).Run(StatusCode::kDecoderFailedInitialization); return; } // Success! config_ = config; state_ = DecoderState::kNormal; output_cb_ = output_cb; std::move(bound_init_cb).Run(OkStatus()); } void VpxVideoDecoder::Decode(scoped_refptr<DecoderBuffer> buffer, DecodeCB decode_cb) { DVLOG(3) << __func__ << ": " << buffer->AsHumanReadableString(); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(buffer); DCHECK(decode_cb); DCHECK_NE(state_, DecoderState::kUninitialized) << "Called Decode() before successful Initialize()"; DecodeCB bound_decode_cb = bind_callbacks_ ? BindToCurrentLoop(std::move(decode_cb)) : std::move(decode_cb); if (state_ == DecoderState::kError) { std::move(bound_decode_cb).Run(DecodeStatus::DECODE_ERROR); return; } if (state_ == DecoderState::kDecodeFinished) { std::move(bound_decode_cb).Run(DecodeStatus::OK); return; } if (state_ == DecoderState::kNormal && buffer->end_of_stream()) { state_ = DecoderState::kDecodeFinished; std::move(bound_decode_cb).Run(DecodeStatus::OK); return; } scoped_refptr<VideoFrame> video_frame; if (!VpxDecode(buffer.get(), &video_frame)) { state_ = DecoderState::kError; std::move(bound_decode_cb).Run(DecodeStatus::DECODE_ERROR); return; } // We might get a successful VpxDecode but not a frame if only a partial // decode happened. if (video_frame) { video_frame->metadata().power_efficient = false; output_cb_.Run(video_frame); } // VideoDecoderShim expects |decode_cb| call after |output_cb_|. std::move(bound_decode_cb).Run(DecodeStatus::OK); } void VpxVideoDecoder::Reset(base::OnceClosure reset_cb) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); state_ = DecoderState::kNormal; if (bind_callbacks_) BindToCurrentLoop(std::move(reset_cb)).Run(); else std::move(reset_cb).Run(); // Allow Initialize() to be called on another thread now. DETACH_FROM_SEQUENCE(sequence_checker_); } bool VpxVideoDecoder::ConfigureDecoder(const VideoDecoderConfig& config) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (config.codec() != VideoCodec::kVP8 && config.codec() != VideoCodec::kVP9) return false; #if BUILDFLAG(ENABLE_FFMPEG_VIDEO_DECODERS) // When enabled, ffmpeg handles VP8 that doesn't have alpha, and // VpxVideoDecoder will handle VP8 with alpha. FFvp8 is being deprecated. // See http://crbug.com/992235. if (base::FeatureList::IsEnabled(kFFmpegDecodeOpaqueVP8) && config.codec() == VideoCodec::kVP8 && config.alpha_mode() == VideoDecoderConfig::AlphaMode::kIsOpaque) { return false; } #endif DCHECK(!vpx_codec_); vpx_codec_ = InitializeVpxContext(config); if (!vpx_codec_) return false; // Configure VP9 to decode on our buffers to skip a data copy on // decoding. For YV12A-VP9, we use our buffers for the Y, U and V planes and // copy the A plane. if (config.codec() == VideoCodec::kVP9) { DCHECK(vpx_codec_get_caps(vpx_codec_->iface) & VPX_CODEC_CAP_EXTERNAL_FRAME_BUFFER); DCHECK(!memory_pool_); memory_pool_ = new FrameBufferPool(); if (vpx_codec_set_frame_buffer_functions( vpx_codec_.get(), &GetVP9FrameBuffer, &ReleaseVP9FrameBuffer, memory_pool_.get())) { DLOG(ERROR) << "Failed to configure external buffers. " << vpx_codec_error(vpx_codec_.get()); return false; } vpx_codec_err_t status = vpx_codec_control(vpx_codec_.get(), VP9D_SET_LOOP_FILTER_OPT, 1); if (status != VPX_CODEC_OK) { DLOG(ERROR) << "Failed to enable VP9D_SET_LOOP_FILTER_OPT. " << vpx_codec_error(vpx_codec_.get()); return false; } } if (config.alpha_mode() == VideoDecoderConfig::AlphaMode::kIsOpaque) return true; DCHECK(!vpx_codec_alpha_); vpx_codec_alpha_ = InitializeVpxContext(config); return !!vpx_codec_alpha_; } void VpxVideoDecoder::CloseDecoder() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Note: The vpx_codec_destroy() calls below don't release the memory // allocated for vpx_codec_ctx, they just release internal allocations, so we // still need std::unique_ptr to release the structure memory. if (vpx_codec_) vpx_codec_destroy(vpx_codec_.get()); if (vpx_codec_alpha_) vpx_codec_destroy(vpx_codec_alpha_.get()); vpx_codec_.reset(); vpx_codec_alpha_.reset(); if (memory_pool_) { memory_pool_->Shutdown(); memory_pool_ = nullptr; } } void VpxVideoDecoder::Detach() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!bind_callbacks_); CloseDecoder(); DETACH_FROM_SEQUENCE(sequence_checker_); } bool VpxVideoDecoder::VpxDecode(const DecoderBuffer* buffer, scoped_refptr<VideoFrame>* video_frame) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(video_frame); DCHECK(!buffer->end_of_stream()); { TRACE_EVENT1("media", "vpx_codec_decode", "buffer", buffer->AsHumanReadableString()); vpx_codec_err_t status = vpx_codec_decode(vpx_codec_.get(), buffer->data(), buffer->data_size(), nullptr /* user_priv */, 0 /* deadline */); if (status != VPX_CODEC_OK) { DLOG(ERROR) << "vpx_codec_decode() error: " << vpx_codec_err_to_string(status); return false; } } // Gets pointer to decoded data. vpx_codec_iter_t iter = NULL; const vpx_image_t* vpx_image = vpx_codec_get_frame(vpx_codec_.get(), &iter); if (!vpx_image) { *video_frame = nullptr; return true; } const vpx_image_t* vpx_image_alpha = nullptr; const auto alpha_decode_status = DecodeAlphaPlane(vpx_image, &vpx_image_alpha, buffer); if (alpha_decode_status == kAlphaPlaneError) { return false; } else if (alpha_decode_status == kNoAlphaPlaneData) { *video_frame = nullptr; return true; } if (!CopyVpxImageToVideoFrame(vpx_image, vpx_image_alpha, video_frame)) return false; if (vpx_image_alpha && config_.codec() == VideoCodec::kVP8) { libyuv::CopyPlane(vpx_image_alpha->planes[VPX_PLANE_Y], vpx_image_alpha->stride[VPX_PLANE_Y], (*video_frame)->visible_data(VideoFrame::kAPlane), (*video_frame)->stride(VideoFrame::kAPlane), (*video_frame)->visible_rect().width(), (*video_frame)->visible_rect().height()); } (*video_frame)->set_timestamp(buffer->timestamp()); (*video_frame)->set_hdr_metadata(config_.hdr_metadata()); // Prefer the color space from the config if available. It generally comes // from the color tag which is more expressive than the vp8 and vp9 bitstream. if (config_.color_space_info().IsSpecified()) { (*video_frame) ->set_color_space(config_.color_space_info().ToGfxColorSpace()); return true; } auto primaries = gfx::ColorSpace::PrimaryID::INVALID; auto transfer = gfx::ColorSpace::TransferID::INVALID; auto matrix = gfx::ColorSpace::MatrixID::INVALID; auto range = vpx_image->range == VPX_CR_FULL_RANGE ? gfx::ColorSpace::RangeID::FULL : gfx::ColorSpace::RangeID::LIMITED; switch (vpx_image->cs) { case VPX_CS_BT_601: case VPX_CS_SMPTE_170: primaries = gfx::ColorSpace::PrimaryID::SMPTE170M; transfer = gfx::ColorSpace::TransferID::SMPTE170M; matrix = gfx::ColorSpace::MatrixID::SMPTE170M; break; case VPX_CS_SMPTE_240: primaries = gfx::ColorSpace::PrimaryID::SMPTE240M; transfer = gfx::ColorSpace::TransferID::SMPTE240M; matrix = gfx::ColorSpace::MatrixID::SMPTE240M; break; case VPX_CS_BT_709: primaries = gfx::ColorSpace::PrimaryID::BT709; transfer = gfx::ColorSpace::TransferID::BT709; matrix = gfx::ColorSpace::MatrixID::BT709; break; case VPX_CS_BT_2020: primaries = gfx::ColorSpace::PrimaryID::BT2020; if (vpx_image->bit_depth >= 12) transfer = gfx::ColorSpace::TransferID::BT2020_12; else if (vpx_image->bit_depth >= 10) transfer = gfx::ColorSpace::TransferID::BT2020_10; else transfer = gfx::ColorSpace::TransferID::BT709; matrix = gfx::ColorSpace::MatrixID::BT2020_NCL; // is this right? break; case VPX_CS_SRGB: primaries = gfx::ColorSpace::PrimaryID::BT709; transfer = gfx::ColorSpace::TransferID::IEC61966_2_1; matrix = gfx::ColorSpace::MatrixID::GBR; break; default: break; } // TODO(ccameron): Set a color space even for unspecified values. if (primaries != gfx::ColorSpace::PrimaryID::INVALID) { (*video_frame) ->set_color_space(gfx::ColorSpace(primaries, transfer, matrix, range)); } return true; } VpxVideoDecoder::AlphaDecodeStatus VpxVideoDecoder::DecodeAlphaPlane( const struct vpx_image* vpx_image, const struct vpx_image** vpx_image_alpha, const DecoderBuffer* buffer) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!vpx_codec_alpha_ || buffer->side_data_size() < 8) { return kAlphaPlaneProcessed; } // First 8 bytes of side data is |side_data_id| in big endian. const uint64_t side_data_id = base::NetToHost64( *(reinterpret_cast<const uint64_t*>(buffer->side_data()))); if (side_data_id != 1) { return kAlphaPlaneProcessed; } // Try and decode buffer->side_data() minus the first 8 bytes as a full // frame. { TRACE_EVENT1("media", "vpx_codec_decode_alpha", "buffer", buffer->AsHumanReadableString()); vpx_codec_err_t status = vpx_codec_decode(vpx_codec_alpha_.get(), buffer->side_data() + 8, buffer->side_data_size() - 8, nullptr /* user_priv */, 0 /* deadline */); if (status != VPX_CODEC_OK) { DLOG(ERROR) << "vpx_codec_decode() failed for the alpha: " << vpx_codec_error(vpx_codec_.get()); return kAlphaPlaneError; } } vpx_codec_iter_t iter_alpha = NULL; *vpx_image_alpha = vpx_codec_get_frame(vpx_codec_alpha_.get(), &iter_alpha); if (!(*vpx_image_alpha)) { return kNoAlphaPlaneData; } if ((*vpx_image_alpha)->d_h != vpx_image->d_h || (*vpx_image_alpha)->d_w != vpx_image->d_w) { DLOG(ERROR) << "The alpha plane dimensions are not the same as the " "image dimensions."; return kAlphaPlaneError; } return kAlphaPlaneProcessed; } bool VpxVideoDecoder::CopyVpxImageToVideoFrame( const struct vpx_image* vpx_image, const struct vpx_image* vpx_image_alpha, scoped_refptr<VideoFrame>* video_frame) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(vpx_image); VideoPixelFormat codec_format; switch (vpx_image->fmt) { case VPX_IMG_FMT_I420: codec_format = vpx_image_alpha ? PIXEL_FORMAT_I420A : PIXEL_FORMAT_I420; break; case VPX_IMG_FMT_I422: codec_format = PIXEL_FORMAT_I422; break; case VPX_IMG_FMT_I444: codec_format = PIXEL_FORMAT_I444; break; case VPX_IMG_FMT_I42016: switch (vpx_image->bit_depth) { case 10: codec_format = PIXEL_FORMAT_YUV420P10; break; case 12: codec_format = PIXEL_FORMAT_YUV420P12; break; default: DLOG(ERROR) << "Unsupported bit depth: " << vpx_image->bit_depth; return false; } break; case VPX_IMG_FMT_I42216: switch (vpx_image->bit_depth) { case 10: codec_format = PIXEL_FORMAT_YUV422P10; break; case 12: codec_format = PIXEL_FORMAT_YUV422P12; break; default: DLOG(ERROR) << "Unsupported bit depth: " << vpx_image->bit_depth; return false; } break; case VPX_IMG_FMT_I44416: switch (vpx_image->bit_depth) { case 10: codec_format = PIXEL_FORMAT_YUV444P10; break; case 12: codec_format = PIXEL_FORMAT_YUV444P12; break; default: DLOG(ERROR) << "Unsupported bit depth: " << vpx_image->bit_depth; return false; } break; default: DLOG(ERROR) << "Unsupported pixel format: " << vpx_image->fmt; return false; } // The mixed |w|/|d_h| in |coded_size| is intentional. Setting the correct // coded width is necessary to allow coalesced memory access, which may avoid // frame copies. Setting the correct coded height however does not have any // benefit, and only risk copying too much data. const gfx::Size coded_size(vpx_image->w, vpx_image->d_h); const gfx::Size visible_size(vpx_image->d_w, vpx_image->d_h); // Compute natural size by scaling visible size by *pixel* aspect ratio. Note // that we could instead use vpx_image r_w and r_h, but doing so would allow // pixel aspect ratio to change on a per-frame basis which would make // vpx_video_decoder inconsistent with decoders where changes to // pixel aspect ratio are not surfaced (e.g. Android MediaCodec). const gfx::Size natural_size = config_.aspect_ratio().GetNaturalSize(gfx::Rect(visible_size)); if (memory_pool_) { DCHECK_EQ(VideoCodec::kVP9, config_.codec()); if (vpx_image_alpha) { size_t alpha_plane_size = vpx_image_alpha->stride[VPX_PLANE_Y] * vpx_image_alpha->d_h; uint8_t* alpha_plane = memory_pool_->AllocateAlphaPlaneForFrameBuffer( alpha_plane_size, vpx_image->fb_priv); if (!alpha_plane) // In case of OOM, abort copy. return false; libyuv::CopyPlane(vpx_image_alpha->planes[VPX_PLANE_Y], vpx_image_alpha->stride[VPX_PLANE_Y], alpha_plane, vpx_image_alpha->stride[VPX_PLANE_Y], vpx_image_alpha->d_w, vpx_image_alpha->d_h); *video_frame = VideoFrame::WrapExternalYuvaData( codec_format, coded_size, gfx::Rect(visible_size), natural_size, vpx_image->stride[VPX_PLANE_Y], vpx_image->stride[VPX_PLANE_U], vpx_image->stride[VPX_PLANE_V], vpx_image_alpha->stride[VPX_PLANE_Y], vpx_image->planes[VPX_PLANE_Y], vpx_image->planes[VPX_PLANE_U], vpx_image->planes[VPX_PLANE_V], alpha_plane, kNoTimestamp); } else { *video_frame = VideoFrame::WrapExternalYuvData( codec_format, coded_size, gfx::Rect(visible_size), natural_size, vpx_image->stride[VPX_PLANE_Y], vpx_image->stride[VPX_PLANE_U], vpx_image->stride[VPX_PLANE_V], vpx_image->planes[VPX_PLANE_Y], vpx_image->planes[VPX_PLANE_U], vpx_image->planes[VPX_PLANE_V], kNoTimestamp); } if (!(*video_frame)) return false; video_frame->get()->AddDestructionObserver( memory_pool_->CreateFrameCallback(vpx_image->fb_priv)); return true; } *video_frame = frame_pool_.CreateFrame(codec_format, visible_size, gfx::Rect(visible_size), natural_size, kNoTimestamp); if (!(*video_frame)) return false; for (int plane = 0; plane < 3; plane++) { libyuv::CopyPlane( vpx_image->planes[plane], vpx_image->stride[plane], (*video_frame)->visible_data(plane), (*video_frame)->stride(plane), (*video_frame)->row_bytes(plane), (*video_frame)->rows(plane)); } return true; } } // namespace media
bsd-3-clause
operasoftware/presto-testo
core/features/dateParsing/TestCases/individual/SpaceSeparator/170.html
318
<!DOCTYPE html> <html> <meta charset="utf-8"> <title>Date parser test — 0&lt;=x&lt;=69 and 0&lt;=y&lt;=69 and 1000&lt;=z&lt;=9999 — 65 65 7311</title> <script src="../date_test.js"></script> <p>Failed (Script did not run)</p> <script> test_date("65 65 7311", 7316, 6, 3, 22, 0, 0) </script> </html>
bsd-3-clause
sethmenghi/pylog_parse
pylog_parse/workflow.py
4335
"""Workflow for uploading many many many log files at once.""" from __future__ import absolute_import import os from os.path import isfile, getsize import logging import re import luigi import psycopg2 import pandas as pd # import sqlalchemy try: from .pylog_parse import LogFile except: from pylog_parse import LogFile logger = logging.getLogger(__name__) class LogTask(luigi.Task): """Base task for log workflow.""" path = luigi.Parameter() logtype = luigi.Parameter() _conf = luigi.configuration.get_config() _conf.reload() _password = _conf.get('postgres', 'password') _host = _conf.get('postgres', 'host') _port = _conf.get('postgres', 'port') _database = _conf.get('pylog', 'database') _user = _conf.get('postgres', 'user') _url = """postgresql://{u}:{p}@{h}:{port}/{db}""".format(u=_user, p=_password, h=_host, port=_port, db=_database) @property def url(self): """Postgresql url property.""" return self._url def folder_size(path): """Return size of folder at path.""" return sum(getsize(f) for f in os.listdir('.') if isfile(f)) def list_directory_files(path, folders=False): """Yield all filenames in a path.""" for f in os.listdir(path): if f[0] == '.': continue current_path = os.path.join(path, f) if folders is False: if os.path.isfile(current_path): if os.path.getsize(current_path) != 0: yield current_path else: file_ext = os.path.splitext(f)[1] if file_ext == '' or file_ext == '/': yield current_path def get_subfolders(path): for f in list_directory_files(path, folders=True): file_ext = os.path.splitext(f)[1] if file_ext == ''or file_ext == '/': yield f def get_sublogs(path): for f in list_directory_files(path): file_ext = os.path.splitext(f)[1] if file_ext == '.log': yield f class CheckLogPath(luigi.ExternalTask): path = luigi.Parameter() def output(self): return luigi.LocalTarget(path=self.path) class UploadLogs(LogTask): def requires(self): return CheckLogPath(path=self.path) def output(self): groups = re.search(r'2015.(\d{2}).(\d{2})', self.path).groups() csv = '/home/ubuntu/elb2/2015-{m}-{d}.csv'.format(m=groups[0], d=groups[1]) return luigi.LocalTarget(path=csv) def run(self): conn = psycopg2.connect(self.url) log = LogFile(path=self.path, log_type=self.logtype) cursor = conn.cursor() cursor.close() log.to_csv(self.output().path, con=conn, copy=True) if os.path.exists(self.output().path): df = pd.DataFrame({'length': log.length}, index=[0]) os.remove(self.output().path) df.to_csv(self.output().path, index=False) # Only keep head of csv class LogPaths(LogTask): def requires(self): log_files = [f for f in get_sublogs(self.path)] subfolders = [f for f in get_subfolders(self.path)] logger.debug('Path: {p}'.format(p=self.path)) logger.debug('Subfolders: {s}'.format(s=subfolders)) logger.debug('Subfiles: {f}'.format(f=log_files)) for fold in subfolders: sub = [f for f in get_subfolders(fold)] files = [f for f in get_sublogs(fold)] if len(sub) > 0: logger.info('Subfolders of {f}: {s}'.format(f=fold, s=sub)) yield LogPaths(path=fold, logtype=self.logtype) elif len(files) > 0: yield UploadLogs(path=fold, logtype=self.logtype) for f in log_files: yield UploadLogs(path=f, logtype=self.logtype) def run(self): total_length = 0 for f in self.input(): total_length = total_length + pd.read_csv(f.path()).iloc[0][0] logger.info('AllFilesLength: {l}'.format(l=total_length)) if __name__ == '__main__': luigi.run()
bsd-3-clause
seif/NHibernate.ZMQLogPublisher
src/NHibernate.ZMQLogPublisher/SocketManager.cs
1545
namespace NHibernate.ZMQLogPublisher { using System.Collections.Concurrent; using System.Collections.Generic; using ZMQ; public class SocketManager { private readonly Context context; private ConcurrentDictionary<string, Socket> sockets; private object synclock = new object(); private bool terminated; public SocketManager() { this.context = new Context(1); this.sockets = new ConcurrentDictionary<string, Socket>(); } public bool Terminated { get { return this.terminated; } } public Context Context { get { return this.context; } } public Socket CreateSocketForKey(string loggerKey, SocketType socketType) { return this.sockets.GetOrAdd( loggerKey, key => { var socket = this.Context.Socket(socketType); this.sockets.TryAdd(loggerKey, socket); return socket; }); } public void Terminate() { this.terminated = true; foreach (var socket in sockets.Values) { lock (this.synclock) { socket.Dispose(); } } sockets.Clear(); this.Context.Dispose(); } } }
bsd-3-clause
cullina/Extractor
src/BinaryTree.hs
2206
module BinaryTree ( BinaryTree(..), newNode, value, left, right, getNode, safeGetValue, modifyNode, setNode, listToTree, append, flatten, Bit.natToBits ) where import Bit import Data.List(foldl') data BinaryTree a = Leaf | Branch (Maybe a) (BinaryTree a) (BinaryTree a) instance Show a => Show (BinaryTree a) where show Leaf = "_" show (Branch Nothing l r) = "(_," ++ show l ++ "," ++ show r ++ ")" show (Branch (Just x) l r) = "(" ++ show x ++ "," ++ show l ++ "," ++ show r ++ ")" newNode x = Branch (Just x) Leaf Leaf value Leaf = Nothing value (Branch x _ _) = x left Leaf = Leaf left (Branch _ l _) = l right Leaf = Leaf right (Branch _ _ r) = r getNode Leaf _ = Leaf getNode t@(Branch _ _ _) [] = t getNode (Branch _ l r) (b:bs) = if b then getNode r bs else getNode l bs -- Ignores all leading zeros and one leading one, then calls f. -- If there is no one, returns Nothing ignorePrefixBits _ [] = Nothing ignorePrefixBits f (b:bs) = if b then f bs else ignorePrefixBits f bs safeGetValue tree = ignorePrefixBits (value . getNode tree) modifyNode f Leaf [] = Branch (f Nothing) Leaf Leaf modifyNode f (Branch x l r) [] = Branch (f x) l r modifyNode f Leaf (b:bs) = if b then Branch Nothing Leaf (modifyNode f Leaf bs) else Branch Nothing (modifyNode f Leaf bs) Leaf modifyNode f (Branch x l r) (b:bs) = if b then Branch x l (modifyNode f r bs) else Branch x (modifyNode f l bs) r setNode value = modifyNode (const (Just value)) listToTree xs = snd $ foldl' append ([], Leaf) xs append (n, tree) x = (incrementNat n, setNode x tree n) getDepth :: Int -> BinaryTree a -> [Maybe a] getDepth n = concat . getDepth' n getDepth' :: Int -> BinaryTree a -> [[Maybe a]] getDepth' 0 _ = [] getDepth' n t = let l = getDepth' (n - 1) $ left t r = getDepth' (n - 1) $ right t in [value t] : zipWith (++) l r findDepth Leaf = 0 findDepth (Branch _ l r) = 1 + max (findDepth l) (findDepth r) flatten tree = getDepth (findDepth tree) tree
bsd-3-clause
dynamic/silverstripe-flexslider
CONTRIBUTING.md
1248
# Contributing - Maintenance on this module is a shared effort of those who use it - To contribute improvements to the code, ensure you raise a pull request and discuss with the module maintainers - Please follow the SilverStripe [code contribution guidelines](https://docs.silverstripe.org/en/contributing/code/) and [Module Standard](https://docs.silverstripe.org/en/developer_guides/extending/modules/#module-standard) - Supply documentation that followS the [GitHub Flavored Markdown](https://help.github.com/articles/markdown-basics/) conventions - When having discussions about this module in issues or pull request please adhere to the [SilverStripe Community Code of Conduct](https://docs.silverstripe.org/en/contributing/code_of_conduct/) ## Contributor license agreement By supplying code to this module in patches, tickets and pull requests, you agree to assign copyright of that code to Dynamic, on the condition that these code changes are released under the same BSD license as the original module. We ask for this so that the ownership in the license is clear and unambiguous. By releasing this code under a permissive license such as BSD, this copyright assignment won't prevent you from using the code in any way you see fit.
bsd-3-clause
srz-zumix/iutest
test/syntax_tests.cpp
29693
//====================================================================== //----------------------------------------------------------------------- /** * @file syntax_tests.cpp * @brief syntax test * * @author t.shirayanagi * @par copyright * Copyright (C) 2013-2021, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== //====================================================================== // include #include "iutest.hpp" #include "pred_tests.hpp" #include <limits> namespace syntax_tests { #ifndef IUTEST_NO_VARIADIC_MACROS template<int A, int B>struct T { template<typename U> static U call(U v) { return v; } }; #endif IUTEST_PRAGMA_WARN_PUSH() IUTEST_PRAGMA_WARN_DISABLE_DANGLING_ELSE() IUTEST_PRAGMA_WARN_DISABLE_FLOAT_CONVERSION() IUTEST(SyntaxTest, True) { if( bool b = true ) IUTEST_ASSERT_TRUE(b) << b; if( bool b = true ) IUTEST_EXPECT_TRUE(b) << b; if( bool b = true ) IUTEST_INFORM_TRUE(b) << b; if( bool b = true ) IUTEST_ASSUME_TRUE(b) << b; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicTrue) { if( bool b = true ) IUTEST_ASSERT_TRUE(T<0, 0>::call(b)) << b; if( bool b = true ) IUTEST_EXPECT_TRUE(T<0, 0>::call(b)) << b; if( bool b = true ) IUTEST_INFORM_TRUE(T<0, 0>::call(b)) << b; if( bool b = true ) IUTEST_ASSUME_TRUE(T<0, 0>::call(b)) << b; } #endif IUTEST(SyntaxTest, False) { if( bool b = false ) IUTEST_ASSERT_FALSE(b) << b; if( bool b = false ) IUTEST_EXPECT_FALSE(b) << b; if( bool b = false ) IUTEST_INFORM_FALSE(b) << b; if( bool b = false ) IUTEST_ASSUME_FALSE(b) << b; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicFalse) { if( bool b = false ) IUTEST_ASSERT_FALSE(T<0, 0>::call(b)) << b; if( bool b = false ) IUTEST_EXPECT_FALSE(T<0, 0>::call(b)) << b; if( bool b = false ) IUTEST_INFORM_FALSE(T<0, 0>::call(b)) << b; if( bool b = false ) IUTEST_ASSUME_FALSE(T<0, 0>::call(b)) << b; } #endif IUTEST(SyntaxTest, EQ) { if( int x = 1 ) IUTEST_ASSERT_EQ(1, x) << x; if( int x = 1 ) IUTEST_EXPECT_EQ(1, x) << x; if( int x = 1 ) IUTEST_INFORM_EQ(1, x) << x; if( int x = 1 ) IUTEST_ASSUME_EQ(1, x) << x; } IUTEST(SyntaxTest, EQ_COLLECTIONS) { int a[] = { 0, 1, 2, 3, 4 }; int b[] = { 0, 1, 2, 3, 4 }; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSERT_EQ_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_EXPECT_EQ_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_INFORM_EQ_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSUME_EQ_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; } IUTEST(SyntaxTest, NE_COLLECTIONS) { int a[] = { 0, 1, 2, 3, 4 }; int b[] = { 0, 1, 5, 3, 4 }; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSERT_NE_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_EXPECT_NE_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_INFORM_NE_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSUME_NE_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; } IUTEST(SyntaxTest, EQ_RANGE) { int a[] = { 0, 1, 2, 3, 4 }; int b[] = { 0, 1, 2, 3, 4 }; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSERT_EQ_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_EXPECT_EQ_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_INFORM_EQ_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSUME_EQ_RANGE(a, b) << size; } IUTEST(SyntaxTest, NE_RANGE) { int a[] = { 0, 1, 2, 3, 4 }; int b[] = { 0, 1, 0, 3, 4 }; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSERT_NE_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_EXPECT_NE_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_INFORM_NE_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSUME_NE_RANGE(a, b) << size; } IUTEST(SyntaxTest, NE) { if( int x = 1 ) IUTEST_ASSERT_NE(0, x) << x; if( int x = 1 ) IUTEST_EXPECT_NE(0, x) << x; if( int x = 1 ) IUTEST_INFORM_NE(0, x) << x; if( int x = 1 ) IUTEST_ASSUME_NE(0, x) << x; } IUTEST(SyntaxTest, LT) { if( int x = 1 ) IUTEST_ASSERT_LT(0, x) << x; if( int x = 1 ) IUTEST_EXPECT_LT(0, x) << x; if( int x = 1 ) IUTEST_INFORM_LT(0, x) << x; if( int x = 1 ) IUTEST_ASSUME_LT(0, x) << x; } IUTEST(SyntaxTest, LE) { if( int x = 1 ) IUTEST_ASSERT_LE(1, x) << x; if( int x = 1 ) IUTEST_EXPECT_LE(1, x) << x; if( int x = 1 ) IUTEST_INFORM_LE(1, x) << x; if( int x = 1 ) IUTEST_ASSUME_LE(1, x) << x; } IUTEST(SyntaxTest, GT) { if( int x = 1 ) IUTEST_ASSERT_GT(2, x) << x; if( int x = 1 ) IUTEST_EXPECT_GT(2, x) << x; if( int x = 1 ) IUTEST_INFORM_GT(2, x) << x; if( int x = 1 ) IUTEST_ASSUME_GT(2, x) << x; } IUTEST(SyntaxTest, GE) { if( int x = 1 ) IUTEST_ASSERT_GE(1, x) << x; if( int x = 1 ) IUTEST_EXPECT_GE(1, x) << x; if( int x = 1 ) IUTEST_INFORM_GE(1, x) << x; if( int x = 1 ) IUTEST_ASSUME_GE(1, x) << x; } IUTEST(SyntaxTest, Float) { if( float f = 1.0f ) IUTEST_ASSERT_FLOAT_EQ(1.0f, f) << f; if( float f = 1.0f ) IUTEST_EXPECT_FLOAT_EQ(1.0f, f) << f; if( float f = 1.0f ) IUTEST_INFORM_FLOAT_EQ(1.0f, f) << f; if( float f = 1.0f ) IUTEST_ASSUME_FLOAT_EQ(1.0f, f) << f; } IUTEST(SyntaxTest, Double) { if( double d = 1.0 ) IUTEST_ASSERT_DOUBLE_EQ(1.0, d) << d; if( double d = 1.0 ) IUTEST_EXPECT_DOUBLE_EQ(1.0, d) << d; if( double d = 1.0 ) IUTEST_INFORM_DOUBLE_EQ(1.0, d) << d; if( double d = 1.0 ) IUTEST_ASSUME_DOUBLE_EQ(1.0, d) << d; } #if IUTEST_HAS_LONG_DOUBLE IUTEST(SyntaxTest, LongDouble) { if( long double d = 1.0l ) IUTEST_ASSERT_LONG_DOUBLE_EQ(1.0l, d) << d; if( long double d = 1.0l ) IUTEST_EXPECT_LONG_DOUBLE_EQ(1.0l, d) << d; if( long double d = 1.0l ) IUTEST_INFORM_LONG_DOUBLE_EQ(1.0l, d) << d; if( long double d = 1.0l ) IUTEST_ASSUME_LONG_DOUBLE_EQ(1.0l, d) << d; } #endif IUTEST(SyntaxTest, Complex) { ::std::complex<float> c(1.0f, 1.0f); if( float d = 1.0 ) IUTEST_ASSERT_COMPLEX_EQ(::std::complex<float>(d, d), c) << c; if( float d = 1.0 ) IUTEST_EXPECT_COMPLEX_EQ(::std::complex<float>(d, d), c) << c; if( float d = 1.0 ) IUTEST_INFORM_COMPLEX_EQ(::std::complex<float>(d, d), c) << c; if( float d = 1.0 ) IUTEST_ASSUME_COMPLEX_EQ(::std::complex<float>(d, d), c) << c; } IUTEST(SyntaxTest, Near) { if( int x = 1 ) IUTEST_ASSERT_NEAR(0, x, 2) << x; if( int x = 1 ) IUTEST_EXPECT_NEAR(0, x, 2) << x; if( int x = 1 ) IUTEST_INFORM_NEAR(0, x, 2) << x; if( int x = 1 ) IUTEST_ASSUME_NEAR(0, x, 2) << x; } IUTEST(SyntaxTest, AlmostEq) { if( int x = 1 ) IUTEST_ASSERT_ALMOST_EQ(1, x); if( int x = 1 ) IUTEST_EXPECT_ALMOST_EQ(1, x); if( int x = 1 ) IUTEST_INFORM_ALMOST_EQ(1, x); if( int x = 1 ) IUTEST_ASSUME_ALMOST_EQ(1, x); } IUTEST(SyntaxTest, AlmostFloatEq) { if( float x = 1.0f ) IUTEST_ASSERT_ALMOST_EQ(1.0f, x); if( float x = 1.0f ) IUTEST_EXPECT_ALMOST_EQ(1.0f, x); if( float x = 1.0f ) IUTEST_INFORM_ALMOST_EQ(1.0f, x); if( float x = 1.0f ) IUTEST_ASSUME_ALMOST_EQ(1.0f, x); } IUTEST(SyntaxTest, AlmostDoubleEq) { if( double x = 1.0 ) IUTEST_ASSERT_ALMOST_EQ(1.0, x); if( double x = 1.0 ) IUTEST_EXPECT_ALMOST_EQ(1.0, x); if( double x = 1.0 ) IUTEST_INFORM_ALMOST_EQ(1.0, x); if( double x = 1.0 ) IUTEST_ASSUME_ALMOST_EQ(1.0, x); } #if IUTEST_HAS_LONG_DOUBLE IUTEST(SyntaxTest, AlmostLongDoubleEq) { if( long double x = 1.0l ) IUTEST_ASSERT_ALMOST_EQ(1.0l, x); if( long double x = 1.0l ) IUTEST_EXPECT_ALMOST_EQ(1.0l, x); if( long double x = 1.0l ) IUTEST_INFORM_ALMOST_EQ(1.0l, x); if( long double x = 1.0l ) IUTEST_ASSUME_ALMOST_EQ(1.0l, x); } #endif IUTEST(SyntaxTest, AlmostComplexEq) { ::std::complex<double> c(1.0, 0.0); if( double x = 1.0 ) IUTEST_ASSERT_ALMOST_EQ(c, x); if( double x = 1.0 ) IUTEST_EXPECT_ALMOST_EQ(x, c); if( double x = 1.0 ) IUTEST_INFORM_ALMOST_EQ(::std::complex<double>(x, x), c); if( double x = 1.0 ) IUTEST_ASSUME_ALMOST_EQ(c, ::std::complex<double>(x, x)); } IUTEST(SyntaxTest, Null) { int* p = NULL; if( int x = 1 ) IUTEST_ASSERT_NULL(p) << x; if( int x = 1 ) IUTEST_EXPECT_NULL(p) << x; if( int x = 1 ) IUTEST_INFORM_NULL(p) << x; if( int x = 1 ) IUTEST_ASSUME_NULL(p) << x; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicNull) { int* p = NULL; if( int x = 1 ) IUTEST_ASSERT_NULL(T<0, 0>::call(p)) << x; if( int x = 1 ) IUTEST_EXPECT_NULL(T<0, 0>::call(p)) << x; if( int x = 1 ) IUTEST_INFORM_NULL(T<0, 0>::call(p)) << x; if( int x = 1 ) IUTEST_ASSUME_NULL(T<0, 0>::call(p)) << x; } #endif IUTEST(SyntaxTest, NotNull) { if( void* p = this ) IUTEST_ASSERT_NOTNULL(p) << p; if( void* p = this ) IUTEST_EXPECT_NOTNULL(p) << p; if( void* p = this ) IUTEST_INFORM_NOTNULL(p) << p; if( void* p = this ) IUTEST_ASSUME_NOTNULL(p) << p; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicNotNull) { if( void* p = this ) IUTEST_ASSERT_NOTNULL(T<0, 0>::call(p)) << p; if( void* p = this ) IUTEST_EXPECT_NOTNULL(T<0, 0>::call(p)) << p; if( void* p = this ) IUTEST_INFORM_NOTNULL(T<0, 0>::call(p)) << p; if( void* p = this ) IUTEST_ASSUME_NOTNULL(T<0, 0>::call(p)) << p; } #endif IUTEST(SyntaxTest, Same) { int v = 0; if( int* p = &v ) IUTEST_ASSERT_SAME(v, *p) << p; if( int* p = &v ) IUTEST_EXPECT_SAME(v, *p) << p; if( int* p = &v ) IUTEST_INFORM_SAME(v, *p) << p; if( int* p = &v ) IUTEST_ASSUME_SAME(v, *p) << p; } IUTEST(SyntaxTest, StrEq) { const char test[] = "test"; if( const char* p = "test" ) IUTEST_ASSERT_STREQ(p, test) << p; if( const char* p = "test" ) IUTEST_EXPECT_STREQ(p, test) << p; if( const char* p = "test" ) IUTEST_INFORM_STREQ(p, test) << p; if( const char* p = "test" ) IUTEST_ASSUME_STREQ(p, test) << p; } IUTEST(SyntaxTest, StrNe) { const char test[] = "Test"; if( const char* p = "test" ) IUTEST_ASSERT_STRNE(p, test) << p; if( const char* p = "test" ) IUTEST_EXPECT_STRNE(p, test) << p; if( const char* p = "test" ) IUTEST_INFORM_STRNE(p, test) << p; if( const char* p = "test" ) IUTEST_ASSUME_STRNE(p, test) << p; } IUTEST(SyntaxTest, StrCaseEq) { const char test[] = "Test"; if( const char* p = "test" ) IUTEST_ASSERT_STRCASEEQ(p, test) << p; if( const char* p = "test" ) IUTEST_EXPECT_STRCASEEQ(p, test) << p; if( const char* p = "test" ) IUTEST_INFORM_STRCASEEQ(p, test) << p; if( const char* p = "test" ) IUTEST_ASSUME_STRCASEEQ(p, test) << p; } IUTEST(SyntaxTest, StrCaseNe) { const char test[] = "host"; if( const char* p = "test" ) IUTEST_ASSERT_STRCASENE(p, test) << p; if( const char* p = "test" ) IUTEST_EXPECT_STRCASENE(p, test) << p; if( const char* p = "test" ) IUTEST_INFORM_STRCASENE(p, test) << p; if( const char* p = "test" ) IUTEST_ASSUME_STRCASENE(p, test) << p; } IUTEST(SyntaxTest, StrLn) { const char test[] = "test"; if( int len = 4 ) IUTEST_ASSERT_STRLNEQ(len, test) << len; if( int len = 4 ) IUTEST_EXPECT_STRLNEQ(len, test) << len; if( int len = 4 ) IUTEST_INFORM_STRLNEQ(len, test) << len; if( int len = 4 ) IUTEST_ASSUME_STRLNEQ(len, test) << len; } IUTEST(SyntaxTest, Nan) { float fnan = ::std::numeric_limits<float>::quiet_NaN(); double dnan = ::std::numeric_limits<double>::quiet_NaN(); if( fnan ) IUTEST_ASSERT_NAN(fnan) << fnan; if( fnan ) IUTEST_EXPECT_NAN(fnan) << fnan; if( dnan ) IUTEST_INFORM_NAN(dnan) << dnan; if( dnan ) IUTEST_ASSUME_NAN(dnan) << dnan; } #if defined(IUTEST_OS_WINDOWS) IUTEST(SyntaxTest, HResultSucceeded) { if( int x=1 ) IUTEST_ASSERT_HRESULT_SUCCEEDED(0) << x; if( int x=1 ) IUTEST_EXPECT_HRESULT_SUCCEEDED(0) << x; if( int x=1 ) IUTEST_INFORM_HRESULT_SUCCEEDED(0) << x; if( int x=1 ) IUTEST_ASSUME_HRESULT_SUCCEEDED(0) << x; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicHResultSucceeded) { if( int x=1 ) IUTEST_ASSERT_HRESULT_SUCCEEDED(T<0, 0>::call(0)) << x; if( int x=1 ) IUTEST_EXPECT_HRESULT_SUCCEEDED(T<0, 0>::call(0)) << x; if( int x=1 ) IUTEST_INFORM_HRESULT_SUCCEEDED(T<0, 0>::call(0)) << x; if( int x=1 ) IUTEST_ASSUME_HRESULT_SUCCEEDED(T<0, 0>::call(0)) << x; } #endif IUTEST(SyntaxTest, HResultFailed) { if( int x=1 ) IUTEST_ASSERT_HRESULT_FAILED(-1) << x; if( int x=1 ) IUTEST_EXPECT_HRESULT_FAILED(-1) << x; if( int x=1 ) IUTEST_INFORM_HRESULT_FAILED(-1) << x; if( int x=1 ) IUTEST_ASSUME_HRESULT_FAILED(-1) << x; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicHResultFailed) { if( int x=1 ) IUTEST_ASSERT_HRESULT_FAILED(T<0, 0>::call(-1)) << x; if( int x=1 ) IUTEST_EXPECT_HRESULT_FAILED(T<0, 0>::call(-1)) << x; if( int x=1 ) IUTEST_INFORM_HRESULT_FAILED(T<0, 0>::call(-1)) << x; if( int x=1 ) IUTEST_ASSUME_HRESULT_FAILED(T<0, 0>::call(-1)) << x; } #endif #endif IUTEST(SyntaxTest, Skip) { if( int x = 1 ) IUTEST_SKIP() << x; } IUTEST(SyntaxTest, Pred1) { if( int x=1 ) IUTEST_ASSERT_PRED1(IsOdd, x) << x; if( int x=1 ) IUTEST_EXPECT_PRED1(IsOdd, x) << x; if( int x=1 ) IUTEST_INFORM_PRED1(IsOdd, x) << x; if( int x=1 ) IUTEST_ASSUME_PRED1(IsOdd, x) << x; } IUTEST(SyntaxTest, Pred2) { if( int x=1 ) IUTEST_ASSERT_PRED2(IsGreater, 3, x) << x; if( int x=1 ) IUTEST_EXPECT_PRED2(IsGreater, 3, x) << x; if( int x=1 ) IUTEST_INFORM_PRED2(IsGreater, 3, x) << x; if( int x=1 ) IUTEST_ASSUME_PRED2(IsGreater, 3, x) << x; } IUTEST(SyntaxTest, Pred3) { if( int x=1 ) IUTEST_ASSERT_PRED3(PredTest3, 0, x, 2) << x; if( int x=1 ) IUTEST_EXPECT_PRED3(PredTest3, 0, x, 2) << x; if( int x=1 ) IUTEST_INFORM_PRED3(PredTest3, 0, x, 2) << x; if( int x=1 ) IUTEST_ASSUME_PRED3(PredTest3, 0, x, 2) << x; } IUTEST(SyntaxTest, Pred4) { if( int x=1 ) IUTEST_ASSERT_PRED4(PredTest4, 0, x, 2, 3) << x; if( int x=1 ) IUTEST_EXPECT_PRED4(PredTest4, 0, x, 2, 3) << x; if( int x=1 ) IUTEST_INFORM_PRED4(PredTest4, 0, x, 2, 3) << x; if( int x=1 ) IUTEST_ASSUME_PRED4(PredTest4, 0, x, 2, 3) << x; } IUTEST(SyntaxTest, Pred5) { if( int x=1 ) IUTEST_ASSERT_PRED5(PredTest5, 0, x, 2, 3, 4) << x; if( int x=1 ) IUTEST_EXPECT_PRED5(PredTest5, 0, x, 2, 3, 4) << x; if( int x=1 ) IUTEST_INFORM_PRED5(PredTest5, 0, x, 2, 3, 4) << x; if( int x=1 ) IUTEST_ASSUME_PRED5(PredTest5, 0, x, 2, 3, 4) << x; } #if IUTEST_HAS_MATCHERS IUTEST(SyntaxTest, That) { if( int x=1 ) IUTEST_ASSERT_THAT(x, ::iutest::Eq(1)) << x; if( int x=1 ) IUTEST_EXPECT_THAT(x, ::iutest::Le(1)) << x; if( int x=1 ) IUTEST_INFORM_THAT(x, ::iutest::Ge(1)) << x; if( int x=1 ) IUTEST_ASSUME_THAT(x, ::iutest::Ne(0)) << x; } struct X { int a, b; X(int _a, int _b) : a(_a), b(_b) {} int GetA() const { return a; } }; int X2(int value) { return value*2; } IUTEST(SyntaxTest, Matcher) { ::std::vector<int> v; v.push_back(0); v.push_back(1); v.push_back(2); int a[3] = { 0, 1, 2 }; int b[4] = { 0, 1, 2, 3 }; X x(0, 1); int z=1; IUTEST_EXPECT_THAT(a, ::iutest::Contains(0)); IUTEST_EXPECT_THAT(a, ::iutest::Contains(::iutest::Lt(10))); #if IUTEST_HAS_MATCHER_EACH IUTEST_EXPECT_THAT(a, ::iutest::Each(::iutest::Le(10))); IUTEST_EXPECT_THAT(a, ::iutest::Each(::iutest::_)); IUTEST_EXPECT_THAT(a, ::iutest::Each(::iutest::A<int>())); #endif IUTEST_EXPECT_THAT(&x, ::iutest::Field(&X::a, 0)); IUTEST_EXPECT_THAT(x, ::iutest::Field(&X::a, 0)); IUTEST_EXPECT_THAT(&x, ::iutest::Property(&X::GetA, 0)); IUTEST_EXPECT_THAT(x, ::iutest::Property(&X::GetA, 0)); IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArray(a)); IUTEST_EXPECT_THAT(v, ::iutest::ElementsAreArray(a)); #if !defined(IUTEST_USE_GMOCK) || (GMOCK_VER >= 0x01070000) IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArray(v)); IUTEST_EXPECT_THAT(v, ::iutest::ElementsAreArray(v)); #endif IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArray(b, 3)); #if IUTEST_HAS_INITIALIZER_LIST IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArray({0, 1, 2})); #endif IUTEST_EXPECT_THAT(1, ::iutest::ResultOf(X2, 2)); IUTEST_EXPECT_THAT(1, ::iutest::ResultOf(X2, ::iutest::Gt(1))); IUTEST_EXPECT_THAT(z, ::iutest::TypedEq<int>(1.0)); } #if IUTEST_HAS_MATCHER_ELEMENTSAREARRAYFORWARD IUTEST(SyntaxTest, ElementsAreArrayForward) { ::std::vector<int> v; v.push_back(0); v.push_back(1); v.push_back(2); int a[3] = { 0, 1, 2 }; int b[4] = { 0, 1, 2, 3 }; IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArrayForward(a)); IUTEST_EXPECT_THAT(v, ::iutest::ElementsAreArrayForward(a)); IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArrayForward(v)); IUTEST_EXPECT_THAT(v, ::iutest::ElementsAreArrayForward(v)); IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArrayForward(b, 1)); #if IUTEST_HAS_INITIALIZER_LIST IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArrayForward({0, 1, 2})); #endif } #endif #if IUTEST_HAS_MATCHER_REGEX IUTEST(SyntaxTest, MatcherRegex) { ::std::string s = "greeeeeen"; IUTEST_EXPECT_THAT(s, ::iutest::MatchesRegex("gre+n")); IUTEST_EXPECT_THAT("hogeeeeeet", ::iutest::MatchesRegex("hoge+t")); IUTEST_EXPECT_THAT(s, ::iutest::ContainsRegex("e")); IUTEST_EXPECT_THAT("hogeeeeeet", ::iutest::ContainsRegex("hoge+")); } #endif IUTEST(SyntaxTest, MatcherPredicate) { IUTEST_EXPECT_TRUE(::iutest::Value(2, 2)); IUTEST_EXPECT_TRUE(::iutest::Value(2, ::iutest::Eq(2))); } #if IUTEST_HAS_MATCHER_ALLOF_AND_ANYOF IUTEST(SyntaxTest, AllOf) { #if IUTEST_HAS_MATCHER_VARIADIC IUTEST_EXPECT_THAT("9347812650", ::iutest::AllOf( ::iutest::HasSubstr("0") , ::iutest::HasSubstr("1") , ::iutest::HasSubstr("2") , ::iutest::HasSubstr("3") , ::iutest::HasSubstr("4") , ::iutest::HasSubstr("5") , ::iutest::HasSubstr("6") , ::iutest::HasSubstr("7") , ::iutest::HasSubstr("8") , ::iutest::HasSubstr("9") , ::iutest::HasSubstr("0") )); #else IUTEST_EXPECT_THAT("9347812650", ::iutest::AllOf( ::iutest::HasSubstr("0") , ::iutest::HasSubstr("1") , ::iutest::HasSubstr("2") , ::iutest::HasSubstr("3") , ::iutest::HasSubstr("4") , ::iutest::HasSubstr("5") , ::iutest::HasSubstr("6") , ::iutest::HasSubstr("7") , ::iutest::HasSubstr("8") , ::iutest::HasSubstr("9") )); #endif } IUTEST(SyntaxTest, AnyOf) { #if IUTEST_HAS_MATCHER_VARIADIC IUTEST_EXPECT_THAT("hoge7", ::iutest::AnyOf( ::iutest::HasSubstr("0") , ::iutest::HasSubstr("1") , ::iutest::HasSubstr("2") , ::iutest::HasSubstr("3") , ::iutest::HasSubstr("4") , ::iutest::HasSubstr("5") , ::iutest::HasSubstr("6") , ::iutest::HasSubstr("7") , ::iutest::HasSubstr("8") , ::iutest::HasSubstr("9") , ::iutest::HasSubstr("0") )); #else IUTEST_EXPECT_THAT("hoge7", ::iutest::AnyOf( ::iutest::HasSubstr("0") , ::iutest::HasSubstr("1") , ::iutest::HasSubstr("2") , ::iutest::HasSubstr("3") , ::iutest::HasSubstr("4") , ::iutest::HasSubstr("5") , ::iutest::HasSubstr("6") , ::iutest::HasSubstr("7") , ::iutest::HasSubstr("8") , ::iutest::HasSubstr("9") )); #endif } #endif #endif #if !defined(IUTEST_USE_GTEST) #if !defined(IUTEST_NO_VARIADIC_MACROS) #if IUTEST_HAS_VARIADIC_TEMPLATES IUTEST(SyntaxTest, VariadicPred) { if( int x=1 ) IUTEST_ASSERT_PRED(PredTest6, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_EXPECT_PRED(PredTest6, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_INFORM_PRED(PredTest6, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_ASSUME_PRED(PredTest6, 0, x, 2, 3, 4, 5) << x; } #endif IUTEST(SyntaxTest, VariadicPredFormat) { if( int x=1 ) IUTEST_ASSERT_PRED_FORMAT(Pred6Formater, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_EXPECT_PRED_FORMAT(Pred6Formater, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_INFORM_PRED_FORMAT(Pred6Formater, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_ASSUME_PRED_FORMAT(Pred6Formater, 0, x, 2, 3, 4, 5) << x; } #endif #endif #if IUTEST_HAS_EXCEPTIONS static void ExceptionFunction(int i) { switch( i ) { case 0: return; case 1: throw 2; case 2: throw ::std::bad_exception(); case 3: throw "error"; case 4: throw ::std::string("error"); case 5: throw 0.1f; default: break; } } IUTEST(SyntaxTest, ExceptionThrow) { if( int x = 2 ) IUTEST_ASSERT_THROW(ExceptionFunction(x), ::std::bad_exception) << x; if( int x = 2 ) IUTEST_EXPECT_THROW(ExceptionFunction(x), ::std::bad_exception) << x; if( int x = 2 ) IUTEST_INFORM_THROW(ExceptionFunction(x), ::std::bad_exception) << x; if( int x = 2 ) IUTEST_ASSUME_THROW(ExceptionFunction(x), ::std::bad_exception) << x; } IUTEST(SyntaxTest, ExceptionAnyThrow) { if( int x = 1 ) IUTEST_ASSERT_ANY_THROW(throw ::std::bad_exception()) << x; if( int x = 1 ) IUTEST_EXPECT_ANY_THROW(throw ::std::bad_exception()) << x; if( int x = 1 ) IUTEST_INFORM_ANY_THROW(throw ::std::bad_exception()) << x; if( int x = 1 ) IUTEST_ASSUME_ANY_THROW(throw ::std::bad_exception()) << x; } IUTEST(SyntaxTest, ExceptionNoThrow) { if( int x = 1 ) IUTEST_ASSERT_NO_THROW((void)x) << x; if( int x = 1 ) IUTEST_EXPECT_NO_THROW((void)x) << x; if( int x = 1 ) IUTEST_INFORM_NO_THROW((void)x) << x; if( int x = 1 ) IUTEST_ASSUME_NO_THROW((void)x) << x; } IUTEST(SyntaxTest, ExceptionValueEQ) { if( int x = 1 ) IUTEST_ASSERT_THROW_VALUE_EQ(throw 1, int, x) << x; if( int x = 1 ) IUTEST_EXPECT_THROW_VALUE_EQ(throw 1, int, x) << x; if( int x = 1 ) IUTEST_INFORM_THROW_VALUE_EQ(throw 1, int, x) << x; if( int x = 1 ) IUTEST_ASSUME_THROW_VALUE_EQ(throw 1, int, x) << x; } IUTEST(SyntaxTest, ExceptionValueNE) { if( int x = 1 ) IUTEST_ASSERT_THROW_VALUE_NE(throw 2, int, x) << x; if( int x = 1 ) IUTEST_EXPECT_THROW_VALUE_NE(throw 2, int, x) << x; if( int x = 1 ) IUTEST_INFORM_THROW_VALUE_NE(throw 2, int, x) << x; if( int x = 1 ) IUTEST_ASSUME_THROW_VALUE_NE(throw 2, int, x) << x; } IUTEST(SyntaxTest, ExceptionValueSTREQ) { if( int x = 1 ) IUTEST_ASSERT_THROW_VALUE_STREQ(throw "error", const char *, "error") << x; if( int x = 1 ) IUTEST_EXPECT_THROW_VALUE_STREQ(throw "error", const char *, "error") << x; if( int x = 1 ) IUTEST_INFORM_THROW_VALUE_STREQ(throw "error", const char *, "error") << x; if( int x = 1 ) IUTEST_ASSUME_THROW_VALUE_STREQ(throw "error", const char *, "error") << x; } IUTEST(SyntaxTest, ExceptionValueSTRCASEEQ) { if( int x = 1 ) IUTEST_ASSERT_THROW_VALUE_STRCASEEQ(throw "error", const char *, "Error") << x; if( int x = 1 ) IUTEST_EXPECT_THROW_VALUE_STRCASEEQ(throw "error", const char *, "Error") << x; if( int x = 1 ) IUTEST_INFORM_THROW_VALUE_STRCASEEQ(throw "error", const char *, "Error") << x; if( int x = 1 ) IUTEST_ASSUME_THROW_VALUE_STRCASEEQ(throw "error", const char *, "Error") << x; } IUTEST(SyntaxTest, ExceptionValueFormat) { if( float x = 0.1f ) IUTEST_ASSERT_THROW_PRED_FORMAT2(::iutest::internal::CmpHelperFloatingPointEQ<float> , ExceptionFunction(5), float, x) << x; if( float x = 0.1f ) IUTEST_EXPECT_THROW_PRED_FORMAT2(::iutest::internal::CmpHelperFloatingPointEQ<float> , ExceptionFunction(5), float, x) << x; if( float x = 0.1f ) IUTEST_INFORM_THROW_PRED_FORMAT2(::iutest::internal::CmpHelperFloatingPointEQ<float> , ExceptionFunction(5), float, x) << x; if( float x = 0.1f ) IUTEST_ASSUME_THROW_PRED_FORMAT2(::iutest::internal::CmpHelperFloatingPointEQ<float> , ExceptionFunction(5), float, x) << x; } class exception_test { public: explicit exception_test(const ::std::vector<int>&) { IUTEST_SUPPRESS_UNREACHABLE_CODE_WARNING(throw ::std::exception()); } }; IUTEST(SyntaxTest, ExceptionVectorConstructor) { ::std::vector<int> a; IUTEST_ASSERT_THROW(exception_test(a), ::std::exception); } #endif #if !defined(IUTEST_USE_GTEST) && defined(__WANDBOX__) IUTEST(SyntaxTest, ShowFeature) { ::iutest::detail::iuOptionMessage::ShowFeature(); } IUTEST(SyntaxTest, ShowSpec) { ::iutest::detail::iuOptionMessage::ShowSpec(); } #endif #if IUTEST_HAS_TYPED_TEST template<typename T> class TypedPrintToTest : public ::iutest::Test {}; typedef ::iutest::Types<char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long, int*> PrintStringTestTypes; IUTEST_TYPED_TEST_SUITE(TypedPrintToTest, PrintStringTestTypes); IUTEST_TYPED_TEST(TypedPrintToTest, Print) { TypeParam a = 0; TypeParam& b = a; const TypeParam c = a; const volatile TypeParam d = a; IUTEST_SUCCEED() << ::iutest::PrintToString(a); IUTEST_SUCCEED() << ::iutest::PrintToString(b); IUTEST_SUCCEED() << ::iutest::PrintToString(c); IUTEST_SUCCEED() << ::iutest::PrintToString(d); } #endif IUTEST(PrintToTest, RawArray) { { unsigned char a[3] = {0, 1, 2}; const unsigned char b[3] = {0, 1, 2}; const volatile unsigned char c[3] = {0, 1, 2}; volatile unsigned char d[3] = {0, 1, 2}; IUTEST_SUCCEED() << ::iutest::PrintToString(a); IUTEST_SUCCEED() << ::iutest::PrintToString(b); IUTEST_SUCCEED() << ::iutest::PrintToString(c); IUTEST_SUCCEED() << ::iutest::PrintToString(d); } { char a[3] = {0, 1, 2}; const char b[3] = {0, 1, 2}; const volatile char c[3] = {0, 1, 2}; volatile char d[3] = {0, 1, 2}; IUTEST_SUCCEED() << ::iutest::PrintToString(a); IUTEST_SUCCEED() << ::iutest::PrintToString(b); IUTEST_SUCCEED() << ::iutest::PrintToString(c); IUTEST_SUCCEED() << ::iutest::PrintToString(d); } } #if IUTEST_HAS_IOMANIP IUTEST(PrintToTest, Iomanip) { IUTEST_SUCCEED() << ::std::endl; IUTEST_SUCCEED() << ::std::ends; } #endif #if IUTEST_HAS_CHAR16_T IUTEST(PrintToTest, U16String) { IUTEST_SUCCEED() << u"test"; } #if IUTEST_HAS_CXX_HDR_STRING_VIEW IUTEST(PrintToTest, U16StringStringView) { ::std::u16string_view view = u"Hello"; IUTEST_SUCCEED() << view; } #endif #endif #if IUTEST_HAS_CHAR32_T IUTEST(PrintToTest, U32String) { IUTEST_SUCCEED() << U"TEST"; } #if IUTEST_HAS_CXX_HDR_STRING_VIEW IUTEST(PrintToTest, U32StringStringView) { ::std::u32string_view view = U"Hello"; IUTEST_SUCCEED() << view; } #endif #endif #if defined(__WANDBOX__) #if IUTEST_HAS_PARAM_TEST class ValuesTest : public ::iutest::TestWithParam<int> {}; IUTEST_P(ValuesTest, Test) { } IUTEST_INSTANTIATE_TEST_SUITE_P( X1, ValuesTest, ::iutest::Values(1) ); IUTEST_INSTANTIATE_TEST_SUITE_P( X2, ValuesTest, ::iutest::Values(1, 2) ); #if IUTEST_HAS_VARIADIC_VALUES IUTEST_INSTANTIATE_TEST_SUITE_P( X51, ValuesTest , ::iutest::Values( IUTEST_PP_ENUM_PARAMS(51, IUTEST_PP_EMPTY()) ) ); #endif #endif #endif IUTEST_PRAGMA_WARN_POP() } // end of namespace syntax_tests
bsd-3-clause
danakj/chromium
chrome/browser/services/gcm/gcm_profile_service_unittest.cc
8567
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "build/build_config.h" #include "chrome/browser/services/gcm/gcm_profile_service_factory.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/channel_info.h" #include "chrome/test/base/testing_profile.h" #include "components/gcm_driver/gcm_profile_service.h" #if defined(OS_CHROMEOS) #include "chromeos/dbus/dbus_thread_manager.h" #endif #include "components/gcm_driver/fake_gcm_app_handler.h" #include "components/gcm_driver/fake_gcm_client.h" #include "components/gcm_driver/fake_gcm_client_factory.h" #include "components/gcm_driver/gcm_client.h" #include "components/gcm_driver/gcm_client_factory.h" #include "components/gcm_driver/gcm_driver.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" namespace gcm { namespace { const char kTestAppID[] = "TestApp"; const char kUserID[] = "user"; std::unique_ptr<KeyedService> BuildGCMProfileService( content::BrowserContext* context) { Profile* profile = Profile::FromBrowserContext(context); base::SequencedWorkerPool* worker_pool = content::BrowserThread::GetBlockingPool(); scoped_refptr<base::SequencedTaskRunner> blocking_task_runner( worker_pool->GetSequencedTaskRunnerWithShutdownBehavior( worker_pool->GetSequenceToken(), base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)); return base::WrapUnique(new gcm::GCMProfileService( profile->GetPrefs(), profile->GetPath(), profile->GetRequestContext(), chrome::GetChannel(), std::unique_ptr<ProfileIdentityProvider>(new ProfileIdentityProvider( SigninManagerFactory::GetForProfile(profile), ProfileOAuth2TokenServiceFactory::GetForProfile(profile), LoginUIServiceFactory::GetShowLoginPopupCallbackForProfile(profile))), std::unique_ptr<gcm::GCMClientFactory>(new gcm::FakeGCMClientFactory( content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::UI), content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::IO))), content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::UI), content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::IO), blocking_task_runner)); } } // namespace class GCMProfileServiceTest : public testing::Test { protected: GCMProfileServiceTest(); ~GCMProfileServiceTest() override; // testing::Test: void SetUp() override; void TearDown() override; FakeGCMClient* GetGCMClient() const; void CreateGCMProfileService(); void RegisterAndWaitForCompletion(const std::vector<std::string>& sender_ids); void UnregisterAndWaitForCompletion(); void SendAndWaitForCompletion(const OutgoingMessage& message); void RegisterCompleted(const base::Closure& callback, const std::string& registration_id, GCMClient::Result result); void UnregisterCompleted(const base::Closure& callback, GCMClient::Result result); void SendCompleted(const base::Closure& callback, const std::string& message_id, GCMClient::Result result); GCMDriver* driver() const { return gcm_profile_service_->driver(); } std::string registration_id() const { return registration_id_; } GCMClient::Result registration_result() const { return registration_result_; } GCMClient::Result unregistration_result() const { return unregistration_result_; } std::string send_message_id() const { return send_message_id_; } GCMClient::Result send_result() const { return send_result_; } private: content::TestBrowserThreadBundle thread_bundle_; std::unique_ptr<TestingProfile> profile_; GCMProfileService* gcm_profile_service_; std::unique_ptr<FakeGCMAppHandler> gcm_app_handler_; std::string registration_id_; GCMClient::Result registration_result_; GCMClient::Result unregistration_result_; std::string send_message_id_; GCMClient::Result send_result_; DISALLOW_COPY_AND_ASSIGN(GCMProfileServiceTest); }; GCMProfileServiceTest::GCMProfileServiceTest() : gcm_profile_service_(NULL), gcm_app_handler_(new FakeGCMAppHandler), registration_result_(GCMClient::UNKNOWN_ERROR), send_result_(GCMClient::UNKNOWN_ERROR) { } GCMProfileServiceTest::~GCMProfileServiceTest() { } FakeGCMClient* GCMProfileServiceTest::GetGCMClient() const { return static_cast<FakeGCMClient*>( gcm_profile_service_->driver()->GetGCMClientForTesting()); } void GCMProfileServiceTest::SetUp() { #if defined(OS_CHROMEOS) // Create a DBus thread manager setter for its side effect. // Ignore the return value. chromeos::DBusThreadManager::GetSetterForTesting(); #endif TestingProfile::Builder builder; profile_ = builder.Build(); } void GCMProfileServiceTest::TearDown() { gcm_profile_service_->driver()->RemoveAppHandler(kTestAppID); } void GCMProfileServiceTest::CreateGCMProfileService() { gcm_profile_service_ = static_cast<GCMProfileService*>( GCMProfileServiceFactory::GetInstance()->SetTestingFactoryAndUse( profile_.get(), &BuildGCMProfileService)); gcm_profile_service_->driver()->AddAppHandler( kTestAppID, gcm_app_handler_.get()); } void GCMProfileServiceTest::RegisterAndWaitForCompletion( const std::vector<std::string>& sender_ids) { base::RunLoop run_loop; gcm_profile_service_->driver()->Register( kTestAppID, sender_ids, base::Bind(&GCMProfileServiceTest::RegisterCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); } void GCMProfileServiceTest::UnregisterAndWaitForCompletion() { base::RunLoop run_loop; gcm_profile_service_->driver()->Unregister( kTestAppID, base::Bind(&GCMProfileServiceTest::UnregisterCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); } void GCMProfileServiceTest::SendAndWaitForCompletion( const OutgoingMessage& message) { base::RunLoop run_loop; gcm_profile_service_->driver()->Send( kTestAppID, kUserID, message, base::Bind(&GCMProfileServiceTest::SendCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); } void GCMProfileServiceTest::RegisterCompleted( const base::Closure& callback, const std::string& registration_id, GCMClient::Result result) { registration_id_ = registration_id; registration_result_ = result; callback.Run(); } void GCMProfileServiceTest::UnregisterCompleted( const base::Closure& callback, GCMClient::Result result) { unregistration_result_ = result; callback.Run(); } void GCMProfileServiceTest::SendCompleted( const base::Closure& callback, const std::string& message_id, GCMClient::Result result) { send_message_id_ = message_id; send_result_ = result; callback.Run(); } TEST_F(GCMProfileServiceTest, RegisterAndUnregister) { CreateGCMProfileService(); std::vector<std::string> sender_ids; sender_ids.push_back("sender"); RegisterAndWaitForCompletion(sender_ids); std::string expected_registration_id = FakeGCMClient::GenerateGCMRegistrationID(sender_ids); EXPECT_EQ(expected_registration_id, registration_id()); EXPECT_EQ(GCMClient::SUCCESS, registration_result()); UnregisterAndWaitForCompletion(); EXPECT_EQ(GCMClient::SUCCESS, unregistration_result()); } TEST_F(GCMProfileServiceTest, Send) { CreateGCMProfileService(); OutgoingMessage message; message.id = "1"; message.data["key1"] = "value1"; SendAndWaitForCompletion(message); EXPECT_EQ(message.id, send_message_id()); EXPECT_EQ(GCMClient::SUCCESS, send_result()); } } // namespace gcm
bsd-3-clause
GaloisInc/ivory-tower-stm32
ivory-bsp-stm32/src/Ivory/BSP/STM32F427/DMA.hs
1945
-- -- DMA.hs --- STM32F427 DMA driver. -- -- Copyright (C) 2015, Galois, Inc. -- All Rights Reserved. -- module Ivory.BSP.STM32F427.DMA where import Ivory.BSP.STM32.Peripheral.DMA import Ivory.Language import Ivory.HW import Ivory.BSP.STM32.Interrupt import Ivory.BSP.STM32F427.RCC import Ivory.BSP.STM32F427.MemoryMap import Ivory.BSP.STM32F427.Interrupt ahb1Enable :: BitDataField RCC_AHB1ENR Bit -> Ivory eff () ahb1Enable bit = modifyReg regRCC_AHB1ENR (setBit bit) ahb1Disable :: BitDataField RCC_AHB1ENR Bit -> Ivory eff () ahb1Disable bit = modifyReg regRCC_AHB1ENR (clearBit bit) dma1 :: DMA dma1 = mkDMA dma1_periph_base (ahb1Enable rcc_ahb1en_dma1) (ahb1Disable rcc_ahb1en_dma1) ints "dma1" where ints = DMAInterrupt { dmaInterruptStream0 = HasSTM32Interrupt DMA1_Stream0 , dmaInterruptStream1 = HasSTM32Interrupt DMA1_Stream1 , dmaInterruptStream2 = HasSTM32Interrupt DMA1_Stream2 , dmaInterruptStream3 = HasSTM32Interrupt DMA1_Stream3 , dmaInterruptStream4 = HasSTM32Interrupt DMA1_Stream4 , dmaInterruptStream5 = HasSTM32Interrupt DMA1_Stream5 , dmaInterruptStream6 = HasSTM32Interrupt DMA1_Stream6 , dmaInterruptStream7 = HasSTM32Interrupt DMA1_Stream7 } dma2 :: DMA dma2 = mkDMA dma2_periph_base (ahb1Enable rcc_ahb1en_dma2) (ahb1Disable rcc_ahb1en_dma2) ints "dma2" where ints = DMAInterrupt { dmaInterruptStream0 = HasSTM32Interrupt DMA2_Stream0 , dmaInterruptStream1 = HasSTM32Interrupt DMA2_Stream1 , dmaInterruptStream2 = HasSTM32Interrupt DMA2_Stream2 , dmaInterruptStream3 = HasSTM32Interrupt DMA2_Stream3 , dmaInterruptStream4 = HasSTM32Interrupt DMA2_Stream4 , dmaInterruptStream5 = HasSTM32Interrupt DMA2_Stream5 , dmaInterruptStream6 = HasSTM32Interrupt DMA2_Stream6 , dmaInterruptStream7 = HasSTM32Interrupt DMA2_Stream7 }
bsd-3-clause
changfuguo/vuejs-boilerplate
server/config/route.js
383
/** * @decription mock file config * * 该文件实现路由的配置,在没有test准备好的情况下可以直接走这个mock数据 * key: 为要匹配的路由 * value: 为对应的参数配置 * method: get或者post,router的方法 * filename: 对应的mock文件 */ module.exports = { '/api/realtime': { method: "post", filename: "realtime.js" } };
bsd-3-clause
endlessm/chromium-browser
components/autofill_assistant/browser/selector_unittest.cc
3076
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill_assistant/browser/selector.h" #include "base/macros.h" #include "components/autofill_assistant/browser/service.pb.h" #include "testing/gmock/include/gmock/gmock.h" namespace autofill_assistant { namespace { TEST(SelectorTest, FromProto) { ElementReferenceProto proto; proto.add_selectors("a"); proto.add_selectors("b"); proto.set_inner_text_pattern("c"); proto.set_value_pattern("d"); proto.set_visibility_requirement(MUST_BE_VISIBLE); proto.set_pseudo_type(PseudoType::BEFORE); Selector selector(proto); EXPECT_THAT(selector.selectors, testing::ElementsAre("a", "b")); EXPECT_TRUE(selector.must_be_visible); EXPECT_EQ("c", selector.inner_text_pattern); EXPECT_EQ("d", selector.value_pattern); EXPECT_EQ(PseudoType::BEFORE, selector.pseudo_type); } TEST(SelectorTest, ToProto) { Selector selector; selector.selectors.emplace_back("a"); selector.selectors.emplace_back("b"); selector.inner_text_pattern = "c"; selector.value_pattern = "d"; selector.must_be_visible = true; selector.pseudo_type = PseudoType::BEFORE; ElementReferenceProto proto = selector.ToElementReferenceProto(); EXPECT_THAT(proto.selectors(), testing::ElementsAre("a", "b")); EXPECT_EQ("c", proto.inner_text_pattern()); EXPECT_EQ("d", proto.value_pattern()); EXPECT_EQ(MUST_BE_VISIBLE, proto.visibility_requirement()); EXPECT_EQ(PseudoType::BEFORE, proto.pseudo_type()); } TEST(SelectorTest, Comparison) { EXPECT_FALSE(Selector({"a"}) == Selector({"b"})); EXPECT_LT(Selector({"a"}), Selector({"b"})); EXPECT_TRUE(Selector({"a"}) == Selector({"a"})); EXPECT_FALSE(Selector({"a"}, PseudoType::BEFORE) == Selector({"a"}, PseudoType::AFTER)); EXPECT_LT(Selector({"a"}, PseudoType::BEFORE), Selector({"a"}, PseudoType::AFTER)); EXPECT_LT(Selector({"a"}, PseudoType::BEFORE), Selector({"b"})); EXPECT_TRUE(Selector({"a"}, PseudoType::BEFORE) == Selector({"a"}, PseudoType::BEFORE)); EXPECT_FALSE(Selector({"a"}) == Selector({"a"}).MustBeVisible()); EXPECT_LT(Selector({"a"}), Selector({"a"}).MustBeVisible()); EXPECT_TRUE(Selector({"a"}).MustBeVisible() == Selector({"a"}).MustBeVisible()); EXPECT_FALSE(Selector({"a"}).MatchingInnerText("a") == Selector({"a"}).MatchingInnerText("b")); EXPECT_LT(Selector({"a"}).MatchingInnerText("a"), Selector({"a"}).MatchingInnerText("b")); EXPECT_TRUE(Selector({"a"}).MatchingInnerText("a") == Selector({"a"}).MatchingInnerText("a")); EXPECT_FALSE(Selector({"a"}).MatchingValue("a") == Selector({"a"}).MatchingValue("b")); EXPECT_LT(Selector({"a"}).MatchingValue("a"), Selector({"a"}).MatchingValue("b")); EXPECT_TRUE(Selector({"a"}).MatchingValue("a") == Selector({"a"}).MatchingValue("a")); } } // namespace } // namespace autofill_assistant
bsd-3-clause
idlesign/makeapp
makeapp/app_templates/__default__/docs/Makefile
616
# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = {{ app_name }} SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
bsd-3-clause
i-e-b/SevenDigital.Messaging
src/SevenDigital.Messaging/IReceiver.cs
2465
using System; using SevenDigital.Messaging.MessageReceiving; namespace SevenDigital.Messaging { /// <summary> /// A receiver node source that can produce competitive or co-operative consumers /// </summary> public interface IReceiver { /// <summary> /// Map handlers to a listener on a named endpoint. /// All other listeners on this endpoint will compete for messages /// (i.e. only one listener will get a given message) /// </summary> IReceiverNode TakeFrom(Endpoint endpoint, Action<IMessageBinding> bindings); /// <summary> /// Map handlers to a listener on a unique endpoint. /// All listeners mapped this way will receive all messages. /// </summary> IReceiverNode Listen(Action<IMessageBinding> bindings); } /// <summary> /// Interface for binding message types to handlers /// </summary> public interface IMessageBinding: IBinding { /// <summary> /// Handle a message type. Must complete With&lt;&gt;() to bind to a handler. /// </summary> IHandlerBinding<TMessage> Handle<TMessage>() where TMessage:IMessage; } /// <summary> /// Interface for binding message types to handlers /// </summary> public interface IHandlerBinding<TMessage>where TMessage:IMessage { /// <summary> /// Bind a handler to the selected message /// </summary> IMessageBinding With<THandler>() where THandler : IHandle<TMessage>; } /// <summary> /// Control methods for IReceiver. /// Seperated to simplify receiver interface. /// </summary> public interface IReceiverControl: IDisposable { /// <summary> /// Close all receiver nodes that have been created /// </summary> void Shutdown(); /// <summary> /// Unregister a node from the shutdown list /// </summary> void Remove(IReceiverNode node); /// <summary> /// Set maximum concurrent handlers per receiver node /// </summary> void SetConcurrentHandlers(int max); /// <summary> /// Set purging policy. If true, all waiting messages are DELETED when a handler is registered. /// This setting is meant for integration tests. /// Default is false. /// </summary> bool PurgeOnConnect { get; set; } /// <summary> /// Set cleanup policy. If true, all endpoints generated in integration mode /// are deleted when the receiver is disposed. /// Default is false. /// </summary> bool DeleteIntegrationEndpointsOnShutdown { get; set; } } }
bsd-3-clause
statsmodels/statsmodels.github.io
v0.12.1/generated/statsmodels.discrete.discrete_model.DiscreteResults.predict.html
21391
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.discrete.discrete_model.DiscreteResults.predict &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/language_data.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.discrete.discrete_model.DiscreteResults.remove_data" href="statsmodels.discrete.discrete_model.DiscreteResults.remove_data.html" /> <link rel="prev" title="statsmodels.discrete.discrete_model.DiscreteResults.normalized_cov_params" href="statsmodels.discrete.discrete_model.DiscreteResults.normalized_cov_params.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.discrete.discrete_model.DiscreteResults.predict" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.1</span> <span class="md-header-nav__topic"> statsmodels.discrete.discrete_model.DiscreteResults.predict </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../discretemod.html" class="md-tabs__link">Regression with Discrete Dependent Variable</a></li> <li class="md-tabs__item"><a href="statsmodels.discrete.discrete_model.DiscreteResults.html" class="md-tabs__link">statsmodels.discrete.discrete_model.DiscreteResults</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.1</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../regression.html" class="md-nav__link">Linear Regression</a> </li> <li class="md-nav__item"> <a href="../glm.html" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a> </li> <li class="md-nav__item"> <a href="../rlm.html" class="md-nav__link">Robust Linear Models</a> </li> <li class="md-nav__item"> <a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a> </li> <li class="md-nav__item"> <a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../anova.html" class="md-nav__link">ANOVA</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.discrete.discrete_model.DiscreteResults.predict.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-discrete-discrete-model-discreteresults-predict--page-root">statsmodels.discrete.discrete_model.DiscreteResults.predict<a class="headerlink" href="#generated-statsmodels-discrete-discrete-model-discreteresults-predict--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py method"> <dt id="statsmodels.discrete.discrete_model.DiscreteResults.predict"> <code class="sig-prename descclassname">DiscreteResults.</code><code class="sig-name descname">predict</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">exog</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">transform</span><span class="o">=</span><span class="default_value">True</span></em>, <em class="sig-param"><span class="o">*</span><span class="n">args</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwargs</span></em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.discrete.discrete_model.DiscreteResults.predict" title="Permalink to this definition">¶</a></dt> <dd><p>Call self.model.predict with self.params as the first argument.</p> <dl class="field-list"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"><dl> <dt><strong>exog</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array-like" title="(in NumPy v1.19)"><span>array_like</span></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>The values for which you want to predict. see Notes below.</p> </dd> <dt><strong>transform</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#bltin-boolean-values" title="(in Python v3.9)"><span class="xref std std-ref">bool</span></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first.</p> </dd> <dt><strong>*args</strong></dt><dd><p>Additional arguments to pass to the model, see the predict method of the model for the details.</p> </dd> <dt><strong>**kwargs</strong></dt><dd><p>Additional keywords arguments to pass to the model, see the predict method of the model for the details.</p> </dd> </dl> </dd> <dt class="field-even">Returns</dt> <dd class="field-even"><dl class="simple"> <dt><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array-like" title="(in NumPy v1.19)"><span>array_like</span></a></dt><dd><p>See self.model.predict.</p> </dd> </dl> </dd> </dl> <p class="rubric">Notes</p> <p>The types of exog that are supported depends on whether a formula was used in the specification of the model.</p> <p>If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object that contains numpy arrays.</p> <p>If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array.</p> <p>Row indices as in pandas data frames are supported, and added to the returned prediction.</p> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.discrete.discrete_model.DiscreteResults.normalized_cov_params.html" title="statsmodels.discrete.discrete_model.DiscreteResults.normalized_cov_params" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.discrete.discrete_model.DiscreteResults.normalized_cov_params </span> </div> </a> <a href="statsmodels.discrete.discrete_model.DiscreteResults.remove_data.html" title="statsmodels.discrete.discrete_model.DiscreteResults.remove_data" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.discrete.discrete_model.DiscreteResults.remove_data </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Oct 29, 2020. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
bsd-3-clause
rpeerbits/demo-yii
api/namespace-app.html
1705
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Namespace app</title> <link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e"> </head> <body> <div id="left"> <div id="menu"> <a href="index.html" title="Overview"><span>Overview</span></a> <div id="groups"> <h3>Namespaces</h3> <ul> <li class="active"> <a href="namespace-app.html"> app<span></span> </a> <ul> <li> <a href="namespace-app.controllers.html"> controllers </a> </li> </ul></li> </ul> </div> <div id="elements"> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <form id="search"> <input type="hidden" name="cx" value=""> <input type="hidden" name="ie" value="UTF-8"> <input type="text" name="q" class="text" placeholder="Search"> </form> <div id="navigation"> <ul> <li> <a href="index.html" title="Overview"><span>Overview</span></a> </li> <li class="active"> <span>Namespace</span> </li> <li> <span>Class</span> </li> </ul> <ul> </ul> <ul> </ul> </div> <div id="content" class="namespace"> <h1>Namespace app</h1> <table class="summary" id="namespaces"> <caption>Namespaces summary</caption> <tr> <td class="name"><a href="namespace-app.controllers.html">app\controllers</a></td> </tr> </table> </div> <div id="footer"> API documentation generated by <a href="http://apigen.org">ApiGen</a> </div> </div> </div> <script src="resources/combined.js?cd021bc814832c24a7cec5319ea03335bfba1caf"></script> <script src="elementlist.js?54e344d792026957e21ef3f8d245f94a1368d3a6"></script> </body> </html>
bsd-3-clause
fhsctv/ctv2base
module/Base/src/Base/Form/Hydrator/User.php
1947
<?php namespace Base\Form\Hydrator; use Zend\Stdlib\Hydrator\HydratorInterface; use Base\Constants as C; class User implements HydratorInterface { public function extract($object) { $filter = function($value) { return !(($value === null) || ($value === '')); }; $data = array( 'user_id' => $object->getUserId(), 'username' => $object->getUserName(), 'email' => $object->getEmail(), 'display_name' => $object->getDisplayName(), 'password' => $object->getPassword(), 'state' => $object->getState(), ); $result = array_filter($data, $filter); // var_dump(__METHOD__, 'EXT_OBJ', $object, 'EXT_RES', $result); return $result; } public function hydrate(array $data, $object) { (!isset($data['user_id']) || $this->isEmpty($data['user_id'])) ? : $object->setUserId($data['user_id']); (!isset($data['username']) || $this->isEmpty($data['username'])) ? : $object->setUserName($data['username']); (!isset($data['email']) || $this->isEmpty($data['email'])) ? : $object->setEmail($data['email']); (!isset($data['display_name']) || $this->isEmpty($data['display_name'])) ? : $object->setDisplayName($data['display_name']); (!isset($data['password']) || $this->isEmpty($data['password'])) ? : $object->setPassword($data['password']); (!isset($data['state']) || $this->isEmpty($data['state'])) ? : $object->setState($data['state']); // var_dump(__METHOD__, 'HYD_SRCDATA', $data, 'HYD_RES', $object); return $object; } private function isEmpty($value) { return (($value === null) || ($value === '')); } }
bsd-3-clause
furious-luke/django-scrape
setup.py
990
import os from setuptools import setup, find_packages setup( name='django-scrape', version='0.1', author='Luke Hodkinson', author_email='[email protected]', maintainer='Luke Hodkinson', maintainer_email='[email protected]', url='https://github.com/furious-luke/django-scrape', description='A django application for easier web scraping.', long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), classifiers = [ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', ], license='BSD', packages=find_packages(), include_package_data=True, package_data={'': ['*.txt', '*.js', '*.html', '*.*']}, install_requires=['setuptools'], zip_safe=False, )
bsd-3-clause
geneontology/go-site
metadata/rules/ABOUT.md
335
# GO Rules This folder contains the metadata for all annotation and ontology QC rules in GO. Each rule has an identifier, metadata and descriptions. Some rules are automatable, in which case the metadata contains the information required to execute it. For more details for GOC members on how to create rules, see [SOP.md](SOP.md)
bsd-3-clause
shockedbear/board
frontend/config/params.php
75
<?php return [ 'adminEmail' => '[email protected]', ];
bsd-3-clause
statsmodels/statsmodels.github.io
v0.12.2/generated/statsmodels.stats.power.NormalIndPower.html
21919
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.stats.power.NormalIndPower &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.stats.power.NormalIndPower.plot_power" href="statsmodels.stats.power.NormalIndPower.plot_power.html" /> <link rel="prev" title="statsmodels.stats.power.GofChisquarePower.solve_power" href="statsmodels.stats.power.GofChisquarePower.solve_power.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.stats.power.NormalIndPower" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.2</span> <span class="md-header-nav__topic"> statsmodels.stats.power.NormalIndPower </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../stats.html" class="md-tabs__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.2</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../stats.html" class="md-nav__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a> </li> <li class="md-nav__item"> <a href="../contingency_tables.html" class="md-nav__link">Contingency tables</a> </li> <li class="md-nav__item"> <a href="../imputation.html" class="md-nav__link">Multiple Imputation with Chained Equations</a> </li> <li class="md-nav__item"> <a href="../emplike.html" class="md-nav__link">Empirical Likelihood <code class="xref py py-mod docutils literal notranslate"><span class="pre">emplike</span></code></a> </li> <li class="md-nav__item"> <a href="../distributions.html" class="md-nav__link">Distributions</a> </li> <li class="md-nav__item"> <a href="../graphics.html" class="md-nav__link">Graphics</a> </li> <li class="md-nav__item"> <a href="../iolib.html" class="md-nav__link">Input-Output <code class="xref py py-mod docutils literal notranslate"><span class="pre">iolib</span></code></a> </li> <li class="md-nav__item"> <a href="../tools.html" class="md-nav__link">Tools</a> </li> <li class="md-nav__item"> <a href="../large_data.html" class="md-nav__link">Working with Large Data Sets</a> </li> <li class="md-nav__item"> <a href="../optimization.html" class="md-nav__link">Optimization</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.stats.power.NormalIndPower.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-stats-power-normalindpower--page-root">statsmodels.stats.power.NormalIndPower<a class="headerlink" href="#generated-statsmodels-stats-power-normalindpower--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py class"> <dt id="statsmodels.stats.power.NormalIndPower"> <em class="property">class </em><code class="sig-prename descclassname">statsmodels.stats.power.</code><code class="sig-name descname">NormalIndPower</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">ddof</span><span class="o">=</span><span class="default_value">0</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwds</span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/stats/power.html#NormalIndPower"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.stats.power.NormalIndPower" title="Permalink to this definition">¶</a></dt> <dd><p>Statistical Power calculations for z-test for two independent samples.</p> <p>currently only uses pooled variance</p> <p class="rubric">Methods</p> <table class="longtable docutils align-default"> <colgroup> <col style="width: 10%"/> <col style="width: 90%"/> </colgroup> <tbody> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.stats.power.NormalIndPower.plot_power.html#statsmodels.stats.power.NormalIndPower.plot_power" title="statsmodels.stats.power.NormalIndPower.plot_power"><code class="xref py py-obj docutils literal notranslate"><span class="pre">plot_power</span></code></a>([dep_var, nobs, effect_size, …])</p></td> <td><p>Plot power with number of observations or effect size on x-axis</p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="statsmodels.stats.power.NormalIndPower.power.html#statsmodels.stats.power.NormalIndPower.power" title="statsmodels.stats.power.NormalIndPower.power"><code class="xref py py-obj docutils literal notranslate"><span class="pre">power</span></code></a>(effect_size, nobs1, alpha[, ratio, …])</p></td> <td><p>Calculate the power of a z-test for two independent sample</p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.stats.power.NormalIndPower.solve_power.html#statsmodels.stats.power.NormalIndPower.solve_power" title="statsmodels.stats.power.NormalIndPower.solve_power"><code class="xref py py-obj docutils literal notranslate"><span class="pre">solve_power</span></code></a>([effect_size, nobs1, alpha, …])</p></td> <td><p>solve for any one parameter of the power of a two sample z-test</p></td> </tr> </tbody> </table> <p class="rubric">Methods</p> <table class="longtable docutils align-default"> <colgroup> <col style="width: 10%"/> <col style="width: 90%"/> </colgroup> <tbody> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.stats.power.NormalIndPower.plot_power.html#statsmodels.stats.power.NormalIndPower.plot_power" title="statsmodels.stats.power.NormalIndPower.plot_power"><code class="xref py py-obj docutils literal notranslate"><span class="pre">plot_power</span></code></a>([dep_var, nobs, effect_size, …])</p></td> <td><p>Plot power with number of observations or effect size on x-axis</p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="statsmodels.stats.power.NormalIndPower.power.html#statsmodels.stats.power.NormalIndPower.power" title="statsmodels.stats.power.NormalIndPower.power"><code class="xref py py-obj docutils literal notranslate"><span class="pre">power</span></code></a>(effect_size, nobs1, alpha[, ratio, …])</p></td> <td><p>Calculate the power of a z-test for two independent sample</p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.stats.power.NormalIndPower.solve_power.html#statsmodels.stats.power.NormalIndPower.solve_power" title="statsmodels.stats.power.NormalIndPower.solve_power"><code class="xref py py-obj docutils literal notranslate"><span class="pre">solve_power</span></code></a>([effect_size, nobs1, alpha, …])</p></td> <td><p>solve for any one parameter of the power of a two sample z-test</p></td> </tr> </tbody> </table> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.stats.power.GofChisquarePower.solve_power.html" title="statsmodels.stats.power.GofChisquarePower.solve_power" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.stats.power.GofChisquarePower.solve_power </span> </div> </a> <a href="statsmodels.stats.power.NormalIndPower.plot_power.html" title="statsmodels.stats.power.NormalIndPower.plot_power" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.stats.power.NormalIndPower.plot_power </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Feb 02, 2021. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.4.3. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
bsd-3-clause
bwohlberg/sporco
docs/source/_static/sporco.css
4859
/* -*- css -*- * * Sphinx haiku theme CSS customization for SPORCO docs. * */ body { line-height: 1.4; font-size: 90%; } h2 { padding-bottom: 5px; border-bottom: 1px solid #d0d0d0; margin-bottom: 16px; } h3 { padding-bottom: 5px; border-bottom: none; margin-bottom: 16px; font-size: 1.05em; } h4, h5, h6 { padding-bottom: 5px; border-bottom: none; margin-bottom: 16px; } /* * Style for function parameters/returns description tables (field list). * Copied from scipy.css, with modifications. */ table.field-list { border-collapse: collapse; border-spacing: 5px; margin-left: 1px; margin-top: 0.5em; } table.field-list th.field-name { text-align: left; padding: 1px 8px 1px 5px; white-space: nowrap; background-color: #ebebeb; width: 7em; } table.field-list td.field-body { padding-left: 10px; border-left: none !important; } table.field-list td.field-body > p { font-style: italic; } table.field-list td.field-body > p > strong { font-style: normal; } td.field-body blockquote { border-left: none; margin: 0; padding-left: 30px; } /* * Alternative style for function parameters/returns descriptions for sphinx * 2.x. */ dl.field-list { border-collapse: collapse; border-spacing: 5px; margin-left: 1px; margin-top: 0.75em; } dl.field-list > dt { flex-basis: 8em; } dl.field-list dt.field-odd, dt.field-even { text-align: left; padding: 1px 8px 1px 5px; white-space: nowrap; background-color: #ebebeb; width: 7em; } /* * Style for custom class kwargs for documenting **kwargs parameters * (see sporco.plot.plot). */ table.kwargs { border: 1px solid black; border-collapse: collapse; } table.kwargs tbody { border: 1px solid black; } table.kwargs th { border: 1px solid black; background-color: #d5d5d5; } table.kwargs td { border: 1px solid black; } table.kwargs.docutils { margin-top: 0.5em; } /* * Style for class, method, function, and exception docs. */ .class, .function, .exception { margin-bottom: 4em; background-color: #f8f8f8; padding: 5px 10px; border-radius: 4px; } dl.class { margin-top: 3em; margin-bottom: 2em; border-style: solid; border-width: 3px; border-color: #f7f7f7; } dl.class dl.class { background-color: #f4f4f4; border-color: #f3f3f3; } dl.function > dt:first-child, dl.class > dt:first-child, dl.exception > dt:first-child { background-color: #ebebeb; padding: 2px 5px 2px 5px; border-radius: 3px; } dl.function > dd > p:first-child, dl.class > dd > p:nth-child(2), dl.method > dd > p:first-child, dl.exception > dd > p:nth-child(2) { margin-bottom: 0.5em; font-family: 'Lucida Sans Unicode', 'Arial', 'Helvetica'; font-size: 110%; } dl.class > dt:first-child + dd > p:first-child { margin-bottom: 0.8em; } dl.method > dt:first-child, dl.staticmethod > dt:first-child, dl.classmethod > dt:first-child { background-color: #ebebeb; padding: 2px 5px 2px 5px; border-radius: 3px; } dl.function > dd { margin-top: 0.8em; } dl.function { margin-top: 0; margin-bottom: 1em; border-style: solid; border-width: 3px; border-color: #f7f7f7; } dl.exception { margin-top: 1em; margin-bottom: 1em; border-style: solid; border-width: 3px; border-color: #f7f7f7; } dl.exception > dt:first-child + dd > p:first-child { margin-bottom: 0.8em; } /* * Style for autosummary-like tables of modules, functions, etc. */ table.longtable.docutils, table.longtable.docutils td { border-style: solid; border-width: 1px; border-color: #808080; background-color: #fbfbfb; } div.module-table table, div.module-table td { border-style: solid; border-width: 1px; border-color: #808080; background-color: #fbfbfb; } div.module-table table { width: 100%; } /* * Modify font weight of link text. */ a.external { font-weight: normal; } a.reference.internal span.doc { font-weight: 500; } a.reference.internal { font-size: 95%; font-weight: 500; } span.std.std-ref { font-weight: 500; } div.topnav a, div.bottomnav a { font-weight: 500; } /* * Miscellaneous. */ .admonition.seealso { background-color: #f0f0f8; } .highlight > pre { border-radius: 4px; margin-top: 1em; margin-bottom: 1em; border-color: #f0f0f0; background-color: #f0f0f8; } [class='docutils literal'] > .pre { background-color: transparent; color: #000080; } code { background-color: transparent; } ul { padding-left: 1em; margin-top: 3px; } div.content ul > li { -moz-background-clip:border; -moz-background-inline-policy:continuous; -moz-background-origin:padding; background: none; list-style-image: none; list-style-type: square; padding: 0 0 0 0.5em; } blockquote div p { margin: 2px; } code, .rst-content tt, .linenodiv pre, div[class^="highlight"] pre { font-family: 'Inconsolata', 'Monaco', 'Consolas', monospace; font-size: 85%; }
bsd-3-clause
bss/mixpanel-celery
mixpanel/tests.py
7560
from __future__ import absolute_import import base64 import json import unittest import urllib import urllib2 import urlparse from celery.exceptions import RetryTaskError from mock import MagicMock as Mock import mock from . import tasks from .conf import settings as mp_settings class TestCase(unittest.TestCase): def setUp(self): super(TestCase, self).setUp() patcher = mock.patch('urllib2.urlopen') self.addCleanup(patcher.stop) self.mock_urlopen = patcher.start() self.mock_urlopen.return_value.read.return_value = '1' # Setup token for mixpanel mp_settings.MIXPANEL_API_TOKEN = 'testmixpanel' @staticmethod def assertDictEqual(a, b): assert a == b, "Dicts are not equal.\nExpected: %s\nActual: %s" % ( json.dumps(b, indent=3, sort_keys=True), json.dumps(a, indent=3, sort_keys=True)) def _test_any(self, task, *args, **kwargs): result = kwargs.pop('result', True) server = kwargs.pop('server', mp_settings.MIXPANEL_API_SERVER) endpoint = kwargs.pop('endpoint', mp_settings.MIXPANEL_TRACKING_ENDPOINT) data = kwargs.pop('data', {}) actual = task(*args, **kwargs) self.assertTrue(self.mock_urlopen.called) self.assertEqual(actual, result) url = self.mock_urlopen.call_args[0][0] scheme, netloc, path, params, querystr, frag = urlparse.urlparse(url) query = urlparse.parse_qs(querystr, keep_blank_values=True, strict_parsing=True) self.assertEqual(netloc, server) self.assertEqual(path, endpoint) self.assertEqual(query.keys(), ['data']) datastr = base64.b64decode(query['data'][0]) actual = json.loads(datastr) self.assertDictEqual(actual, data) class EventTrackerTest(TestCase): def _test_event(self, *args, **kwargs): return self._test_any(tasks.event_tracker, *args, **kwargs) def test_event(self): self._test_event('clicked button', data={ "event": "clicked button", "properties": { "token": "testmixpanel" }, }, ) def test_event_props(self): self._test_event('User logged in', properties={ "distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0", "partner": True, "userid": 456, "code": "double oh 7", }, data={ "event": "User logged in", "properties": { "distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0", "partner": True, "userid": 456, "code": "double oh 7", "token": "testmixpanel", }, }, ) def test_event_token(self): self._test_event('Override token', token="footoken", data={ "event": "Override token", "properties": { "token": "footoken" }, }, ) class PeopleTrackerTest(TestCase): def _test_people(self, *args, **kwargs): kwargs.setdefault('endpoint', mp_settings.MIXPANEL_PEOPLE_TRACKING_ENDPOINT) return self._test_any(tasks.people_tracker, *args, **kwargs) def test_validation(self): self.assertRaises(tasks.InvalidPeopleProperties, tasks.people_tracker, 'foo') self.assertRaises(tasks.InvalidPeopleProperties, tasks.people_tracker, 'foo', set={1:2}, add={3:4}) result = tasks.people_tracker('foo', set={1:2}) self.assertEqual(result, True) result = tasks.people_tracker('foo', add={3:4}) self.assertEqual(result, True) def test_people_set(self): self._test_people('c9533b5b-d69e-479a-ae5f-42dd7a9752a0', set={ "$first_name": "Aron", }, data={ "$distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0", "$token": "testmixpanel", "$set": { "$first_name": "Aron", }, }) def test_people_add(self): self._test_people('c9533b5b-d69e-479a-ae5f-42dd7a9752a0', add={ "visits": 1, }, data={ "$distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0", "$token": "testmixpanel", "$add": { "visits": 1, }, }) def test_people_token(self): self._test_people('c9533b5b-d69e-479a-ae5f-42dd7a9752a0', token="footoken", set={ "$first_name": "Aron", }, data={ "$distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0", "$token": "footoken", "$set": { "$first_name": "Aron", }, }) def test_people_extra(self): self._test_people('c9533b5b-d69e-479a-ae5f-42dd7a9752a0', set={ "$first_name": "Aron", }, extra={ "$ignore_time": True, }, data={ "$distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0", "$token": "testmixpanel", "$ignore_time": True, "$set": { "$first_name": "Aron", }, }) class FunnelTrackerTest(TestCase): def _test_funnel(self, *args, **kwargs): return self._test_any(tasks.funnel_event_tracker, *args, **kwargs) def test_validation(self): funnel = 'test_funnel' step = 'test_step' goal = 'test_goal' # Missing distinct_id properties = {} self.assertRaises(tasks.InvalidFunnelProperties, tasks.funnel_event_tracker, funnel, step, goal, properties) # With distinct_id properties = { 'distinct_id': 'c9533b5b-d69e-479a-ae5f-42dd7a9752a0', } result = tasks.funnel_event_tracker(funnel, step, goal, properties) self.assertEqual(result, True) def test_funnel(self): funnel = 'test_funnel' step = 'test_step' goal = 'test_goal' self._test_funnel(funnel, step, goal, properties={ 'distinct_id': 'c9533b5b-d69e-479a-ae5f-42dd7a9752a0', }, data={ "event": "mp_funnel", "properties": { "distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0", "funnel": "test_funnel", "goal": "test_goal", "step": "test_step", "token": "testmixpanel" }, }, ) class FailuresTestCase(TestCase): def test_failed_request(self): self.mock_urlopen.side_effect = urllib2.URLError("You're doing it wrong") # This wants to test RetryTaskError, but that isn't available with # CELERY_ALWAYS_EAGER self.assertRaises(tasks.FailedEventRequest, # RetryTaskError tasks.event_tracker, 'event_foo') def test_failed_response(self): self.mock_urlopen.return_value.read.return_value = '0' result = tasks.event_tracker('event_foo') self.assertEqual(result, False)
bsd-3-clause
makinacorpus/reportlab-ecomobile
src/reportlab/rl_config.py
10215
#Copyright ReportLab Europe Ltd. 2000-2004 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/rl_config.py __version__=''' $Id$ ''' __doc__='''Configuration file. You may edit this if you wish.''' allowTableBoundsErrors = 1 # set to 0 to die on too large elements in tables in debug (recommend 1 for production use) shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultGraphicsFontName= 'Times-Roman' #initializer for STATE_DEFAULTS in shapes.py pageCompression = 1 # default page compression mode defaultPageSize = 'A4' #default page size defaultImageCaching = 0 #set to zero to remove those annoying cached images ZLIB_WARNINGS = 1 warnOnMissingFontGlyphs = 0 #if 1, warns of each missing glyph verbose = 0 showBoundary = 0 # turns on and off boundary behaviour in Drawing emptyTableAction= 'error' # one of 'error', 'indicate', 'ignore' invariant= 0 #produces repeatable,identical PDFs with same timestamp info (for regression testing) eps_preview_transparent= None #set to white etc eps_preview= 1 #set to False to disable eps_ttf_embed= 1 #set to False to disable eps_ttf_embed_uid= 0 #set to 1 to enable overlapAttachedSpace= 1 #if set non false then adajacent flowable space after #and space before are merged (max space is used). longTableOptimize = 0 #default don't use Henning von Bargen's long table optimizations autoConvertEncoding = 0 #convert internally as needed (experimental) _FUZZ= 1e-6 #fuzz for layout arithmetic wrapA85= 0 #set to 1 to get old wrapped line behaviour fsEncodings=('utf8','cp1252','cp430') #encodings to attempt utf8 conversion with odbc_driver= 'odbc' #default odbc driver platypus_link_underline= 0 #paragraph links etc underlined if true canvas_basefontname= 'Helvetica' #this is used to initialize the canvas; if you override to make #something else you are responsible for ensuring the font is registered etc etc allowShortTableRows=1 #allows some rows in a table to be short imageReaderFlags=0 #attempt to convert images into internal memory files to reduce #the number of open files (see lib.utils.ImageReader) #if imageReaderFlags&2 then attempt autoclosing of those files #if imageReaderFlags&4 then cache data #if imageReaderFlags==-1 then use Ralf Schmitt's re-opening approach # places to look for T1Font information T1SearchPath = ( 'c:/Program Files/Adobe/Acrobat 9.0/Resource/Font', 'c:/Program Files/Adobe/Acrobat 8.0/Resource/Font', 'c:/Program Files/Adobe/Acrobat 7.0/Resource/Font', 'c:/Program Files/Adobe/Acrobat 6.0/Resource/Font', #Win32, Acrobat 6 'c:/Program Files/Adobe/Acrobat 5.0/Resource/Font', #Win32, Acrobat 5 'c:/Program Files/Adobe/Acrobat 4.0/Resource/Font', #Win32, Acrobat 4 '%(disk)s/Applications/Python %(sys_version)s/reportlab/fonts', #Mac? '/usr/lib/Acrobat9/Resource/Font', #Linux, Acrobat 5? '/usr/lib/Acrobat8/Resource/Font', #Linux, Acrobat 5? '/usr/lib/Acrobat7/Resource/Font', #Linux, Acrobat 5? '/usr/lib/Acrobat6/Resource/Font', #Linux, Acrobat 5? '/usr/lib/Acrobat5/Resource/Font', #Linux, Acrobat 5? '/usr/lib/Acrobat4/Resource/Font', #Linux, Acrobat 4 '/usr/local/Acrobat9/Resource/Font', #Linux, Acrobat 5? '/usr/local/Acrobat8/Resource/Font', #Linux, Acrobat 5? '/usr/local/Acrobat7/Resource/Font', #Linux, Acrobat 5? '/usr/local/Acrobat6/Resource/Font', #Linux, Acrobat 5? '/usr/local/Acrobat5/Resource/Font', #Linux, Acrobat 5? '/usr/local/Acrobat4/Resource/Font', #Linux, Acrobat 4 '%(REPORTLAB_DIR)s/fonts', #special '%(REPORTLAB_DIR)s/../fonts', #special '%(REPORTLAB_DIR)s/../../fonts', #special '%(HOME)s/fonts', #special ) # places to look for TT Font information TTFSearchPath = ( 'c:/winnt/fonts', 'c:/windows/fonts', '/usr/lib/X11/fonts/TrueType/', '%(REPORTLAB_DIR)s/fonts', #special '%(REPORTLAB_DIR)s/../fonts', #special '%(REPORTLAB_DIR)s/../../fonts',#special '%(HOME)s/fonts', #special #mac os X - from #http://developer.apple.com/technotes/tn/tn2024.html '~/Library/Fonts', '/Library/Fonts', '/Network/Library/Fonts', '/System/Library/Fonts', ) # places to look for CMap files - should ideally merge with above CMapSearchPath = ( '/usr/lib/Acrobat9/Resource/CMap', '/usr/lib/Acrobat8/Resource/CMap', '/usr/lib/Acrobat7/Resource/CMap', '/usr/lib/Acrobat6/Resource/CMap', '/usr/lib/Acrobat5/Resource/CMap', '/usr/lib/Acrobat4/Resource/CMap', '/usr/local/Acrobat9/Resource/CMap', '/usr/local/Acrobat8/Resource/CMap', '/usr/local/Acrobat7/Resource/CMap', '/usr/local/Acrobat6/Resource/CMap', '/usr/local/Acrobat5/Resource/CMap', '/usr/local/Acrobat4/Resource/CMap', 'C:\\Program Files\\Adobe\\Acrobat\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 9.0\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 8.0\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 7.0\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 6.0\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 5.0\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\CMap', '%(REPORTLAB_DIR)s/fonts/CMap', #special '%(REPORTLAB_DIR)s/../fonts/CMap', #special '%(REPORTLAB_DIR)s/../../fonts/CMap', #special '%(HOME)s/fonts/CMap', #special ) #### Normally don't need to edit below here #### try: from local_rl_config import * except: pass _SAVED = {} sys_version=None def _setOpt(name, value, conv=None): '''set a module level value from environ/default''' from os import environ ename = 'RL_'+name if environ.has_key(ename): value = environ[ename] if conv: value = conv(value) globals()[name] = value def _startUp(): '''This function allows easy resetting to the global defaults If the environment contains 'RL_xxx' then we use the value else we use the given default''' V='''T1SearchPath CMapSearchPath TTFSearchPath allowTableBoundsErrors shapeChecking defaultEncoding defaultGraphicsFontName pageCompression defaultPageSize defaultImageCaching ZLIB_WARNINGS warnOnMissingFontGlyphs verbose showBoundary emptyTableAction invariant eps_preview_transparent eps_preview eps_ttf_embed eps_ttf_embed_uid overlapAttachedSpace longTableOptimize autoConvertEncoding _FUZZ wrapA85 fsEncodings odbc_driver platypus_link_underline canvas_basefontname allowShortTableRows imageReaderFlags'''.split() import os, sys global sys_version, _unset_ sys_version = sys.version.split()[0] #strip off the other garbage from reportlab.lib import pagesizes from reportlab.lib.utils import rl_isdir if _SAVED=={}: _unset_ = getattr(sys,'_rl_config__unset_',None) if _unset_ is None: class _unset_: pass sys._rl_config__unset_ = _unset_ = _unset_() for k in V: _SAVED[k] = globals()[k] #places to search for Type 1 Font files import reportlab D = {'REPORTLAB_DIR': os.path.abspath(os.path.dirname(reportlab.__file__)), 'HOME': os.environ.get('HOME',os.getcwd()), 'disk': os.getcwd().split(':')[0], 'sys_version': sys_version, } for name in ('T1SearchPath','TTFSearchPath','CMapSearchPath'): P=[] for p in _SAVED[name]: d = (p % D).replace('/',os.sep) if rl_isdir(d): P.append(d) _setOpt(name,P) for k in V[3:]: v = _SAVED[k] if isinstance(v,(int,float)): conv = type(v) elif k=='defaultPageSize': conv = lambda v,M=pagesizes: getattr(M,v) else: conv = None _setOpt(k,v,conv) _registered_resets=[] def register_reset(func): _registered_resets[:] = [x for x in _registered_resets if x()] L = [x for x in _registered_resets if x() is func] if L: return from weakref import ref _registered_resets.append(ref(func)) def _reset(): #attempt to reset reportlab and friends _startUp() #our reset for f in _registered_resets[:]: c = f() if c: c() else: _registered_resets.remove(f) _startUp()
bsd-3-clause
nwjs/chromium.src
components/feature_engagement/internal/never_event_storage_validator.h
1266
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_FEATURE_ENGAGEMENT_INTERNAL_NEVER_EVENT_STORAGE_VALIDATOR_H_ #define COMPONENTS_FEATURE_ENGAGEMENT_INTERNAL_NEVER_EVENT_STORAGE_VALIDATOR_H_ #include <string> #include "base/macros.h" #include "components/feature_engagement/internal/event_storage_validator.h" namespace feature_engagement { // A EventStorageValidator that never acknowledges that an event should be kept // or stored. class NeverEventStorageValidator : public EventStorageValidator { public: NeverEventStorageValidator(); NeverEventStorageValidator(const NeverEventStorageValidator&) = delete; NeverEventStorageValidator& operator=(const NeverEventStorageValidator&) = delete; ~NeverEventStorageValidator() override; // EventStorageValidator implementation. bool ShouldStore(const std::string& event_name) const override; bool ShouldKeep(const std::string& event_name, uint32_t event_day, uint32_t current_day) const override; }; } // namespace feature_engagement #endif // COMPONENTS_FEATURE_ENGAGEMENT_INTERNAL_NEVER_EVENT_STORAGE_VALIDATOR_H_
bsd-3-clause
plum-umd/c-strider
examples/redis-2.0.2/zmalloc.c
5173
/* zmalloc - total amount of allocated memory aware version of malloc() * * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include "config.h" #if defined(__sun) #define PREFIX_SIZE sizeof(long long) #else #define PREFIX_SIZE sizeof(size_t) #endif #define increment_used_memory(__n) do { \ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \ if (zmalloc_thread_safe) { \ pthread_mutex_lock(&used_memory_mutex); \ used_memory += _n; \ pthread_mutex_unlock(&used_memory_mutex); \ } else { \ used_memory += _n; \ } \ } while(0) #define decrement_used_memory(__n) do { \ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \ if (zmalloc_thread_safe) { \ pthread_mutex_lock(&used_memory_mutex); \ used_memory -= _n; \ pthread_mutex_unlock(&used_memory_mutex); \ } else { \ used_memory -= _n; \ } \ } while(0) static size_t used_memory = 0; static int zmalloc_thread_safe = 0; pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER; static void zmalloc_oom(size_t size) { fprintf(stderr, "zmalloc: Out of memory trying to allocate %zu bytes\n", size); fflush(stderr); abort(); } void *zmalloc(size_t size) { /* void *ptr = malloc(size+PREFIX_SIZE); */ /* if (!ptr) zmalloc_oom(size); */ /* #ifdef HAVE_MALLOC_SIZE */ /* increment_used_memory(redis_malloc_size(ptr)); */ /* return ptr; */ /* #else */ /* //\*((size_t*)ptr) = size; */ /* increment_used_memory(size+PREFIX_SIZE); */ /* return (char*)ptr+PREFIX_SIZE; */ /* #endif */ return malloc(size); } void *zrealloc(void *ptr, size_t size) { /* #ifndef HAVE_MALLOC_SIZE */ /* void *realptr; */ /* #endif */ /* size_t oldsize; */ /* void *newptr; */ /* if (ptr == NULL) return zmalloc(size); */ /* #ifdef HAVE_MALLOC_SIZE */ /* oldsize = redis_malloc_size(ptr); */ /* newptr = realloc(ptr,size); */ /* if (!newptr) zmalloc_oom(size); */ /* decrement_used_memory(oldsize); */ /* increment_used_memory(redis_malloc_size(newptr)); */ /* return newptr; */ /* #else */ /* realptr = (char*)ptr-PREFIX_SIZE; */ /* oldsize = *((size_t*)realptr); */ /* newptr = realloc(realptr,size+PREFIX_SIZE); */ /* if (!newptr) zmalloc_oom(size); */ /* *((size_t*)newptr) = size; */ /* decrement_used_memory(oldsize); */ /* increment_used_memory(size); */ /* return (char*)newptr+PREFIX_SIZE; */ /* #endif */ return realloc(ptr, size); } void zfree(void *ptr) { /* #ifndef HAVE_MALLOC_SIZE */ /* void *realptr; */ /* size_t oldsize; */ /* #endif */ /* if (ptr == NULL) return; */ /* #ifdef HAVE_MALLOC_SIZE */ /* decrement_used_memory(redis_malloc_size(ptr)); */ /* free(ptr); */ /* #else */ /* realptr = (char*)ptr-PREFIX_SIZE; */ /* oldsize = *((size_t*)realptr); */ /* decrement_used_memory(oldsize+PREFIX_SIZE); */ /* free(realptr); */ /* #endif */ free(ptr); } char *zstrdup(const char *s) { /* size_t l = strlen(s)+1; */ /* char *p = zmalloc(l); */ /* memcpy(p,s,l); */ /* return p; */ return strdup(s); } size_t zmalloc_used_memory(void) { size_t um; if (zmalloc_thread_safe) pthread_mutex_lock(&used_memory_mutex); um = used_memory; if (zmalloc_thread_safe) pthread_mutex_unlock(&used_memory_mutex); return um; } void zmalloc_enable_thread_safeness(void) { zmalloc_thread_safe = 1; }
bsd-3-clause
mikem2005/vijava
src/com/vmware/vim25/DiagnosticManagerLogCreator.java
2018
/*================================================================================ Copyright (c) 2009 VMware, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25; /** @author Steve Jin ([email protected]) */ public enum DiagnosticManagerLogCreator { vpxd ("vpxd"), vpxa ("vpxa"), hostd ("hostd"), serverd ("serverd"), install ("install"), vpxClient ("vpxClient"), recordLog ("recordLog"); private final String val; private DiagnosticManagerLogCreator(String val) { this.val = val; } }
bsd-3-clause
epri-dev/PT2
src/main/java/org/epri/pt2/DO/EthernetIfaceDO.java
2820
//********************************************************************************************************************* // EthernetIfaceDO.java // // Copyright 2014 ELECTRIC POWER RESEARCH INSTITUTE, INC. All rights reserved. // // PT2 ("this software") is licensed under BSD 3-Clause license. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // • Redistributions of source code must retain the above copyright notice, this list of conditions and // the following disclaimer. // // • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and // the following disclaimer in the documentation and/or other materials provided with the distribution. // // • Neither the name of the Electric Power Research Institute, Inc. (“EPRI”) nor the names of its contributors // may be used to endorse or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL EPRI BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // //********************************************************************************************************************* // // Code Modification History: // ------------------------------------------------------------------------------------------------------------------- // 11/20/2012 - Tam T. Do, Southwest Research Institute (SwRI) // Generated original version of source code. // 10/22/2014 - Tam T. Do, Southwest Research Institute (SwRI) // Added DNP3 software capabilities. //********************************************************************************************************************* // package org.epri.pt2.DO; import javax.persistence.Entity; import org.epri.pt2.InterfaceType; /** * Implements the ethernet interface data object. * * @author tdo * */ @Entity public class EthernetIfaceDO extends AbstractIfaceDO { public EthernetIfaceDO() { super(InterfaceType.Ethernet); } public int compareTo(AbstractIfaceDO o) { return getId() - o.getId(); } }
bsd-3-clause
EasonPai/using-neon-animation
web/styles.css
445
/* Copyright (c) 2016, <your name>. All rights reserved. Use of this source code */ /* is governed by a BSD-style license that can be found in the LICENSE file. */ body { font-family: RobotoDraft, sans-serif; color: #333; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-tap-highlight-color: rgba(0,0,0,0); -webkit-touch-callout: none; overflow: hidden; }
bsd-3-clause
clbanning/j2x
j2xindent_test.go
788
package j2x import ( "encoding/json" "fmt" "testing" ) func TestMashalIndent(t *testing.T) { var s = `{ "head":[ "one", 2, true, { "key":"value" } ] }` fmt.Println("\nTestMashalIndent ... list :", s) v, err := MarshalIndent(s," "," ") if err != nil { fmt.Println("err:",err.Error()) } fmt.Printf("v:\n%s",string(v)) s = `{ "head":{ "line":[ "one", 2, true, { "key":"value" } ] } }` m := make(map[string]interface{},0) err = json.Unmarshal([]byte(s), &m) type mystruct struct { S string F float64 } ms := mystruct{ S:"now's the time", F:3.14159625 } m["mystruct"] = interface{}(ms) fmt.Println("\nTestMarshalIndent ... mystruct", m) v, err = MarshalIndent(m," "," ") if err != nil { fmt.Println("err:",err.Error()) } fmt.Printf("v:\n%s",string(v)) }
bsd-3-clause
kevintvh/sodium
java/src/sodium/LazyCell.java
411
package sodium; class LazyCell<A> extends Cell<A> { LazyCell(final Stream<A> event, final Lazy<A> lazyInitValue) { super(event, null); this.lazyInitValue = lazyInitValue; } @Override A sampleNoTrans() { if (value == null && lazyInitValue != null) { value = lazyInitValue.get(); lazyInitValue = null; } return value; } }
bsd-3-clause
statsmodels/statsmodels.github.io
0.9.0/generated/statsmodels.sandbox.regression.gmm.IVGMM.html
15943
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>statsmodels.sandbox.regression.gmm.IVGMM &#8212; statsmodels 0.9.0 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.sandbox.regression.gmm.IVGMM.calc_weightmatrix" href="statsmodels.sandbox.regression.gmm.IVGMM.calc_weightmatrix.html" /> <link rel="prev" title="statsmodels.sandbox.regression.gmm.IV2SLS.whiten" href="statsmodels.sandbox.regression.gmm.IV2SLS.whiten.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.sandbox.regression.gmm.IVGMM.calc_weightmatrix.html" title="statsmodels.sandbox.regression.gmm.IVGMM.calc_weightmatrix" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.sandbox.regression.gmm.IV2SLS.whiten.html" title="statsmodels.sandbox.regression.gmm.IV2SLS.whiten" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../gmm.html" accesskey="U">Generalized Method of Moments <code class="docutils literal notranslate"><span class="pre">gmm</span></code></a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-sandbox-regression-gmm-ivgmm"> <h1>statsmodels.sandbox.regression.gmm.IVGMM<a class="headerlink" href="#statsmodels-sandbox-regression-gmm-ivgmm" title="Permalink to this headline">¶</a></h1> <dl class="class"> <dt id="statsmodels.sandbox.regression.gmm.IVGMM"> <em class="property">class </em><code class="descclassname">statsmodels.sandbox.regression.gmm.</code><code class="descname">IVGMM</code><span class="sig-paren">(</span><em>endog</em>, <em>exog</em>, <em>instrument</em>, <em>k_moms=None</em>, <em>k_params=None</em>, <em>missing='none'</em>, <em>**kwds</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/sandbox/regression/gmm.html#IVGMM"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.sandbox.regression.gmm.IVGMM" title="Permalink to this definition">¶</a></dt> <dd><p>Basic class for instrumental variables estimation using GMM</p> <p>A linear function for the conditional mean is defined as default but the methods should be overwritten by subclasses, currently <cite>LinearIVGMM</cite> and <cite>NonlinearIVGMM</cite> are implemented as subclasses.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="statsmodels.sandbox.regression.gmm.LinearIVGMM.html#statsmodels.sandbox.regression.gmm.LinearIVGMM" title="statsmodels.sandbox.regression.gmm.LinearIVGMM"><code class="xref py py-class docutils literal notranslate"><span class="pre">LinearIVGMM</span></code></a>, <a class="reference internal" href="statsmodels.sandbox.regression.gmm.NonlinearIVGMM.html#statsmodels.sandbox.regression.gmm.NonlinearIVGMM" title="statsmodels.sandbox.regression.gmm.NonlinearIVGMM"><code class="xref py py-class docutils literal notranslate"><span class="pre">NonlinearIVGMM</span></code></a></p> </div> <p class="rubric">Methods</p> <table border="1" class="longtable docutils"> <colgroup> <col width="10%" /> <col width="90%" /> </colgroup> <tbody valign="top"> <tr class="row-odd"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.calc_weightmatrix.html#statsmodels.sandbox.regression.gmm.IVGMM.calc_weightmatrix" title="statsmodels.sandbox.regression.gmm.IVGMM.calc_weightmatrix"><code class="xref py py-obj docutils literal notranslate"><span class="pre">calc_weightmatrix</span></code></a>(moms[,&nbsp;weights_method,&nbsp;…])</td> <td>calculate omega or the weighting matrix</td> </tr> <tr class="row-even"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.fit.html#statsmodels.sandbox.regression.gmm.IVGMM.fit" title="statsmodels.sandbox.regression.gmm.IVGMM.fit"><code class="xref py py-obj docutils literal notranslate"><span class="pre">fit</span></code></a>([start_params,&nbsp;maxiter,&nbsp;inv_weights,&nbsp;…])</td> <td>Estimate parameters using GMM and return GMMResults</td> </tr> <tr class="row-odd"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.fitgmm.html#statsmodels.sandbox.regression.gmm.IVGMM.fitgmm" title="statsmodels.sandbox.regression.gmm.IVGMM.fitgmm"><code class="xref py py-obj docutils literal notranslate"><span class="pre">fitgmm</span></code></a>(start[,&nbsp;weights,&nbsp;optim_method,&nbsp;…])</td> <td>estimate parameters using GMM</td> </tr> <tr class="row-even"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.fitgmm_cu.html#statsmodels.sandbox.regression.gmm.IVGMM.fitgmm_cu" title="statsmodels.sandbox.regression.gmm.IVGMM.fitgmm_cu"><code class="xref py py-obj docutils literal notranslate"><span class="pre">fitgmm_cu</span></code></a>(start[,&nbsp;optim_method,&nbsp;optim_args])</td> <td>estimate parameters using continuously updating GMM</td> </tr> <tr class="row-odd"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.fititer.html#statsmodels.sandbox.regression.gmm.IVGMM.fititer" title="statsmodels.sandbox.regression.gmm.IVGMM.fititer"><code class="xref py py-obj docutils literal notranslate"><span class="pre">fititer</span></code></a>(start[,&nbsp;maxiter,&nbsp;start_invweights,&nbsp;…])</td> <td>iterative estimation with updating of optimal weighting matrix</td> </tr> <tr class="row-even"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.fitstart.html#statsmodels.sandbox.regression.gmm.IVGMM.fitstart" title="statsmodels.sandbox.regression.gmm.IVGMM.fitstart"><code class="xref py py-obj docutils literal notranslate"><span class="pre">fitstart</span></code></a>()</td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.from_formula.html#statsmodels.sandbox.regression.gmm.IVGMM.from_formula" title="statsmodels.sandbox.regression.gmm.IVGMM.from_formula"><code class="xref py py-obj docutils literal notranslate"><span class="pre">from_formula</span></code></a>(formula,&nbsp;data[,&nbsp;subset,&nbsp;drop_cols])</td> <td>Create a Model from a formula and dataframe.</td> </tr> <tr class="row-even"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.get_error.html#statsmodels.sandbox.regression.gmm.IVGMM.get_error" title="statsmodels.sandbox.regression.gmm.IVGMM.get_error"><code class="xref py py-obj docutils literal notranslate"><span class="pre">get_error</span></code></a>(params)</td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective.html#statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective" title="statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective"><code class="xref py py-obj docutils literal notranslate"><span class="pre">gmmobjective</span></code></a>(params,&nbsp;weights)</td> <td>objective function for GMM minimization</td> </tr> <tr class="row-even"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective_cu.html#statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective_cu" title="statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective_cu"><code class="xref py py-obj docutils literal notranslate"><span class="pre">gmmobjective_cu</span></code></a>(params[,&nbsp;weights_method,&nbsp;wargs])</td> <td>objective function for continuously updating GMM minimization</td> </tr> <tr class="row-odd"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.gradient_momcond.html#statsmodels.sandbox.regression.gmm.IVGMM.gradient_momcond" title="statsmodels.sandbox.regression.gmm.IVGMM.gradient_momcond"><code class="xref py py-obj docutils literal notranslate"><span class="pre">gradient_momcond</span></code></a>(params[,&nbsp;epsilon,&nbsp;centered])</td> <td>gradient of moment conditions</td> </tr> <tr class="row-even"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.momcond.html#statsmodels.sandbox.regression.gmm.IVGMM.momcond" title="statsmodels.sandbox.regression.gmm.IVGMM.momcond"><code class="xref py py-obj docutils literal notranslate"><span class="pre">momcond</span></code></a>(params)</td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.momcond_mean.html#statsmodels.sandbox.regression.gmm.IVGMM.momcond_mean" title="statsmodels.sandbox.regression.gmm.IVGMM.momcond_mean"><code class="xref py py-obj docutils literal notranslate"><span class="pre">momcond_mean</span></code></a>(params)</td> <td>mean of moment conditions,</td> </tr> <tr class="row-even"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.predict.html#statsmodels.sandbox.regression.gmm.IVGMM.predict" title="statsmodels.sandbox.regression.gmm.IVGMM.predict"><code class="xref py py-obj docutils literal notranslate"><span class="pre">predict</span></code></a>(params[,&nbsp;exog])</td> <td>After a model has been fit predict returns the fitted values.</td> </tr> <tr class="row-odd"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.score.html#statsmodels.sandbox.regression.gmm.IVGMM.score" title="statsmodels.sandbox.regression.gmm.IVGMM.score"><code class="xref py py-obj docutils literal notranslate"><span class="pre">score</span></code></a>(params,&nbsp;weights[,&nbsp;epsilon,&nbsp;centered])</td> <td></td> </tr> <tr class="row-even"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.score_cu.html#statsmodels.sandbox.regression.gmm.IVGMM.score_cu" title="statsmodels.sandbox.regression.gmm.IVGMM.score_cu"><code class="xref py py-obj docutils literal notranslate"><span class="pre">score_cu</span></code></a>(params[,&nbsp;epsilon,&nbsp;centered])</td> <td></td> </tr> <tr class="row-odd"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.set_param_names.html#statsmodels.sandbox.regression.gmm.IVGMM.set_param_names" title="statsmodels.sandbox.regression.gmm.IVGMM.set_param_names"><code class="xref py py-obj docutils literal notranslate"><span class="pre">set_param_names</span></code></a>(param_names[,&nbsp;k_params])</td> <td>set the parameter names in the model</td> </tr> <tr class="row-even"><td><a class="reference internal" href="statsmodels.sandbox.regression.gmm.IVGMM.start_weights.html#statsmodels.sandbox.regression.gmm.IVGMM.start_weights" title="statsmodels.sandbox.regression.gmm.IVGMM.start_weights"><code class="xref py py-obj docutils literal notranslate"><span class="pre">start_weights</span></code></a>([inv])</td> <td></td> </tr> </tbody> </table> <p class="rubric">Attributes</p> <table border="1" class="longtable docutils"> <colgroup> <col width="10%" /> <col width="90%" /> </colgroup> <tbody valign="top"> <tr class="row-odd"><td><code class="xref py py-obj docutils literal notranslate"><span class="pre">endog_names</span></code></td> <td>Names of endogenous variables</td> </tr> <tr class="row-even"><td><code class="xref py py-obj docutils literal notranslate"><span class="pre">exog_names</span></code></td> <td>Names of exogenous variables</td> </tr> <tr class="row-odd"><td><code class="xref py py-obj docutils literal notranslate"><span class="pre">results_class</span></code></td> <td></td> </tr> </tbody> </table> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.sandbox.regression.gmm.IV2SLS.whiten.html" title="previous chapter">statsmodels.sandbox.regression.gmm.IV2SLS.whiten</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.sandbox.regression.gmm.IVGMM.calc_weightmatrix.html" title="next chapter">statsmodels.sandbox.regression.gmm.IVGMM.calc_weightmatrix</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.sandbox.regression.gmm.IVGMM.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.7.4. </div> </body> </html>
bsd-3-clause
statsmodels/statsmodels.github.io
v0.10.0/generated/statsmodels.discrete.discrete_model.Poisson.loglikeobs.html
8374
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>statsmodels.discrete.discrete_model.Poisson.loglikeobs &#8212; statsmodels v0.10.0 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.discrete.discrete_model.Poisson.pdf" href="statsmodels.discrete.discrete_model.Poisson.pdf.html" /> <link rel="prev" title="statsmodels.discrete.discrete_model.Poisson.loglike" href="statsmodels.discrete.discrete_model.Poisson.loglike.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.discrete.discrete_model.Poisson.pdf.html" title="statsmodels.discrete.discrete_model.Poisson.pdf" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.discrete.discrete_model.Poisson.loglike.html" title="statsmodels.discrete.discrete_model.Poisson.loglike" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../discretemod.html" >Regression with Discrete Dependent Variable</a> |</li> <li class="nav-item nav-item-2"><a href="statsmodels.discrete.discrete_model.Poisson.html" accesskey="U">statsmodels.discrete.discrete_model.Poisson</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-discrete-discrete-model-poisson-loglikeobs"> <h1>statsmodels.discrete.discrete_model.Poisson.loglikeobs<a class="headerlink" href="#statsmodels-discrete-discrete-model-poisson-loglikeobs" title="Permalink to this headline">¶</a></h1> <p>method</p> <dl class="method"> <dt id="statsmodels.discrete.discrete_model.Poisson.loglikeobs"> <code class="sig-prename descclassname">Poisson.</code><code class="sig-name descname">loglikeobs</code><span class="sig-paren">(</span><em class="sig-param">params</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/discrete/discrete_model.html#Poisson.loglikeobs"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.discrete.discrete_model.Poisson.loglikeobs" title="Permalink to this definition">¶</a></dt> <dd><p>Loglikelihood for observations of Poisson model</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"><dl class="simple"> <dt><strong>params</strong><span class="classifier">array-like</span></dt><dd><p>The parameters of the model.</p> </dd> </dl> </dd> <dt class="field-even">Returns</dt> <dd class="field-even"><dl class="simple"> <dt><strong>loglike</strong><span class="classifier">array-like</span></dt><dd><p>The log likelihood for each observation of the model evaluated at <cite>params</cite>. See Notes</p> </dd> </dl> </dd> </dl> <p class="rubric">Notes</p> <div class="math notranslate nohighlight"> \[\ln L_{i}=\left[-\lambda_{i}+y_{i}x_{i}^{\prime}\beta-\ln y_{i}!\right]\]</div> <p>for observations <span class="math notranslate nohighlight">\(i=1,...,n\)</span></p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.discrete.discrete_model.Poisson.loglike.html" title="previous chapter">statsmodels.discrete.discrete_model.Poisson.loglike</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.discrete.discrete_model.Poisson.pdf.html" title="next chapter">statsmodels.discrete.discrete_model.Poisson.pdf</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.discrete.discrete_model.Poisson.loglikeobs.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2. </div> </body> </html>
bsd-3-clause
livibetter-backup/twimonial
src/index.py
2779
import os from google.appengine.api import memcache from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from twimonial.models import Twimonial, User from twimonial.ui import render_write import config class HomePage(webapp.RequestHandler): def get(self): if config.CACHE: # Check cache first cached_page = memcache.get('homepage') if cached_page: self.response.out.write(cached_page) return # Get latest five testimonials latest_twimonials = [t.dictize() for t in Twimonial.all().order('-created_at').fetch(5)] tmpl_values = { 'latest_twimonials': latest_twimonials, 'pop_users_twimonials': User.get_popular_users_testimonials(), } # Send out and cache it rendered_page = render_write(tmpl_values, 'home.html', self.request, self.response) if config.CACHE: memcache.set('homepage', rendered_page, config.CACHE_TIME_HOMEPAGE) def head(self): pass class NotFoundPage(webapp.RequestHandler): def get(self): self.error(404) tmpl_values = { } render_write(tmpl_values, '404.html', self.request, self.response) def head(self): self.error(404) class StaticPage(webapp.RequestHandler): def get(self, pagename): render_write({}, pagename + '.html', self.request, self.response) def head(self): pass class ListPage(webapp.RequestHandler): def get(self, screen_names_string): limit = 10 screen_names = [name for name in screen_names_string.split('-') if name][:limit] screen_names.sort() screen_names_string = '-'.join(screen_names) # Check cache first cached_page = memcache.get(screen_names_string, 'listpage') if cached_page: self.response.out.write(cached_page) return twimonials = [t.dictize() for t in Twimonial.get_tos(screen_names)] missings = [] t_screen_names = [t['to_user']['screen_name'].lower() for t in twimonials] for name in screen_names: if name.lower() not in t_screen_names: missings.append(name) tmpl_values = { 'twimonials': twimonials, 'missings': ', '.join(missings), } # Send out and cache it rendered_page = render_write(tmpl_values, 'list.html', self.request, self.response) memcache.set(screen_names_string, rendered_page, config.CACHE_TIME_LISTPAGE, namespace='listpage') application = webapp.WSGIApplication([ ('/', HomePage), ('/(about|terms|faq)', StaticPage), ('/list/([-_a-zA-Z0-9]+)', ListPage), ('/.*', NotFoundPage), ], debug=config.DEBUG) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
bsd-3-clause
bryantmakesprog/incremental
README.md
45
# incremental Template for incremental game.
bsd-3-clause
1GHL/2013y
exercise/816/create_file.sh
194
#!/bin/bash #input set -xv debug=1 USAGE='usage: sh $1 $2 ;'\ '$1: is value of [1,2] create file or directory '\ '$2: is number ' echo $USAGE echo $0 echo $1 echo $2 echo $# if [ $# -eq 2 ]
bsd-3-clause
matt-42/FrameworkBenchmarks
frameworks/PHP/php-ngx/php-ngx.dockerfile
1193
FROM ubuntu:19.10 ARG DEBIAN_FRONTEND=noninteractive RUN apt-get update -yqq && apt-get install -yqq software-properties-common > /dev/null RUN LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php > /dev/null RUN apt-get update -yqq > /dev/null && \ apt-get install -yqq wget git unzip libxml2-dev cmake make systemtap-sdt-dev \ zlibc zlib1g zlib1g-dev libpcre3 libpcre3-dev libargon2-0-dev libsodium-dev \ php7.4 php7.4-common php7.4-dev libphp7.4-embed php7.4-mysql nginx > /dev/null ADD ./ ./ ENV NGINX_VERSION=1.17.6 RUN git clone -b v0.0.22 --single-branch --depth 1 https://github.com/rryqszq4/ngx_php7.git > /dev/null RUN wget -q http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz && \ tar -zxf nginx-${NGINX_VERSION}.tar.gz && \ cd nginx-${NGINX_VERSION} && \ export PHP_LIB=/usr/lib && \ ./configure --user=www --group=www \ --prefix=/nginx \ --with-ld-opt="-Wl,-rpath,$PHP_LIB" \ --add-module=/ngx_php7/third_party/ngx_devel_kit \ --add-module=/ngx_php7 > /dev/null && \ make > /dev/null && make install > /dev/null CMD /nginx/sbin/nginx -c /deploy/nginx.conf
bsd-3-clause
NeuroRoboticTech/AnimatLabPublicSource
Libraries/BulletAnimatSim/BlOsgGeometry.h
711
#pragma once namespace BulletAnimatSim { namespace Environment { btHeightfieldTerrainShape BULLET_PORT *CreateBtHeightField(osg::HeightField *osgHeightField, float fltSegWidth, float fltSegLength, float &fltMinHeight, float &fltMaxHeight, btScalar **aryHeightData); btConvexHullShape BULLET_PORT *OsgMeshToConvexHull(osg::Node *lpNode, bool bOptimize, float fltMargin); btConvexHullShape* OsgConvexShrunkenHullCollisionShape( osg::Node* node ); float BULLET_PORT OsgConvexHullVolume( osg::Node* nod); btVector3 Vec3AnimatToBullet(const CStdFPoint &vPoint); CStdFPoint Vec3BulletToAnimat(const btVector3 &vPoint); } // Environment } //BulletAnimatSim
bsd-3-clause
todor-dk/HTML-Renderer
Source/Testing/HtmlRenderer.DomParseTester/DomComparing/ViewModels/Comment.cs
403
using HtmlRenderer.TestLib.Dom; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HtmlRenderer.DomParseTester.DomComparing.ViewModels { public sealed class Comment : CharacterData<ReferenceComment> { public Comment(Context context, ReferenceComment model) : base(context, model) { } } }
bsd-3-clause
ric2b/Vivaldi-browser
chromium/chrome/browser/ash/policy/reporting/arc_app_install_event_logger.cc
8972
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/policy/reporting/arc_app_install_event_logger.h" #include <stdint.h> #include <algorithm> #include <iterator> #include "ash/components/arc/arc_prefs.h" #include "base/bind.h" #include "base/files/file_path.h" #include "base/location.h" #include "base/task/post_task.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "base/values.h" #include "chrome/browser/ash/arc/arc_util.h" #include "chrome/browser/ash/arc/policy/arc_policy_util.h" #include "chrome/browser/ash/policy/reporting/install_event_logger_base.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/profiles/profile.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_namespace.h" #include "components/policy/policy_constants.h" #include "components/policy/proto/device_management_backend.pb.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" namespace em = enterprise_management; namespace policy { namespace { constexpr int kNonComplianceReasonAppNotInstalled = 5; std::set<std::string> GetRequestedPackagesFromPolicy( const policy::PolicyMap& policy) { const base::Value* const arc_enabled = policy.GetValue(key::kArcEnabled); if (!arc_enabled || !arc_enabled->is_bool() || !arc_enabled->GetBool()) { return {}; } const base::Value* const arc_policy = policy.GetValue(key::kArcPolicy); if (!arc_policy || !arc_policy->is_string()) { return {}; } return arc::policy_util::GetRequestedPackagesFromArcPolicy( arc_policy->GetString()); } } // namespace ArcAppInstallEventLogger::ArcAppInstallEventLogger(Delegate* delegate, Profile* profile) : InstallEventLoggerBase(profile), delegate_(delegate) { if (!arc::IsArcAllowedForProfile(profile_)) { AddForSetOfApps(GetPackagesFromPref(arc::prefs::kArcPushInstallAppsPending), CreateEvent(em::AppInstallReportLogEvent::CANCELED)); Clear(profile_); return; } policy::PolicyService* const policy_service = profile_->GetProfilePolicyConnector()->policy_service(); EvaluatePolicy(policy_service->GetPolicies(policy::PolicyNamespace( policy::POLICY_DOMAIN_CHROME, std::string())), true /* initial */); observing_ = true; arc::ArcPolicyBridge* bridge = arc::ArcPolicyBridge::GetForBrowserContext(profile_); bridge->AddObserver(this); policy_service->AddObserver(policy::POLICY_DOMAIN_CHROME, this); } ArcAppInstallEventLogger::~ArcAppInstallEventLogger() { if (log_collector_) { log_collector_->OnLogout(); } if (observing_) { arc::ArcPolicyBridge::GetForBrowserContext(profile_)->RemoveObserver(this); profile_->GetProfilePolicyConnector()->policy_service()->RemoveObserver( policy::POLICY_DOMAIN_CHROME, this); } } // static void ArcAppInstallEventLogger::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterListPref(arc::prefs::kArcPushInstallAppsRequested); registry->RegisterListPref(arc::prefs::kArcPushInstallAppsPending); } // static void ArcAppInstallEventLogger::Clear(Profile* profile) { profile->GetPrefs()->ClearPref(arc::prefs::kArcPushInstallAppsRequested); profile->GetPrefs()->ClearPref(arc::prefs::kArcPushInstallAppsPending); } void ArcAppInstallEventLogger::AddForAllPackages( std::unique_ptr<em::AppInstallReportLogEvent> event) { EnsureTimestampSet(event.get()); AddForSetOfApps(GetPackagesFromPref(arc::prefs::kArcPushInstallAppsPending), std::move(event)); } void ArcAppInstallEventLogger::Add( const std::string& package, bool gather_disk_space_info, std::unique_ptr<em::AppInstallReportLogEvent> event) { AddEvent(package, gather_disk_space_info, event); } void ArcAppInstallEventLogger::OnPolicyUpdated( const policy::PolicyNamespace& ns, const policy::PolicyMap& previous, const policy::PolicyMap& current) { EvaluatePolicy(current, false /* initial */); } void ArcAppInstallEventLogger::OnPolicySent(const std::string& policy) { requested_in_arc_ = arc::policy_util::GetRequestedPackagesFromArcPolicy(policy); } void ArcAppInstallEventLogger::OnComplianceReportReceived( const base::Value* compliance_report) { const base::Value* const details = compliance_report->FindKeyOfType( "nonComplianceDetails", base::Value::Type::LIST); if (!details) { return; } const std::set<std::string> previous_pending = GetPackagesFromPref(arc::prefs::kArcPushInstallAppsPending); std::set<std::string> pending_in_arc; for (const auto& detail : details->GetList()) { const base::Value* const reason = detail.FindKeyOfType("nonComplianceReason", base::Value::Type::INTEGER); if (!reason || reason->GetInt() != kNonComplianceReasonAppNotInstalled) { continue; } const base::Value* const app_name = detail.FindKeyOfType("packageName", base::Value::Type::STRING); if (!app_name || app_name->GetString().empty()) { continue; } pending_in_arc.insert(app_name->GetString()); } const std::set<std::string> current_pending = GetDifference( previous_pending, GetDifference(requested_in_arc_, pending_in_arc)); const std::set<std::string> removed = GetDifference(previous_pending, current_pending); AddForSetOfAppsWithDiskSpaceInfo( removed, CreateEvent(em::AppInstallReportLogEvent::SUCCESS)); if (removed.empty()) { return; } SetPref(arc::prefs::kArcPushInstallAppsPending, current_pending); if (!current_pending.empty()) { UpdateCollector(current_pending); } else { StopCollector(); } } std::set<std::string> ArcAppInstallEventLogger::GetPackagesFromPref( const std::string& pref_name) const { std::set<std::string> packages; for (const auto& package : profile_->GetPrefs()->GetList(pref_name)->GetList()) { if (!package.is_string()) { continue; } packages.insert(package.GetString()); } return packages; } void ArcAppInstallEventLogger::SetPref(const std::string& pref_name, const std::set<std::string>& packages) { base::Value value(base::Value::Type::LIST); for (const std::string& package : packages) { value.Append(package); } profile_->GetPrefs()->Set(pref_name, value); } void ArcAppInstallEventLogger::UpdateCollector( const std::set<std::string>& pending) { if (!log_collector_) { log_collector_ = std::make_unique<ArcAppInstallEventLogCollector>( this, profile_, pending); } else { log_collector_->OnPendingPackagesChanged(pending); } } void ArcAppInstallEventLogger::StopCollector() { log_collector_.reset(); } void ArcAppInstallEventLogger::EvaluatePolicy(const policy::PolicyMap& policy, bool initial) { const std::set<std::string> previous_requested = GetPackagesFromPref(arc::prefs::kArcPushInstallAppsRequested); const std::set<std::string> previous_pending = GetPackagesFromPref(arc::prefs::kArcPushInstallAppsPending); const std::set<std::string> current_requested = GetRequestedPackagesFromPolicy(policy); const std::set<std::string> added = GetDifference(current_requested, previous_requested); const std::set<std::string> removed = GetDifference(previous_pending, current_requested); AddForSetOfAppsWithDiskSpaceInfo( added, CreateEvent(em::AppInstallReportLogEvent::SERVER_REQUEST)); AddForSetOfApps(removed, CreateEvent(em::AppInstallReportLogEvent::CANCELED)); const std::set<std::string> current_pending = GetDifference( current_requested, GetDifference(previous_requested, previous_pending)); SetPref(arc::prefs::kArcPushInstallAppsRequested, current_requested); SetPref(arc::prefs::kArcPushInstallAppsPending, current_pending); if (!current_pending.empty()) { UpdateCollector(current_pending); if (initial) { log_collector_->OnLogin(); } } else { StopCollector(); } } void ArcAppInstallEventLogger::AddForSetOfApps( const std::set<std::string>& packages, std::unique_ptr<em::AppInstallReportLogEvent> event) { delegate_->GetAndroidId( base::BindOnce(&ArcAppInstallEventLogger::OnGetAndroidId, weak_factory_.GetWeakPtr(), packages, std::move(event))); } void ArcAppInstallEventLogger::OnGetAndroidId( const std::set<std::string>& packages, std::unique_ptr<em::AppInstallReportLogEvent> event, bool ok, int64_t android_id) { if (ok) { event->set_android_id(android_id); } delegate_->Add(packages, *event); } } // namespace policy
bsd-3-clause
marcioAlmada/CLIFramework
src/CLIFramework/Component/Table/CellAttribute.php
3942
<?php namespace CLIFramework\Component\Table; use CLIFramework\Ansi\Colors; class CellAttribute { const ALIGN_RIGHT = 1; const ALIGN_LEFT = 2; const ALIGN_CENTER = 3; const WRAP = 1; const CLIP = 2; const ELLIPSIS = 3; protected $alignment = 2; protected $formatter; protected $textOverflow = CellAttribute::WRAP; protected $backgroundColor; protected $foregroundColor; /* protected $style; public function __construct(TableStyle $style) { $this->style = $style; } public function setStyle(TableStyle $style) { $this->style = $style; } */ public function setAlignment($alignment) { $this->alignment = $alignment; } public function setFormatter($formatter) { $this->formatter = $formatter; } public function getFormatter() { return $this->formatter; } public function setTextOverflow($overflowType) { $this->textOverflow = $overflowType; } /** * The default cell text formatter */ public function format($cell) { if ($this->formatter) { return call_user_func($this->formatter, $cell); } return $cell; } public function setBackgroundColor($color) { $this->backgroundColor = $color; } public function setForegroundColor($color) { $this->foregroundColor = $color; } public function getForegroundColor() { return $this->foregroundColor; // TODO: fallback to table style } public function getBackgroundColor() { return $this->backgroundColor; // TODO: fallback to table style } /** * When inserting rows, we pre-explode the lines to extra rows from Table * hence this method is separated for pre-processing.. */ public function handleTextOverflow($cell, $maxWidth) { $lines = explode("\n",$cell); if ($this->textOverflow == self::WRAP) { $maxLineWidth = max(array_map('mb_strlen', $lines)); if ($maxLineWidth > $maxWidth) { $cell = wordwrap($cell, $maxWidth, "\n"); // Re-explode the lines $lines = explode("\n",$cell); } } elseif ($this->textOverflow == self::ELLIPSIS) { if (mb_strlen($lines[0]) > $maxWidth) { $lines = array(mb_substr($lines[0], 0, $maxWidth - 2) . '..'); } } elseif ($this->textOverflow == self::CLIP) { if (mb_strlen($lines[0]) > $maxWidth) { $lines = array(mb_substr($lines[0], 0, $maxWidth)); } } return $lines; } public function renderCell($cell, $width, $style) { $out = ''; $out .= str_repeat($style->cellPaddingChar, $style->cellPadding); /* if ($this->backgroundColor || $this->foregroundColor) { $decoratedCell = Colors::decorate($cell, $this->foregroundColor, $this->backgroundColor); $width += mb_strlen($decoratedCell) - mb_strlen($cell); $cell = $decoratedCell; } */ if ($this->alignment === CellAttribute::ALIGN_LEFT) { $out .= str_pad($cell, $width, ' '); // default alignment = LEFT } elseif ($this->alignment === CellAttribute::ALIGN_RIGHT) { $out .= str_pad($cell, $width, ' ', STR_PAD_LEFT); } elseif ($this->alignment === CellAttribute::ALIGN_CENTER) { $out .= str_pad($cell, $width, ' ', STR_PAD_BOTH); } else { $out .= str_pad($cell, $width, ' '); // default alignment } $out .= str_repeat($style->cellPaddingChar, $style->cellPadding); if ($this->backgroundColor || $this->foregroundColor) { return Colors::decorate($out, $this->foregroundColor, $this->backgroundColor); } return $out; } }
bsd-3-clause
Rombur/DataTransferKit
packages/Interface/src/DTK_DOFMap.hpp
3843
/**************************************************************************** * Copyright (c) 2012-2020 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ /*! * \file DTK_DOFMap.hpp * \brief Degree-of-freedom map. */ //---------------------------------------------------------------------------// #ifndef DTK_DOFMAP_HPP #define DTK_DOFMAP_HPP #include <Kokkos_Core.hpp> #include <Kokkos_DynRankView.hpp> namespace DataTransferKit { //---------------------------------------------------------------------------// /*! * \class DOFMap. * * \brief Trivially-copyable degree-of-freedom map. * * \tparam ViewProperties Properties of the contained Kokkos views. */ template <class... ViewProperties> class DOFMap { public: //! View Traits. using ViewTraits = typename Kokkos::ViewTraits<int, ViewProperties...>; //! Globally-unique ids for dofs represented on this process. These may or //! may not be locally owned but every dof for every object defined on //! this process must be available in this list. This list is of rank-1 //! and of length equal to the number of degrees of freedom on the local //! MPI rank. Dimensions: (dof) Kokkos::View<GlobalOrdinal *, ViewProperties...> global_dof_ids; //! For every object of the given type in the object list give the local //! dof ids for that object. The local dof ids correspond to the index of //! the entry in the global dof id view. This view can be either rank-1 or //! rank-2 //! //! If this view is defined as rank-1 it represents unstructured rank-2 //! data. It should be sized as (total sum of the number of dofs defined on //! each object) or the total sum of the entries in the dof_per_object //! view. Consider the \f$n^th\f$ dof of object \f$i\f$ to be \f$d^i_n\f$ //! which is //! equal to the local index of the corresponding node in the nodes //! view. Two objects, the first with 5 dofs and the second with 4 would //! then be defined via this view as: \f$(d^1_1, d^1_2, d^1_3, d^1_4, d^1_5, //! d^2_1, d^2_2, d^2_3, d^2_4 )\f$ with the dofs_per_object view reading //! \f$(5, 4)\f$. Dimensions: (object * dof). //! //! If this view is rank-2, then it represents a fixed number of dofs per //! object. The ordering of the dofs for each object should be the same as //! the case of rank-1 input. Dimensions: (object, dof). Kokkos::DynRankView<LocalOrdinal, ViewProperties...> object_dof_ids; //! The number of degrees of freedom on each object. This view is only //! necessary if the object_dof_ids array is rank-1. This view is rank-1 //! and of length of the number of objects of the given type in the //! list. Dimensions: (object). Kokkos::View<unsigned *, ViewProperties...> dofs_per_object; }; //---------------------------------------------------------------------------// } // namespace DataTransferKit //---------------------------------------------------------------------------// #endif // end DTK_DOFMAP_HPP //---------------------------------------------------------------------------// // end DTK_DOFMap.hpp //---------------------------------------------------------------------------//
bsd-3-clause
endlessm/chromium-browser
third_party/angle/src/libANGLE/capture_gles_3_0_params.cpp
34588
// // Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // capture_gles3_params.cpp: // Pointer parameter capture functions for the OpenGL ES 3.0 entry points. #include "libANGLE/capture_gles_2_0_autogen.h" #include "libANGLE/capture_gles_3_0_autogen.h" using namespace angle; namespace gl { void CaptureClearBufferfv_value(const State &glState, bool isCallValid, GLenum buffer, GLint drawbuffer, const GLfloat *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureClearBufferiv_value(const State &glState, bool isCallValid, GLenum buffer, GLint drawbuffer, const GLint *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureClearBufferuiv_value(const State &glState, bool isCallValid, GLenum buffer, GLint drawbuffer, const GLuint *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureCompressedTexImage3D_data(const State &glState, bool isCallValid, TextureTarget targetPacked, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data, ParamCapture *paramCapture) { if (glState.getTargetBuffer(gl::BufferBinding::PixelUnpack)) { return; } if (!data) { return; } CaptureMemory(data, imageSize, paramCapture); } void CaptureCompressedTexSubImage3D_data(const State &glState, bool isCallValid, TextureTarget targetPacked, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data, ParamCapture *paramCapture) { CaptureCompressedTexImage3D_data(glState, isCallValid, targetPacked, level, 0, width, height, depth, 0, imageSize, data, paramCapture); } void CaptureDeleteQueries_idsPacked(const State &glState, bool isCallValid, GLsizei n, const QueryID *ids, ParamCapture *paramCapture) { CaptureMemory(ids, sizeof(QueryID) * n, paramCapture); } void CaptureDeleteSamplers_samplersPacked(const State &glState, bool isCallValid, GLsizei count, const SamplerID *samplers, ParamCapture *paramCapture) { CaptureMemory(samplers, sizeof(SamplerID) * count, paramCapture); } void CaptureDeleteTransformFeedbacks_idsPacked(const State &glState, bool isCallValid, GLsizei n, const TransformFeedbackID *ids, ParamCapture *paramCapture) { CaptureMemory(ids, sizeof(TransformFeedbackID) * n, paramCapture); } void CaptureDeleteVertexArrays_arraysPacked(const State &glState, bool isCallValid, GLsizei n, const VertexArrayID *arrays, ParamCapture *paramCapture) { CaptureMemory(arrays, sizeof(VertexArrayID) * n, paramCapture); } void CaptureDrawBuffers_bufs(const State &glState, bool isCallValid, GLsizei n, const GLenum *bufs, ParamCapture *paramCapture) { CaptureMemory(bufs, sizeof(GLenum) * n, paramCapture); } void CaptureDrawElementsInstanced_indices(const State &glState, bool isCallValid, PrimitiveMode modePacked, GLsizei count, DrawElementsType typePacked, const void *indices, GLsizei instancecount, ParamCapture *paramCapture) { CaptureDrawElements_indices(glState, isCallValid, modePacked, count, typePacked, indices, paramCapture); } void CaptureDrawRangeElements_indices(const State &glState, bool isCallValid, PrimitiveMode modePacked, GLuint start, GLuint end, GLsizei count, DrawElementsType typePacked, const void *indices, ParamCapture *paramCapture) { CaptureDrawElements_indices(glState, isCallValid, modePacked, count, typePacked, indices, paramCapture); } void CaptureGenQueries_idsPacked(const State &glState, bool isCallValid, GLsizei n, QueryID *ids, ParamCapture *paramCapture) { CaptureGenHandles(n, ids, paramCapture); } void CaptureGenSamplers_samplersPacked(const State &glState, bool isCallValid, GLsizei count, SamplerID *samplers, ParamCapture *paramCapture) { CaptureGenHandles(count, samplers, paramCapture); } void CaptureGenTransformFeedbacks_idsPacked(const State &glState, bool isCallValid, GLsizei n, TransformFeedbackID *ids, ParamCapture *paramCapture) { CaptureGenHandles(n, ids, paramCapture); } void CaptureGenVertexArrays_arraysPacked(const State &glState, bool isCallValid, GLsizei n, VertexArrayID *arrays, ParamCapture *paramCapture) { CaptureGenHandles(n, arrays, paramCapture); } void CaptureGetActiveUniformBlockName_length(const State &glState, bool isCallValid, ShaderProgramID program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetActiveUniformBlockName_uniformBlockName(const State &glState, bool isCallValid, ShaderProgramID program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetActiveUniformBlockiv_params(const State &glState, bool isCallValid, ShaderProgramID program, GLuint uniformBlockIndex, GLenum pname, GLint *params, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetActiveUniformsiv_uniformIndices(const State &glState, bool isCallValid, ShaderProgramID program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetActiveUniformsiv_params(const State &glState, bool isCallValid, ShaderProgramID program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetBufferParameteri64v_params(const State &glState, bool isCallValid, BufferBinding targetPacked, GLenum pname, GLint64 *params, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetBufferPointerv_params(const State &glState, bool isCallValid, BufferBinding targetPacked, GLenum pname, void **params, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetFragDataLocation_name(const State &glState, bool isCallValid, ShaderProgramID program, const GLchar *name, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetInteger64i_v_data(const State &glState, bool isCallValid, GLenum target, GLuint index, GLint64 *data, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetInteger64v_data(const State &glState, bool isCallValid, GLenum pname, GLint64 *data, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetIntegeri_v_data(const State &glState, bool isCallValid, GLenum target, GLuint index, GLint *data, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetInternalformativ_params(const State &glState, bool isCallValid, GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params, ParamCapture *paramCapture) { // From the OpenGL ES 3.0 spec: // // The information retrieved will be written to memory addressed by the pointer specified in // params. // // No more than bufSize integers will be written to this memory. // // If pname is GL_NUM_SAMPLE_COUNTS, the number of sample counts that would be returned by // querying GL_SAMPLES will be returned in params. // // If pname is GL_SAMPLES, the sample counts supported for internalformat and target are written // into params in descending numeric order. Only positive values are returned. // // Querying GL_SAMPLES with bufSize of one will return just the maximum supported number of // samples for this format. if (bufSize == 0) return; if (params) { // For GL_NUM_SAMPLE_COUNTS, only one value is returned // For GL_SAMPLES, two values will be returned, unless bufSize limits it to one uint32_t paramCount = (pname == GL_SAMPLES && bufSize > 1) ? 2 : 1; paramCapture->readBufferSizeBytes = sizeof(GLint) * paramCount; } } void CaptureGetProgramBinary_length(const State &glState, bool isCallValid, ShaderProgramID program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary, ParamCapture *paramCapture) { if (length) { paramCapture->readBufferSizeBytes = sizeof(GLsizei); } } void CaptureGetProgramBinary_binaryFormat(const State &glState, bool isCallValid, ShaderProgramID program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary, ParamCapture *paramCapture) { paramCapture->readBufferSizeBytes = sizeof(GLenum); } void CaptureGetProgramBinary_binary(const State &glState, bool isCallValid, ShaderProgramID program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary, ParamCapture *paramCapture) { // If we have length, then actual binarySize was written there // Otherwise, we don't know how many bytes were written if (!length) { UNIMPLEMENTED(); return; } GLsizei binarySize = *length; if (binarySize > bufSize) { // This is a GL error, but clamp it anyway binarySize = bufSize; } paramCapture->readBufferSizeBytes = binarySize; } void CaptureGetQueryObjectuiv_params(const State &glState, bool isCallValid, QueryID id, GLenum pname, GLuint *params, ParamCapture *paramCapture) { // This only returns one value paramCapture->readBufferSizeBytes = sizeof(GLint); } void CaptureGetQueryiv_params(const State &glState, bool isCallValid, QueryType targetPacked, GLenum pname, GLint *params, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetSamplerParameterfv_params(const State &glState, bool isCallValid, SamplerID sampler, GLenum pname, GLfloat *params, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetSamplerParameteriv_params(const State &glState, bool isCallValid, SamplerID sampler, GLenum pname, GLint *params, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetSynciv_length(const State &glState, bool isCallValid, GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values, ParamCapture *paramCapture) { if (length) { paramCapture->readBufferSizeBytes = sizeof(GLsizei); } } void CaptureGetSynciv_values(const State &glState, bool isCallValid, GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values, ParamCapture *paramCapture) { // Spec: On success, GetSynciv replaces up to bufSize integers in values with the corresponding // property values of the object being queried. The actual number of integers replaced is // returned in *length.If length is NULL, no length is returned. if (bufSize == 0) return; if (values) { paramCapture->readBufferSizeBytes = sizeof(GLint) * bufSize; } } void CaptureGetTransformFeedbackVarying_length(const State &glState, bool isCallValid, ShaderProgramID program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetTransformFeedbackVarying_size(const State &glState, bool isCallValid, ShaderProgramID program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetTransformFeedbackVarying_type(const State &glState, bool isCallValid, ShaderProgramID program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetTransformFeedbackVarying_name(const State &glState, bool isCallValid, ShaderProgramID program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetUniformBlockIndex_uniformBlockName(const State &glState, bool isCallValid, ShaderProgramID program, const GLchar *uniformBlockName, ParamCapture *paramCapture) { CaptureString(uniformBlockName, paramCapture); } void CaptureGetUniformIndices_uniformNames(const State &glState, bool isCallValid, ShaderProgramID program, GLsizei uniformCount, const GLchar *const *uniformNames, GLuint *uniformIndices, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetUniformIndices_uniformIndices(const State &glState, bool isCallValid, ShaderProgramID program, GLsizei uniformCount, const GLchar *const *uniformNames, GLuint *uniformIndices, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetUniformuiv_params(const State &glState, bool isCallValid, ShaderProgramID program, UniformLocation location, GLuint *params, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetVertexAttribIiv_params(const State &glState, bool isCallValid, GLuint index, GLenum pname, GLint *params, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureGetVertexAttribIuiv_params(const State &glState, bool isCallValid, GLuint index, GLenum pname, GLuint *params, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureInvalidateFramebuffer_attachments(const State &glState, bool isCallValid, GLenum target, GLsizei numAttachments, const GLenum *attachments, ParamCapture *paramCapture) { CaptureMemory(attachments, sizeof(GLenum) * numAttachments, paramCapture); paramCapture->value.voidConstPointerVal = paramCapture->data[0].data(); } void CaptureInvalidateSubFramebuffer_attachments(const State &glState, bool isCallValid, GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureProgramBinary_binary(const State &glState, bool isCallValid, ShaderProgramID program, GLenum binaryFormat, const void *binary, GLsizei length, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureSamplerParameterfv_param(const State &glState, bool isCallValid, SamplerID sampler, GLenum pname, const GLfloat *param, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureSamplerParameteriv_param(const State &glState, bool isCallValid, SamplerID sampler, GLenum pname, const GLint *param, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureTexImage3D_pixels(const State &glState, bool isCallValid, TextureTarget targetPacked, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels, ParamCapture *paramCapture) { if (glState.getTargetBuffer(gl::BufferBinding::PixelUnpack)) { return; } if (!pixels) { return; } const gl::InternalFormat &internalFormatInfo = gl::GetInternalFormatInfo(format, type); const gl::PixelUnpackState &unpack = glState.getUnpackState(); const Extents size(width, height, depth); GLuint endByte = 0; bool unpackSize = internalFormatInfo.computePackUnpackEndByte(type, size, unpack, true, &endByte); ASSERT(unpackSize); CaptureMemory(pixels, static_cast<size_t>(endByte), paramCapture); } void CaptureTexSubImage3D_pixels(const State &glState, bool isCallValid, TextureTarget targetPacked, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels, ParamCapture *paramCapture) { CaptureTexImage3D_pixels(glState, isCallValid, targetPacked, level, 0, width, height, depth, 0, format, type, pixels, paramCapture); } void CaptureTransformFeedbackVaryings_varyings(const State &glState, bool isCallValid, ShaderProgramID program, GLsizei count, const GLchar *const *varyings, GLenum bufferMode, ParamCapture *paramCapture) { for (GLsizei index = 0; index < count; ++index) { CaptureString(varyings[index], paramCapture); } } void CaptureUniform1uiv_value(const State &glState, bool isCallValid, UniformLocation location, GLsizei count, const GLuint *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureUniform2uiv_value(const State &glState, bool isCallValid, UniformLocation location, GLsizei count, const GLuint *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureUniform3uiv_value(const State &glState, bool isCallValid, UniformLocation location, GLsizei count, const GLuint *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureUniform4uiv_value(const State &glState, bool isCallValid, UniformLocation location, GLsizei count, const GLuint *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureUniformMatrix2x3fv_value(const State &glState, bool isCallValid, UniformLocation location, GLsizei count, GLboolean transpose, const GLfloat *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureUniformMatrix2x4fv_value(const State &glState, bool isCallValid, UniformLocation location, GLsizei count, GLboolean transpose, const GLfloat *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureUniformMatrix3x2fv_value(const State &glState, bool isCallValid, UniformLocation location, GLsizei count, GLboolean transpose, const GLfloat *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureUniformMatrix3x4fv_value(const State &glState, bool isCallValid, UniformLocation location, GLsizei count, GLboolean transpose, const GLfloat *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureUniformMatrix4x2fv_value(const State &glState, bool isCallValid, UniformLocation location, GLsizei count, GLboolean transpose, const GLfloat *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureUniformMatrix4x3fv_value(const State &glState, bool isCallValid, UniformLocation location, GLsizei count, GLboolean transpose, const GLfloat *value, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureVertexAttribI4iv_v(const State &glState, bool isCallValid, GLuint index, const GLint *v, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureVertexAttribI4uiv_v(const State &glState, bool isCallValid, GLuint index, const GLuint *v, ParamCapture *paramCapture) { UNIMPLEMENTED(); } void CaptureVertexAttribIPointer_pointer(const State &glState, bool isCallValid, GLuint index, GLint size, VertexAttribType typePacked, GLsizei stride, const void *pointer, ParamCapture *paramCapture) { CaptureVertexAttribPointer_pointer(glState, isCallValid, index, size, typePacked, false, stride, pointer, paramCapture); } } // namespace gl
bsd-3-clause
markfinal/BuildAMation
tests/CodeGenTest/bam/Scripts/TestApp.cs
1985
#region License // Copyright (c) 2010-2019, Mark Final // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License using CodeGenTest.CodeGenExtension; namespace CodeGenTest { sealed class TestApp : C.ConsoleApplication { protected override void Init() { base.Init(); var source = this.CreateCSourceCollection("$(packagedir)/source/testapp/main.c"); /*var generatedSourceTuple = */source.GenerateSource(); } } }
bsd-3-clause
fleurdeswift/webdeveloper
Runtime/NodeLight/NodeBuffer.h
245
// // NodeBuffer.h // NodeLight // #import <JavaScriptCore/JavaScriptCore.h> JSClassRef NodeBufferClass(); void NodeBufferExpose(JSContextRef context, JSValueRef* exception); JSValueRef JSValueFromNSData(JSContextRef context, NSData *data);
bsd-3-clause
frankpaul142/aurasur
vendor/paypal/rest-api-sdk-php/sample/invoice/CancelInvoice.php
1327
<?php // # Cancel Invoice Sample // This sample code demonstrate how you can cancel // an invoice. /** @var Invoice $invoice */ $invoice = require 'SendInvoice.php'; use PayPal\Api\Invoice; use PayPal\Api\CancelNotification; try { // ### Cancel Notification Object // This would send a notification to both merchant as well // the payer about the cancellation. The information of // merchant and payer is retrieved from the invoice details $notify = new CancelNotification(); $notify ->setSubject("Past due") ->setNote("Canceling invoice") ->setSendToMerchant(true) ->setSendToPayer(true); // ### Cancel Invoice // Cancel invoice object by calling the // static `cancel` method // on the Invoice class by passing a valid // notification object // (See bootstrap.php for more on `ApiContext`) $cancelStatus = $invoice->cancel($notify, $apiContext); } catch (Exception $ex) { // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY ResultPrinter::printError("Cancel Invoice", "Invoice", null, $notify, $ex); exit(1); } // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY ResultPrinter::printResult("Cancel Invoice", "Invoice", $invoice->getId(), $notify, null);
bsd-3-clause
pgaultier/sweelix-yii2-plupload
src/behaviors/AutomaticUpload.php
19061
<?php /** * AutomaticUpload.php * * PHP version 5.4+ * * @author Philippe Gaultier <[email protected]> * @copyright 2010-2014 Sweelix * @license http://www.sweelix.net/license license * @version 1.0.3 * @link http://www.sweelix.net * @category behaviors * @package sweelix.yii2.plupload.behaviors */ namespace sweelix\yii2\plupload\behaviors; use sweelix\yii2\plupload\components\UploadedFile; use yii\base\Behavior; use yii\base\InvalidParamException; use yii\validators\FileValidator; use yii\db\ActiveRecord; use yii\helpers\Json; use yii\helpers\Html; use Yii; use Exception; /** * This UploadedFile handle automagically the upload process in * models * * @author Philippe Gaultier <[email protected]> * @copyright 2010-2014 Sweelix * @license http://www.sweelix.net/license license * @version 1.0.3 * @link http://www.sweelix.net * @category behaviors * @package sweelix.yii2.plupload.behaviors * @since 1.0.0 */ class AutomaticUpload extends Behavior { /** * @var array handled attributes */ public $attributes=[]; /** * @var string define locale for sanitize (it would probably be better to use Yii::$app locale) */ public static $sanitizeLocale = 'fr_FR.UTF8'; /** * @var callable function used to serialize attributes. default to json */ public $serializeCallback; /** * @var callable function used to unserialize attributes. default to json */ public $unserializeCallback; /** * @var boolean check if we must wayt for afterInsert to save the files */ protected $modelShouldBeSaved = false; /** * @var boolean check if we are "re-saving" data in afterSave (when we recompute the path) */ protected $modelIsUpdating = false; /** * List of tracked events * * @return array * @since 1.0.0 */ public function events() { return [ // ActiveRecord::EVENT_INIT => 'afterInit', ActiveRecord::EVENT_AFTER_FIND => 'afterFind', ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert', ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert', ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate', ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate', ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete', ]; } /** * Serialize file attribute when multifile upload is active * * @param string $attribute the attribute name * * @return void * @since 1.0.0 */ protected function serializeAttribute($attribute) { if ($this->isMultifile($attribute) === true) { if (is_callable($this->serializeCallback) === true) { $this->owner->{$attribute} = call_user_func([$this, 'serializeCallback'], $this->owner->{$attribute}); } else { $data = $this->owner->{$attribute}; if (is_array($data) === true) { $data = array_filter($data, function($el) { return (empty($el) === false); }); } $this->owner->{$attribute} = Json::encode($data); } } else { $realData = $this->owner->{$attribute}; if (is_array($realData) === true) { $realData = array_pop($realData); } $this->owner->{$attribute} = $realData; } } /** * Unserialize file attribute when multifile upload is active * * @param string $attribute the attribute name * * @return void * @since 1.0.0 */ protected function unserializeAttribute($attribute) { if (self::isMultifile($attribute) === true) { if (is_callable($this->unserializeCallback) === true) { $attributeContent = call_user_func([$this, 'unserializeCallback'], $this->owner->{$attribute}); } else { try { $attributeContent = Json::decode($this->owner->{$attribute}); } catch (InvalidParamException $e) { $attributeContent = []; } } if ((is_array($attributeContent) === false) && (empty($attributeContent) === false)) { $attributeContent = [$attributeContent]; } $this->owner->{$attribute} = $attributeContent; } } /** * Clean up file name * * @param string $name file name to sanitize * * @return string * @since 1.0.0 */ public static function sanitize($name) { // we can sanitize file a litlle better anyway, this should tdo the trick with all noob users setlocale(LC_ALL, self::$sanitizeLocale); $name = iconv('utf-8', 'ASCII//TRANSLIT//IGNORE', $name); setlocale(LC_ALL, 0); return preg_replace('/([^a-z0-9\._\-])+/iu', '-', $name); } /** * Check if current attribute support multifile * * @param string $attribute check if file attribute support multifile * * @return boolean * @since 1.0.0 */ public function isMultifile($attribute) { $config = $this->getValidatorConfig($attribute); return $config['multiFile']; } /** * Get max file size allowed for the attribute * * @param string $attribute the source attribute * * @return integer * @since 1.0.1 */ public function getMaxFileSize($attribute) { $config = $this->getValidatorConfig($attribute); return (int)$config['maxFileSize']; } /** * Get file extensions allowed for the attribute * * @param string $attribute the source attribute * * @return string * @since 1.0.1 */ public function getFileExtensions($attribute) { $config = $this->getValidatorConfig($attribute); return $config['allowedExtensions']; } /** * @var array lazy loaded file information */ private static $validatorConfig = []; /** * Retrieve the validator configuration * * @param string $attribute attribute which is validated * * @return array * @since 1.0.1 */ protected function getValidatorConfig($attribute) { if (isset(self::$validatorConfig[$attribute]) === false) { self::$validatorConfig[$attribute] = false; $config = [ 'multiFile' => false, 'maxFileSize' => 0, 'allowedExtensions' => null, ]; foreach ($this->owner->getActiveValidators($attribute) as $validator) { if ($validator instanceof FileValidator) { // we can set all the parameters if ($validator->maxFiles > 1) { // multi add brackets $config['multiFile'] = true; } if (empty($validator->extensions) === false) { $config['allowedExtensions'] = implode(',', $validator->extensions); } if (($validator->maxSize !== null) && ($validator->maxSize > 0)) { $config['maxFileSize'] = $validator->maxSize; } // we should not have multiple file validators for the same file break; } } self::$validatorConfig[$attribute] = $config; } return self::$validatorConfig[$attribute]; } /** * Perform file save before insert if we can * If not, we delay the file processing on after insert * * @return void * @since 1.0.0 */ public function beforeInsert() { foreach ($this->attributes as $attribute => $config) { if ($this->shouldExpandAliasPath($attribute) === true) { $this->modelShouldBeSaved = true; break; } } if ($this->modelShouldBeSaved === false) { $this->beforeUpdate(); } else { foreach ($this->attributes as $attribute => $config) { $this->serializeAttribute($attribute); } } } /** * Perform file save after insert if we need to recompute the path * * @return void * @since 1.0.0 */ public function afterInsert() { if ($this->modelShouldBeSaved === true) { // avoid to save everything twice $this->modelShouldBeSaved = false; foreach ($this->attributes as $attribute => $config) { $this->unserializeAttribute($attribute); } $this->beforeUpdate(); $attributes = array_keys($this->attributes); $sAttributes = []; foreach ($attributes as $attribute) { $sAttributes[$attribute] = $this->owner->{$attribute}; } if (empty($sAttributes) === false) { $condition = $this->owner->getPrimaryKey(true); $modelClass = get_class($this->owner); $command = $modelClass::getDb()->createCommand(); $command->update($modelClass::tableName(), $sAttributes, $condition); $command->execute(); } foreach ($this->attributes as $attribute => $config) { $this->unserializeAttribute($attribute); } } } /** * Unserialize attributes * * @return void * @since 1.0.0 */ public function afterFind() { foreach ($this->attributes as $attribute => $config) { $this->unserializeAttribute($attribute); } } /** * Remove useless data from the properties and return a clean array * * @param array $propertyData property files * * @return array * @since 1.0.0 */ protected function cleanUpProperty($propertyData) { $propertyData = array_map(function ($el) { return trim($el); }, $propertyData); return array_filter($propertyData); } /** * Like insert but we will never need to recompute the key * * @return void * @since 1.0.0 */ public function beforeUpdate() { foreach ($this->attributes as $attribute => $config) { $aliasPath = $this->getAliasPath($attribute, true); if (is_array($this->owner->{$attribute}) === false) { if (empty($this->owner->{$attribute}) === false) { $this->owner->{$attribute} = [$this->owner->{$attribute}]; } else { $this->owner->{$attribute} = []; } } // clean up attributes $this->owner->{$attribute} = $this->cleanUpProperty($this->owner->{$attribute}); $selectedFiles = $this->owner->{$attribute}; $savedFiles = []; $attributeName = Html::getInputName($this->owner, $attribute); $uploadedFiles = UploadedFile::getInstancesByName($attributeName); foreach ($uploadedFiles as $instance) { if (in_array($instance->name, $selectedFiles) === true) { $fileName = static::sanitize($instance->name); if (empty($instance->tempName) === true) { // image was uploaded earlier // we should probably check if image is always available $savedFiles[] = $fileName; } else { $targetFile = Yii::getAlias($aliasPath.'/'.$fileName); $targetPath = pathinfo($targetFile, PATHINFO_DIRNAME); if (is_dir($targetPath) === false) { if (mkdir($targetPath, 0755, true) === false) { throw new Exception('Unable to create path : "'.$targetPath.'"'); } } if ($instance->saveAs($targetFile) === true) { //TODO: saved files must be removed - correct place would be in UploadedFile $savedFiles[] = $fileName; } } } } $this->owner->{$attribute} = $savedFiles; $this->serializeAttribute($attribute); } } /** * Should only reset attributes as expected * * @return void * @since 1.0.0 */ public function afterUpdate() { // UploadedFile::reset(); if ($this->modelIsUpdating === false) { foreach ($this->attributes as $attribute => $config) { $this->unserializeAttribute($attribute); } } } /** * Check if attibute is handled automagically * * @param string $attribute attribute to check * * @return boolean * @since 1.0.0 */ public function isAutomatic($attribute) { return array_key_exists($attribute, $this->attributes); } /** * Return current file(s) attribute with the(ir) full path * * @param string $attribute attribute to retrieve * @param boolean $expanded should we expand parameters if they are used in the path * * @return mixed * @since 1.0.0 */ public function getAsFilePath($attribute, $expanded = false) { if (($this->isMultifile($attribute) === true) && (is_array($this->owner->{$attribute}) === true) && (empty($this->owner->{$attribute}) === false)) { return array_map(function ($el) use ($attribute, $expanded) { return Yii::getAlias($this->getAliasPath($attribute, $expanded).'/'.$el); }, $this->owner->{$attribute}); } elseif (empty($this->owner->{$attribute}) === false) { return Yii::getAlias($this->getAliasPath($attribute, $expanded).'/'.$this->owner->{$attribute}); } else { return null; } } /** * Return current file(s) attribute with the(ir) full url * * @param string $attribute attribute to retrieve * @param boolean $expanded should we expand parameters if they are used in the url * * @return mixed * @since 1.0.0 */ public function getAsFileUrl($attribute, $expanded = false) { if (($this->isMultifile($attribute) === true) && (is_array($this->owner->{$attribute}) === true)) { return array_map(function ($el) use ($attribute, $expanded) { return Yii::getAlias($this->getAliasUrl($attribute, $expanded).'/'.$el); }, $this->owner->{$attribute}); } elseif (empty($this->owner->{$attribute}) === false) { return Yii::getAlias($this->getAliasUrl($attribute, $expanded).'/'.$this->owner->{$attribute}); } else { return null; } } /** * Get Alias path for selected attribute * * @param string $attribute name of selected attribute * @param boolean $expand should we expand the alias path with model values * * @return string * @since 1.0.0 */ public function getAliasPath($attribute, $expand = false) { if (isset($this->attributes[$attribute]['basePath']) === true) { $basePath = $this->attributes[$attribute]['basePath']; if ($expand === true) { $expansionVars = $this->getAliasPathExpansionVars($attribute); if (empty($expansionVars) === false) { $basePath = str_replace(array_keys($expansionVars), array_values($expansionVars), $basePath); } } return $basePath; } else { return '@webroot'; } } /** * Check if current path should be expanded * * @param string $attribute attribute to check * * @return boolean * @since 1.0.0 */ public function shouldExpandAliasPath($attribute) { $aliasPath = $this->getAliasPath($attribute); return (preg_match_all('/{([^}]+)}/', $aliasPath)>0); } /** * Get variables used for path expansion * * @param string $attribute attribute to check * * @return mixed * @since 1.0.0 */ public function getAliasPathExpansionVars($attribute) { $expansionVars = []; $aliasPath = $this->getAliasPath($attribute); if ($aliasPath !== null) { $nbMatches = preg_match_all('/{([^}]+)}/', $aliasPath, $matches); if ($nbMatches > 0) { foreach ($matches[1] as $expandAttribute) { $expansionVars['{'.$expandAttribute.'}'] = $this->owner->{$expandAttribute}; } } } return (empty($expansionVars) === true)?null:$expansionVars; } /** * Get Alias URL for selected attribute * * @param string $attribute name of selected attribute * @param boolean $expand should we expand the alias url with model values * * @return string * @since 1.0.0 */ public function getAliasUrl($attribute, $expand = false) { if (isset($this->attributes[$attribute]['baseUrl']) === true) { $baseUrl = $this->attributes[$attribute]['baseUrl']; if ($expand === true) { $expansionVars = $this->getAliasUrlExpansionVars($attribute); if (empty($expansionVars) === false) { $baseUrl = str_replace(array_keys($expansionVars), array_values($expansionVars), $baseUrl); } } return $baseUrl; } else { return '@web'; } } /** * Check if current URL should be expanded * * @param string $attribute attribute to check * * @return boolean * @since 1.0.0 */ public function shouldExpandAliasUrl($attribute) { $aliasUrl = $this->getAliasUrl($attribute); return (preg_match_all('/{([^}]+)}/', $aliasUrl)>0); } /** * Get variables used for URL expansion * * @param string $attribute attribute to check * * @return mixed * @since 1.0.0 */ public function getAliasUrlExpansionVars($attribute) { $expansionVars = []; $aliasUrl = $this->getAliasUrl($attribute); if ($aliasUrl !== null) { $nbMatches = preg_match_all('/{([^}]+)}/', $aliasUrl, $matches); if ($nbMatches > 0) { foreach ($matches[1] as $expandAttribute) { $expansionVars['{'.$expandAttribute.'}'] = $this->owner->{$expandAttribute}; } } } return (empty($expansionVars) === true)?null:$expansionVars; } }
bsd-3-clause
microdisk/customre_website
frontend/models/ActivationCodeResetRequestForm.php
1755
<?php namespace frontend\models; use Yii; use yii\base\Model; use common\models\User; /** * Activation reset request form */ class ActivationCodeResetRequestForm extends Model { // Init Public Constants const STATUS_SUCCESS = 100; const STATUS_ERROR_ACCOUNT_ALREADY_ACTIVATED = 200; const STATUS_ERROR_ACCOUNT_NOT_FOUND = 300; const STATUS_ERROR_MAIL_NOT_SENT = 400; // Init Public Variables public $email; /** * @inheritdoc */ public function rules() { return [ [ 'email', 'trim' ], [ 'email', 'required' ], [ 'email', 'email' ], [ 'email', 'exist', 'targetClass' => '\common\models\User', 'filter' => [ 'status' => User::STATUS_ACTIVE ], 'message' => 'There is no user with such email.' ] ]; } /** * Sends an email with a link, for resetting the password. * * @return bool whether the email was send */ public function sendEmail() { /* @var $user User */ $user = User::findOne ( [ 'status' => User::STATUS_ACTIVE, 'email' => $this->email ] ); if (! $user) { return self::STATUS_ERROR_ACCOUNT_NOT_FOUND; } if (! $user->ActivationDateTime == null) { return self::STATUS_ERROR_ACCOUNT_ALREADY_ACTIVATED; } // Send an Email if (Yii::$app->mailer->compose ( "accountActivation", [ 'model' => $user ] )->setTo ( array ( $user->email => $user->FirstName ) )->setFrom ( array ( Yii::$app->params ['adminEmail'] => 'Custom Reminder Administrator' ) )->setSubject ( 'Account Activation Required for ' . $user->FirstName )->send () == true) { return self::STATUS_SUCCESS; } else { return self::STATUS_ERROR_MAIL_NOT_SENT; } } }
bsd-3-clause
avinashc89/grpc_273
PollService/build/docs/javadoc/constant-values.html
6992
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_40) on Mon Mar 23 05:48:17 UTC 2015 --> <title>Constant Field Values (grpc-PollService 0.1.0-SNAPSHOT API)</title> <meta name="date" content="2015-03-23"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> <script type="text/javascript" src="script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Constant Field Values (grpc-PollService 0.1.0-SNAPSHOT API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="edu/sjsu/cmpe273/lab2/package-summary.html">Package</a></li> <li>Class</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?constant-values.html" target="_top">Frames</a></li> <li><a href="constant-values.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Constant Field Values" class="title">Constant Field Values</h1> <h2 title="Contents">Contents</h2> <ul> <li><a href="#edu.sjsu">edu.sjsu.*</a></li> </ul> </div> <div class="constantValuesContainer"><a name="edu.sjsu"> <!-- --> </a> <h2 title="edu.sjsu">edu.sjsu.*</h2> <ul class="blockList"> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>edu.sjsu.cmpe273.lab2.<a href="edu/sjsu/cmpe273/lab2/PollRequest.html" title="class in edu.sjsu.cmpe273.lab2">PollRequest</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="edu.sjsu.cmpe273.lab2.PollRequest.CHOICE_FIELD_NUMBER"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="edu/sjsu/cmpe273/lab2/PollRequest.html#CHOICE_FIELD_NUMBER">CHOICE_FIELD_NUMBER</a></code></td> <td class="colLast"><code>5</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="edu.sjsu.cmpe273.lab2.PollRequest.EXPIREDAT_FIELD_NUMBER"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="edu/sjsu/cmpe273/lab2/PollRequest.html#EXPIREDAT_FIELD_NUMBER">EXPIREDAT_FIELD_NUMBER</a></code></td> <td class="colLast"><code>4</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="edu.sjsu.cmpe273.lab2.PollRequest.MODERATORID_FIELD_NUMBER"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="edu/sjsu/cmpe273/lab2/PollRequest.html#MODERATORID_FIELD_NUMBER">MODERATORID_FIELD_NUMBER</a></code></td> <td class="colLast"><code>1</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="edu.sjsu.cmpe273.lab2.PollRequest.QUESTION_FIELD_NUMBER"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="edu/sjsu/cmpe273/lab2/PollRequest.html#QUESTION_FIELD_NUMBER">QUESTION_FIELD_NUMBER</a></code></td> <td class="colLast"><code>2</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="edu.sjsu.cmpe273.lab2.PollRequest.STARTEDAT_FIELD_NUMBER"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="edu/sjsu/cmpe273/lab2/PollRequest.html#STARTEDAT_FIELD_NUMBER">STARTEDAT_FIELD_NUMBER</a></code></td> <td class="colLast"><code>3</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>edu.sjsu.cmpe273.lab2.<a href="edu/sjsu/cmpe273/lab2/PollResponse.html" title="class in edu.sjsu.cmpe273.lab2">PollResponse</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="edu.sjsu.cmpe273.lab2.PollResponse.ID_FIELD_NUMBER"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="edu/sjsu/cmpe273/lab2/PollResponse.html#ID_FIELD_NUMBER">ID_FIELD_NUMBER</a></code></td> <td class="colLast"><code>1</code></td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="edu/sjsu/cmpe273/lab2/package-summary.html">Package</a></li> <li>Class</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?constant-values.html" target="_top">Frames</a></li> <li><a href="constant-values.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
bsd-3-clause
sahara108/apptentive-ios
ApptentiveConnect/source/ATConnect.h
20486
// // ATConnect.h // ApptentiveConnect // // Created by Andrew Wooster on 3/12/11. // Copyright 2011 Apptentive, Inc.. All rights reserved. // #if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #elif TARGET_OS_MAC #import <Cocoa/Cocoa.h> #endif #define kATConnectVersionString @"2.0.2" #if TARGET_OS_IPHONE # define kATConnectPlatformString @"iOS" #elif TARGET_OS_MAC # define kATConnectPlatformString @"Mac OS X" @class ATFeedbackWindowController; #endif @protocol ATConnectDelegate; /** Notification sent when Message Center unread messages count changes. */ extern NSString *const ATMessageCenterUnreadCountChangedNotification; /** Notification sent when the user has agreed to rate the application. */ extern NSString *const ATAppRatingFlowUserAgreedToRateAppNotification; /** Notification sent when a survey is shown. */ extern NSString *const ATSurveyShownNotification; /** Notification sent when a survey is submitted by the user. */ extern NSString *const ATSurveySentNotification; /** When a survey is shown or sent, notification's userInfo dictionary will contain the ATSurveyIDKey key. Value is the ID of the survey that was shown or sent. */ extern NSString *const ATSurveyIDKey; /** Supported Push Providers for use in `setPushNotificationIntegration:withDeviceToken:` */ typedef NS_ENUM(NSInteger, ATPushProvider){ ATPushProviderApptentive, ATPushProviderUrbanAirship, ATPushProviderAmazonSNS, ATPushProviderParse, }; /** `ATConnect` is a singleton which is used as the main point of entry for the Apptentive service. ## Configuration Before calling any other methods on the shared `ATConnect` instance, set the API key: [[ATConnect sharedConnection].apiKey = @"your API key here"; ## Engagement Events The Ratings Prompt and other Apptentive interactions are targeted to certain Apptentive events. For example, you could decide to show the Ratings Prompt after an event named "user_completed_level" has been engaged. You can later reconfigure the Ratings Prompt interaction to instead show after engaging "user_logged_in". You would add calls at these points to optionally engage with the user: [[ATConnect sharedConnection] engage:@"completed_level" fromViewController:viewController]; See the readme for more information. ## Notifications `ATMessageCenterUnreadCountChangedNotification` Sent when the number of unread messages changes. The notification object is undefined. The `userInfo` dictionary contains a `count` key, the value of which is the number of unread messages. `ATAppRatingFlowUserAgreedToRateAppNotification` Sent when the user has agreed to rate the application. `ATSurveySentNotification` Sent when a survey is submitted by the user. The userInfo dictionary will have a key named `ATSurveyIDKey`, with a value of the id of the survey that was sent. ## Integrations Keys for currently supported integrations: * `ATIntegrationKeyApptentive` - For Apptentive Push * `ATIntegrationKeyUrbanAirship` - For Urban Airship * `ATIntegrationKeyAmazonSNS` - For Amazon SNS * `ATIntegrationKeyKahuna` - For Kahuna * `ATIntegrationKeyParse` - For Parse */ @protocol ATConnectOurDelegate <NSObject> @optional -(NSString*)answerForHiddenQuestion:(NSString*)question; -(void)didCompletedSurvey; -(void)didCancelSurvey; -(void)willPresentSurvey; @end @interface ATConnect : NSObject { @private #if TARGET_OS_IPHONE UIColor *tintColor; #elif TARGET_OS_MAC ATFeedbackWindowController *feedbackWindowController; #endif NSMutableDictionary *customPersonData; NSMutableDictionary *customDeviceData; NSMutableDictionary *integrationConfiguration; NSString *apiKey; BOOL showEmailField; NSString *initialUserName; NSString *initialUserEmailAddress; NSString *customPlaceholderText; BOOL useMessageCenter; } @property (nonatomic, assign) id<ATConnectOurDelegate>atDelegate; ///--------------------------------- /// @name Basic Usage ///--------------------------------- /** The API key for Apptentive. This key is found on the Apptentive website under Settings, API & Development. */ @property (nonatomic, copy) NSString *apiKey; /** The app's iTunes App ID. You can find this in iTunes Connect, and is the numeric "Apple ID" shown on your app details page. */ @property (nonatomic, copy) NSString *appID; /** The shared singleton of `ATConnect`. */ + (ATConnect *)sharedConnection; /** An object conforming to the `ATConnectDelegate` protocol */ @property (nonatomic, weak) id<ATConnectDelegate> delegate; ///--------------------------------- /// @name Interface Customization ///--------------------------------- /** Toggles the display of an email field in the message panel. `YES` by default. */ @property (nonatomic, assign) BOOL showEmailField; /** Set this if you want some custom text to appear as a placeholder in the feedback text box. */ @property (nonatomic, copy) NSString *customPlaceholderText; #if TARGET_OS_IPHONE /** A tint color to use in Apptentive-specific UI. Overrides the default tintColor acquired from your app, in case you're using one that doesn't look great with Apptentive-specific UI. @deprecated Use `[UIAppearance appearanceWhenContainedIn:[ATNavigationController class], nil].tintColor` */ @property (nonatomic, strong) UIColor *tintColor DEPRECATED_ATTRIBUTE; #endif //@tuan.nguyen: our custom methods -(NSString*)answerForHiddenQuestion:(NSString*)question; -(void)didCompletedSurvey; -(void)didCancelSurvey; -(void)willPresentSurvey; #if TARGET_OS_IPHONE ///-------------------- /// @name Presenting UI ///-------------------- /** Determines if Message Center will be displayed when `presentMessageCenterFromViewController:` is called. If app has not yet synced with Apptentive, you will be unable to display Message Center. Use `canShowMessageCenter` to determine if Message Center is ready to be displayed. If Message Center is not ready you could, for example, hide the "Message Center" button in your interface. **/ - (BOOL)canShowMessageCenter; /** Presents Message Center modally from the specified view controller. If the SDK has yet to sync with the Apptentive server, this method returns NO and displays a "We're attempting to connect" view in place of Message Center. @param viewController The view controller from which to present Message Center. @return `YES` if Message Center was presented, `NO` otherwise. */ - (BOOL)presentMessageCenterFromViewController:(UIViewController *)viewController; /** Presents Message Center from a given view controller with custom data. If the SDK has yet to sync with the Apptentive server, this method returns NO and displays a "We're attempting to connect" view in place of Message Center. @param viewController The view controller from which to present Message Center. @param customData A dictionary of key/value pairs to be associated with any messages sent via Message Center. @return `YES` if Message Center was presented, `NO` otherwise. */ - (BOOL)presentMessageCenterFromViewController:(UIViewController *)viewController withCustomData:(NSDictionary *)customData; /** Returns the current number of unread messages in Message Center. These are the messages sent via the Apptentive website to this user. @return The number of unread messages. */ - (NSUInteger)unreadMessageCount; /** Returns a "badge" than can be used as a UITableViewCell accessoryView to indicate the current number of unread messages. To keep this value updated, your view controller will must register for `ATMessageCenterUnreadCountChangedNotification` and reload the table view cell when a notification is received. @param apptentiveHeart A Boolean value indicating whether to include a heart logo adjacent to the number. @return A badge view suitable for use as a table view cell accessory view. */ - (UIView *)unreadMessageCountAccessoryView:(BOOL)apptentiveHeart; /** Forwards a push notification from your application delegate to Apptentive Connect. If the push notification originated from Apptentive, Message Center will be presented from the view controller. @param userInfo The `userInfo` dictionary of the notification. @param viewController The view controller Message Center may be presented from. */ - (void)didReceiveRemoteNotification:(NSDictionary *)userInfo fromViewController:(UIViewController *)viewController; /** Deprecated in 2.0.0 in favor of the better-named `canShowInteractionForEvent:` @param event A string representing the name of the event. @return `YES` if the event will show an interaction, `NO` otherwise. */ - (BOOL)willShowInteractionForEvent:(NSString *)event DEPRECATED_ATTRIBUTE; /** Returns a Boolean value indicating whether the given event will cause an Interaction to be shown. For example, returns YES if a survey is ready to be shown the next time you engage your survey-targeted event. You can use this method to hide a "Show Survey" button in your app if there is no survey to take. @param event A string representing the name of the event. @return `YES` if the event will show an interaction, `NO` otherwise. */ - (BOOL)canShowInteractionForEvent:(NSString *)event; /** Shows interaction UI, if applicable, related to a given event. For example, if you have an upgrade message to display on app launch, you might call with event label set to `@"app.launch"` here, along with the view controller an upgrade message might be displayed from. @param event A string representing the name of the event. @param viewController A view controller Apptentive UI may be presented from. @return `YES` if an interaction was triggered by the event, `NO` otherwise. */ - (BOOL)engage:(NSString *)event fromViewController:(UIViewController *)viewController; /** Shows interaction UI, if applicable, related to a given event, and attaches the specified custom data to the event. @param event A string representing the name of the event. @param customData A dictionary of key/value pairs to be associated with the event. Keys and values should conform to standards of NSJSONSerialization's `isValidJSONObject:`. @param viewController A view controller Apptentive UI may be presented from. @return `YES` if an interaction was triggered by the event, `NO` otherwise. */ - (BOOL)engage:(NSString *)event withCustomData:(NSDictionary *)customData fromViewController:(UIViewController *)viewController; /** Shows interaction UI, if applicable, related to a given event. Attaches the specified custom data to the event along with the specified extended data. @param event A string representing the name of the event. @param customData A dictionary of key/value pairs to be associated with the event. Keys and values should conform to standards of NSJSONSerialization's `isValidJSONObject:`. @param extendedData An array of dictionaries with specific Apptentive formatting. For example, [ATConnect extendedDataDate:[NSDate date]]. @param viewController A view controller Apptentive UI may be presented from. @return `YES` if an interaction was triggered by the event, `NO` otherwise. */ - (BOOL)engage:(NSString *)event withCustomData:(NSDictionary *)customData withExtendedData:(NSArray *)extendedData fromViewController:(UIViewController *)viewController; /** Dismisses Message Center. @param animated `YES` to animate the dismissal, otherwise `NO`. @param completion A block called at the conclusion of the message center being dismissed. @discussion Under normal circumstances, Message Center will be dismissed by the user tapping the Close button, so it is not necessary to call this method. */ - (void)dismissMessageCenterAnimated:(BOOL)animated completion:(void (^)(void))completion; #elif TARGET_OS_MAC ///--------------------------- /// @name Presenting UI (OS X) ///--------------------------- /** Presents a feedback window (OS X framework only). @param sender The originator of the action. */ - (IBAction)showFeedbackWindow:(id)sender; #endif ///-------------------- /// @name Extended Data for Events ///-------------------- /** Used to specify a point in time in an event's extended data. @param date A date and time to be included in an event's extended data. @return An extended data dictionary representing a point in time, to be included in an event's extended data. */ + (NSDictionary *)extendedDataDate:(NSDate *)date; /** Used to specify a geographic coordinate in an event's extended data. @param latitude A location's latitude coordinate. @param longitude A location's longitude coordinate. @return An extended data dictionary representing a geographic coordinate, to be included in an event's extended data. */ + (NSDictionary *)extendedDataLocationForLatitude:(double)latitude longitude:(double)longitude; /** Used to specify a commercial transaction (incorporating multiple items) in an event's extended data. @param transactionID The transaction's ID. @param affiliation The store or affiliation from which this transaction occurred. @param revenue The transaction's revenue. @param shipping The transaction's shipping cost. @param tax Tax on the transaction. @param currency Currency for revenue/shipping/tax values. @param commerceItems An array of commerce items contained in the transaction. Create commerce items with [ATConnect extendedDataCommerceItemWithItemID:name:category:price:quantity:currency:]. @return An extended data dictionary representing a commerce transaction, to be included in an event's extended data. */ + (NSDictionary *)extendedDataCommerceWithTransactionID:(NSString *)transactionID affiliation:(NSString *)affiliation revenue:(NSNumber *)revenue shipping:(NSNumber *)shipping tax:(NSNumber *)tax currency:(NSString *)currency commerceItems:(NSArray *)commerceItems; /** Used to specify a commercial transaction (consisting of a single item) in an event's extended data. @param itemID The transaction item's ID. @param name The transaction item's name. @param category The transaction item's category. @param price The individual item price. @param quantity The number of units purchased. @param currency Currency for price. @return An extended data dictionary representing a single item in a commerce transaction, to be included in an event's extended data. */ + (NSDictionary *)extendedDataCommerceItemWithItemID:(NSString *)itemID name:(NSString *)name category:(NSString *)category price:(NSNumber *)price quantity:(NSNumber *)quantity currency:(NSString *)currency; ///------------------------------------- /// @name Attach Text, Images, and Files ///------------------------------------- /** Attaches text to the user's feedback. This will appear in your online Apptentive dashboard, but will *not* appear in Message Center on the device. @param text The text to attach to the user's feedback as a file. */ - (void)sendAttachmentText:(NSString *)text; /** Attaches an image the user's feedback. This will appear in your online Apptentive dashboard, but will *not* appear in Message Center on the device. @param image The image to attach to the user's feedback as a file. */ - (void)sendAttachmentImage:(UIImage *)image; /** Attaches an arbitrary file to the user's feedback. This will appear in your online Apptentive dashboard, but will *not* appear in Message Center on the device. @param fileData The contents of the file as data. @param mimeType The MIME type of the file data. */ - (void)sendAttachmentFile:(NSData *)fileData withMimeType:(NSString *)mimeType; ///--------------------------------------- /// @name Add Custom Device or Person Data ///--------------------------------------- /** The name of the app user when communicating with Apptentive. */ @property (nonatomic, copy) NSString *personName; /** The email address of the app user in form fields and communicating with Apptentive. */ @property (nonatomic, copy) NSString *personEmailAddress; /** Adds custom data associated with the current person. Adds an additional data field to any feedback sent. This will show up in the person data in the conversation on your Apptentive dashboard. @param object Custom data of type `NSDate`, `NSNumber`, or `NSString`. @param key A key to associate the data with. */ - (void)addCustomPersonData:(NSObject<NSCoding> *)object withKey:(NSString *)key; /** Adds custom data associated with the current device. Adds an additional data field to any feedback sent. This will show up in the device data in the conversation on your Apptentive dashboard. @param object Custom data of type `NSDate`, `NSNumber`, or `NSString`. @param key A key to associate the data with. */ - (void)addCustomDeviceData:(NSObject<NSCoding> *)object withKey:(NSString *)key; /** Removes custom data associated with the current person. Will remove data, if any, associated with the current person with the key `key`. @param key The key of the data. */ - (void)removeCustomPersonDataWithKey:(NSString *)key; /** Removes custom data associated with the current device. Will remove data, if any, associated with the current device with the key `key`. @param key The key of the data. */ - (void)removeCustomDeviceDataWithKey:(NSString *)key; /** Deprecated. Use `-addCustomDeviceData:withKey:` instead. @warning Deprecated! @param object The custom data. @param key The key of the data. */ - (void)addCustomData:(NSObject<NSCoding> *)object withKey:(NSString *)key DEPRECATED_ATTRIBUTE; /** Deprecated. Use `-removeCustomDeviceDataWithKey:` instead. @warning Deprecated! @param key The key of the data. */ - (void)removeCustomDataWithKey:(NSString *)key DEPRECATED_ATTRIBUTE; ///--------------------------------------- /// @name Open App Store ///--------------------------------------- /** Open your app's page on the App Store or Mac App Store. This method can be used to power, for example, a "Rate this app" button in your settings screen. `openAppStore` opens the app store directly, without the normal Apptentive Ratings Prompt. */ - (void)openAppStore; ///------------------------------------ /// @name Add Push Notifications ///------------------------------------ /** Register for Push Notifications with the given service provider. Uses the `deviceToken` from `application:didRegisterForRemoteNotificationsWithDeviceToken:` Only one Push Notification Integration can be added at a time. Setting a Push Notification Integration removes all previously set Push Notification Integrations. @param pushProvider The Push Notification provider with which to register. @param deviceToken The device token used to send Remote Notifications. **/ - (void)setPushNotificationIntegration:(ATPushProvider)pushProvider withDeviceToken:(NSData *)deviceToken; @end /** The `ATConnectDelegate` protocol allows your app to override the default behavior when the Message Center is launched from an incoming push notification. In most cases the default behavior (which walks the view controller stack from the main window's root view controller) will work, but if your app features custom container view controllers, it may behave unexpectedly. In that case an object in your app should implement the `ATConnectDelegate` protocol's `-viewControllerForInteractionsWithConnection:` method and return the view controller from which to present the Message Center interaction. */ @protocol ATConnectDelegate <NSObject> @optional /** Returns a view controller from which to present the MessageCenter interaction. @param connection The `ATConnect` object that is requesting a view controller to present from. @return The view controller your app would like the interaction to be presented from. */ - (UIViewController *)viewControllerForInteractionsWithConnection:(ATConnect *)connection; @end /** The `ATNavigationController class is an empty subclass of UINavigationController that can be used to target UIAppearance settings specifically to Apptentive UI. For instance, to override the default `barTintColor` (white) for navigation controllers in the Apptentive UI, you would call: [[UINavigationBar appearanceWhenContainedIn:[ATNavigationController class], nil].barTintColor = [UIColor magentaColor]; */ @interface ATNavigationController : UINavigationController @end
bsd-3-clause
TheWebster/NotificaThor
src/drawing.c
10061
/* ************************************************************* *\ * drawing.c * * * * Project: NotificaThor * * Author: Christian Weber ([email protected]) * * * * Description: Advanced drawing operations. * \* ************************************************************* */ #include <cairo/cairo.h> #include <cairo/cairo-xcb.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <syslog.h> #include "cairo_guards.h" #include "config.h" #include "text.h" #include "theme.h" #include "com.h" #include "drawing.h" #include "NotificaThor.h" #include "logging.h" #include "images.h" struct fbs_t fallback_surface; char *image_string; /* * Draws a rectangle with rounded corners. * * Parameters: cr - Cairo context. * x, y - Origin of the rectangle. * width, height - Extents of rectangle. * rad_tl, rad_tr, * rad_br, rad_bl, - Radii of the rounded corners. */ static void cairo_rounded_rectangle( cairo_t *cr, double x, double y, double width, double height, double rad_tl, double rad_tr, double rad_br, double rad_bl) { rad_tl = ( rad_tl < 0 ) ? 0 : rad_tl; rad_tr = ( rad_tr < 0 ) ? 0 : rad_tr; rad_br = ( rad_br < 0 ) ? 0 : rad_br; rad_bl = ( rad_bl < 0 ) ? 0 : rad_bl; cairo_new_sub_path( cr); cairo_arc( cr, x+rad_tl , y+rad_tl , rad_tl, 2*(M_PI/2), 3*(M_PI/2)); cairo_arc( cr, x+width-rad_tr, y+rad_tr , rad_tr, 3*(M_PI/2), 4*(M_PI/2)); cairo_arc( cr, x+width-rad_br, y+height-rad_br, rad_br, 0 , 1*(M_PI/2)); cairo_arc( cr, x+rad_bl , y+height-rad_bl, rad_bl, 1*(M_PI/2), 2*(M_PI/2)); cairo_close_path( cr); }; /* * Adds a solid-colored mesh to a mesh pattern. * * Parameters: pattern - Mesh pattern, to which the mesh should be added. * x0, y0, * x1, y1, * x2, y2, * x3, y3 - Coordinates of the mesh. * color - Color of the mesh. */ static void solid_mesh( cairo_pattern_t *pattern, double x0, double y0, double x1, double y1, double x2, double y2, double x3, double y3, uint32_t color) { int i; cairo_mesh_pattern_begin_patch( pattern); cairo_mesh_pattern_move_to( pattern, x0, y0); cairo_mesh_pattern_line_to( pattern, x1, y1); cairo_mesh_pattern_line_to( pattern, x2, y2); cairo_mesh_pattern_line_to( pattern, x3, y3); cairo_mesh_pattern_line_to( pattern, x0, y0); for( i = 0; i < 4; i++ ) cairo_mesh_pattern_set_corner_color_rgba( pattern, i, cairo_rgba( color)); cairo_mesh_pattern_end_patch( pattern); }; /* * Draws a radial gradient as corner. * * Parameters: pattern - Mesh pattern, to which the mesh should be added. * x0, y0 - Coordinates of outer corner. * dirx, diry - Radius of corner, direction is controlled by sign. * width - Border width. * color1, color2 - Colors of the gradient. */ static void gradient_corner( cairo_pattern_t *pattern, double x0, double y0, int dirx, int diry, unsigned int width, uint32_t color1, uint32_t color2) { int radx, rady; if( width > abs( dirx) ) { if( dirx > 0 ) radx = width; else radx = -width; if( diry > 0 ) rady = width; else rady = -width; } else { radx = dirx; rady = diry; } cairo_mesh_pattern_begin_patch( pattern); cairo_mesh_pattern_move_to( pattern, x0 + dirx, y0); cairo_mesh_pattern_curve_to( pattern, x0 + (double)dirx/2, y0, x0, y0 + (double)diry/2, x0, y0 + diry); cairo_mesh_pattern_line_to( pattern, x0 + radx, y0 + rady); cairo_mesh_pattern_line_to( pattern, x0 + radx, y0 + rady); cairo_mesh_pattern_line_to( pattern, x0 + dirx, y0); cairo_mesh_pattern_set_corner_color_rgba( pattern, 0, cairo_rgba( color1)); cairo_mesh_pattern_set_corner_color_rgba( pattern, 1, cairo_rgba( color2)); cairo_mesh_pattern_set_corner_color_rgba( pattern, 2, cairo_rgba( color2)); cairo_mesh_pattern_set_corner_color_rgba( pattern, 3, cairo_rgba( color1)); cairo_mesh_pattern_end_patch( pattern); }; /* * Creates a cairo pattern for drawing a split border. * * Parameters: surface - Surface around which a border should be drawn. * x0, y0, x1, y1 - Coordinates of the pattern. * color_t - Color of top border. * color_r - Color of right border. * color_b - Color of bottom border. * color_l - Color of left border. * * Returns: The the pattern containing the bordermap. */ static cairo_pattern_t * bordermap( surface_t *surface, double x0, double y0, double x1, double y1, uint32_t color_t, uint32_t color_r, uint32_t color_b, uint32_t color_l) { double in_x0 = x0 + surface->border.width; double in_x1 = x1 - surface->border.width; double in_y0 = y0 + surface->border.width; double in_y1 = y1 - surface->border.width; cairo_pattern_t *pattern = cairo_pattern_create_mesh(); // top mesh solid_mesh( pattern, x0, y0, x1, y0, in_x1, in_y0, in_x0, in_y0, color_t); // right mesh solid_mesh( pattern, x1, y0, x1, y1, in_x1, in_y1, in_x1, in_y0, color_r); // bottom mesh solid_mesh( pattern, x1, y1, x0, y1, in_x0, in_y1, in_x1, in_y1, color_b); // left mesh solid_mesh( pattern, x0, y1, x0, y0, in_x0, in_y0, in_x0, in_y1, color_l); // top-left corner gradient_corner( pattern, x0, y0, surface->rad_tl, surface->rad_tl, surface->border.width, color_t, color_l); // top-right corner gradient_corner( pattern, x1, y0, -surface->rad_tr, surface->rad_tr, surface->border.width, color_t, color_r); // bottom-right corner gradient_corner( pattern, x1, y1, -surface->rad_br, -surface->rad_br, surface->border.width, color_b, color_r); // bottom-left corner gradient_corner( pattern, x0, y1, surface->rad_bl, -surface->rad_bl, surface->border.width, color_b, color_l); return pattern; }; /* * Fills cairo's current path with the layers of a surface. * * Parameters: cr - Cairo context. * surface - surface_t containing the layers. * * Returns: 0 on success and -1 when nothing can be drawn. */ int set_layer( cairo_t *cr, layer_t *layer) { cairo_pattern_t *pat; cairo_status_t status; /** empty png pattern **/ if( layer->pattern == NULL ) { if( !image_string || !*image_string ) return -1; pat = get_pattern_for_png( image_string); if( (status = cairo_pattern_status( pat)) != CAIRO_STATUS_SUCCESS ) { thor_log( LOG_ERR, "Reading '%s': %s.", image_string, cairo_status_to_string( status)); return -1; } image_string += strlen( image_string) + 1; } else pat = layer->pattern; cairo_set_source( cr, pat); cairo_set_operator( cr, layer->operator); return 0; }; /* * Draws a surface. * * Parameters: cr - Cairo context. * surface - Surface structure. * control - Control flags. * x, y, * width, height - Coordinates. */ void draw_surface( cairo_t *cr, surface_t *surface, int control, double x, double y, double width, double height) { int i = -1; cairo_rounded_rectangle( cr, x, y, width, height, surface->rad_tl, surface->rad_tr, surface->rad_br, surface->rad_bl); if( control & CONTROL_USE_MATRIX ) cairo_restore( cr); else { cairo_translate( cr, x, y); cairo_scale( cr, width, height); } if( surface->nlayers == 0 ) { cairo_set_source_rgba( cr, cairo_rgba( fallback_surface.surf_color)); cairo_set_operator( cr, fallback_surface.surf_op); cairo_fill_preserve( cr); } else { for( i = 0; i < surface->nlayers; i++ ) { if( set_layer( cr, &surface->layer[i]) == 0 ) cairo_fill_preserve( cr); } } cairo_clip( cr); if( control & CONTROL_SAVE_MATRIX ) cairo_save( cr); cairo_identity_matrix( cr); }; void draw_border( cairo_t *cr, surface_t *surface, int outer, double x, double y, double width, double height) { if( surface->border.width > 0 ) { cairo_pattern_t *bmap = NULL; double snap = (double)surface->border.width / 2; if( outer ) { x -= surface->border.width; y -= surface->border.width; width += 2 * surface->border.width; height += 2 * surface->border.width; cairo_rounded_rectangle( cr, x, y, width, height, surface->rad_tl, surface->rad_tr, surface->rad_br, surface->rad_bl); cairo_reset_clip( cr); cairo_clip( cr); } cairo_translate( cr, x, y); cairo_rounded_rectangle( cr, snap, snap, width - surface->border.width, height - surface->border.width, surface->rad_tl - snap, surface->rad_tr - snap, surface->rad_br - snap, surface->rad_bl - snap); switch( surface->border.type ) { case BORDER_TYPE_SOLID: bmap = cairo_pattern_create_rgba( cairo_rgba( surface->border.color)); break; case BORDER_TYPE_TOPLEFT: bmap = bordermap( surface, -0.5, 0, width, height, surface->border.topcolor, surface->border.color, surface->border.color, surface->border.topcolor); break; case BORDER_TYPE_TOPRIGHT: bmap = bordermap( surface, 0, 0, width, height, surface->border.topcolor, surface->border.topcolor, surface->border.color, surface->border.color); break; } cairo_set_line_width( cr, surface->border.width); cairo_set_operator( cr, surface->border.operator); cairo_set_source( cr, bmap); cairo_stroke( cr); cairo_pattern_destroy( bmap); cairo_identity_matrix( cr); } cairo_reset_clip( cr); };
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s03/CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82a.cpp
3366
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82a.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-82a.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: malloc Allocate data using malloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #include "std_testcase.h" #include "CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82 { #ifndef OMITBAD void bad() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (int64_t *)malloc(100*sizeof(int64_t)); if (data == NULL) {exit(-1);} CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_base* baseObject = new CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_bad; baseObject->action(data); delete baseObject; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int64_t * data; /* Initialize data*/ data = NULL; /* FIX: Allocate memory from the heap using new */ data = new int64_t; CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_base* baseObject = new CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_goodG2B; baseObject->action(data); delete baseObject; } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (int64_t *)malloc(100*sizeof(int64_t)); if (data == NULL) {exit(-1);} CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_base* baseObject = new CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_goodB2G; baseObject->action(data); delete baseObject; } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
UNFPAInnovation/GetIn_Mobile
app/src/main/java/org/sana/android/fragment/ObserverListFragment.java
8088
package org.sana.android.fragment; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.telephony.PhoneNumberUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.TextView; import android.widget.Toast; import org.sana.R; import org.sana.android.activity.ObserverList; import org.sana.android.content.Uris; import org.sana.android.content.core.ObserverWrapper; import org.sana.android.provider.Observers; import org.sana.android.util.PhoneUtil; import org.sana.core.Observer; import java.util.HashMap; import java.util.Locale; import java.util.Map; import static android.telephony.PhoneNumberUtils.formatNumberToE164; /** * A fragment representing a list of Items. * <p/> * Activities containing this fragment MUST implement the {@link ModelSelectedListener} * interface. */ public class ObserverListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener { // TODO: Customize parameter argument names private static final String ARG_COLUMN_COUNT = "column-count"; // TODO: Customize parameters private int mColumnCount = 1; private ModelSelectedListener<Observer> mListener = null; private ObserverCursorAdapter mAdapter = null; private Uri mUri = Observers.CONTENT_URI; // static final String[] mProjection = null; public static final String TAG = ObserverListFragment.class.getName(); static ObserverList observerList = new ObserverList(); static final String[] mProjection = new String[] { Observers.Contract._ID, Observers.Contract.FIRST_NAME, Observers.Contract.LAST_NAME, Observers.Contract.PHONE_NUMBER, Observers.Contract.LOCATIONS }; // static final String mSelect = Observers.Contract.ROLE +" = '"+ observerList.getUser() +"'"; static final String userSelect = Observers.Contract.ROLE +" = 'vht'"; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public ObserverListFragment() { } // TODO: Customize parameter initialization @SuppressWarnings("unused") public static ObserverListFragment newInstance(int columnCount) { ObserverListFragment fragment = new ObserverListFragment(); Bundle args = new Bundle(); args.putInt(ARG_COLUMN_COUNT, columnCount); // args.putString("user", observerListuser); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_observer_list, container, false); // TODO Anything else related to the view that needs to happen here // Toast.makeText(ObserverListFragment.this.getContext(), ""+mSelect, Toast.LENGTH_SHORT).show(); return view; } @Override public void onAttach(Context context) { super.onAttach(context); // userSelect = Observers.Contract.ROLE +" = 'midwife'"; // final String mSelect = Observers.Contract.ROLE +" = '"+ observerList.getUser() +"'"; if (context instanceof ModelSelectedListener) { mListener = (ModelSelectedListener<Observer>) context; } else { throw new RuntimeException(context.toString() + " must implement ModelSelectedListener<Observer>"); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // TODO initialize mAdapter mAdapter = new ObserverCursorAdapter(getActivity(), null, 0); setListAdapter(mAdapter); LoaderManager.enableDebugLogging(true); getActivity().getSupportLoaderManager().initLoader(Uris.OBSERVER_DIR, null, this); // set the list item click listener getListView().setOnItemClickListener(this); } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String user = Observers.Contract.ROLE +" = '"+ getActivity().getIntent().getStringExtra("user") +"'"; CursorLoader loader = new CursorLoader(getActivity(), mUri, null,//mProjection, //mSelect user, null, null); return loader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (cursor == null){ ((TextView)getListView().getEmptyView()).setText(getString(R.string.msg_drivers_vht)); } if(cursor != null){ if(cursor.getCount() == 0) { ((TextView)getListView().getEmptyView()).setText(getString(R.string.msg_drivers_vht)); } else{ ((ObserverCursorAdapter) this.getListAdapter()).swapCursor(cursor); } } } @Override public void onLoaderReset(Loader<Cursor> loader) { ((ObserverCursorAdapter)this.getListAdapter()).swapCursor(null); } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Implement click to call functionality Object number = view.getTag(); if(number != null){ try { PhoneUtil.call(getActivity(), String.valueOf(number)); } catch(Exception e){ Toast.makeText(getActivity(), R.string.error_unable_to_call, Toast.LENGTH_LONG); } } else { if (mListener != null) { mListener.onModelSelected((Observer)mAdapter.getItem(position)); } } } public static class ObserverCursorAdapter extends CursorAdapter{ protected Map<Integer, Observer> mHolders = new HashMap<>(); public ObserverCursorAdapter(Context context, Cursor c, int resId) { super(context, c); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); View child = inflater.inflate(R.layout.list_item_observer, parent, false); return child; } @Override public void bindView(View view, Context context, Cursor cursor) { ObserverWrapper wrapper = new ObserverWrapper(cursor); if(wrapper == null || wrapper.isBeforeFirst() || cursor.getCount() == 0) return; Observer obj = (Observer) wrapper.getObject(); view.setTag(obj.getPhoneNumber()); // TODO fill in any fields etc setText(view, R.id.first_name, obj.getFirstName()); setText(view, R.id.last_name, obj.getLastName()); setText(view, R.id.phone_number, obj.getPhoneNumber()); mHolders.put(cursor.getPosition(), obj); Log.v(TAG,",.,.,.<><><><><><.,.,.,.<><><><>"+obj.getFirstName()); } public Object getItem(int position){ return mHolders.get(position); } protected void setText(View root, int resId, String text){ TextView child = (TextView) root.findViewById(resId); child.setText(text); } } }
bsd-3-clause
endlessm/chromium-browser
third_party/perfetto/src/trace_processor/metrics/android/span_view_stats.sql
1382
-- -- Copyright 2019 The Android Open Source Project -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- https://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- DROP TABLE IF EXISTS {{table_name}}_stats; CREATE TABLE {{table_name}}_stats ( process_name TEXT PRIMARY KEY, min_value REAL, max_value REAL, avg_value REAL ); INSERT INTO {{table_name}}_stats SELECT process.name AS process_name, MIN(span.{{table_name}}_val) AS min_value, MAX(span.{{table_name}}_val) AS max_value, SUM(span.{{table_name}}_val * span.dur) / SUM(span.dur) AS avg_value FROM {{table_name}}_span AS span JOIN process USING(upid) WHERE process.name IS NOT NULL GROUP BY 1 ORDER BY 1; DROP VIEW IF EXISTS {{table_name}}_stats_proto; CREATE VIEW {{table_name}}_stats_proto AS SELECT process_name, AndroidMemoryMetric_Counter( 'min', min_value, 'max', max_value, 'avg', avg_value ) AS proto FROM {{table_name}}_stats;
bsd-3-clause
TonyBrewer/OpenHT
tests/obk/src_pers/PersObk_src.cpp
716
#include "Ht.h" #include "PersObk.h" void CPersObk::PersObk() { if (PR_htValid) { switch (PR_htInst) { case OBK_PUSH: { if (P_loopCnt == 0) { HtContinue(OBK_RTN); break; } if (SendHostDataBusy()) { HtRetry(); break; } uint64_t data = (uint64_t)((uint64_t)P_pau << 56); data |= (uint64_t)((uint64_t)P_loopCnt); #ifndef _HTV if (!(P_loopCnt % 10000)) fprintf(stderr, "%d loopCnt = %d\n", (int)P_pau, (int)P_loopCnt); #endif SendHostData(data); P_loopCnt -= 1; HtContinue(OBK_PUSH); } break; case OBK_RTN: { if (SendReturnBusy_htmain()) { HtRetry(); break; } SendReturn_htmain(); } break; default: assert(0); } } }
bsd-3-clause
endlessm/chromium-browser
chrome/browser/resources/new_tab_page/customize_dialog.html
5854
<style include="cr-hidden-style cr-icons"> ::part(dialog) { min-width: 800px; } :host { --border-width: 1px; } div[slot=title] { align-items: center; color: var(--ntp-primary-text-color); display: flex; flex-direction: row; height: 58px; padding: 0; } div[slot=body] { color: var(--cr-primary-text-color); display: flex; flex-direction: column; overflow: hidden; padding: 0; } #bodyContainer { display: flex; flex-direction: row; overflow: hidden; } div[slot=button-container] { padding-top: 16px; } #menuContainer, #pagesContainer { max-height: 395px; overflow: hidden; } #leftTitleSpacer, #menuContainer { flex-basis: 232px; } #title { line-height: 1.5; margin-bottom: -2px; padding-inline-end: 24px; user-select: none; } #title, #pagesContainer { flex-grow: 1; } #menu { height: calc(100% - 2 * var(--border-width)); overflow: auto; } #pages { height: 100%; overflow: auto; } #pages > iron-pages { /* Margin is for focus outline. */ margin: 2px; min-height: 389px; } div[scroll-border] { border-bottom: var(--border-width) solid transparent; } div[scroll-border][show-1], div[scroll-border][show-2] { border-bottom-color: var(--ntp-border-color); } #menu { display: flex; flex-direction: column; } .menu-item { align-items: center; border-radius: 0 16px 16px 0; color: var(--ntp-primary-text-color); cursor: pointer; display: flex; flex-direction: row; flex-shrink: 0; font-size: 14px; height: 32px; margin-bottom: 16px; outline: none; width: 192px; } :host-context([dir=rtl]) .menu-item { border-radius: 16px 0 0 16px; } .menu-item:hover, .menu-item:focus { background-color: var(--ntp-hover-background-color); } .menu-item:active { background-color: var(--ntp-active-background-color); } .menu-item[selected] { background-color: var(--ntp-selected-background-color); color: var(--ntp-selected-primary-text-color); } .menu-item-icon { -webkit-mask-repeat: no-repeat; -webkit-mask-size: 100%; background-color: var(--ntp-primary-text-color); height: 20px; margin-inline-end: 16px; margin-inline-start: 24px; width: 20px; } .menu-item[selected] .menu-item-icon { background-color: var(--ntp-selected-primary-text-color); } #backgroundsIcon { -webkit-mask-image: url(icons/backgrounds.svg); } #shortcutsIcon { -webkit-mask-image: url(icons/link.svg); } #themesIcon { -webkit-mask-image: url(icons/colors.svg); } #backButton { --cr-icon-button-fill-color: var(--ntp-primary-text-color); margin-inline-end: 4px; /* So that the arrow aligns with the grid. */ margin-inline-start: -12px; } #titleNavigation { align-items: center; display: flex; flex-direction: row; } cr-toggle { margin-inline-end: 12px; } #collectionTitle { flex-grow: 1; } </style> <cr-dialog id="dialog" on-cancel="onCancel_" show-on-attach> <div slot="title"> <div id="leftTitleSpacer"></div> <div id="title"> <div id="titleText" hidden="[[showTitleNavigation_]]"> $i18n{customizeThisPage} </div> <div id="titleNavigation" hidden="[[!showTitleNavigation_]]"> <cr-icon-button id="backButton" class="icon-arrow-back" on-click="onBackClick_" title="$i18n{backButton}"> </cr-icon-button> <div id="collectionTitle">[[selectedCollection_.label]]</div> <cr-toggle id="refreshToggle" checked="[[isRefreshToggleChecked_]]" on-change="onBackgroundDailyRefreshToggleChange_"> </cr-toggle> $i18n{refreshDaily} </div> </div> </div> <div slot="body"> <div id="topPageScrollBorder" scroll-border></div> <div id="bodyContainer"> <div id="menuContainer"> <div id="menu"> <iron-selector selected-attribute="selected" attr-for-selected="page-name" selected="{{selectedPage_}}" on-keydown="onMenuItemKeyDown_"> <div class="menu-item" page-name="backgrounds" tabindex="0"> <div id="backgroundsIcon" class="menu-item-icon"></div> $i18n{backgroundsMenuItem} </div> <div class="menu-item" page-name="shortcuts" tabindex="0"> <div id="shortcutsIcon" class="menu-item-icon"></div> $i18n{shortcutsMenuItem} </div> <div class="menu-item" page-name="themes" tabindex="0"> <div id="themesIcon" class="menu-item-icon"></div> $i18n{themesMenuItem} </div> </iron-selector> </div> </div> <div id="pagesContainer"> <div id="pages"> <iron-pages selected="[[selectedPage_]]" attr-for-selected="page-name"> <ntp-customize-backgrounds id="backgrounds" page-name="backgrounds" selected-collection="{{selectedCollection_}}" theme="[[theme]]" background-selection="{{backgroundSelection}}"> </ntp-customize-backgrounds> <ntp-customize-shortcuts page-name="shortcuts"> </ntp-customize-shortcuts> <ntp-customize-themes page-name="themes" theme="[[theme]]"> </ntp-customize-themes> </iron-pages> </div> </div> </div> <div id="bottomPageScrollBorder" scroll-border></div> </div> <div slot="button-container"> <cr-button class="cancel-button" on-click="onCancelClick_"> $i18n{cancelButton} </cr-button> <cr-button class="action-button" on-click="onDoneClick_"> $i18n{doneButton} </cr-button> </div> </cr-dialog>
bsd-3-clause
laurenyew/cOrcS
src/orc/lib/web/Browse.scala
1526
// // Browse.scala -- Scala class/trait/object Browse // Project OrcScala // // $Id: Browse.scala 2933 2011-12-15 16:26:02Z jthywissen $ // // Created by dkitchin on Jan 18, 2011. // // Copyright (c) 2011 The University of Texas at Austin. All rights reserved. // // Use and redistribution of this file is governed by the license terms in // the LICENSE file found in the project's top-level directory and also found at // URL: http://orc.csres.utexas.edu/license.shtml . // package orc.lib.web import orc.values.sites.Site1 import orc.values.sites.TypedSite import orc.types.OverloadedType import orc.types.StringType import orc.types.JavaObjectType import orc.types.SimpleFunctionType import orc.types.SignalType import orc.types.Top import orc.Handle import orc.OrcEvent import orc.error.runtime.ArgumentTypeMismatchException import java.net.URL /** * Open a new browser window or tab for the specified URL. * * @author dkitchin */ case class BrowseEvent(val url: URL) extends OrcEvent object Browse extends Site1 with TypedSite { def call(v: AnyRef, h: Handle) = { v match { case url: URL => { h.notifyOrc(BrowseEvent(url)) h.publish() } case s: String => call(new URL(s), h) case a => throw new ArgumentTypeMismatchException(0, "URL", if (a != null) a.getClass().toString() else "null") } } def orcType = OverloadedType(List( SimpleFunctionType(StringType, SignalType), SimpleFunctionType(JavaObjectType(classOf[URL]), SignalType))) }
bsd-3-clause
GaloisInc/hacrypto
competitions/CAESAR/competitions.cr.yp.to/faq.html
7152
<html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type=text/css> body{font-family:sans-serif;font-size:1em} h1{font-size:1.7em;} h2{font-size:1.4em;} h3{font-size:1.1em;} p{font-size:0.8em;line-height:1.5em;} blockquote{font-size:0.8em;line-height:1.5em;} ul{font-size:0.8em;line-height:1.5em;} ul ul{font-size:1em;line-height:1.5em;} ol{font-size:0.8em;line-height:1.5em;} pre{font-family:monospace,monospace;font-size:0.8em;} tt{font-family:monospace,monospace;font-size:1em;} </style> <title> Crypto competitions: CAESAR frequently asked questions </title> </head> <body> <table width="100%"> <tr valign=top> <td align=left><h1>Cryptographic competitions</h1></td> </tr> </table> <hr> <table width="100%"><tr> <td width="15%" align=left valign=top><table border width="100%" bgcolor="#e0e0e0"><tr><td width="100%"><table width="100%"> <tr><td width="100%" bgcolor="#e0e0e0"><a href="index.html" style="text-decoration:none"><font size=2 color="#000080">Introduction</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="secret.html" style="text-decoration:none"><font size=2 color="#000080">Secret-key cryptography</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="disasters.html" style="text-decoration:none"><font size=2 color="#000080">Disasters</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="features.html" style="text-decoration:none"><font size=2 color="#000080">Features</font></a></td></tr> </table></td></tr><tr><td width="100%"><table width="100%"> <tr><td width="100%" bgcolor="#e0e0e0"><font size=2 color="#000000"><b>Focused competitions:</b></font></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="aes.html" style="text-decoration:none"><font size=2 color="#000080">AES</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="estream.html" style="text-decoration:none"><font size=2 color="#000080">eSTREAM</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="sha3.html" style="text-decoration:none"><font size=2 color="#000080">SHA-3</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="phc.html" style="text-decoration:none"><font size=2 color="#000080">PHC</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="caesar.html" style="text-decoration:none"><font size=2 color="#000080">CAESAR</font></a></td></tr> </table></td></tr><tr><td width="100%"><table width="100%"> <tr><td width="100%" bgcolor="#e0e0e0"><font size=2 color="#000000"><b>Broader evaluations:</b></font></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="cryptrec.html" style="text-decoration:none"><font size=2 color="#000080">CRYPTREC</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="nessie.html" style="text-decoration:none"><font size=2 color="#000080">NESSIE</font></a></td></tr> </table></td></tr><tr><td width="100%"><table width="100%"> <tr><td width="100%" bgcolor="#e0e0e0"><font size=2 color="#000000"><b>CAESAR details:</b></font></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="caesar-submissions.html" style="text-decoration:none"><font size=2 color="#000080">Submissions</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="caesar-call.html" style="text-decoration:none"><font size=2 color="#000080">Call for submissions</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="caesar-call-5.html" style="text-decoration:none"><font size=2 color="#000080">Call draft 5</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="caesar-call-4.html" style="text-decoration:none"><font size=2 color="#000080">Call draft 4</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="caesar-call-3.html" style="text-decoration:none"><font size=2 color="#000080">Call draft 3</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="caesar-call-2.html" style="text-decoration:none"><font size=2 color="#000080">Call draft 2</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="caesar-call-1.html" style="text-decoration:none"><font size=2 color="#000080">Call draft 1</font></a></td></tr> <tr><td width="100%" bgcolor="#e0e0e0"><a href="caesar-committee.html" style="text-decoration:none"><font size=2 color="#000080">Committee</font></a></td></tr> <tr><td width="100%" bgcolor="#ffff00"><font size=2 color="#000000">Frequently asked questions</font></td></tr> </table></td></tr></table> </td><td align=left valign=top> <h2>CAESAR frequently asked questions</h2> <h3>Can I tweak my cipher?</h3> <p> Cipher v2 in the second round is not required to be the same as Cipher v1 in the first round. Designers are free to announce plans for Cipher v2 at any time. However, designers will not be allowed to modify Cipher v1; it is important for evaluators to have stable targets for the duration of the first round. </p> <h3>Will there be a single CAESAR winner?</h3> <p> The CAESAR selection committee will select a portfolio of algorithms. Experience with previous competitions suggests that a single-algorithm portfolio is unlikely to provide as much value as a multiple-algorithm portfolio. Of course, final decisions are up to the selection committee. <h3>Will the CAESAR winners be standards?</h3> <p> Standards committees may find the CAESAR results to be useful, but CAESAR per se is not a standardization project. <h3>Is CAESAR run by NIST?</h3> <p> No. CAESAR is run by the international cryptologic research community. The University of Illinois at Chicago applied to NIST for funding for a "Cryptographic competitions" grant, and is using some of this funding to support CAESAR benchmarking and the Directions in Authenticated Ciphers workshop series, but NIST has not been consulted regarding the CAESAR details. Of course, NIST cryptographers are welcome to provide public input to CAESAR. <h3>Will a CAESAR winner be renamed as the "CAESAR cipher"?</h3> <p> No. The AES competition eventually renamed Rijndael as AES, Rijndael-128 as AES-128, etc.; but CAESAR, like eSTREAM, will not rename any algorithms. <h3>Will selection-committee members be permitted to submit algorithms?</h3> <p> Yes. They will, however, not participate in committee discussions regarding their own algorithms. <h3>Will the selection committee justify its decisions?</h3> <p> The selection committee will issue a report that, for each selected algorithm, cites the previously published analyses that led the algorithm to be selected. This report should not be interpreted as a negative comment regarding other algorithms; an excellent algorithm might fail to be selected simply because not enough analysis was available at the time of the committee decision. <h3>Will there be any appeal of the committee decisions?</h3> <p> No. If submitters disagree with published analyses then they are expected to promptly and publicly respond to those analyses, not to wait for subsequent committee decisions. <hr><font size=1><b>Version:</b> This is version 2014.03.18 of the faq.html web page. </td></tr></table> </body> </html>
bsd-3-clause
mikem2005/vijava
src/com/vmware/vim25/CannotAddHostWithFTVmAsStandalone.java
1790
/*================================================================================ Copyright (c) 2009 VMware, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25; /** @author Steve Jin ([email protected]) */ public class CannotAddHostWithFTVmAsStandalone extends HostConnectFault { }
bsd-3-clause
fraunhoferfokus/govapps
data-portlet/src/main/java/de/fraunhofer/fokus/movepla/portlets/E_Stati.java
2939
package de.fraunhofer.fokus.movepla.portlets; /* * #%L * govapps_data * $Id: E_Stati.java 566 2014-11-13 15:22:01Z sma $ * %% * Copyright (C) 2013 - 2014 Fraunhofer FOKUS / CC ÖFIT * %% * Copyright (c) 2,013, Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3) All advertising materials mentioning features or use of this software must * display the following acknowledgement: * This product includes software developed by Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT. * * 4) Neither the name of the organization nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDER ''AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL * Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * #L% */ public enum E_Stati { APPLICATION_STATUS_SUBMITTED("APPLICATION_STATUS_SUBMITTED", 1), APPLICATION_STATUS_DELETED("APPLICATION_STATUS_DELETED", 2), APPLICATION_STATUS_RESUBMITTED("APPLICATION_STATUS_RESUBMITTED", 3), APPLICATION_STATUS_VERIFIED_AND_RESUBMITTED("APPLICATION_STATUS_VERIFIED_AND_RESUBMITTED", -3), APPLICATION_STATUS_REJECTED("APPLICATION_STATUS_REJECTED", -1), APPLICATION_STATUS_VERIFIED("APPLICATION_STATUS_VERIFIED", 4), APPLICATION_STATUS_CERTIFIED("APPLICATION_STATUS_CERTIFIED", 5), APPLICATION_STATUS_OLD_VERIFIED("APPLICATION_STATUS_OLD_VERIFIED", 6); private String m_strStatus; private int m_intStatus; private E_Stati(String strStatus, int intStatus) { m_strStatus = strStatus; m_intStatus = intStatus; } public String getStrStatus() { return m_strStatus; } public int getIntStatus() { return m_intStatus; } }
bsd-3-clause
onsoul/ha-db
saas-mycat/saas/src/main/java/com/hitler/common/model/menu/NavMenu.java
1481
package com.hitler.common.model.menu; import java.io.Serializable; import java.util.Collection; /** * 导航栏菜单vo * @author Kylin * 2015-10-10 上午9:44:27 */ public class NavMenu implements Serializable { private static final long serialVersionUID = 1L; private Integer id; /** * 显示内容 */ public String text; /** * 图标 */ public String icon; /** * 子节点 */ public Collection<? extends Serializable> children; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Collection<? extends Serializable> getChildren() { return children; } public void setChildren(Collection<? extends Serializable> children) { this.children = children; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((text == null) ? 0 : text.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NavMenu other = (NavMenu) obj; if (text == null) { if (other.text != null) return false; } else if (!text.equals(other.text)) return false; return true; } }
bsd-3-clause
pmeisen/dis-timeintervaldataanalyzer
test/net/meisen/dissertation/performance/indexes/IDataGenerator.java
359
package net.meisen.dissertation.performance.indexes; /** * Helper interface to provide different data generators * * @author pmeisen * */ public interface IDataGenerator { /** * Creates a generated {@code Object} the time of generation should be equal * for each object. * * @return a generated object */ public Object generateData(); }
bsd-3-clause
diagrams/diagrams-contrib
src/Diagrams/TwoD/Path/Follow.hs
3104
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Diagrams.TwoD.Path.Follow -- Copyright : (c) 2016 Brent Yorgey -- License : BSD-style (see LICENSE) -- Maintainer : [email protected] -- -- An alternative monoid for trails which rotates trails so their -- starting and ending tangents match at join points. -- ----------------------------------------------------------------------------- module Diagrams.TwoD.Path.Follow ( Following, follow, unfollow ) where import Diagrams.Prelude import Data.Monoid.SemiDirectProduct.Strict -- | @Following@ is just like @Trail' Line V2@, except that it has a -- different 'Monoid' instance. @Following@ values are -- concatenated, just like regular lines, except that they are also -- rotated so the tangents match at the join point. In addition, -- they are normalized so the tangent at the start point is in the -- direction of the positive x axis (essentially we are considering -- trails equivalent up to rotation). -- -- Pro tip: you can concatenate a list of trails so their tangents -- match using 'ala' from "Control.Lens", like so: -- -- @ala follow foldMap :: [Trail' Line V2 n] -> Trail' Line V2 n@ -- -- This is illustrated in the example below. -- -- <<diagrams/src_Diagrams_TwoD_Path_Follow_followExample.svg#diagram=followExample&width=400>> -- -- > import Control.Lens (ala) -- > import Diagrams.TwoD.Path.Follow -- > -- > wibble :: Trail' Line V2 Double -- > wibble = hrule 1 <> hrule 0.5 # rotateBy (1/6) <> hrule 0.5 # rotateBy (-1/6) <> a -- > where a = arc (xDir # rotateBy (-1/4)) (1/5 @@ turn) -- > # scale 0.7 -- > -- > followExample = -- > [ wibble -- > , wibble -- > # replicate 5 -- > # ala follow foldMap -- > ] -- > # map stroke -- > # map centerXY -- > # vsep 1 -- > # frame 0.5 -- newtype Following n = Following { unFollowing :: Semi (Trail' Line V2 n) (Angle n) } deriving (Monoid, Semigroup) -- | Note this is only an iso when considering trails equivalent up to -- rotation. instance RealFloat n => Wrapped (Following n) where type Unwrapped (Following n) = Trail' Line V2 n _Wrapped' = iso unfollow follow instance RealFloat n => Rewrapped (Following n) (Following n') -- | Create a @Following@ from a line, normalizing it (by rotation) -- so that it starts in the positive x direction. follow :: RealFloat n => Trail' Line V2 n -> Following n follow t = Following $ (t # rotate (signedAngleBetween unitX s)) `tag` theta where s = tangentAtStart t e = tangentAtEnd t theta = signedAngleBetween e s -- | Project out the line from a `Following`. -- -- If trails are considered equivalent up to rotation, then -- 'unfollow' and 'follow' are inverse. unfollow :: Following n -> Trail' Line V2 n unfollow = untag . unFollowing
bsd-3-clause
yoannd/mtcp
dpdk-2.2.0/build/build/lib/librte_mbuf_offload/.librte_mbuf_offload.a.cmd
78
cmd_librte_mbuf_offload.a = ar crDs librte_mbuf_offload.a rte_mbuf_offload.o
bsd-3-clause
exponent/exponent
android/versioned-abis/expoview-abi41_0_0/src/main/java/abi41_0_0/expo/modules/analytics/segment/SegmentModule.java
9079
// Copyright 2015-present 650 Industries. All rights reserved. package abi41_0_0.expo.modules.analytics.segment; import android.content.Context; import android.content.SharedPreferences; import androidx.annotation.Nullable; import com.segment.analytics.Analytics; import com.segment.analytics.Options; import com.segment.analytics.Properties; import com.segment.analytics.Traits; import com.segment.analytics.android.integrations.firebase.FirebaseIntegration; import java.util.HashMap; import java.util.Map; import abi41_0_0.org.unimodules.core.ExportedModule; import abi41_0_0.org.unimodules.core.ModuleRegistry; import abi41_0_0.org.unimodules.core.Promise; import abi41_0_0.org.unimodules.core.interfaces.ExpoMethod; import abi41_0_0.org.unimodules.interfaces.constants.ConstantsInterface; public class SegmentModule extends ExportedModule { private static final String NAME = "ExponentSegment"; private static final String ENABLED_PREFERENCE_KEY = "enabled"; private static final String TAG = SegmentModule.class.getSimpleName(); private static int sCurrentTag = 0; private Context mContext; private Analytics mClient; private ConstantsInterface mConstants; // We have to keep track of `enabled` on our own. // Since we have to change tag every time (see commit 083f051), Segment may or may not properly apply // remembered preference to the instance. The module in a standalone app would start disabled // (settings = { 0 => disabled }, tag = 0) but after OTA update it would reload with // (settings = { 0 => disabled }, tag = 1) and segment would become enabled if the app does not // disable it on start. private SharedPreferences mSharedPreferences; public SegmentModule(Context context) { super(context); mContext = context; mSharedPreferences = mContext.getSharedPreferences(NAME, Context.MODE_PRIVATE); } private static Traits readableMapToTraits(Map<String, Object> properties) { Traits traits = new Traits(); for (String key : properties.keySet()) { Object value = properties.get(key); if (value instanceof Map) { traits.put(key, coalesceAnonymousMapToJsonObject((Map) value)); } else { traits.put(key, value); } } return traits; } private static Map<String, Object> coalesceAnonymousMapToJsonObject(Map map) { Map<String, Object> validObject = new HashMap<>(); for (Object key : map.keySet()) { if (key instanceof String) { Object value = map.get(key); if (value instanceof Map) { validObject.put((String) key, coalesceAnonymousMapToJsonObject((Map) value)); } else { validObject.put((String) key, value); } } } return validObject; } private static Options readableMapToOptions(Map<String, Object> properties) { Options options = new Options(); if (properties != null) { for (Map.Entry<String, Object> entry : properties.entrySet()) { String keyName = entry.getKey(); if (keyName.equals("context") && entry.getValue() != null) { Map<String, Object> contexts = (Map) entry.getValue(); for (Map.Entry<String, Object> context : contexts.entrySet()) { options.putContext(context.getKey(), context.getValue()); } } else if (keyName.equals("integrations") && entry.getValue() != null) { options = addIntegrationsToOptions(options, (Map) entry.getValue()); } } } return options; } private static Options addIntegrationsToOptions(Options options, Map<String,Object> integrations) { for (Map.Entry<String, Object> integration : integrations.entrySet()) { String integrationKey = integration.getKey(); if (integration.getValue() instanceof Map) { Map integrationOptions = (Map) integration.getValue(); if (integrationOptions.get("enabled") instanceof Boolean) { boolean enabled = (Boolean) integrationOptions.get("enabled"); options.setIntegration(integrationKey, enabled); } else if (integrationOptions.get("enabled") instanceof String) { String enabled = (String) integrationOptions.get("enabled"); options.setIntegration(integrationKey, Boolean.valueOf(enabled)); } if (integrationOptions.get("options") instanceof Map) { Map<String, Object> jsonOptions = coalesceAnonymousMapToJsonObject((Map) integrationOptions.get("options")); options.setIntegrationOptions(integrationKey, jsonOptions); } } } return options; } private static Properties readableMapToProperties(Map<String, Object> properties) { Properties result = new Properties(); for (String key : properties.keySet()) { Object value = properties.get(key); if (value instanceof Map) { result.put(key, coalesceAnonymousMapToJsonObject((Map) value)); } else { result.put(key, value); } } return result; } @Override public String getName() { return NAME; } @ExpoMethod public void initialize(final String writeKey, Promise promise) { Analytics.Builder builder = new Analytics.Builder(mContext, writeKey); builder.tag(Integer.toString(sCurrentTag++)); builder.use(FirebaseIntegration.FACTORY); mClient = builder.build(); mClient.optOut(!getEnabledPreferenceValue()); promise.resolve(null); } @ExpoMethod public void identify(final String userId, Promise promise) { if (mClient != null) { mClient.identify(userId); } promise.resolve(null); } @ExpoMethod public void identifyWithTraits(final String userId, final Map<String, Object> properties, @Nullable final Map<String, Object> options, Promise promise) { if (mClient != null) { mClient.identify(userId, readableMapToTraits(properties), readableMapToOptions(options)); } promise.resolve(null); } @ExpoMethod public void track(final String eventName, Promise promise) { if (mClient != null) { mClient.track(eventName); } promise.resolve(null); } @ExpoMethod public void trackWithProperties(final String eventName, final Map<String, Object> properties, @Nullable final Map<String, Object> options, Promise promise) { if (mClient != null) { mClient.track(eventName, readableMapToProperties(properties), readableMapToOptions(options)); } promise.resolve(null); } @ExpoMethod public void alias(final String newId, final Map<String, Object> options, Promise promise) { Analytics client = mClient; if (client != null) { client.alias(newId, readableMapToOptions(options)); promise.resolve(null); } else { promise.reject("E_NO_SEG", "Segment instance has not been initialized yet, have you tried calling Segment.initialize prior to calling Segment.alias?"); } } @ExpoMethod public void group(final String groupId, Promise promise) { if (mClient != null) { mClient.group(groupId); } promise.resolve(null); } @ExpoMethod public void groupWithTraits(final String groupId, final Map<String, Object> properties, @Nullable final Map<String, Object> options, Promise promise) { if (mClient != null) { mClient.group(groupId, readableMapToTraits(properties), readableMapToOptions(options)); } promise.resolve(null); } @ExpoMethod public void screen(final String screenName, Promise promise) { if (mClient != null) { mClient.screen(screenName); } promise.resolve(null); } @ExpoMethod public void screenWithProperties(final String screenName, final Map<String, Object> properties, @Nullable final Map<String, Object> options, Promise promise) { if (mClient != null) { mClient.screen(null, screenName, readableMapToProperties(properties), readableMapToOptions(options)); } promise.resolve(null); } @ExpoMethod public void flush(Promise promise) { if (mClient != null) { mClient.flush(); } promise.resolve(null); } @ExpoMethod public void reset(Promise promise) { if (mClient != null) { mClient.reset(); } promise.resolve(null); } @ExpoMethod public void getEnabledAsync(final Promise promise) { promise.resolve(getEnabledPreferenceValue()); } @ExpoMethod public void setEnabledAsync(final boolean enabled, final Promise promise) { if (mConstants.getAppOwnership().equals("expo")) { promise.reject("E_UNSUPPORTED", "Setting Segment's `enabled` is not supported in Expo Go."); return; } mSharedPreferences.edit().putBoolean(ENABLED_PREFERENCE_KEY, enabled).apply(); if (mClient != null) { mClient.optOut(!enabled); } promise.resolve(null); } @Override public void onCreate(ModuleRegistry moduleRegistry) { mConstants = null; if (moduleRegistry != null) { mConstants = moduleRegistry.getModule(ConstantsInterface.class); } } private boolean getEnabledPreferenceValue() { return mSharedPreferences.getBoolean(ENABLED_PREFERENCE_KEY, true); } }
bsd-3-clause
endlessm/chromium-browser
third_party/llvm/lldb/include/lldb/Core/FileLineResolver.h
2120
//===-- FileLineResolver.h --------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLDB_CORE_FILELINERESOLVER_H #define LLDB_CORE_FILELINERESOLVER_H #include "lldb/Core/SearchFilter.h" #include "lldb/Symbol/SymbolContext.h" #include "lldb/Utility/FileSpec.h" #include "lldb/lldb-defines.h" #include <stdint.h> namespace lldb_private { class Address; class Stream; /// \class FileLineResolver FileLineResolver.h "lldb/Core/FileLineResolver.h" /// This class finds address for source file and line. Optionally, it will /// look for inlined instances of the file and line specification. class FileLineResolver : public Searcher { public: FileLineResolver() : m_file_spec(), m_line_number(UINT32_MAX), // Set this to zero for all lines in a file m_sc_list(), m_inlines(true) {} FileLineResolver(const FileSpec &resolver, uint32_t line_no, bool check_inlines); ~FileLineResolver() override; Searcher::CallbackReturn SearchCallback(SearchFilter &filter, SymbolContext &context, Address *addr) override; lldb::SearchDepth GetDepth() override; void GetDescription(Stream *s) override; const SymbolContextList &GetFileLineMatches() { return m_sc_list; } void Clear(); void Reset(const FileSpec &file_spec, uint32_t line, bool check_inlines); protected: FileSpec m_file_spec; // This is the file spec we are looking for. uint32_t m_line_number; // This is the line number that we are looking for. SymbolContextList m_sc_list; bool m_inlines; // This determines whether the resolver looks for inlined // functions or not. private: DISALLOW_COPY_AND_ASSIGN(FileLineResolver); }; } // namespace lldb_private #endif // LLDB_CORE_FILELINERESOLVER_H
bsd-3-clause
endlessm/chromium-browser
third_party/blink/renderer/platform/graphics/dark_mode_color_classifier_test.cc
3260
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/graphics/dark_mode_color_classifier.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/graphics/color.h" #include "third_party/blink/renderer/platform/graphics/dark_mode_settings.h" #include "third_party/blink/renderer/platform/graphics/graphics_types.h" #include "third_party/skia/include/core/SkColor.h" namespace blink { namespace { Color GetColorWithBrightness(int target_brightness) { CHECK_GE(target_brightness, 0); CHECK_LE(target_brightness, 256); return Color(target_brightness, target_brightness, target_brightness); } TEST(DarkModeColorClassifierTest, ApplyFilterToDarkTextOnly) { DarkModeSettings settings; settings.mode = DarkModeInversionAlgorithm::kSimpleInvertForTesting; settings.text_brightness_threshold = 200; auto classifier = DarkModeColorClassifier::MakeTextColorClassifier(settings); // Verify that the following are inverted: // * black text // * text darker than the text brightness threshold // and the following are not inverted: // * white text // * text brighter than the text brightness threshold // * text at the brightness threshold EXPECT_EQ(DarkModeClassification::kApplyFilter, classifier->ShouldInvertColor(GetColorWithBrightness( settings.text_brightness_threshold - 5))); EXPECT_EQ(DarkModeClassification::kApplyFilter, classifier->ShouldInvertColor(Color::kBlack)); EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter, classifier->ShouldInvertColor(Color::kWhite)); EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter, classifier->ShouldInvertColor(GetColorWithBrightness( settings.text_brightness_threshold + 5))); EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter, classifier->ShouldInvertColor( GetColorWithBrightness(settings.text_brightness_threshold))); } TEST(DarkModeColorClassifierTest, ApplyFilterToLightBackgroundElementsOnly) { DarkModeSettings settings; settings.mode = DarkModeInversionAlgorithm::kSimpleInvertForTesting; settings.background_brightness_threshold = 200; auto classifier = DarkModeColorClassifier::MakeBackgroundColorClassifier(settings); EXPECT_EQ(DarkModeClassification::kApplyFilter, classifier->ShouldInvertColor(Color::kWhite)); EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter, classifier->ShouldInvertColor(Color::kBlack)); EXPECT_EQ(DarkModeClassification::kApplyFilter, classifier->ShouldInvertColor(GetColorWithBrightness( settings.background_brightness_threshold + 5))); EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter, classifier->ShouldInvertColor(GetColorWithBrightness( settings.background_brightness_threshold))); EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter, classifier->ShouldInvertColor(GetColorWithBrightness( settings.background_brightness_threshold - 5))); } } // namespace } // namespace blink
bsd-3-clause
endlessm/chromium-browser
third_party/blink/renderer/core/css/basic_shape_functions.cc
15126
/* * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "third_party/blink/renderer/core/css/basic_shape_functions.h" #include "third_party/blink/renderer/core/css/css_basic_shape_values.h" #include "third_party/blink/renderer/core/css/css_identifier_value.h" #include "third_party/blink/renderer/core/css/css_numeric_literal_value.h" #include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h" #include "third_party/blink/renderer/core/css/css_ray_value.h" #include "third_party/blink/renderer/core/css/css_value_pair.h" #include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h" #include "third_party/blink/renderer/core/style/basic_shapes.h" #include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/core/style/style_ray.h" namespace blink { static StyleRay::RaySize KeywordToRaySize(CSSValueID id) { switch (id) { case CSSValueID::kClosestSide: return StyleRay::RaySize::kClosestSide; case CSSValueID::kClosestCorner: return StyleRay::RaySize::kClosestCorner; case CSSValueID::kFarthestSide: return StyleRay::RaySize::kFarthestSide; case CSSValueID::kFarthestCorner: return StyleRay::RaySize::kFarthestCorner; case CSSValueID::kSides: return StyleRay::RaySize::kSides; default: NOTREACHED(); return StyleRay::RaySize::kClosestSide; } } static CSSValueID RaySizeToKeyword(StyleRay::RaySize size) { switch (size) { case StyleRay::RaySize::kClosestSide: return CSSValueID::kClosestSide; case StyleRay::RaySize::kClosestCorner: return CSSValueID::kClosestCorner; case StyleRay::RaySize::kFarthestSide: return CSSValueID::kFarthestSide; case StyleRay::RaySize::kFarthestCorner: return CSSValueID::kFarthestCorner; case StyleRay::RaySize::kSides: return CSSValueID::kSides; } NOTREACHED(); return CSSValueID::kInvalid; } static CSSValue* ValueForCenterCoordinate( const ComputedStyle& style, const BasicShapeCenterCoordinate& center, EBoxOrient orientation) { if (center.GetDirection() == BasicShapeCenterCoordinate::kTopLeft) return CSSValue::Create(center.length(), style.EffectiveZoom()); CSSValueID keyword = orientation == EBoxOrient::kHorizontal ? CSSValueID::kRight : CSSValueID::kBottom; return MakeGarbageCollected<CSSValuePair>( CSSIdentifierValue::Create(keyword), CSSValue::Create(center.length(), style.EffectiveZoom()), CSSValuePair::kDropIdenticalValues); } static CSSValuePair* ValueForLengthSize(const LengthSize& length_size, const ComputedStyle& style) { return MakeGarbageCollected<CSSValuePair>( CSSValue::Create(length_size.Width(), style.EffectiveZoom()), CSSValue::Create(length_size.Height(), style.EffectiveZoom()), CSSValuePair::kKeepIdenticalValues); } static CSSValue* BasicShapeRadiusToCSSValue(const ComputedStyle& style, const BasicShapeRadius& radius) { switch (radius.GetType()) { case BasicShapeRadius::kValue: return CSSValue::Create(radius.Value(), style.EffectiveZoom()); case BasicShapeRadius::kClosestSide: return CSSIdentifierValue::Create(CSSValueID::kClosestSide); case BasicShapeRadius::kFarthestSide: return CSSIdentifierValue::Create(CSSValueID::kFarthestSide); } NOTREACHED(); return nullptr; } CSSValue* ValueForBasicShape(const ComputedStyle& style, const BasicShape* basic_shape) { switch (basic_shape->GetType()) { case BasicShape::kStyleRayType: { const StyleRay& ray = To<StyleRay>(*basic_shape); return MakeGarbageCollected<cssvalue::CSSRayValue>( *CSSNumericLiteralValue::Create( ray.Angle(), CSSPrimitiveValue::UnitType::kDegrees), *CSSIdentifierValue::Create(RaySizeToKeyword(ray.Size())), (ray.Contain() ? CSSIdentifierValue::Create(CSSValueID::kContain) : nullptr)); } case BasicShape::kStylePathType: return To<StylePath>(basic_shape)->ComputedCSSValue(); case BasicShape::kBasicShapeCircleType: { const BasicShapeCircle* circle = To<BasicShapeCircle>(basic_shape); cssvalue::CSSBasicShapeCircleValue* circle_value = MakeGarbageCollected<cssvalue::CSSBasicShapeCircleValue>(); circle_value->SetCenterX(ValueForCenterCoordinate( style, circle->CenterX(), EBoxOrient::kHorizontal)); circle_value->SetCenterY(ValueForCenterCoordinate( style, circle->CenterY(), EBoxOrient::kVertical)); circle_value->SetRadius( BasicShapeRadiusToCSSValue(style, circle->Radius())); return circle_value; } case BasicShape::kBasicShapeEllipseType: { const BasicShapeEllipse* ellipse = To<BasicShapeEllipse>(basic_shape); auto* ellipse_value = MakeGarbageCollected<cssvalue::CSSBasicShapeEllipseValue>(); ellipse_value->SetCenterX(ValueForCenterCoordinate( style, ellipse->CenterX(), EBoxOrient::kHorizontal)); ellipse_value->SetCenterY(ValueForCenterCoordinate( style, ellipse->CenterY(), EBoxOrient::kVertical)); ellipse_value->SetRadiusX( BasicShapeRadiusToCSSValue(style, ellipse->RadiusX())); ellipse_value->SetRadiusY( BasicShapeRadiusToCSSValue(style, ellipse->RadiusY())); return ellipse_value; } case BasicShape::kBasicShapePolygonType: { const BasicShapePolygon* polygon = To<BasicShapePolygon>(basic_shape); auto* polygon_value = MakeGarbageCollected<cssvalue::CSSBasicShapePolygonValue>(); polygon_value->SetWindRule(polygon->GetWindRule()); const Vector<Length>& values = polygon->Values(); for (unsigned i = 0; i < values.size(); i += 2) { polygon_value->AppendPoint( CSSPrimitiveValue::CreateFromLength(values.at(i), style.EffectiveZoom()), CSSPrimitiveValue::CreateFromLength(values.at(i + 1), style.EffectiveZoom())); } return polygon_value; } case BasicShape::kBasicShapeInsetType: { const BasicShapeInset* inset = To<BasicShapeInset>(basic_shape); auto* inset_value = MakeGarbageCollected<cssvalue::CSSBasicShapeInsetValue>(); inset_value->SetTop(CSSPrimitiveValue::CreateFromLength( inset->Top(), style.EffectiveZoom())); inset_value->SetRight(CSSPrimitiveValue::CreateFromLength( inset->Right(), style.EffectiveZoom())); inset_value->SetBottom(CSSPrimitiveValue::CreateFromLength( inset->Bottom(), style.EffectiveZoom())); inset_value->SetLeft(CSSPrimitiveValue::CreateFromLength( inset->Left(), style.EffectiveZoom())); inset_value->SetTopLeftRadius( ValueForLengthSize(inset->TopLeftRadius(), style)); inset_value->SetTopRightRadius( ValueForLengthSize(inset->TopRightRadius(), style)); inset_value->SetBottomRightRadius( ValueForLengthSize(inset->BottomRightRadius(), style)); inset_value->SetBottomLeftRadius( ValueForLengthSize(inset->BottomLeftRadius(), style)); return inset_value; } default: return nullptr; } } static Length ConvertToLength(const StyleResolverState& state, const CSSPrimitiveValue* value) { if (!value) return Length::Fixed(0); return value->ConvertToLength(state.CssToLengthConversionData()); } static LengthSize ConvertToLengthSize(const StyleResolverState& state, const CSSValuePair* value) { if (!value) return LengthSize(Length::Fixed(0), Length::Fixed(0)); return LengthSize( ConvertToLength(state, &To<CSSPrimitiveValue>(value->First())), ConvertToLength(state, &To<CSSPrimitiveValue>(value->Second()))); } static BasicShapeCenterCoordinate ConvertToCenterCoordinate( const StyleResolverState& state, CSSValue* value) { BasicShapeCenterCoordinate::Direction direction; Length offset = Length::Fixed(0); CSSValueID keyword = CSSValueID::kTop; if (!value) { keyword = CSSValueID::kCenter; } else if (auto* identifier_value = DynamicTo<CSSIdentifierValue>(value)) { keyword = identifier_value->GetValueID(); } else if (auto* value_pair = DynamicTo<CSSValuePair>(value)) { keyword = To<CSSIdentifierValue>(value_pair->First()).GetValueID(); offset = ConvertToLength(state, &To<CSSPrimitiveValue>(value_pair->Second())); } else { offset = ConvertToLength(state, To<CSSPrimitiveValue>(value)); } switch (keyword) { case CSSValueID::kTop: case CSSValueID::kLeft: direction = BasicShapeCenterCoordinate::kTopLeft; break; case CSSValueID::kRight: case CSSValueID::kBottom: direction = BasicShapeCenterCoordinate::kBottomRight; break; case CSSValueID::kCenter: direction = BasicShapeCenterCoordinate::kTopLeft; offset = Length::Percent(50); break; default: NOTREACHED(); direction = BasicShapeCenterCoordinate::kTopLeft; break; } return BasicShapeCenterCoordinate(direction, offset); } static BasicShapeRadius CssValueToBasicShapeRadius( const StyleResolverState& state, const CSSValue* radius) { if (!radius) return BasicShapeRadius(BasicShapeRadius::kClosestSide); if (auto* radius_identifier_value = DynamicTo<CSSIdentifierValue>(radius)) { switch (radius_identifier_value->GetValueID()) { case CSSValueID::kClosestSide: return BasicShapeRadius(BasicShapeRadius::kClosestSide); case CSSValueID::kFarthestSide: return BasicShapeRadius(BasicShapeRadius::kFarthestSide); default: NOTREACHED(); break; } } return BasicShapeRadius( ConvertToLength(state, To<CSSPrimitiveValue>(radius))); } scoped_refptr<BasicShape> BasicShapeForValue( const StyleResolverState& state, const CSSValue& basic_shape_value) { scoped_refptr<BasicShape> basic_shape; if (IsA<cssvalue::CSSBasicShapeCircleValue>(basic_shape_value)) { const auto& circle_value = To<cssvalue::CSSBasicShapeCircleValue>(basic_shape_value); scoped_refptr<BasicShapeCircle> circle = BasicShapeCircle::Create(); circle->SetCenterX( ConvertToCenterCoordinate(state, circle_value.CenterX())); circle->SetCenterY( ConvertToCenterCoordinate(state, circle_value.CenterY())); circle->SetRadius(CssValueToBasicShapeRadius(state, circle_value.Radius())); basic_shape = std::move(circle); } else if (IsA<cssvalue::CSSBasicShapeEllipseValue>(basic_shape_value)) { const auto& ellipse_value = To<cssvalue::CSSBasicShapeEllipseValue>(basic_shape_value); scoped_refptr<BasicShapeEllipse> ellipse = BasicShapeEllipse::Create(); ellipse->SetCenterX( ConvertToCenterCoordinate(state, ellipse_value.CenterX())); ellipse->SetCenterY( ConvertToCenterCoordinate(state, ellipse_value.CenterY())); ellipse->SetRadiusX( CssValueToBasicShapeRadius(state, ellipse_value.RadiusX())); ellipse->SetRadiusY( CssValueToBasicShapeRadius(state, ellipse_value.RadiusY())); basic_shape = std::move(ellipse); } else if (IsA<cssvalue::CSSBasicShapePolygonValue>(basic_shape_value)) { const cssvalue::CSSBasicShapePolygonValue& polygon_value = To<cssvalue::CSSBasicShapePolygonValue>(basic_shape_value); scoped_refptr<BasicShapePolygon> polygon = BasicShapePolygon::Create(); polygon->SetWindRule(polygon_value.GetWindRule()); const HeapVector<Member<CSSPrimitiveValue>>& values = polygon_value.Values(); for (unsigned i = 0; i < values.size(); i += 2) polygon->AppendPoint(ConvertToLength(state, values.at(i).Get()), ConvertToLength(state, values.at(i + 1).Get())); basic_shape = std::move(polygon); } else if (IsA<cssvalue::CSSBasicShapeInsetValue>(basic_shape_value)) { const cssvalue::CSSBasicShapeInsetValue& rect_value = To<cssvalue::CSSBasicShapeInsetValue>(basic_shape_value); scoped_refptr<BasicShapeInset> rect = BasicShapeInset::Create(); rect->SetTop(ConvertToLength(state, rect_value.Top())); rect->SetRight(ConvertToLength(state, rect_value.Right())); rect->SetBottom(ConvertToLength(state, rect_value.Bottom())); rect->SetLeft(ConvertToLength(state, rect_value.Left())); rect->SetTopLeftRadius( ConvertToLengthSize(state, rect_value.TopLeftRadius())); rect->SetTopRightRadius( ConvertToLengthSize(state, rect_value.TopRightRadius())); rect->SetBottomRightRadius( ConvertToLengthSize(state, rect_value.BottomRightRadius())); rect->SetBottomLeftRadius( ConvertToLengthSize(state, rect_value.BottomLeftRadius())); basic_shape = std::move(rect); } else if (const auto* ray_value = DynamicTo<cssvalue::CSSRayValue>(basic_shape_value)) { float angle = ray_value->Angle().ComputeDegrees(); StyleRay::RaySize size = KeywordToRaySize(ray_value->Size().GetValueID()); bool contain = !!ray_value->Contain(); basic_shape = StyleRay::Create(angle, size, contain); } else { NOTREACHED(); } return basic_shape; } FloatPoint FloatPointForCenterCoordinate( const BasicShapeCenterCoordinate& center_x, const BasicShapeCenterCoordinate& center_y, FloatSize box_size) { float x = FloatValueForLength(center_x.ComputedLength(), box_size.Width()); float y = FloatValueForLength(center_y.ComputedLength(), box_size.Height()); return FloatPoint(x, y); } } // namespace blink
bsd-3-clause
tferega/selenate
code/Server/src/main/scala/net/selenate/server/settings/ProfileSettings.scala
2017
package net.selenate.server package settings import java.io.File import net.selenate.common.exceptions.SeException object ProfileSettings { private def parseDisplay(display: String): DisplaySettings = display.toLowerCase match { case "main" => DisplaySettings.Main case "firstfree" => DisplaySettings.FirstFree case IsInt(num) => DisplaySettings.Specific(num) case _ => throw new SeException(s"""Error while parsing configuration. Offending entry: server.pool.display. Expected one of ["Main", "FirstFree", num], received "$display".""") } private def parseBinaryLocation(binaryLocation: String): File = { val file = new File(binaryLocation) if (!file.exists) throw new SeException(s"""Error while parsing configuration. Offending entry: server.pool.binary. Path "$binaryLocation" does not exist.""") if (!file.isFile) throw new SeException(s"""Error while parsing configuration. Offending entry: server.pool.binary. Path "$binaryLocation" is not a file.""") if (!file.canExecute) throw new SeException(s"""Error while parsing configuration. Offending entry: server.pool.binary. File "$binaryLocation" is not executable.""") file } def parsePrefs(prefs: Map[String, String]): Map[String, AnyRef] = prefs.mapValues { entry => entry match { case IsBoolean(bool) => bool case IsInteger(int) => int case IsString(str) => str case _ => throw new SeException(s"""Error while parsing configuration. Offending entry: server.pool.prefs.$entry. Malformed entry.""") } } def fromConfig( display: String, binaryLocation: Option[String], prefs: Map[String, String]) = new ProfileSettings( display = parseDisplay(display), binaryLocation = binaryLocation map parseBinaryLocation, prefMap = parsePrefs(prefs)) } case class ProfileSettings( val display: DisplaySettings, val binaryLocation: Option[File], val prefMap: Map[String, AnyRef])
bsd-3-clause